cartethyia 2.8.0 → 2.8.1

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 (348) hide show
  1. package/.env.example +3 -3
  2. package/dist/dashboard/assets/{BannedPage-Cc0vKpMG.js → BannedPage-Dq530awD.js} +1 -1
  3. package/dist/dashboard/assets/BannedPage-Dq530awD.js.gz +0 -0
  4. package/dist/dashboard/assets/{CliToolDetailPage-Bqj2aa1T.js → CliToolDetailPage-DZzaS-7S.js} +1 -1
  5. package/dist/dashboard/assets/CliToolDetailPage-DZzaS-7S.js.gz +0 -0
  6. package/dist/dashboard/assets/{CliToolsPage-CXsaOAO2.js → CliToolsPage-DaZZ3cqP.js} +1 -1
  7. package/dist/dashboard/assets/CliToolsPage-DaZZ3cqP.js.gz +0 -0
  8. package/dist/dashboard/assets/{CombosPage-BeLpJ4ma.js → CombosPage-BlC_xdkX.js} +1 -1
  9. package/dist/dashboard/assets/CombosPage-BlC_xdkX.js.gz +0 -0
  10. package/dist/dashboard/assets/{ConsoleLogPage-DnV0uZ3m.js → ConsoleLogPage-D-rqeVtG.js} +1 -1
  11. package/dist/dashboard/assets/ConsoleLogPage-D-rqeVtG.js.gz +0 -0
  12. package/dist/dashboard/assets/{CustomizationPage-CBxAjo63.js → CustomizationPage-7xT5yg2E.js} +1 -1
  13. package/dist/dashboard/assets/CustomizationPage-7xT5yg2E.js.gz +0 -0
  14. package/dist/dashboard/assets/{HealthEventsModal-B5yEE0k6.js → HealthEventsModal-Clq8E9cW.js} +1 -1
  15. package/dist/dashboard/assets/HealthEventsModal-Clq8E9cW.js.gz +0 -0
  16. package/dist/dashboard/assets/{InjectSystemPromptPanel-BWFLECmz.js → InjectSystemPromptPanel-6Teoq9Se.js} +1 -1
  17. package/dist/dashboard/assets/InjectSystemPromptPanel-6Teoq9Se.js.gz +0 -0
  18. package/dist/dashboard/assets/{LoginPage-CgoPc5B9.js → LoginPage-CZuI0MAR.js} +1 -1
  19. package/dist/dashboard/assets/LoginPage-CZuI0MAR.js.gz +0 -0
  20. package/dist/dashboard/assets/{ModelPicker-D9bFQern.js → ModelPicker-C1hNTlkr.js} +1 -1
  21. package/dist/dashboard/assets/ModelPicker-C1hNTlkr.js.gz +0 -0
  22. package/dist/dashboard/assets/{OverviewPage-B_p4tL8k.js → OverviewPage-0yfhSI1C.js} +1 -1
  23. package/dist/dashboard/assets/OverviewPage-0yfhSI1C.js.gz +0 -0
  24. package/dist/dashboard/assets/ProviderDetailPage-xqTxdQ4c.js +8 -0
  25. package/dist/dashboard/assets/ProviderDetailPage-xqTxdQ4c.js.gz +0 -0
  26. package/dist/dashboard/assets/{ProviderIcon-D_0PiZtg.js → ProviderIcon-Ddhm1InL.js} +1 -1
  27. package/dist/dashboard/assets/ProviderIcon-Ddhm1InL.js.gz +0 -0
  28. package/dist/dashboard/assets/{ProvidersPage-CLI2bJTK.js → ProvidersPage-C3fYuu6i.js} +1 -1
  29. package/dist/dashboard/assets/ProvidersPage-C3fYuu6i.js.gz +0 -0
  30. package/dist/dashboard/assets/ProxyPage-CHtJtZ3u.js +9 -0
  31. package/dist/dashboard/assets/ProxyPage-CHtJtZ3u.js.gz +0 -0
  32. package/dist/dashboard/assets/{QuotaPage-DA-a1iSN.js → QuotaPage-D1RV_2BX.js} +1 -1
  33. package/dist/dashboard/assets/QuotaPage-D1RV_2BX.js.gz +0 -0
  34. package/dist/dashboard/assets/{SettingsPage-CctTga2C.js → SettingsPage-BzZAvYSX.js} +1 -1
  35. package/dist/dashboard/assets/SettingsPage-BzZAvYSX.js.gz +0 -0
  36. package/dist/dashboard/assets/{SetupPage-febLU4r1.js → SetupPage--s-EfEIL.js} +1 -1
  37. package/dist/dashboard/assets/SetupPage--s-EfEIL.js.gz +0 -0
  38. package/dist/dashboard/assets/{StudioPage-M6fvR5Wz.js → StudioPage-BjXFGSK4.js} +1 -1
  39. package/dist/dashboard/assets/StudioPage-BjXFGSK4.js.gz +0 -0
  40. package/dist/dashboard/assets/{UsagePage-nyeuRqz9.js → UsagePage-CP8F8BN7.js} +1 -1
  41. package/dist/dashboard/assets/UsagePage-CP8F8BN7.js.gz +0 -0
  42. package/dist/dashboard/assets/{api-keys-BFOlvrJC.js → api-keys-2hc12Uz2.js} +1 -1
  43. package/dist/dashboard/assets/api-keys-2hc12Uz2.js.gz +0 -0
  44. package/dist/dashboard/assets/app-DGXbNfAR.css +2 -0
  45. package/dist/dashboard/assets/app-DGXbNfAR.css.gz +0 -0
  46. package/dist/dashboard/assets/{assert-CqTLw5e7.js → assert-BMcj1xZE.js} +1 -1
  47. package/dist/dashboard/assets/assert-BMcj1xZE.js.gz +0 -0
  48. package/dist/dashboard/assets/{badge-C83EqLB0.js → badge-DkRUuVfz.js} +1 -1
  49. package/dist/dashboard/assets/badge-DkRUuVfz.js.gz +0 -0
  50. package/dist/dashboard/assets/{banner-D1xn7pIe.js → banner-CDjW841Q.js} +1 -1
  51. package/dist/dashboard/assets/banner-CDjW841Q.js.gz +0 -0
  52. package/dist/dashboard/assets/{card-DU3Lq5Lm.js → card-Bto5UlL9.js} +1 -1
  53. package/dist/dashboard/assets/card-Bto5UlL9.js.gz +0 -0
  54. package/dist/dashboard/assets/{cli-tools-Dw1U_drK.js → cli-tools-DaH6g9hL.js} +1 -1
  55. package/dist/dashboard/assets/cli-tools-DaH6g9hL.js.gz +0 -0
  56. package/dist/dashboard/assets/{clipboard-button-CEL5Sg_J.js → clipboard-button-BYKBCzjk.js} +1 -1
  57. package/dist/dashboard/assets/clipboard-button-BYKBCzjk.js.gz +0 -0
  58. package/dist/dashboard/assets/{dialog-BjFR5UHy.js → dialog-DL0Zftwv.js} +1 -1
  59. package/dist/dashboard/assets/dialog-DL0Zftwv.js.gz +0 -0
  60. package/dist/dashboard/assets/{drawer-HvBW0AjI.js → drawer-Dpx_UXaS.js} +1 -1
  61. package/dist/dashboard/assets/drawer-Dpx_UXaS.js.gz +0 -0
  62. package/dist/dashboard/assets/{entry-CECVELyy.js → entry-BV7-1NoM.js} +1 -1
  63. package/dist/dashboard/assets/entry-BV7-1NoM.js.gz +0 -0
  64. package/dist/dashboard/assets/{entry-DYYofQ7W.js → entry-CGvdNU6r.js} +1 -1
  65. package/dist/dashboard/assets/entry-CGvdNU6r.js.gz +0 -0
  66. package/dist/dashboard/assets/{entry-BSu3gFlt.js → entry-DScKYvZj.js} +3 -3
  67. package/dist/dashboard/assets/entry-DScKYvZj.js.gz +0 -0
  68. package/dist/dashboard/assets/{formatters-DLW4i8zK.js → formatters-BS3DZlZj.js} +1 -1
  69. package/dist/dashboard/assets/formatters-BS3DZlZj.js.gz +0 -0
  70. package/dist/dashboard/assets/{index-1-fCqe64.js → index-SQnvvTWX.js} +2 -2
  71. package/dist/dashboard/assets/index-SQnvvTWX.js.gz +0 -0
  72. package/dist/dashboard/assets/{inline-DGvU2oLK.js → inline-Dl-cuLK0.js} +1 -1
  73. package/dist/dashboard/assets/inline-Dl-cuLK0.js.gz +0 -0
  74. package/dist/dashboard/assets/{input-iNnO1X2K.js → input-Bfx0EzRc.js} +1 -1
  75. package/dist/dashboard/assets/input-Bfx0EzRc.js.gz +0 -0
  76. package/dist/dashboard/assets/{layout-0q8UGypb.js → layout-BxhbQ_JS.js} +1 -1
  77. package/dist/dashboard/assets/layout-BxhbQ_JS.js.gz +0 -0
  78. package/dist/dashboard/assets/{list-row-C0w2bQjJ.js → list-row-D49Y4ptn.js} +1 -1
  79. package/dist/dashboard/assets/list-row-D49Y4ptn.js.gz +0 -0
  80. package/dist/dashboard/assets/{live-M5aJ_xCa.js → live-CbVTdX9V.js} +1 -1
  81. package/dist/dashboard/assets/live-CbVTdX9V.js.gz +0 -0
  82. package/dist/dashboard/assets/{network-BKeQGT3K.js → network-JGvDveof.js} +1 -1
  83. package/dist/dashboard/assets/network-JGvDveof.js.gz +0 -0
  84. package/dist/dashboard/assets/{numbers-CivAk3da.js → numbers-Dw6kiew-.js} +1 -1
  85. package/dist/dashboard/assets/numbers-Dw6kiew-.js.gz +0 -0
  86. package/dist/dashboard/assets/{pagination-CpzvI5ep.js → pagination-iUoI8GeE.js} +1 -1
  87. package/dist/dashboard/assets/pagination-iUoI8GeE.js.gz +0 -0
  88. package/dist/dashboard/assets/providers/sensenova-intl.png +0 -0
  89. package/dist/dashboard/assets/providers/sensenova.png +0 -0
  90. package/dist/dashboard/assets/{routing-BFQX2VBc.js → routing-8jZr-3WE.js} +1 -1
  91. package/dist/dashboard/assets/routing-8jZr-3WE.js.gz +0 -0
  92. package/dist/dashboard/assets/{select-CXbck0jG.js → select-oO1FxMVb.js} +1 -1
  93. package/dist/dashboard/assets/select-oO1FxMVb.js.gz +0 -0
  94. package/dist/dashboard/assets/{settings-C_XvMHh9.js → settings-CLr3kdIx.js} +1 -1
  95. package/dist/dashboard/assets/settings-CLr3kdIx.js.gz +0 -0
  96. package/dist/dashboard/assets/{stack-DggRiCxE.js → stack-Y3pDteZr.js} +1 -1
  97. package/dist/dashboard/assets/stack-Y3pDteZr.js.gz +0 -0
  98. package/dist/dashboard/assets/{state-ClFzfbYp.js → state-CArX_Iak.js} +1 -1
  99. package/dist/dashboard/assets/state-CArX_Iak.js.gz +0 -0
  100. package/dist/dashboard/assets/{switch-CTIFxKqS.js → switch-DwlwmDO-.js} +1 -1
  101. package/dist/dashboard/assets/switch-DwlwmDO-.js.gz +0 -0
  102. package/dist/dashboard/assets/{useMutation-BClG3yWj.js → useMutation-DJ9GYEgf.js} +1 -1
  103. package/dist/dashboard/assets/useMutation-DJ9GYEgf.js.gz +0 -0
  104. package/dist/dashboard/index.html +2 -2
  105. package/dist/dashboard/index.html.gz +0 -0
  106. package/dist/dashboard/precompressed-assets.json +51 -51
  107. package/migrations/full-postgres/0047_add_provider_device_flow_proxy.sql +17 -0
  108. package/migrations/lite-sqlite3/0047_add_provider_device_flow_proxy.sql +19 -0
  109. package/package.json +1 -1
  110. package/src/boot/app.ts +1 -1
  111. package/src/boot/dependencies.ts +4 -6
  112. package/src/config/providers.ts +6 -5
  113. package/src/config/spec.ts +8 -8
  114. package/src/console/backup/nine-router.ts +71 -10
  115. package/src/console/backup/service.ts +8 -1
  116. package/src/console/console-router.ts +1 -1
  117. package/src/console/domain-registration.ts +7 -2
  118. package/src/console/inferhub/client.ts +1 -1
  119. package/src/console/observability/live.ts +2 -2
  120. package/src/console/providers/catalog/contracts.ts +9 -3
  121. package/src/console/providers/catalog/model-operations.ts +2 -3
  122. package/src/console/providers/catalog/provider-operations.ts +1 -1
  123. package/src/console/providers/catalog/routes.ts +2 -2
  124. package/src/console/providers/catalog/store.ts +1914 -1907
  125. package/src/console/providers/detail/routes.ts +1 -0
  126. package/src/console/providers/detail/store.ts +4 -0
  127. package/src/console/providers/oauth/callback-listener.ts +30 -11
  128. package/src/console/providers/oauth/device-egress.ts +123 -0
  129. package/src/console/providers/oauth/routes.ts +123 -16
  130. package/src/console/quota/account-quota-tenant.ts +5 -5
  131. package/src/console/quota/account-test-egress.ts +2 -2
  132. package/src/console/quota/daily-growth-job.ts +1 -1
  133. package/src/console/routing/pools/contracts.ts +1 -1
  134. package/src/console/routing/pools/operations.ts +1 -1
  135. package/src/console/routing/pools/probe-verdict.ts +2 -2
  136. package/src/console/routing/pools/relay-deploy.ts +1 -1
  137. package/src/console/routing/pools/store.ts +4 -4
  138. package/src/network/client.ts +67 -0
  139. package/src/network/egress/bidi-session.ts +322 -0
  140. package/src/network/egress/dial.ts +201 -0
  141. package/src/network/egress/factory.ts +191 -0
  142. package/src/network/{outbound-fetch.ts → egress/fetch.ts} +195 -29
  143. package/src/network/egress/tls-profile.ts +123 -0
  144. package/src/network/egress/ws.ts +175 -0
  145. package/src/network/{types.ts → pool/agent-config.ts} +1 -1
  146. package/src/network/pool/agent.ts +2 -2
  147. package/src/network/{pool-cooldown-store.ts → pool/cooldown-store.ts} +7 -7
  148. package/src/network/{pool-health-machine.ts → pool/health.ts} +205 -6
  149. package/src/network/pool/resolver.ts +10 -849
  150. package/src/network/pool/selector.ts +2 -2
  151. package/src/network/ssrf.ts +1 -1
  152. package/src/network/{retry.ts → util/retry.ts} +1 -1
  153. package/src/observability/telemetry-buffer.ts +1 -1
  154. package/src/persistence/schema.ts +9 -0
  155. package/src/persistence/ttl-cache.ts +1 -1
  156. package/src/protocol/codecs.ts +58 -1
  157. package/src/protocol/request/messages.ts +31 -18
  158. package/src/protocol/response/messages.ts +34 -7
  159. package/src/protocol/translation/quirks.ts +15 -0
  160. package/src/protocol/upstream/send-claude-messages.ts +2 -2
  161. package/src/providers/adapters/compatible-adapter.ts +5 -0
  162. package/src/providers/authentication/oauth-client.ts +40 -6
  163. package/src/providers/authentication/oauth-device-flow.ts +7 -3
  164. package/src/providers/authentication/oauth-flow-store.ts +82 -1
  165. package/src/providers/authentication/oauth-refresh-service.ts +766 -739
  166. package/src/providers/default-registry.ts +76 -0
  167. package/src/providers/discovery/discovery-types.ts +7 -0
  168. package/src/providers/discovery/probe-phases.ts +6 -2
  169. package/src/providers/discovery/probing-service.ts +7 -0
  170. package/src/providers/integrations/antigravity/antigravity-protocol.ts +11 -0
  171. package/src/providers/integrations/buddy/account.ts +969 -0
  172. package/src/providers/integrations/buddy/capabilities.ts +10 -10
  173. package/src/providers/integrations/buddy/{buddy-catalog-shared.ts → catalog.ts} +198 -136
  174. package/src/providers/integrations/buddy/{buddy-chat-shared.ts → chat.ts} +5 -5
  175. package/src/providers/integrations/buddy/codebuddy/index.ts +429 -0
  176. package/src/providers/integrations/buddy/codebuddy/shared.ts +4 -4
  177. package/src/providers/integrations/buddy/{buddy-identity.ts → headers.ts} +138 -140
  178. package/src/providers/integrations/buddy/lifecycle.ts +1018 -0
  179. package/src/providers/integrations/buddy/{buddy-media.ts → media.ts} +1 -1
  180. package/src/providers/integrations/cline/cline-oauth.ts +10 -5
  181. package/src/providers/integrations/cline/cline.ts +3 -4
  182. package/src/providers/integrations/clixad/clixad-oauth.ts +98 -0
  183. package/src/providers/integrations/clixad/clixad-quota.ts +132 -0
  184. package/src/providers/integrations/clixad/provider.ts +145 -0
  185. package/src/providers/integrations/codex/codex-oauth.ts +8 -5
  186. package/src/providers/integrations/cursor/cursor-auth.ts +1 -1
  187. package/src/providers/integrations/cursor/cursor-hardening.ts +279 -0
  188. package/src/providers/integrations/cursor/cursor-http2.ts +605 -6
  189. package/src/providers/integrations/cursor/cursor-shared.ts +1 -1
  190. package/src/providers/integrations/cursor/cursor.ts +485 -70
  191. package/src/providers/integrations/deepai/deepai-catalog.ts +149 -0
  192. package/src/providers/integrations/deepai/deepai-common.ts +145 -0
  193. package/src/providers/integrations/deepai/deepai-oauth.ts +129 -0
  194. package/src/providers/integrations/deepai/deepai-quota.ts +97 -0
  195. package/src/providers/integrations/deepai/provider.ts +42 -0
  196. package/src/providers/integrations/devin/devin-auth.ts +7 -0
  197. package/src/providers/integrations/factory/factory-oauth.ts +16 -7
  198. package/src/providers/integrations/freebuff/freebuff.ts +2 -2
  199. package/src/providers/integrations/freepi/freepi-catalog.ts +5 -0
  200. package/src/providers/integrations/freepi/freepi-discovery.ts +2 -2
  201. package/src/providers/integrations/freepi/freepi-headers.ts +2 -2
  202. package/src/providers/integrations/freepi/freepi-protocol.ts +11 -2
  203. package/src/providers/integrations/freepi/freepi-realm.ts +0 -3
  204. package/src/providers/integrations/freepi/freepi-session.ts +158 -0
  205. package/src/providers/integrations/freepi/freepi.ts +80 -54
  206. package/src/providers/integrations/github/github-discovery.ts +30 -13
  207. package/src/providers/integrations/github/github-oauth.ts +217 -44
  208. package/src/providers/integrations/github/github-quota.ts +22 -5
  209. package/src/providers/integrations/github/github.ts +40 -32
  210. package/src/providers/integrations/grok/grok-oauth.ts +4 -4
  211. package/src/providers/integrations/hermes/hermes-oauth.ts +3 -3
  212. package/src/providers/integrations/hermes/hermes.ts +34 -5
  213. package/src/providers/integrations/kilo/kilo-oauth.ts +4 -4
  214. package/src/providers/integrations/kilo/kilo.ts +1 -1
  215. package/src/providers/integrations/kimi/kimi-oauth.ts +3 -3
  216. package/src/providers/integrations/kiro/kiro-oauth.ts +2 -2
  217. package/src/providers/integrations/muse/muse-oauth.ts +5 -5
  218. package/src/providers/integrations/opencode/fingerprint.ts +1 -1
  219. package/src/providers/integrations/openrouter/provider.ts +1 -1
  220. package/src/providers/integrations/perch/perch-protocol.ts +0 -3
  221. package/src/providers/integrations/perch/perch.ts +3 -3
  222. package/src/providers/integrations/qoder/claim-qoder-credits.ts +1 -1
  223. package/src/providers/integrations/qoder/qoder-adapter.ts +19 -113
  224. package/src/providers/integrations/qoder/qoder-auth.ts +8 -1
  225. package/src/providers/integrations/qoder/qoder-catalog.ts +1 -1
  226. package/src/providers/integrations/qoder/qoder-chat.ts +25 -8
  227. package/src/providers/integrations/qoder/qoder-checkin.ts +1 -1
  228. package/src/providers/integrations/qoder/qoder-cosy.ts +37 -9
  229. package/src/providers/integrations/qoder/qoder-oauth.ts +9 -2
  230. package/src/providers/integrations/qoder/qoder-realm.ts +13 -36
  231. package/src/providers/integrations/qoder/qoder-sse.ts +447 -68
  232. package/src/providers/integrations/qoder/qoder-types.ts +9 -0
  233. package/src/providers/integrations/qoder/qoder.ts +3 -25
  234. package/src/providers/integrations/sensenova/provider.ts +144 -0
  235. package/src/providers/integrations/trae/trae-quota.ts +15 -1
  236. package/src/providers/integrations/vercel/provider.ts +117 -0
  237. package/src/providers/integrations/vercel/vercel-quota.ts +96 -0
  238. package/src/providers/integrations/xai/xai-oauth.ts +5 -5
  239. package/src/providers/integrations/zcode-start-plan/gifts.ts +1 -1
  240. package/src/providers/integrations/zcode-start-plan/oauth.ts +3 -3
  241. package/src/providers/integrations/zro/zro.ts +2 -1
  242. package/src/providers/operations/account-refresh-status.ts +14 -0
  243. package/src/providers/operations/client-versions.ts +95 -30
  244. package/src/providers/operations/oauth-refresh-lead.ts +46 -22
  245. package/src/providers/operations/provider-caches.ts +1 -1
  246. package/src/providers/operations/provider-credential-service.ts +22 -25
  247. package/src/providers/operations/session-resolution.ts +17 -1
  248. package/src/providers/provider-contracts.ts +2 -2
  249. package/src/providers/provider-metadata.ts +30 -0
  250. package/src/providers/quota/quota-contracts.ts +2 -0
  251. package/src/providers/quota/refresh.ts +25 -3
  252. package/src/security/ip-boundary.ts +1 -1
  253. package/src/transport/dispatch/attempt-finalize.ts +1 -1
  254. package/src/transport/dispatch/attempt-loop.ts +3 -3
  255. package/src/transport/dispatch/handler-deps.ts +1 -1
  256. package/src/transport/dispatch/leases.ts +1 -1
  257. package/src/transport/dispatch/retry-policy.ts +1 -1
  258. package/src/transport/dispatch/streaming/finalize.ts +2 -2
  259. package/src/transport/dispatch/streaming/stream.ts +1 -1
  260. package/src/transport/dispatch/upstream.ts +1 -1
  261. package/src/transport/shutdown-notice.ts +1 -1
  262. package/src/workers/buddy-growth-tasks.ts +8 -8
  263. package/src/workers/daily-checkin.ts +4 -4
  264. package/src/workers/quota-refresh-sweep.ts +1 -1
  265. package/src/workers/zcode-gift-claim.ts +1 -1
  266. package/dist/dashboard/assets/BannedPage-Cc0vKpMG.js.gz +0 -0
  267. package/dist/dashboard/assets/CliToolDetailPage-Bqj2aa1T.js.gz +0 -0
  268. package/dist/dashboard/assets/CliToolsPage-CXsaOAO2.js.gz +0 -0
  269. package/dist/dashboard/assets/CombosPage-BeLpJ4ma.js.gz +0 -0
  270. package/dist/dashboard/assets/ConsoleLogPage-DnV0uZ3m.js.gz +0 -0
  271. package/dist/dashboard/assets/CustomizationPage-CBxAjo63.js.gz +0 -0
  272. package/dist/dashboard/assets/HealthEventsModal-B5yEE0k6.js.gz +0 -0
  273. package/dist/dashboard/assets/InjectSystemPromptPanel-BWFLECmz.js.gz +0 -0
  274. package/dist/dashboard/assets/LoginPage-CgoPc5B9.js.gz +0 -0
  275. package/dist/dashboard/assets/ModelPicker-D9bFQern.js.gz +0 -0
  276. package/dist/dashboard/assets/OverviewPage-B_p4tL8k.js.gz +0 -0
  277. package/dist/dashboard/assets/ProviderDetailPage-rs5E2rxv.js +0 -8
  278. package/dist/dashboard/assets/ProviderDetailPage-rs5E2rxv.js.gz +0 -0
  279. package/dist/dashboard/assets/ProviderIcon-D_0PiZtg.js.gz +0 -0
  280. package/dist/dashboard/assets/ProvidersPage-CLI2bJTK.js.gz +0 -0
  281. package/dist/dashboard/assets/ProxyPage-BwNC_-Cx.js +0 -9
  282. package/dist/dashboard/assets/ProxyPage-BwNC_-Cx.js.gz +0 -0
  283. package/dist/dashboard/assets/QuotaPage-DA-a1iSN.js.gz +0 -0
  284. package/dist/dashboard/assets/SettingsPage-CctTga2C.js.gz +0 -0
  285. package/dist/dashboard/assets/SetupPage-febLU4r1.js.gz +0 -0
  286. package/dist/dashboard/assets/StudioPage-M6fvR5Wz.js.gz +0 -0
  287. package/dist/dashboard/assets/UsagePage-nyeuRqz9.js.gz +0 -0
  288. package/dist/dashboard/assets/api-keys-BFOlvrJC.js.gz +0 -0
  289. package/dist/dashboard/assets/app-Dx2QgsNj.css +0 -2
  290. package/dist/dashboard/assets/app-Dx2QgsNj.css.gz +0 -0
  291. package/dist/dashboard/assets/assert-CqTLw5e7.js.gz +0 -0
  292. package/dist/dashboard/assets/badge-C83EqLB0.js.gz +0 -0
  293. package/dist/dashboard/assets/banner-D1xn7pIe.js.gz +0 -0
  294. package/dist/dashboard/assets/card-DU3Lq5Lm.js.gz +0 -0
  295. package/dist/dashboard/assets/cli-tools-Dw1U_drK.js.gz +0 -0
  296. package/dist/dashboard/assets/clipboard-button-CEL5Sg_J.js.gz +0 -0
  297. package/dist/dashboard/assets/dialog-BjFR5UHy.js.gz +0 -0
  298. package/dist/dashboard/assets/drawer-HvBW0AjI.js.gz +0 -0
  299. package/dist/dashboard/assets/entry-BSu3gFlt.js.gz +0 -0
  300. package/dist/dashboard/assets/entry-CECVELyy.js.gz +0 -0
  301. package/dist/dashboard/assets/entry-DYYofQ7W.js.gz +0 -0
  302. package/dist/dashboard/assets/formatters-DLW4i8zK.js.gz +0 -0
  303. package/dist/dashboard/assets/index-1-fCqe64.js.gz +0 -0
  304. package/dist/dashboard/assets/inline-DGvU2oLK.js.gz +0 -0
  305. package/dist/dashboard/assets/input-iNnO1X2K.js.gz +0 -0
  306. package/dist/dashboard/assets/layout-0q8UGypb.js.gz +0 -0
  307. package/dist/dashboard/assets/list-row-C0w2bQjJ.js.gz +0 -0
  308. package/dist/dashboard/assets/live-M5aJ_xCa.js.gz +0 -0
  309. package/dist/dashboard/assets/network-BKeQGT3K.js.gz +0 -0
  310. package/dist/dashboard/assets/numbers-CivAk3da.js.gz +0 -0
  311. package/dist/dashboard/assets/pagination-CpzvI5ep.js.gz +0 -0
  312. package/dist/dashboard/assets/routing-BFQX2VBc.js.gz +0 -0
  313. package/dist/dashboard/assets/select-CXbck0jG.js.gz +0 -0
  314. package/dist/dashboard/assets/settings-C_XvMHh9.js.gz +0 -0
  315. package/dist/dashboard/assets/stack-DggRiCxE.js.gz +0 -0
  316. package/dist/dashboard/assets/state-ClFzfbYp.js.gz +0 -0
  317. package/dist/dashboard/assets/switch-CTIFxKqS.js.gz +0 -0
  318. package/dist/dashboard/assets/useMutation-BClG3yWj.js.gz +0 -0
  319. package/src/console/providers/catalog/discover-constants.ts +0 -6
  320. package/src/network/pool-health.ts +0 -198
  321. package/src/providers/integrations/buddy/buddy-checkin.ts +0 -521
  322. package/src/providers/integrations/buddy/buddy-cli-headers.ts +0 -76
  323. package/src/providers/integrations/buddy/buddy-conversation-headers.ts +0 -130
  324. package/src/providers/integrations/buddy/buddy-discovery-shared.ts +0 -234
  325. package/src/providers/integrations/buddy/buddy-growth-shared.ts +0 -496
  326. package/src/providers/integrations/buddy/buddy-oauth-shared.ts +0 -341
  327. package/src/providers/integrations/buddy/buddy-quota-shared.ts +0 -417
  328. package/src/providers/integrations/buddy/buddy-server-tools.ts +0 -240
  329. package/src/providers/integrations/buddy/buddy-usage-shared.ts +0 -221
  330. package/src/providers/integrations/buddy/buddy-usage-store.ts +0 -181
  331. package/src/providers/integrations/buddy/codebuddy/cn-catalog.ts +0 -37
  332. package/src/providers/integrations/buddy/codebuddy/cn-provider.ts +0 -188
  333. package/src/providers/integrations/buddy/codebuddy/oauth.ts +0 -47
  334. package/src/providers/integrations/buddy/codebuddy/provider.ts +0 -179
  335. package/src/providers/integrations/buddy/codebuddy/quota.ts +0 -154
  336. package/src/providers/integrations/qoder/chat-proto.ts +0 -328
  337. package/src/providers/integrations/qoder/qoder-grpc.ts +0 -870
  338. package/src/providers/integrations/qoder/qoder-ide.ts +0 -481
  339. /package/dist/dashboard/assets/{app-DIXLjojg.js → app-C0gTXEoN.js} +0 -0
  340. /package/dist/dashboard/assets/{app-DIXLjojg.js.gz → app-C0gTXEoN.js.gz} +0 -0
  341. /package/src/network/{http2-bidi.ts → bidi.ts} +0 -0
  342. /package/src/network/pool/{byte-accounting.ts → accounting.ts} +0 -0
  343. /package/src/network/pool/{pool-scripts.ts → scripts.ts} +0 -0
  344. /package/src/network/pool/{pool-state.ts → state.ts} +0 -0
  345. /package/src/network/{backoff.ts → util/backoff.ts} +0 -0
  346. /package/src/network/{deduplication.ts → util/dedupe.ts} +0 -0
  347. /package/src/network/{ip-utils.ts → util/ip.ts} +0 -0
  348. /package/src/network/{rate-limit-verdict.ts → verdict.ts} +0 -0
@@ -0,0 +1,8 @@
1
+ import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{i}from"./terminal-0_IjPWTk.js";import{t as a}from"./arrow-left-CpBxkoxI.js";import{n as o,t as s}from"./brain-Cwed_72z.js";import{n as c,t as l}from"./fingerprint-pattern-BWuHtbW4.js";import{D as u,E as d,S as f,T as p,a as m,c as h,g,k as _,l as v,m as y,w as b,y as x}from"./numbers-Dw6kiew-.js";import{t as S}from"./circle-alert-CntYHV5v.js";import{t as C}from"./circle-check-BU3v_mFW.js";import{t as w}from"./circle-question-mark-Cz4un8sH.js";import{h as T,l as E,m as D}from"./formatters-BS3DZlZj.js";import{t as O}from"./eye-off-Bk5g2luF.js";import{t as k}from"./eye-C_hawfH4.js";import{t as A}from"./gauge-BbIMy7MB.js";import{t as ee}from"./image-BPaouViG.js";import{n as j,r as M,t as te}from"./state-CArX_Iak.js";import{t as N}from"./key-round-UkavsGxp.js";import{t as ne}from"./layers-2-glBbjl.js";import{r as re}from"./use-modal-focus-By7oJoGd.js";import{r as P,t as F}from"./dialog-DL0Zftwv.js";import{t as ie}from"./pencil-768ysRAr.js";import{t as I}from"./plus-DIdX_g-x.js";import{t as ae}from"./power-off-Yjw9GMJh.js";import{t as L}from"./refresh-cw-BqJFk4sU.js";import{t as oe}from"./rotate-ccw-CufcqITi.js";import{t as se}from"./search-JOKus9rb.js";import{t as R}from"./settings-2-Ds9DQp0t.js";import{t as ce}from"./trash-Cppn5c3R.js";import{t as z}from"./wrench-B6E1oEuY.js";import{E as le,w as ue,y as de}from"./assert-BMcj1xZE.js";import{i as fe,l as B,o as pe,t as V}from"./query-keys-IKLh0YFd.js";import{A as me,D as he,E as ge,F as _e,G as ve,M as ye,N as be,O as xe,P as Se,S as Ce,T as we,_ as Te,b as Ee,ct as De,d as Oe,f as ke,g as Ae,gt as je,h as Me,ht as Ne,i as Pe,k as Fe,l as H,m as Ie,o as Le,ot as Re,p as ze,r as Be,s as Ve,st as He,u as Ue,v as We,x as Ge,y as Ke}from"./entry-DScKYvZj.js";import{n as U,r as qe,t as W}from"./card-Bto5UlL9.js";import{n as G}from"./download-dRFo5_Wu.js";import{f as Je,i as Ye,l as K,n as Xe,r as Ze,s as Qe,u as $e}from"./tokens-COzario9.js";import{t as et}from"./switch-DwlwmDO-.js";import{t as q}from"./badge-DkRUuVfz.js";import{n as J}from"./input-Bfx0EzRc.js";import{t as Y}from"./select-oO1FxMVb.js";import{t as tt}from"./ProviderIcon-Ddhm1InL.js";import{t as X}from"./stack-Y3pDteZr.js";import{n as Z,t as nt}from"./inline-Dl-cuLK0.js";import{c as rt,n as it}from"./api-keys-2hc12Uz2.js";import{a as at,d as ot,s as st,u as ct}from"./quota-DiPD6UKH.js";import{t as lt}from"./settings-CLr3kdIx.js";import{t as ut}from"./banner-CDjW841Q.js";import{c as dt,l as ft,m as pt}from"./routing-8jZr-3WE.js";import{t as mt}from"./list-row-D49Y4ptn.js";import{d as ht,l as gt,u as _t,y as vt}from"./network-JGvDveof.js";import{a as yt,c as bt,d as xt,l as St,o as Ct,t as wt}from"./HealthEventsModal-Clq8E9cW.js";import{r as Tt}from"./privacy-mode-GM8bej85.js";import{t as Et}from"./use-timeout-BwcBBRrT.js";var Dt=e(`cable`,[[`path`,{d:`M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z`,key:`trhst0`}],[`path`,{d:`M17 21v-2`,key:`ds4u3f`}],[`path`,{d:`M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10`,key:`1mo9zo`}],[`path`,{d:`M21 21v-2`,key:`eo0ou`}],[`path`,{d:`M3 5V3`,key:`1k5hjh`}],[`path`,{d:`M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z`,key:`1dd30t`}],[`path`,{d:`M7 5V3`,key:`1t1388`}]]),Ot=e(`gift`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8`,key:`1sqzm4`}],[`path`,{d:`M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5`,key:`kc0143`}],[`rect`,{x:`3`,y:`7`,width:`18`,height:`4`,rx:`1`,key:`1hberx`}]]),kt=e(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),At=e(`lock-open`,[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`,key:`1mm8w8`}]]),jt=e(`package-x`,[[`path`,{d:`M12 22V12`,key:`d0xqtd`}],[`path`,{d:`m16.5 14.5 5 5`,key:`ozpm51`}],[`path`,{d:`m16.5 19.5 5-5`,key:`syf6b9`}],[`path`,{d:`M21 10.5V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.729l7 4a2 2 0 0 0 2 .001l.13-.074`,key:`isw6gs`}],[`path`,{d:`M3.29 7 12 12l8.71-5`,key:`19ckod`}],[`path`,{d:`m7.5 4.27 8.997 5.148`,key:`9yrvtv`}]]),Mt=e(`repeat`,[[`path`,{d:`m17 2 4 4-4 4`,key:`nntrym`}],[`path`,{d:`M3 11v-1a4 4 0 0 1 4-4h14`,key:`84bu3i`}],[`path`,{d:`m7 22-4-4 4-4`,key:`1wqhfi`}],[`path`,{d:`M21 13v1a4 4 0 0 1-4 4H3`,key:`1rx37r`}]]),Nt=e(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),Pt=e(`shuffle`,[[`path`,{d:`m18 14 4 4-4 4`,key:`10pe0f`}],[`path`,{d:`m18 2 4 4-4 4`,key:`pucp1d`}],[`path`,{d:`M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22`,key:`1ailkh`}],[`path`,{d:`M2 6h1.972a4 4 0 0 1 3.6 2.2`,key:`km57vx`}],[`path`,{d:`M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45`,key:`os18l9`}]]),Ft=e(`video`,[[`path`,{d:`m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5`,key:`ftymec`}],[`rect`,{x:`2`,y:`6`,width:`14`,height:`12`,rx:`2`,key:`158x01`}]]),It=e(`waypoints`,[[`path`,{d:`m10.586 5.414-5.172 5.172`,key:`4mc350`}],[`path`,{d:`m18.586 13.414-5.172 5.172`,key:`8c96vv`}],[`path`,{d:`M6 12h12`,key:`8npq4p`}],[`circle`,{cx:`12`,cy:`20`,r:`2`,key:`144qzu`}],[`circle`,{cx:`12`,cy:`4`,r:`2`,key:`muu5ef`}],[`circle`,{cx:`20`,cy:`12`,r:`2`,key:`1xzzfp`}],[`circle`,{cx:`4`,cy:`12`,r:`2`,key:`1hvhnz`}]]),Lt=[`auto`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Rt(e,t){return t===null?e:`${e}(${t})`}var Q=t(n(),1),$=r();function zt({to:e,label:t}){let n=Re();return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{window.history.length>1?n(-1):n(e)},className:`inline-flex items-center gap-3 text-accent text-caption bg-transparent border-0 p-0 cursor-pointer`,children:[(0,$.jsx)(a,{size:14,"aria-hidden":`true`}),t]})}function Bt({title:e,description:t,icon:n,badges:r,actions:i,back:a}){return(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[a?(0,$.jsx)(zt,{...a}):null,(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 flex-wrap`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-5 min-w-0`,children:[n?(0,$.jsx)(`div`,{className:`card-header-icon`,children:n}):null,(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,$.jsx)(`h1`,{className:`text-lead font-bold`,children:e}),r]}),t?(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:t}):null]})]}),i?(0,$.jsx)(`div`,{className:y(`flex items-center gap-4 flex-wrap min-w-0 max-w-full`),children:i}):null]})]})}function Vt(e){return e.requiresAccount&&e.oauthFlows===void 0&&!e.hasAdapterUserAgent}function Ht(e,t=600){let n=(0,Q.useRef)(void 0);return(0,Q.useEffect)(()=>()=>clearTimeout(n.current),[]),r=>{clearTimeout(n.current),n.current=setTimeout(()=>e(r),t)}}var Ut={fallback:`Failover`,roundRobin:`Round robin`},Wt=new Set([`inferhub`,`cline`]);function Gt(e,t){let n=ft(e),r=pt(),[i,a]=(0,Q.useState)(`fallback`),[o,s]=(0,Q.useState)(1),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(`percent`),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(`random`),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{n.data&&(a(n.data.strategy),s(n.data.rotateCount),l(n.data.maxInflight),d(n.data.maxInflightPerProxy??null),p(n.data.usageFloor),h(n.data.usageFloorUnit),_(n.data.skipProxy),y(n.data.deviceFlowProxy??`random`),x(n.data.userAgent),C(n.data.customUserAgent??null))},[n.data]);let w=i=>{r.mutate({providerId:e,request:{enabled:!0,strategy:i.strategy,rotateCount:i.rotateCount,maxInflight:i.maxInflight,maxInflightPerProxy:i.maxInflightPerProxy,usageFloor:i.usageFloor,usageFloorUnit:i.usageFloorUnit,skipProxy:i.skipProxy,deviceFlowProxy:i.deviceFlowProxy,...t?{userAgent:i.userAgent}:{},customUserAgent:i.customUserAgent}},{onError:()=>{n.data&&(a(n.data.strategy),s(n.data.rotateCount),l(n.data.maxInflight),d(n.data.maxInflightPerProxy??null),p(n.data.usageFloor),h(n.data.usageFloorUnit),_(n.data.skipProxy),y(n.data.deviceFlowProxy??`random`),x(n.data.userAgent),C(n.data.customUserAgent??null))}})},T=Ht(e=>w({strategy:i,rotateCount:o,maxInflight:e,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:v,userAgent:b,customUserAgent:S})),E=Ht(e=>w({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:e,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:v,userAgent:b,customUserAgent:S})),D=Ht(e=>w({strategy:i,rotateCount:e,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:v,userAgent:b,customUserAgent:S})),O=Ht(e=>w({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:v,userAgent:e,customUserAgent:S})),k=Ht(e=>w({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:v,userAgent:b,customUserAgent:e}));return{strategy:i,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,setUsageFloor:(e,t)=>{p(e),h(t),w({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:e,usageFloorUnit:t,skipProxy:g,deviceFlowProxy:v,userAgent:b,customUserAgent:S})},skipProxy:g,deviceFlowProxy:v,setDeviceFlowProxy:e=>{y(e),w({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:e,userAgent:b,customUserAgent:S})},userAgent:b,customUserAgent:S,isLoading:n.isPending,isError:n.isError,isSaving:r.isPending,saveFailed:r.isError,refetch:()=>n.refetch(),setMaxInflight:e=>{l(e),T(e)},setMaxInflightPerProxy:e=>{d(e),E(e)},setUserAgent:e=>{x(e),O(e)},setCustomUserAgent:e=>{C(e),k(e)},setSkipProxy:e=>{_(e),w({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:e,deviceFlowProxy:v,userAgent:b,customUserAgent:S})},roundRobinEnabled:i===`round_robin`,setRoundRobinEnabled:e=>{let t=e?`round_robin`:`fallback`;a(t),w({strategy:t,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,deviceFlowProxy:v,userAgent:b,customUserAgent:S})},rotateCount:o,setRotateCount:e=>{s(e),D(e)}}}var Kt=[{value:`least_loaded`,label:`Least loaded`},{value:`round_robin`,label:`Round robin`},{value:`random`,label:`Random`}],qt=[{value:`random`,label:`Random pool (rotate IP)`},{value:`direct`,label:`Direct egress`}],Jt=50,Yt=100;function Xt({children:e,action:t}){return(0,$.jsx)(mt,{actions:t,children:e})}function Zt({providerId:e,clientVersion:t,userAgentEditable:n}){let r=Gt(e,n),i=ht(),a=vt(),[o,s]=(0,Q.useState)(!1),[c,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null);(0,Q.useEffect)(()=>m(null),[e]);let g=Wt.has(e);if(r.isLoading)return(0,$.jsx)(M,{label:`Loading routing...`});if(r.isError)return(0,$.jsx)(j,{message:`Failed to load routing`,onRetry:r.refetch});let _=r.roundRobinEnabled?`${Ut.roundRobin} · ${r.rotateCount} account${r.rotateCount===1?``:`s`} per rotation`:Ut.fallback,v=i.data,b=Kt.find(e=>e.value===v?.strategy),x=v===void 0?`…`:r.skipProxy?`Direct — proxy pools bypassed`:b?v.strategy===`round_robin`?`${b.label} · ${v.rotateCount} per rotation`:b.label:`Unset`,S=r.isSaving?`Saving...`:r.saveFailed?`Save failed — reverted to last saved value`:`Per-account and per-pool routing`,C=r.maxInflight===null,w=C?51:Math.min(51,Math.max(1,r.maxInflight)),T=C?`∞`:String(r.maxInflight),E=r.maxInflightPerProxy===null,D=E?51:Math.min(51,Math.max(1,r.maxInflightPerProxy)),O=E?`∞`:String(r.maxInflightPerProxy),k=r.skipProxy,ee=r.customUserAgent!==null||p!==null?`custom`:`default`,te=e=>{if(e==="default"){m(null),r.setCustomUserAgent(null);return}m(r.customUserAgent??``)},N=e=>{let t=e.trim();if(t===``){m(null),r.setCustomUserAgent(null);return}m(e),r.setCustomUserAgent(t)},re=e=>{r.setRotateCount(Math.min(1e3,Math.max(1,r.rotateCount+e)))},ie=e=>{e!==v?.strategy&&a.mutate({strategy:e})},ae=e=>{v&&a.mutate({rotateCount:Math.min(1e3,Math.max(1,v.rotateCount+e))})},L=t?`${t.client} ${t.version}`:`Provider default`;return(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`Routing Strategy`,subtitle:S,icon:(0,$.jsx)(ne,{size:16})}),(0,$.jsx)(U,{children:(0,$.jsxs)(`div`,{className:`grid gap-5 w-full min-w-0`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4 border-b border-inner-border pb-3`,children:[(0,$.jsx)(`span`,{className:`text-micro font-bold uppercase tracking-label text-text-tertiary`,children:`Provider accounts`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-badge text-text-secondary`,children:[(0,$.jsx)(`span`,{className:`status-indicator-dot${r.roundRobinEnabled?` bg-accent`:` bg-text-tertiary`}`,"aria-hidden":`true`}),_]})]}),(0,$.jsx)(Xt,{action:(0,$.jsxs)($.Fragment,{children:[r.roundRobinEnabled?(0,$.jsxs)(`div`,{role:`group`,"aria-label":`Accounts per rotation`,className:`inline-flex items-center gap-1 rounded-control border border-inner-border bg-surface-1 p-1`,children:[(0,$.jsx)(`span`,{className:`px-2 text-badge text-text-secondary`,children:`Accounts/rotation`}),(0,$.jsx)(h,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Decrease accounts per rotation`,disabled:r.rotateCount<=1,icon:(0,$.jsx)(P,{size:14}),onClick:()=>re(-1)}),(0,$.jsx)(`output`,{className:`min-w-8 text-center text-body font-semibold tabular-nums`,"aria-live":`polite`,children:r.rotateCount}),(0,$.jsx)(h,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Increase accounts per rotation`,disabled:r.rotateCount>=1e3,icon:(0,$.jsx)(I,{size:14}),onClick:()=>re(1)})]}):null,(0,$.jsx)(et,{checked:r.roundRobinEnabled,onChange:r.setRoundRobinEnabled,id:`routing-round-robin`})]}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-round-robin`,children:(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(Mt,{size:15,"aria-hidden":`true`,className:`shrink-0 ${r.roundRobinEnabled?`text-accent`:`text-text-tertiary`}`}),`Rotate accounts`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Off uses priority order with failover. On rotates requests across this provider's accounts.`})]})}),(0,$.jsx)(Xt,{action:(0,$.jsx)(et,{checked:r.skipProxy,onChange:r.setSkipProxy,id:`routing-skip-proxy`}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-skip-proxy`,children:(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(Dt,{size:15,"aria-hidden":`true`,className:`shrink-0 ${r.skipProxy?`text-accent`:`text-text-tertiary`}`}),`Always direct`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Bypass automatic proxy-pool routing for this provider and always dial direct`})]})}),(0,$.jsx)(Xt,{action:(0,$.jsx)(Y,{id:`routing-device-flow-proxy`,"aria-label":`Device login egress`,value:r.deviceFlowProxy,disabled:r.isSaving,options:qt,onValueChange:e=>{(e===`random`||e===`direct`)&&r.setDeviceFlowProxy(e)}}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-device-flow-proxy`,children:(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(l,{size:15,"aria-hidden":`true`,className:`shrink-0 ${r.deviceFlowProxy===`random`?`text-accent`:`text-text-tertiary`}`}),`Device login egress`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Device-code OAuth (start + poll) uses a random active pool by default so the upstream sees a rotating IP. Choose direct egress for one stable address.`})]})})]}),(0,$.jsxs)(`div`,{className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4 border-b border-inner-border pb-3`,children:[(0,$.jsx)(`span`,{className:`text-micro font-bold uppercase tracking-label text-text-tertiary`,children:`Proxy pools`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-badge text-text-secondary`,children:[(0,$.jsx)(`span`,{className:`status-indicator-dot${r.skipProxy?` bg-text-tertiary`:` bg-accent`}`,"aria-hidden":`true`}),x]}),(0,$.jsx)(h,{variant:`ghost`,size:`sm`,className:`shrink-0 -my-1`,"aria-label":`How pool routing works`,onClick:()=>u(!0),children:`How it works`})]}),(0,$.jsx)(Xt,{action:(0,$.jsxs)(Z,{gap:`8px`,align:`center`,children:[v?.strategy===`round_robin`&&!r.skipProxy?(0,$.jsxs)(`div`,{role:`group`,"aria-label":`Pools per rotation`,className:`inline-flex items-center gap-1 rounded-control border border-inner-border bg-surface-1 p-1`,children:[(0,$.jsx)(`span`,{className:`px-2 text-badge text-text-secondary`,children:`Pools/rotation`}),(0,$.jsx)(h,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Decrease pools per rotation`,disabled:a.isPending||v.rotateCount<=1,icon:(0,$.jsx)(P,{size:14}),onClick:()=>ae(-1)}),(0,$.jsx)(`output`,{className:`min-w-8 text-center text-body font-semibold tabular-nums`,"aria-live":`polite`,children:v.rotateCount}),(0,$.jsx)(h,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Increase pools per rotation`,disabled:a.isPending||v.rotateCount>=1e3,icon:(0,$.jsx)(I,{size:14}),onClick:()=>ae(1)})]}):null,(0,$.jsx)(Y,{id:`routing-pool-strategy`,"aria-label":`Pool selection mode`,value:v?.strategy??``,disabled:r.skipProxy||a.isPending,options:Kt,onValueChange:ie})]}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-pool-strategy`,children:(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(Pt,{size:15,"aria-hidden":`true`,className:`shrink-0 ${r.skipProxy?`text-text-tertiary`:`text-accent`}`}),`Pool mode`]})}),(0,$.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`How proxy pools are chosen when this provider dials one.`,r.skipProxy?` Disabled while “Always direct” is on.`:``]})]})})]}),(0,$.jsxs)(`div`,{className:`routing-controls-grid grid gap-5 min-w-0 w-full`,children:[(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold mb-3`,children:[(0,$.jsx)(l,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Client identity`]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(Y,{id:`routing-client-identity`,"aria-label":`Client identity`,value:ee,disabled:!n,options:[{value:`default`,label:`Provider default (unchanged)`},{value:`custom`,label:`Custom`,disabled:!n}],onValueChange:te}),ee===`custom`&&n?(0,$.jsx)(J,{id:`routing-user-agent-custom`,"aria-label":`Custom User-Agent override`,value:p??r.customUserAgent??``,placeholder:`User-Agent for a compatible client`,spellCheck:!1,onChange:e=>N(e.target.value)}):(0,$.jsxs)(`div`,{className:`text-micro text-text-tertiary`,children:[`Provider identity is left unchanged: `,(0,$.jsx)(`code`,{className:`font-mono`,children:L})]}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-1`,children:n?ee===`custom`?`Enter a User-Agent manually for a compatible client. Clear the field to restore the provider default.`:`Uses the provider's native identity without modification.`:`This provider manages its own client identity; custom overrides are unavailable.`})]})]}),(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-max-inflight`,className:`form-label`,children:(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(A,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / account`]})}),(0,$.jsxs)(`div`,{className:`text-badge text-text-tertiary mb-3`,children:[`Per-account ceiling, not a provider-wide one: each account enforces its own limit, so a full account spills to the next. One step past `,Jt,` is unlimited.`]}),(0,$.jsxs)(Z,{gap:`10px`,className:`mt-3`,children:[(0,$.jsx)(`input`,{id:`routing-max-inflight`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":C?`true`:void 0,min:1,max:51,step:1,value:w,"aria-valuetext":C?`Unlimited`:String(r.maxInflight),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&r.setMaxInflight(t>Jt?null:Math.round(t))},style:{"--slider-pct":`${w/51*100}%`}}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per account`,value:T,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){r.setMaxInflight(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&r.setMaxInflight(Math.min(Yt,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${C?`text-status-success`:``}`})]})]})]}),(0,$.jsxs)(`div`,{className:`rounded-control border border-inner-border bg-surface-2`,children:[(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":d,"aria-label":d?`Collapse Advanced`:`Expand Advanced`,onClick:()=>f(e=>!e),className:`flex w-full items-center gap-2 border-0 bg-transparent px-4 py-3 text-left text-inherit`,children:[(0,$.jsx)(je,{size:15,"aria-hidden":`true`,className:y(`shrink-0 transition-transform`,!d&&`-rotate-90`)}),(0,$.jsx)(R,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Advanced`}),(0,$.jsx)(`span`,{className:`ml-auto text-micro text-text-tertiary`,children:`Max inflight / proxy`})]}),d?(0,$.jsx)(`div`,{className:`px-4 pb-4`,children:(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`label`,{htmlFor:`routing-max-inflight-per-proxy`,className:`min-w-0`,children:[(0,$.jsxs)(Z,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(It,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / proxy`]}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Each proxy pool carries at most this many concurrent requests for this provider. Other providers on the same pool are unaffected.`})]}),(0,$.jsx)(h,{variant:`ghost`,size:`sm`,className:`shrink-0`,"aria-label":`How per-proxy limits work`,onClick:()=>s(!0),children:`How it works`})]}),(0,$.jsxs)(Z,{gap:`10px`,className:`mt-3`,children:[(0,$.jsx)(`input`,{id:`routing-max-inflight-per-proxy`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":E?`true`:void 0,min:1,max:51,step:1,disabled:k,value:D,"aria-valuetext":E?`Unlimited`:String(r.maxInflightPerProxy),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&r.setMaxInflightPerProxy(t>Jt?null:Math.round(t))},style:{"--slider-pct":`${D/51*100}%`}}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per proxy`,disabled:k,value:O,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){r.setMaxInflightPerProxy(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&r.setMaxInflightPerProxy(Math.min(Yt,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${E?`text-status-success`:``}`})]}),(0,$.jsx)(`div`,{className:`mt-2 text-badge text-text-tertiary`,children:k?`Always direct is on, so this provider never dials a pool. The limit is kept for when a pool is used again.`:`One step past ${Jt} is unlimited.`})]})}):null]}),(0,$.jsx)(F,{open:o,onClose:()=>s(!1),title:`How concurrency limits stack`,size:`md`,children:(0,$.jsxs)(`div`,{className:`grid gap-4 text-body`,children:[(0,$.jsx)(`p`,{className:`text-text-secondary`,children:`Three limits apply at once. Each one bounds a different thing; none replaces another.`}),(0,$.jsxs)(`dl`,{className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / account`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`One account of this provider, across every proxy. Set here, above.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / proxy`}),(0,$.jsxs)(`dd`,{className:`text-badge text-text-tertiary`,children:[`One proxy pool's concurrent requests `,(0,$.jsx)(`em`,{children:`for this provider`}),`. The same number applies to every pool; each pool counts separately. This is the field above.`]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Pool capacity`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`Everything through one pool, all providers combined. Set on the proxy itself, on the Proxies page.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`API key concurrency`}),(0,$.jsxs)(`dd`,{className:`text-badge text-text-tertiary`,children:[`The key's `,(0,$.jsx)(`em`,{children:`own`}),` limit (`,` `,(0,$.jsx)(`code`,{children:`max_concurrent`}),`, set on the key), which counts every request this key sends across all providers. It is separate from the two limits above: raising this provider's max-inflight does not raise the key's ceiling, and a rejection message that says “This API key is already serving its maximum number of concurrent requests” refers to this number, not to any setting here.`]})]})]}),(0,$.jsxs)(`p`,{className:`text-badge text-text-tertiary`,children:[`A request must clear all three. When a pool is full for this provider, the request moves to another pool that still has room; it only fails with`,` `,(0,$.jsx)(`code`,{children:`429`}),` when every pool is full.`]}),(0,$.jsx)(`p`,{className:`text-badge text-text-tertiary`,children:`Unlimited means no counter is kept for this provider, so the limit costs nothing until you set one.`})]})}),(0,$.jsx)(F,{open:c,onClose:()=>u(!1),title:`How pool routing works`,size:`md`,children:(0,$.jsxs)(`div`,{className:`grid gap-4 text-body`,children:[(0,$.jsx)(`p`,{className:`text-text-secondary`,children:`When a provider dials a proxy pool, the gateway picks the pool with one of three modes. All modes skip pools that are cooling down, full, or disabled — the pool's own gates always apply.`}),(0,$.jsxs)(`dl`,{className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Least loaded`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`Each request goes to the pool with the most headroom (weighted). The default — spreads load and prefers the fastest-available egress.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Round robin`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`Requests rotate across pools in a fixed order, with a set number of successful requests per pool before moving on. Useful for even request counts across pools.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Random`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`Each request picks from the eligible pools at random, so a burst does not gang up on the first pools in the order.`})]})]}),(0,$.jsx)(`p`,{className:`text-badge text-text-tertiary`,children:`Turning on “Always direct” bypasses pools entirely — this mode has no effect then.`})]})}),g&&(0,$.jsxs)(Z,{gap:`6px`,align:`flex-start`,className:`mt-1 text-badge text-text-tertiary`,children:[(0,$.jsx)(kt,{size:12,className:`shrink-0 mt-0.5`}),(0,$.jsx)(`span`,{children:`This provider doesn't reliably work through a plain HTTP/S proxy — use a SOCKS5 or proxy pool instead if you need to route it.`})]})]})})]})}function Qt(e){if(typeof e!=`object`||!e)throw{status:500,code:`invalid_response`,message:`Invalid InferHub summary`};let t=e;return{models:Array.isArray(t.models)?t.models:[],providers:Array.isArray(t.providers)?t.providers:[],pricingConfig:t.pricingConfig??null,meta:t.meta??{fetchedAt:0,ageSeconds:0,stale:!0},error:t.error??null}}function $t(e=!0){return ue({queryKey:V.inferhub.summary,queryFn:e=>pe(`/inferhub/summary`,{signal:de(e)}).then(Qt),enabled:e,...fe,staleTime:6e4})}function en(e){return e===null?`—`:`$${e.toFixed(4)}`}function tn(e){return e===null?`—`:`${e}%`}function nn(e){return e<60?`${e}s ago`:e<3600?`${Math.floor(e/60)}m ago`:`${Math.floor(e/3600)}h ago`}var rn={provider:`Provider (A–Z)`,availability:`Highest availability`,sustainable:`Sustainable price`,price:`Lowest price`,discount:`Biggest discount`};function an(e,t){return(n,r)=>{let i=e(n),a=e(r);return i===null&&a===null?0:i===null?1:a===null?-1:t===`asc`?i-a:a-i}}function on(e){switch(e){case`provider`:return(e,t)=>e.family.localeCompare(t.family,void 0,{sensitivity:`base`})||e.prefix.localeCompare(t.prefix);case`availability`:return(e,t)=>t.providersLive-e.providersLive||an(e=>e.health.successRatePct,`desc`)(e,t);case`sustainable`:return an(e=>e.capacityPriceIn,`asc`);case`price`:return an(e=>e.minAskIn,`asc`);case`discount`:return an(e=>e.tiersIn[0]?.discountPct??null,`desc`)}}function sn(e){return e===`operational`?`ok`:e===`degraded`?`warn`:e===`major_outage`?`err`:`default`}function cn(e,t){return e.providers.find(e=>e.prefix===t)}function ln(e){return e.providersLive>0&&e.routable&&e.minAskIn!==null}function un(){let e=$t(),t=e.data,[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!0),[c,l]=(0,Q.useState)(`provider`),[u,d]=(0,Q.useState)(!1),f=t?.models??[],p=f.filter(ln),m=(0,Q.useMemo)(()=>{let e=[...i?f:p].sort(on(c)),t=new Map;for(let n of e){let e=t.get(n.prefix);e===void 0?t.set(n.prefix,[n]):e.push(n)}return[...t.entries()].map(([e,t])=>({prefix:e,family:t[0]?.family??e,models:t}))},[f,p,i,c]),g=(0,$.jsxs)(h,{variant:`secondary`,size:`sm`,onClick:()=>void e.refetch(),disabled:e.isFetching,title:`Re-read InferHub market data now`,children:[(0,$.jsx)(L,{size:14}),e.isFetching?`Refreshing…`:`Refresh`]});if(t===void 0&&!e.isError)return(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`InferHub market`,subtitle:e.isPending?`Reading market data…`:void 0,icon:(0,$.jsx)(L,{size:16})}),(0,$.jsx)(U,{children:e.isError?(0,$.jsx)(ut,{tone:`danger`,surface:`raised`,live:`none`,children:`InferHub market data could not be read.`}):null})]});if(t===void 0)return(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`InferHub market`,icon:(0,$.jsx)(L,{size:16}),action:g}),(0,$.jsx)(U,{children:(0,$.jsx)(ut,{tone:`danger`,surface:`raised`,live:`none`,children:`InferHub market data could not be read.`})})]});let _=m,v=_.reduce((e,t)=>e+t.models.length,0),b=f.length-v;return(0,$.jsxs)(W,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-3`,children:[(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":n,"aria-label":n?`Collapse InferHub market`:`Expand InferHub market`,onClick:()=>r(e=>!e),className:`flex min-w-0 flex-1 items-center gap-3 border-0 bg-transparent p-0 text-left text-inherit`,children:[(0,$.jsx)(je,{size:15,"aria-hidden":`true`,className:y(`shrink-0 transition-transform`,!n&&`-rotate-90`)}),(0,$.jsxs)(X,{gap:`1px`,children:[(0,$.jsx)(`h2`,{className:`text-body font-bold`,children:`InferHub market`}),t.meta.fetchedAt>0?(0,$.jsxs)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Updated `,nn(t.meta.ageSeconds)]}):null]})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:n?g:null})]}),n?(0,$.jsxs)(U,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,$.jsx)(fn,{onSaved:()=>void e.refetch()}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-caption text-text-secondary`,children:[`Sort`,(0,$.jsx)(Y,{value:c,onValueChange:e=>l(e),options:Object.keys(rn).map(e=>({value:e,label:rn[e]})),"aria-label":`Sort InferHub models`})]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-caption text-text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked),className:`cursor-pointer`}),`Show availability`]})]})]}),t.error===`no_config_key`?(0,$.jsxs)(ut,{tone:`warning`,surface:`raised`,live:`none`,children:[`No InferHub `,(0,$.jsx)(`code`,{children:`config_read`}),` key is configured, so the marketplace catalog cannot be read. Add one above.`]}):null,t.error===`upstream_unavailable`?(0,$.jsxs)(ut,{tone:`warning`,surface:`raised`,live:`none`,children:[`InferHub did not answer. Showing the last snapshot that was read`,t.meta.fetchedAt>0?` (${nn(t.meta.ageSeconds)})`:``,`.`]}):null,t.meta.stale&&t.error===null?(0,$.jsxs)(ut,{tone:`warning`,surface:`raised`,live:`none`,children:[`This snapshot is `,nn(t.meta.ageSeconds),` — press Refresh for current prices.`]}):null,(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsxs)(`p`,{className:`text-micro text-text-tertiary`,children:[v,` of `,f.length,` models`]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(h,{size:`sm`,variant:`secondary`,onClick:()=>d(e=>!e),title:u?`Expand all provider groups`:`Collapse all provider groups`,children:u?`Expand all`:`Collapse all`}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-caption text-text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked),className:`cursor-pointer`}),`Show all`,b>0?(0,$.jsxs)(`span`,{className:`text-micro text-text-tertiary`,children:[`(includes `,b,` hidden)`]}):null]})]})]}),_.length===0?(0,$.jsx)(`p`,{className:`mt-3 text-caption text-text-secondary`,children:`No models to show.`}):(0,$.jsx)(`div`,{className:`mt-3 flex flex-col gap-3`,children:_.map(e=>(0,$.jsx)(dn,{group:e,showUpstreams:o,summary:t,collapsedAll:u},e.prefix))})]}):null]})}function dn({group:e,showUpstreams:t,summary:n,collapsedAll:r}){let[i,a]=(0,Q.useState)(!0),o=!r&&i,s=cn(n,e.prefix),c=s?.familyState??null,l=e.models.find(e=>e.systemPromptNote!==null)?.systemPromptNote??null;return(0,$.jsxs)(`div`,{className:`rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":o,"aria-label":`${o?`Collapse`:`Expand`} ${e.family} models`,onClick:()=>a(e=>!e),className:`flex w-full items-center gap-2 border-0 bg-transparent px-3 py-2 text-left text-inherit`,children:[(0,$.jsx)(je,{size:14,"aria-hidden":`true`,className:y(`shrink-0 transition-transform`,!o&&`-rotate-90`)}),(0,$.jsx)(`span`,{className:`text-caption font-bold`,children:e.family}),(0,$.jsxs)(`span`,{className:`font-mono text-micro text-text-tertiary`,children:[e.prefix,`/`]}),c===null?null:(0,$.jsx)(q,{tone:sn(c),dot:!0,children:c.replace(/_/g,` `)}),t&&s!==void 0?(0,$.jsxs)(`span`,{className:`text-micro text-text-tertiary tabular-nums`,children:[`24h `,tn(s.availability24hPct),` · 7d`,` `,tn(s.availability7dPct)]}):null,(0,$.jsxs)(`span`,{className:`ml-auto text-micro text-text-tertiary`,children:[e.models.length,` model`,e.models.length===1?``:`s`]})]}),o?(0,$.jsxs)(`div`,{className:`px-3 pb-3`,children:[l===null?null:(0,$.jsx)(`p`,{className:`mb-2 text-micro text-text-secondary`,children:l}),(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full text-caption`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`text-left text-text-secondary`,children:[(0,$.jsx)(`th`,{className:`py-1 pr-3`,children:`Model`}),(0,$.jsx)(`th`,{className:`py-1 pr-3`,children:`Input`}),(0,$.jsx)(`th`,{className:`py-1 pr-3`,children:`Output`}),(0,$.jsx)(`th`,{className:`py-1 pr-3`,children:`Discount`}),(0,$.jsx)(`th`,{className:`py-1 pr-3`,children:`Live`}),(0,$.jsx)(`th`,{className:`py-1 pr-3`,children:t?`24h`:`Success`})]})}),(0,$.jsx)(`tbody`,{children:e.models.map(e=>(0,$.jsxs)(`tr`,{className:`border-t border-inner-border`,children:[(0,$.jsx)(`td`,{className:`py-1 pr-3 font-mono`,children:e.id}),(0,$.jsxs)(`td`,{className:`py-1 pr-3 tabular-nums`,children:[en(e.minAskIn),e.capacityPriceIn!==null&&e.capacityPriceIn!==e.minAskIn?(0,$.jsxs)(`div`,{className:`text-micro text-text-secondary`,children:[en(e.capacityPriceIn),` sustainable`]}):null]}),(0,$.jsx)(`td`,{className:`py-1 pr-3 tabular-nums`,children:en(e.minAskOut)}),(0,$.jsx)(`td`,{className:`py-1 pr-3 tabular-nums`,children:e.tiersIn[0]?.discountPct===void 0||e.tiersIn[0]?.discountPct===null?`—`:`−${e.tiersIn[0].discountPct}%`}),(0,$.jsx)(`td`,{className:`py-1 pr-3 tabular-nums`,children:e.providersLive===0?(0,$.jsx)(q,{children:`none`}):e.providersLive}),(0,$.jsx)(`td`,{className:`py-1 pr-3 tabular-nums`,children:tn(t?s?.availability24hPct??null:e.health.successRatePct)})]},e.id))})]})})]}):null]})}function fn({onSaved:e}){let[t,n]=(0,Q.useState)(``),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=async()=>{if(t.trim().length!==0){o(!0),c(null);try{await pe(`/inferhub/key`,{method:`PUT`,body:JSON.stringify({key:t.trim()})}),n(``),i({configured:!0,last4:null}),e()}catch{c(`Could not save the key.`)}finally{o(!1)}}},u=async()=>{o(!0),c(null);try{await pe(`/inferhub/key`,{method:`DELETE`}),i({configured:!1,last4:null}),e()}catch{c(`Could not remove the key.`)}finally{o(!1)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end gap-2`,children:[(0,$.jsx)(`div`,{className:`min-w-64 flex-1`,children:(0,$.jsx)(J,{type:`password`,value:t,onChange:e=>n(e.target.value),placeholder:`sk-airo-… (config_read key)`,"aria-label":`InferHub config_read key`,autoComplete:`off`})}),(0,$.jsx)(h,{size:`sm`,onClick:()=>void l(),disabled:a||t.trim().length===0,children:a?`Saving…`:`Save key`}),r?.configured?(0,$.jsx)(h,{size:`sm`,variant:`secondary`,onClick:()=>void u(),disabled:a,children:`Remove`}):null]}),(0,$.jsxs)(`p`,{className:`text-micro text-text-tertiary`,children:[`Stored encrypted beside the market settings, never in this provider's accounts. Must be a`,` `,(0,$.jsx)(`code`,{children:`config_read`}),` key — never an inference key.`]}),(0,$.jsx)(`p`,{className:`text-micro text-text-tertiary`,children:(0,$.jsxs)(`a`,{href:`https://inferhub.dev/`,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1.5 text-accent hover:underline`,children:[(0,$.jsx)(Ne,{size:12,"aria-hidden":`true`}),`inferhub.dev — create a `,(0,$.jsx)(`code`,{children:`config_read`}),` key`]})}),s===null?null:(0,$.jsx)(ut,{tone:`danger`,surface:`raised`,live:`alert`,children:s})]})}function pn({providerId:e}){let t=Gt(e,!1),n=bt(),r=dt(e),[i,a]=(0,Q.useState)(!1),o=(0,Q.useMemo)(()=>hn(n.data?.accounts??[],e),[n.data,e]),s=(0,Q.useRef)(null),c=(0,Q.useMemo)(()=>[...r.data?.values()??[]].reduce((e,t)=>e+t,0),[r.data]);(0,Q.useEffect)(()=>{if(s.current===null){s.current=c;return}s.current!==c&&(s.current=c,n.refetch())},[c,n]);let[l,u]=(0,Q.useState)(`40`),[d,f]=(0,Q.useState)(`percent`),p=t.usageFloor!==null;(0,Q.useEffect)(()=>{t.usageFloor!==null&&u(String(t.usageFloor)),f(t.usageFloorUnit)},[t.usageFloor,t.usageFloorUnit]);let m=Number(l),g=Number.isInteger(m)&&m>=0&&m<=1e6,_=o===null||o.pooled&&o.remaining<=0?`text-status-danger`:o.percent<=10?`text-status-warning`:`text-status-success`,v=(e,n)=>{(e===null||g)&&t.setUsageFloor(e,n)};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`section`,{className:`usage-floor-panel flex flex-col gap-4 px-5 py-4 border border-inner-border rounded-narrow bg-surface-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,$.jsx)(A,{size:14}),(0,$.jsx)(`span`,{children:`Usage floor`}),(0,$.jsx)(`span`,{className:`badge border border-warning-line bg-surface-2 text-micro tracking-label text-status-warning`,children:`BETA`}),(0,$.jsx)(h,{variant:`ghost`,size:`sm`,icon:(0,$.jsx)(w,{size:14}),"aria-label":`How the usage floor works`,onClick:()=>a(!0),children:`How it works`})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-badge leading-normal text-text-tertiary`,children:`Per account. Skip an account once its remaining allowance reaches this, and send the request to the next one.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4`,children:[o!==null&&(0,$.jsxs)(`div`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`Pooled credits`}),(0,$.jsx)(`span`,{className:`text-text-primary`,children:o.accounts}),(0,$.jsx)(`span`,{children:o.accounts===1?`active account`:`active accounts`}),o.inactiveAccounts>0?(0,$.jsxs)(`span`,{className:`badge border border-warning-line text-status-warning normal-case tracking-normal`,title:`Disabled or cooled accounts hold credits this provider cannot route to. Enable or recover them to add their balance.`,children:[o.inactiveAccounts,` inactive`]}):null]}),(0,$.jsx)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-caption font-semibold tabular-nums text-text-primary`,title:`Combined allowance across active accounts; the usage floor is evaluated per account`,children:o.pooled?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{className:`font-bold ${_}`,children:gn(o.remaining)}),(0,$.jsx)(`span`,{className:`font-medium text-text-secondary`,children:`credits available`}),(0,$.jsxs)(`span`,{className:`font-medium opacity-75`,children:[`of `,gn(o.total)]}),(0,$.jsxs)(`span`,{className:`font-bold ${_}`,children:[o.percent,`%`]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`strong`,{className:`font-bold ${_}`,children:[o.percent,`% left`]}),(0,$.jsx)(`span`,{className:`font-medium text-text-secondary`,children:`lowest independent window`})]})}),(0,$.jsx)(`p`,{className:`text-micro leading-normal text-text-tertiary`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${gn(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),o===null&&(0,$.jsxs)(`p`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2 text-badge leading-normal text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`No quota data is available for these accounts yet. Exhausted quota windows are still skipped.`}),(0,$.jsx)(`span`,{className:`text-micro`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${gn(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),(0,$.jsxs)(`div`,{className:`ml-auto flex max-w-full shrink-0 flex-col items-end justify-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-x-3 gap-y-2`,children:[(0,$.jsx)(`span`,{className:`text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:`Floor threshold`}),(0,$.jsxs)(`label`,{className:`flex h-12 max-w-full items-center overflow-hidden rounded-tiny border border-inner-border bg-surface-1 focus-within:border-text-tertiary`,children:[(0,$.jsx)(`input`,{type:`number`,min:0,max:1e6,value:p?l:``,placeholder:`40`,disabled:!p,"aria-label":`Usage floor amount`,className:`h-full w-24 border-0 bg-transparent px-3 text-right font-mono text-body font-semibold tabular-nums text-text-primary disabled:text-text-tertiary`,onChange:e=>u(e.target.value),onBlur:()=>{p&&v(m,d)}}),(0,$.jsxs)(`select`,{value:d,disabled:!p,"aria-label":`Usage floor unit`,className:`h-full border-0 border-l border-inner-border bg-hover px-3 text-body font-semibold text-text-secondary disabled:cursor-default disabled:opacity-60`,onChange:e=>{let t=e.target.value===`credit`?`credit`:`percent`;f(t),p&&v(m,t)},children:[(0,$.jsx)(`option`,{value:`percent`,children:`%`}),(0,$.jsx)(`option`,{value:`credit`,children:`credits`})]})]}),(0,$.jsx)(et,{checked:p,label:`Enabled`,"aria-label":`Usage floor`,className:`usage-floor-switch`,onChange:e=>v(e?g?m:40:null,d)})]}),t.saveFailed?(0,$.jsx)(`p`,{role:`alert`,className:`text-right text-micro leading-normal text-status-danger`,children:`Usage floor save failed. The last saved setting has been restored.`}):null]})]})]}),(0,$.jsx)(mn,{providerId:e}),(0,$.jsx)(F,{open:i,onClose:()=>a(!1),title:`How the usage floor works`,size:`md`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 text-badge leading-relaxed text-text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`The usage floor is a `,(0,$.jsx)(`strong`,{children:`per-account`}),` guard: when an account's remaining allowance drops to or below the threshold, that account is skipped and the request fails over to the next one. It prevents a spent account from being dialed and erroring upstream.`]}),(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:`Credit mode`}),` sums absolute remaining credits across pooled windows. `,(0,$.jsx)(`strong`,{children:`Percent mode`}),` uses the aggregate credit percentage and the lowest independent percentage window. An account with `,(0,$.jsx)(`em`,{children:`unknown`}),` quota is never treated as below the floor.`]}),(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:`Free-tier models ignore the operator's floor threshold.`}),` `,`Their upstream service is not credit-funded, so the configurable floor does not gate them — an account below the threshold can still serve a free-tier model. Exhausted quota windows still exclude the account: if the provider's own free limit is spent (`,(0,$.jsx)(`code`,{children:`0 left`}),`), it is skipped for free-tier models too.`]}),(0,$.jsx)(`p`,{className:`text-micro text-text-tertiary`,children:`Turning the floor off disables the threshold for all models; exhausted quota windows are still skipped.`})]})})]})}function mn({providerId:e}){let{enabled:t,setEnabled:n}=Tt(e);return(0,$.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-6 px-6 py-5 border border-inner-border rounded-control bg-surface-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-auto basis-110`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,$.jsx)(O,{size:14}),(0,$.jsx)(`span`,{children:`Mysterious accounts`})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-badge leading-normal text-text-tertiary`,children:`Hide this provider's emails and usernames. Stored in this browser only.`})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-4 shrink-0`,children:(0,$.jsx)(et,{checked:t,"aria-label":`Mysterious accounts`,onChange:n})})]})}function hn(e,t){let n=0,r=0,i=0,a=0,o=!1,s=!1,c=null;for(let l of e)if(l.provider===t){if(!l.active){a+=1;continue}if(i+=1,l.quota!==null)for(let e of l.quota.windows){if(e.accounting===`pooled`){let t=typeof e.limit==`number`&&Number.isFinite(e.limit)?e.limit:null;if(t===null)continue;let i=typeof e.remaining==`number`&&Number.isFinite(e.remaining)?e.remaining:typeof e.used==`number`&&Number.isFinite(e.used)?t-e.used:null;if(i===null)continue;n+=Math.min(t,Math.max(0,i)),r+=t,o=!0;continue}if(s=!0,typeof e.remainingPercent==`number`&&Number.isFinite(e.remainingPercent)){let t=Math.min(100,Math.max(0,e.remainingPercent));c=c===null?t:Math.min(c,t)}}}return i===0?null:o?{accounts:i,inactiveAccounts:a,remaining:n,total:r,percent:r>0?Math.round(n/r*100):0,pooled:!0}:s&&c!==null?{accounts:i,inactiveAccounts:a,remaining:0,total:0,percent:Math.round(c),pooled:!1}:null}function gn(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function _n({provider:e}){let t=e.credentialUrl,n=e.credentialHint,r=e.operatorNotice;if(!t&&!n&&!r)return null;let i=e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0,a=n??(i?`This provider authorizes through its own login flow; there is no key to paste.`:e.requiresAccount?`Create a credential on the provider site, then add it as an account below.`:`This provider needs no credential.`);return(0,$.jsx)(W,{density:`compact`,children:(0,$.jsx)(U,{children:(0,$.jsxs)(Z,{gap:`12px`,className:`items-center flex-wrap`,children:[(0,$.jsxs)(`span`,{className:`min-w-110 flex-1 text-caption text-text-secondary`,children:[a,r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`br`,{}),r]}):null]}),t?(0,$.jsxs)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,title:t,className:v({size:`sm`,className:`shrink-0 no-underline`}),children:[(0,$.jsx)(`span`,{className:`btn-icon-wrapper`,"aria-hidden":`true`,children:(0,$.jsx)(Ne,{size:13})}),i?`Sign in`:`Get API Key`]}):null]})})})}function vn({provider:e}){let t=Se(),[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(e.baseUrl??``);(0,Q.useEffect)(()=>{a(e.baseUrl??``)},[e.providerId,e.baseUrl]);let o=(e.baseUrl??``).replace(/\/+$/,``),s=i.trim().replace(/\/+$/,``),c=s!==o,l=s.length>0&&c&&!t.isPending;return(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`Custom Provider Endpoint`,subtitle:`Upstream base URL`,icon:(0,$.jsx)(b,{size:16})}),(0,$.jsx)(U,{children:(0,$.jsxs)(X,{gap:`12px`,children:[n?(0,$.jsx)(J,{label:`Base URL`,id:`custom-provider-base-url`,type:`url`,value:i,onChange:e=>a(e.target.value),placeholder:`https://api.example.com/v1`,autoFocus:!0}):(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-micro font-semibold uppercase tracking-label text-text-tertiary`,children:`Base URL`}),(0,$.jsx)(`code`,{className:`mt-1 block min-w-0 break-all font-mono text-caption text-text-primary`,children:e.baseUrl??`Not configured`})]}),(0,$.jsxs)(Z,{gap:`8px`,className:`w-full flex-wrap`,justify:`end`,children:[n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{size:`sm`,variant:`primary`,icon:(0,$.jsx)(Nt,{size:13}),disabled:!l,loading:t.isPending,onClick:()=>{l&&t.mutate({providerId:e.providerId,request:{baseUrl:s}},{onSuccess:()=>r(!1)})},children:`Save endpoint`}),(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(re,{size:13}),disabled:t.isPending,onClick:()=>{a(e.baseUrl??``),r(!1)},children:`Cancel`})]}):(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(ie,{size:13}),onClick:()=>r(!0),children:`Edit endpoint`}),e.requiresAccount?(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(N,{size:13}),onClick:()=>{let e=document.getElementById(`provider-accounts`);e?.scrollIntoView({behavior:`smooth`,block:`start`}),e?.focus({preventScroll:!0})},children:`Manage API keys`}):null]})]})})]})}async function yn(e,t,n){let r=Array(e.length),i=Math.max(1,Math.min(t,e.length)),a=0;return await Promise.all(Array.from({length:i},async()=>{for(;;){let t=a;if(t>=e.length)return;a+=1;try{r[t]={status:`fulfilled`,value:await n(e[t],t)}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}function bn(e){let t=Object.entries(e.modelCooldowns??{}).filter(([,e])=>Number.isFinite(new Date(e).getTime())&&new Date(e).getTime()>Date.now()),n;for(let e of t)(n===void 0||new Date(e[1]).getTime()<new Date(n[1]).getTime())&&(n=e);return n===void 0?void 0:{count:t.length,modelId:n[0],until:n[1]}}function xn(e){let t=Object.values(e.modelCooldowns??{}).map(e=>new Date(e).getTime()).filter(e=>Number.isFinite(e));return t.length===0?null:Math.max(...t)}function Sn({accountId:e,accountName:t}){let n=yt(e),r=St(e),i=n.isPending||r.isPending;return(0,$.jsx)(h,{size:`sm`,variant:`secondary`,title:`Manually claim available ZCode gift plans`,"aria-label":`Claim gifts for ${t}`,disabled:i,icon:i?(0,$.jsx)(f,{size:12,className:`animate-spin`}):(0,$.jsx)(Ot,{size:12}),onClick:()=>n.mutate(void 0,{onSuccess:e=>{let t=[e.claimed.length>0?`Claimed: ${e.claimed.join(`, `)}`:null,e.detail].filter(Boolean).join(` · `);switch(e.state){case`claimed`:g.success(`Gift plans claimed`,t);break;case`already_claimed`:g.success(`Gift plans already claimed`,t);break;case`nothing`:g.success(`No gift plans to claim`,t);break;case`captcha`:g.warning(`CAPTCHA required — open the ZCode app`,t);break;case`partial`:g.warning(`Gift claim only partially completed`,t);break;case`error`:g.error(`Gift claim failed`,t)}e.claimed.length>0&&r.mutate(void 0,{onSuccess:e=>{e.ok||g.warning(`Gifts claimed; quota refresh failed`,e.message)},onError:e=>g.warning(`Gifts claimed; quota refresh failed`,B(e,`Refresh quota manually`))})},onError:e=>g.error(`Gift claim failed`,B(e,`Unable to claim gift plans`))}),children:i?`Claiming…`:`Claim gifts`})}function Cn({accountId:e,accountName:t}){let n=Ct(e),r=n.isPending;return(0,$.jsx)(h,{size:`sm`,variant:`secondary`,title:`Manually claim the Qoder daily CREDITS campaign`,"aria-label":`Claim credits for ${t}`,disabled:r,icon:r?(0,$.jsx)(f,{size:12,className:`animate-spin`}):(0,$.jsx)(D,{size:12}),onClick:()=>n.mutate(void 0,{onSuccess:e=>{switch(e.state){case`claimed`:g.success(`Qoder credits claimed`,`+${e.amount} credits granted`);break;case`already_claimed`:g.success(`Qoder credits already claimed`,e.detail??void 0);break;case`nothing`:g.success(`No CREDITS campaign`,`No claimable CREDITS campaign is visible for this account right now.`);break;case`error`:g.error(`Qoder credit claim failed`,e.detail??`Claim failed`)}},onError:e=>g.error(`Qoder credit claim failed`,B(e,`Unable to claim credits`))}),children:r?`Claiming…`:`Claim credits`})}var wn={quota_fetch_failed:`Quota unreachable`,quota_exhausted:`Quota exhausted`,quota_unknown:`Quota unknown`,plan_gate:`Plan blocked`,policy_blocked:`Policy blocked`,policy_blocked_banned:`Account banned`,policy_blocked_invalid_request:`Request refused`,rate_limit_transient:`Rate limited`,missing_credential:`No credential`,validation_required:`Verification required`,model_unreachable:`Model unavailable`},Tn=new Set([`quota_fetch_failed`,`quota_unknown`]);function En(e){return e===void 0||e.length===0?!1:!Tn.has(e)}function Dn(e){return e===`oauth`?`Re-login required`:`Replace API key`}function On(e,t,n){return e===`auth_invalidated`?Dn(t):e===`policy_blocked_banned`&&n===`github`?`No Copilot access`:wn[e]??e}var kn=/https?:\/\/[^\s"'\\]+/;function An(e){if(e)return kn.exec(e)?.[0]}function jn({cooldowns:e,reason:t}){if(!e)return null;let n=at(e.until),r=`Soonest: ${e.modelId} — ${n}`;return(0,$.jsxs)(q,{tone:`warn`,dot:!0,title:t?`${t} — ${r}`:r,children:[e.count,` model`,e.count===1?``:`s`,` cooling · `,n]})}function Mn(e){if(e.credentialKind===`oauth`)return`OAuth`;if(e.credentialMode===`jwt`)return`JWT`}function Nn(e){if(!En(e.lastErrorCategory)||e.lastErrorCategory===`quota_exhausted`&&bn(e))return null;let t=On(e.lastErrorCategory,e.credentialKind,e.providerId),n=e.lastError??e.lastErrorCategory;if(e.lastErrorCategory===`policy_blocked_banned`&&e.providerId===`github`)return(0,$.jsx)(q,{tone:`err`,dot:!0,title:n,children:t});if(e.lastErrorCategory===`validation_required`){let r=An(e.lastError);if(r!==void 0)return(0,$.jsx)(`a`,{href:r,target:`_blank`,rel:`noreferrer noopener`,title:n,children:(0,$.jsxs)(q,{tone:`warn`,children:[t,(0,$.jsx)(Ne,{size:12,className:`shrink-0`,"aria-hidden":`true`})]})})}return(0,$.jsx)(q,{tone:`warn`,title:n,children:t})}function Pn(e){return e.credentialKind===`oauth`?`blue`:`ok`}function Fn({account:e}){let t=e.providerCooldowns;if(!t||t.length===0)return null;let n=Date.now(),r=t.filter(e=>new Date(e.until).getTime()>n);if(r.length===0)return null;let i=r.some(e=>e.blocked),a=r.reduce((e,t)=>{let n=new Date(t.until).getTime();return n<e?n:e},1/0),o=r.map(e=>`${e.providerId}: ${e.reason}${e.blocked?` (blocked)`:``}`).join(` · `);return(0,$.jsx)(q,{tone:`warn`,title:`${o} — resets ${at(new Date(a).toISOString())}`,children:i?`Egress blocked`:`Rate-limited`})}function In({account:e}){let t=e.cooldownUntil?new Date(e.cooldownUntil).getTime():NaN,n=Number.isFinite(t)&&t>Date.now(),r=bn(e);if(e.status===`disabled`){let t=Mn(e),n=e.lastErrorCategory===`auth_invalidated`;return(0,$.jsxs)(Z,{gap:`4px`,children:[(0,$.jsxs)(q,{tone:`disabled`,dot:!0,title:e.lastError,children:[`Disabled`,t?` - ${t}`:``]}),n?(0,$.jsx)(q,{tone:`warn`,title:e.lastError,children:Dn(e.credentialKind)}):Nn(e),(0,$.jsx)(jn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]})}return e.status===`active`?(0,$.jsxs)(Z,{gap:`4px`,children:[(0,$.jsxs)(q,{tone:Pn(e),dot:!0,children:[`Active`,Mn(e)?` - ${Mn(e)}`:``]}),(0,$.jsx)(Fn,{account:e}),Nn(e),(0,$.jsx)(jn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):e.status===`cooldown`||n?(0,$.jsxs)(Z,{gap:`4px`,children:[(0,$.jsxs)(q,{tone:`warn`,dot:!0,children:[`Cooldown`,Mn(e)?` - ${Mn(e)}`:``,` `,e.cooldownUntil?`(${at(e.cooldownUntil)})`:``]}),(0,$.jsx)(Fn,{account:e}),Nn(e),(0,$.jsx)(jn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):(0,$.jsx)(q,{tone:`disabled`,children:`Disabled`})}function Ln(e){switch(e){case`google`:case`github`:return{label:`Social`,tone:`accent`};case`builder-id`:case`idc`:return{label:`OIDC`,tone:`default`};case`external_idp`:return{label:`Enterprise IdP`,tone:`default`};case`api_key`:return{label:`API key`,tone:`default`};case`imported`:return{label:`Imported`,tone:`default`};default:return null}}function Rn(e){if(e===void 0)return;let t=new Date(e).getTime();if(Number.isFinite(t))return t<=Date.now()?`Expired ${new Date(e).toLocaleDateString()}`:at(e,!1)}function zn({windows:e}){let t=(e??[]).filter(e=>!st(e)),n=t.filter(e=>e.kind===`session_active`),r=ct(t.filter(e=>e.kind!==`session_active`)),i=t.filter(e=>ot(e)!==`current`&&e.kind!==`session_active`),[,a]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{if(n.length===0)return;let e=setInterval(()=>a(e=>e+1),3e4);return()=>clearInterval(e)},[n.length]),(0,$.jsxs)($.Fragment,{children:[n.map((e,t)=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,"data-tone":`accent`,title:`Session is locked to ${e.modelIds?.join(`, `)??`this model`} until it expires`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Session`}),e.modelIds?.join(`, `)??e.label,` · `,at(e.resetsAt,!1)]},`session-active:${e.modelIds?.join(`,`)??e.label}:${t}`)),r.text!==null&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,"data-tone":r.low?`warn`:void 0,title:r.hasCredits?`${Bn(r.remaining)} credits available`:`Current model grants and account-wide quota limits`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Quota`}),r.text]}),i.map((e,t)=>(0,$.jsxs)(`span`,{className:`text-badge text-text-tertiary`,children:[e.label,e.modelIds?.length?` · ${e.modelIds.join(`, `)}`:``,` · `,ot(e)===`expired`?`Expired`:`Not started yet · Starts ${new Date(e.startsAt).toLocaleString()}`]},`${e.kind??e.label}:${e.startsAt}:${t}`))]})}function Bn(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function Vn({providerId:e,account:t,onClose:n}){let r=_e(),[i,a]=(0,Q.useState)(``),o=t.label||t.id.slice(0,8),s=r.isPending,c=i.trim().length>0&&!s,l=async()=>{try{a(await navigator.clipboard.readText())}catch{g.error(`Clipboard access denied`)}};return(0,$.jsx)(F,{open:!0,onClose:n,title:`Replace API key — ${o}`,width:560,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:n,disabled:s,children:`Cancel`}),(0,$.jsx)(h,{size:`sm`,variant:`primary`,disabled:!c,onClick:()=>{let a=i.trim();a&&r.mutate({providerId:e,accountId:t.id,request:{secret:a}},{onSuccess:()=>{g.success(`API key replaced`,o),n()},onError:e=>{let t=e instanceof Error?e.message:`Unable to update account`;g.error(`Failed to replace key`,t)}})},children:s?`Saving…`:`Replace key`})]}),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,$.jsx)(`p`,{className:`m-0 text-caption text-text-secondary`,children:`Paste the new key for this account. The old key stops working immediately; the account keeps its label, history, and routing.`}),(0,$.jsxs)(X,{gap:`6px`,className:`min-w-0`,children:[(0,$.jsx)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:`New API key`}),(0,$.jsx)(`textarea`,{value:i,onChange:e=>a(e.target.value),placeholder:`Paste the replacement key…`,rows:4,spellCheck:!1,autoFocus:!0,className:`font-mono tabular-nums w-full min-w-0 min-h-65 rounded-control border border-inner-border bg-input-bg px-6 py-5 text-caption text-text-primary resize-y box-border`}),(0,$.jsx)(Z,{gap:`8px`,className:`justify-end`,children:(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:()=>void l(),children:`Paste`})})]})]})})}function Hn({providerId:e,account:t,inflight:n,quota:r,selected:a,onToggleSelect:o,onDelete:s}){let c=_e(),l=we(),u=St(t.id),d=_t(),m=t.kind===`pool`,_=t.networkPoolId,v=gt(m?_:void 0),y=t.status===`disabled`,b=t.cooldownUntil?new Date(t.cooldownUntil).getTime():NaN,x=Number.isFinite(b)&&b>Date.now(),S=bn(t)!==void 0,C=typeof t.lastErrorCategory==`string`&&t.lastErrorCategory.length>0&&t.lastErrorCategory!==`auth_invalidated`,w=t.status===`cooldown`||x||S||C,[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(!1),[,ee]=(0,Q.useState)(0),[ne,re]=(0,Q.useState)(!1),[P,I]=(0,Q.useState)(``),L=Tt(e),se=t.accountEmail??t.accountName??t.label?.match(/[^\s@]+@[^\s@]+/)?.[0]??t.label??t.id.slice(0,8),R=L.enabled?`Mysterious accounts`:se,z=Rn(t.tokenExpiresAt),le=xn(t),ue=Math.max(x&&t.cooldownUntil?b:0,le??0);(0,Q.useEffect)(()=>{if(ue<=Date.now())return;let e=setInterval(()=>ee(e=>e+1),1e3);return()=>clearInterval(e)},[ue]);let de=()=>{let n=P.trim();re(!1),n&&n!==(t.label??``)&&c.mutate({providerId:e,accountId:t.id,request:{label:n}},{onSuccess:()=>g.success(`Account renamed`,n),onError:e=>g.error(`Rename failed`,e.message??`Unable to rename account`)})};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`account-row account-row-grid grid items-center gap-5 px-5 py-4 border rounded-control bg-surface-2 ${a?`border-accent`:`border-inner-border`} hover:bg-hover`,role:`listitem`,"data-selected":a?`true`:void 0,style:{opacity:y?.62:1},children:[(0,$.jsx)(`div`,{className:`flex items-center`,children:(0,$.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(t.id,e.target.checked),"aria-label":`Select ${R}`,className:`cursor-pointer`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex flex-col gap-1.5`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-3 min-w-0`,children:ne?(0,$.jsx)(J,{value:P,onChange:e=>I(e.target.value),onKeyDown:e=>{e.key===`Enter`&&de(),e.key===`Escape`&&re(!1)},onBlur:de,autoFocus:!0,"aria-label":`Account label`,className:`text-body max-w-120`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-body font-semibold text-text-primary min-w-0 overflow-hidden text-ellipsis whitespace-nowrap`,title:t.label||t.id,children:R}),m?(0,$.jsx)(`span`,{className:`inline-flex items-center gap-1 px-2 py-0.5 border border-inner-border rounded-tiny bg-surface-1 text-micro font-bold uppercase tracking-label text-text-secondary`,title:`Proxy pool routing as an account for this ip-scoped provider`,children:`Pool`}):null,(()=>{let e=Ln(t.authMethod);return e===null?null:(0,$.jsx)(`span`,{className:`inline-flex items-center gap-1 px-2 py-0.5 border rounded-tiny text-micro font-bold uppercase tracking-label ${e.tone===`accent`?`border-accent bg-accent-soft text-accent`:`border-inner-border bg-surface-1 text-text-secondary`}`,title:`Signed in via ${e.label}`,children:e.label})})(),(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 grid place-items-center w-10 h-10 p-0 border-0 bg-transparent text-text-tertiary cursor-pointer rounded-tiny hover:bg-inner-border hover:text-text-primary`,title:`Rename account`,"aria-label":`Rename ${R}`,onClick:()=>{I(t.label??``),re(!0)},children:(0,$.jsx)(ie,{size:11})})]})}),(0,$.jsxs)(`div`,{className:`flex items-center flex-nowrap gap-2 min-w-0 overflow-hidden`,children:[(0,$.jsx)(In,{account:t}),z?(0,$.jsx)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:z,children:z}):null]}),(0,$.jsxs)(`div`,{className:`flex items-center flex-wrap gap-2 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Today: ${t.usageToday.totalTokens.toLocaleString()} tokens, ${t.usageToday.requests.toLocaleString()} requests`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Today`}),t.usageToday.totalTokens.toLocaleString(),` tok · `,t.usageToday.requests.toLocaleString(),` req`]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Lifetime totals are backfilled from telemetry still retained when tracking starts; new totals survive telemetry cleanup.`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`All time`}),t.usageAllTime.totalTokens.toLocaleString(),` tok · `,t.usageAllTime.requests.toLocaleString(),` req`]}),(0,$.jsx)(zn,{windows:r}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Concurrency comes from this provider’s Routing Strategy; accounts carry no manual ceilings.`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`In flight`}),n?.toLocaleString()??`—`]})]})]}),(0,$.jsxs)(`div`,{className:`account-row-actions flex items-center justify-end gap-3 flex-wrap`,children:[e===`zcode-start`&&!m&&(0,$.jsx)(Sn,{accountId:t.id,accountName:R}),(e===`qoder`||e===`qodercn`)&&!m&&(0,$.jsx)(Cn,{accountId:t.id,accountName:R}),m?(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(i,{size:12}),label:`Health`,"aria-label":`Health for ${R}`,onClick:()=>O(!0),title:`View pool health & error history`}):(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(i,{size:12}),label:`Health`,"aria-label":`Health for ${R}`,onClick:()=>E(!0),title:`View Health & Error History`}),m?(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:d.isPending?(0,$.jsx)(f,{size:12,className:`animate-spin`}):(0,$.jsx)(p,{size:12}),label:d.isPending?`Testing…`:`Test`,"aria-label":`Test ${R}`,disabled:d.isPending||_===void 0,onClick:()=>{_&&d.mutate({poolId:_,providerId:e},{onSuccess:e=>{e.status===`allowed`?g.success(`Pool probe passed`,R):e.status===`blocked`?g.error(`Pool blocked`,e.reason??`Upstream refused this egress`):e.status===`throttled`?g.error(`Pool rate-limited`,e.reason??`Address accepted; rate limit spent`):g.error(`Pool unreachable`,e.reason??`Probe could not complete`)},onError:e=>g.error(`Pool probe failed`,e.message??`Probe failed`)})},title:`Probe this pool against the provider`}):(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:u.isPending?(0,$.jsx)(f,{size:12,className:`animate-spin`}):(0,$.jsx)(p,{size:12}),label:u.isPending?`Testing…`:`Test`,"aria-label":`Test ${R}`,disabled:u.isPending,onClick:()=>{u.mutate(void 0,{onSuccess:e=>{e?.ok?g.success(`Account test passed`,R):g.error(`Account test failed`,e?.message??`Provider reported an error`)},onError:e=>g.error(`Account test failed`,e.message??`Unable to test account`)})},title:`Refresh quota and health for this account`}),m?null:(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(N,{size:12}),label:`Edit key`,"aria-label":`Replace API key for ${R}`,onClick:()=>A(!0),title:`Replace API key`}),m?null:(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:y?(0,$.jsx)(At,{size:12}):(0,$.jsx)(ae,{size:12}),label:y?`Enable`:`Disable`,"aria-label":y?`Enable ${R}`:`Disable ${R}`,disabled:c.isPending,onClick:()=>{let n=y;c.mutate({providerId:e,accountId:t.id,request:{status:n?`active`:`disabled`}},{onSuccess:()=>g.success(n?`Account enabled`:`Account disabled`,R),onError:e=>g.error(`Update failed`,e.message??`Unable to update account`)})},title:y?`Enable account`:`Disable account`}),w?(0,$.jsx)(h,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(oe,{size:12,className:l.isPending?`animate-spin`:``}),label:l.isPending?`Recovering…`:`Recover`,"aria-label":`Recover ${R}`,disabled:l.isPending,onClick:()=>l.mutate({providerId:e,accountId:t.id}),title:`Clear cooldown / restore active status`}):null,m?null:(0,$.jsx)(h,{size:`icon`,variant:`danger`,icon:(0,$.jsx)(ce,{size:12}),label:`Delete`,"aria-label":`Delete ${R}`,onClick:()=>s(t),title:`Delete account`})]})]}),T&&(0,$.jsx)(wt,{summary:{providerId:e,accountId:t.id,title:t.label||t.id.slice(0,8),status:t.status,errorCategory:t.lastErrorCategory??void 0,errorMessage:t.lastError??void 0,emptyMessage:`Status transitions, rate limits, and auto-recoveries will appear here.`,staticToken:t.staticToken===!0,credentialKind:t.credentialKind,credentialMode:t.credentialMode,jwtIssuer:t.jwtIssuer},onClose:()=>E(!1)}),k&&(0,$.jsx)(Vn,{providerId:e,account:t,onClose:()=>A(!1)}),D&&(0,$.jsx)(F,{open:!0,title:`Pool Health & Error History`,onClose:()=>O(!1),width:640,footer:(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:()=>O(!1),children:`Close`}),children:(0,$.jsx)(`div`,{className:`flex flex-col gap-3 min-h-40`,children:v.isPending?(0,$.jsx)(M,{label:`Loading pool health events…`}):v.isError?(0,$.jsx)(j,{message:`Failed to load pool health events`,onRetry:()=>void v.refetch()}):(v.data??[]).length===0?(0,$.jsx)(te,{compact:!0,title:`No health events recorded`,message:`Status transitions, rate limits, and auto-recoveries will appear here.`}):(0,$.jsx)(`div`,{className:`scroll-region max-h-160 overflow-y-auto pr-1 flex flex-col gap-3`,children:(v.data??[]).map(e=>(0,$.jsxs)(`div`,{className:`rounded-control border border-inner-border bg-surface-2 px-4 py-3 text-badge`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsx)(`span`,{className:`font-mono tabular-nums text-micro text-text-tertiary`,children:new Date(e.createdAt).toLocaleString()}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-text-tertiary text-micro uppercase tracking-label`,children:[e.fromStatus??`—`,` → `,e.toStatus]}),e.errorCategory?(0,$.jsx)(`span`,{className:`rounded-pill border border-warning-line bg-surface-2 px-2.5 py-px font-mono text-micro text-status-warning`,children:e.errorCategory}):null]})]}),e.reason?(0,$.jsx)(`p`,{className:`mt-2 text-micro text-text-secondary [overflow-wrap:anywhere] break-words`,children:e.reason}):null]},e.id))})})})]})}var Un=[`access`,`accessToken`,`access_token`,`sessionToken`,`session_token`,`token`,`apiKey`,`api_key`,`key`,`credential`,`pat`,`secret`],Wn=[`refresh`,`refreshToken`,`refresh_token`],Gn=[`credentialKind`,`providerId`,`accessToken`],Kn=[`accounts`,`items`,`connections`],qn=[`email`,`name`,`accountId`,`account_id`,`id`,`login`,`username`];function Jn(e){if(typeof e==`object`&&e&&!Array.isArray(e))return Object.fromEntries(Object.entries(e))}function Yn(e){let t=e.data;if(typeof t==`string`)try{return Jn(JSON.parse(t))}catch{return}return Jn(t)}function Xn(e){for(let t of Un){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:t}}let t=Yn(e);if(t)for(let e of Un){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:`data.${e}`}}}function Zn(e){for(let t of qn){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return n.trim()}let t=Yn(e);if(t)for(let e of qn){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function Qn(e){let t=(e,t)=>t.some(t=>typeof e[t]==`string`||typeof e[t]==`number`),n=e=>t(e,Wn);if(n(e))return!0;let r=Yn(e);return r?n(r):!1}function $n(e){let t=e.trim().split(`.`);if(t.length===3)try{let e=t[1].replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=e.padEnd(e.length+(4-e.length%4)%4,`=`);return Jn(JSON.parse(atob(n)))}catch{return}}function er(e){let t=$n(e)?.exp;if(typeof t!=`number`||!Number.isFinite(t))return;let n=new Date(t*1e3);return Number.isFinite(n.getTime())?n.toISOString():void 0}function tr(e){let t={},n=0;for(let r of e.split(/\r?\n/)){let e=/^\s*([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(r),i=e?.[1],a=e?.[2];i!==void 0&&a!==void 0&&(t[i]=a.trim(),n+=1)}return n>0?t:void 0}function nr(e){if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return}}function rr(e){let t=e.trim(),n=Jn(nr(t))??tr(t);return n&&Qn(n)?`oauth`:$n((n?Xn(n)?.value:void 0)??t)===void 0?`api_key`:`jwt`}function ir(e){return e.length!==0&&!!(e.some(e=>Array.isArray(e.cookies)&&(typeof e.domain==`string`||typeof e.originalUrl==`string`))||e.every(e=>typeof e.name==`string`&&typeof e.value==`string`&&(e.domain!==void 0||e.path!==void 0||e.expirationDate!==void 0)))}function ar(e,t){let n,r=!1,i=(e,t)=>{let i=e.toLowerCase();(i===`userid`||i===`uid`||i===`accountid`||i===`cuserid`)&&(n||=t.replace(/^"|"$/g,``).trim()),(i.includes(`token`)||i.includes(`ph`)||i.includes(`auth`)||i.includes(`session`))&&(r=!0)};for(let e of t)if(Array.isArray(e.cookies)){for(let t of e.cookies)if(t&&typeof t==`object`){let e=t;typeof e.name==`string`&&typeof e.value==`string`&&i(e.name,e.value)}}else typeof e.name==`string`&&typeof e.value==`string`&&i(e.name,e.value);return{value:e,kind:r?`oauth`:`api_key`,...n?{identity:n}:{}}}function or(e){let t=e.credentialKind;if(typeof t==`string`&&typeof e.accessToken==`string`&&Gn.every(t=>t in e)){let n=typeof e.label==`string`&&e.label.trim().length>0?e.label.trim():void 0,r=e.accessToken,i=t===`oauth`&&Qn(e);return{value:i?JSON.stringify(e):r,kind:i?`oauth`:`api_key`,...n?{identity:n}:{}}}let n=Xn(e),r=Qn(e)?`oauth`:rr(n?.value??JSON.stringify(e)),i=r===`oauth`?JSON.stringify(e):n?.value??JSON.stringify(e),a=Zn(e);return a?{value:i,kind:r,identity:a}:{value:i,kind:r}}function sr(e){for(let t of Kn){let n=e[t];if(!Array.isArray(n))continue;let r=n.map(e=>Jn(e)).filter(e=>e!==void 0);if(r.length>0)return r}}function cr(e){let t=e.trim();if(!t)return[];let n=nr(t);if(Array.isArray(n)){let e=n.map(e=>Jn(e)).filter(e=>e!==void 0);if(e.length>0)return ir(e)?[ar(t,e)]:e.map(or)}else{let e=Jn(n);if(e){let t=sr(e);return t?t.map(or):[or(e)]}}let r=t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);if(r.length===0)return[];if(r.length===1){let e=tr(r[0]);return e?[or(e)]:lr(r[0])}let i=tr(t);return i&&(Xn(i)||Object.keys(i).length===r.length)?[or(i)]:r.flatMap(lr)}function lr(e){let t=Jn(nr(e));if(t){let e=sr(t);return e?e.map(or):[or(t)]}let n=ur(e);return n.length>0?n:[{value:e,kind:rr(e)}]}function ur(e){let t=e.indexOf(`|`);if(t<=0)return[];let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();return!n||!r?[]:[{value:r,kind:rr(r),identity:n}]}function dr(e,t,n){let r=new Set(n),i=1;return e.map(e=>{let n=e.identity;if(!n){for(;r.has(`${t}-${i}`);)i+=1;n=`${t}-${i}`,i+=1}let a=n,o=2;for(;r.has(a);)a=`${n} (${o++})`;return r.add(a),a})}function fr(e){let t=[];for(let n of e){let e=n.text.trim();if(!e)continue;let r=nr(e);if(Array.isArray(r)){let n=r.filter(e=>Jn(e)!==void 0);if(n.length>0&&ir(n)){t.push(e);continue}for(let e of r){let n=Jn(e);t.push(n===void 0?String(e):JSON.stringify(n))}continue}let i=Jn(r);if(i){let n=sr(i);if(n!==void 0){for(let e of n)t.push(JSON.stringify(e));continue}t.push(e);continue}cr(e).length<=1?t.push(e):t.push(...e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0))}let n=t.join(`
2
+ `);return{text:n,entries:cr(n)}}function pr(e,t=50){if(t<1)throw RangeError(`chunk size must be at least 1`);let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var mr=2097152,hr=mr/1048576;function gr({providerId:e,accounts:t,onClose:n}){let r=Le(),i=Ve(),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(`auto`),[p,m]=(0,Q.useState)(!1),_=(0,Q.useRef)(null),y=cr(s),b=y.length>1,x=y.length===1?y[0]:void 0,S=d===`auto`?x?.kind:d,C=x&&S===`jwt`?er(x.value):void 0,w=t.map(e=>e.label),T=b?dr(y,e,w):[],E=e=>{let t=d===`auto`?e.kind===`jwt`?`jwt`:`auto`:d;return{credentialKind:t===`auto`&&e.kind===`oauth`?`oauth`:`api_key`,credentialMode:t,secret:e.value}},D=r.isPending||l,O=async()=>{try{let e=await navigator.clipboard.readText();c(e);let t=cr(e);if(t.length>1)g.success(`Pasted from clipboard`,`Detected ${t.length} credentials`);else{let e=t[0]?.kind??`api_key`,n=e===`oauth`?`OAuth export`:e===`jwt`?`Static JWT`:`API key`;g.success(`Pasted from clipboard`,`Detected: ${n}`)}}catch{g.error(`Clipboard access denied`)}},k=e=>{if(e.length===0)return;let t=e.find(e=>e.size>mr);if(t){g.error(`File too large`,`${t.name} is over ${hr} MB — credential files must be ${hr} MB or smaller.`);return}let n=e.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(typeof r.result==`string`?r.result:``),r.onerror=()=>n(Error(`Could not read ${e.name}`)),r.readAsText(e)}));Promise.all(n).then(t=>{let n=fr(e.map((e,n)=>({name:e.name,text:t[n]??``})));if(n.entries.length===0){g.error(`Nothing to import`,`None of the selected files held a credential the gateway recognises.`);return}c(n.text),g.success(`Imported ${e.length} file${e.length===1?``:`s`}`,n.entries.length>1?`Detected ${n.entries.length} credentials`:n.entries[0]?.kind===`oauth`?`Detected: OAuth export`:`Detected: API key`)}).catch(e=>g.error(`Could not read those files`,String(e)))},A=async()=>{if(y.length!==0){if(y.length===1){let t=y[0];r.mutate({providerId:e,request:{label:(a.trim()||t.identity)??void 0,...E(t)}},{onSuccess:()=>{g.success(`Account connected`,`New ${t.kind===`oauth`?`OAuth`:t.kind===`jwt`?`Static JWT`:`API key`} account registered successfully`),n()},onError:e=>g.error(`Failed to add account`,e.message??`Invalid credentials`)});return}u(!0);try{let t=pr(y.map((e,t)=>({label:T[t],...E(e)}))),r=0,a=[],o=!1;for(let[n,s]of t.entries())try{let t=await i.mutateAsync({providerId:e,accounts:s});r+=t.created;let o=n*50;for(let e of t.results)e.ok||a.push(`${T[o+e.index]??o+e.index}: ${e.error??`rejected`}`)}catch(e){o=!0,a.push(`chunk ${n+1}/${t.length}: ${B(e,`request failed`)}`);break}let s=a.length;r>0&&g.success(`${r} account${r===1?``:`s`} added`,o?`stopped partway; ${s} failed`:s>0?`${s} skipped`:void 0),s>0&&g.error(`${s} account${s===1?``:`s`} skipped`,a.slice(0,5).join(`
3
+ `)+(s>5?`\n…and ${s-5} more`:``)),r>0&&n()}finally{u(!1)}}};return(0,$.jsx)(F,{open:!0,onClose:n,title:`Add Account (API key / JSON)`,width:560,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:n,disabled:D,children:`Cancel`}),(0,$.jsx)(h,{size:`sm`,variant:`primary`,disabled:D||y.length===0,onClick:()=>void A(),children:D?`Connecting...`:b?`Add ${y.length} Accounts`:`Add Account`})]}),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[!b&&(0,$.jsx)(J,{label:`Account label (optional)`,value:a,onChange:e=>o(e.target.value),placeholder:x?.identity??`${e} account`}),(0,$.jsx)(Y,{label:`Credential type`,id:`credential-mode`,value:d,onValueChange:e=>f(e===`jwt`||e===`api_key`?e:`auto`),options:[{value:`auto`,label:`Auto — detect JWT, OAuth, or API key`},{value:`jwt`,label:`JWT — static, no refresh`},{value:`api_key`,label:`API key — do not decode as JWT`}]}),(0,$.jsxs)(X,{gap:`6px`,className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsxs)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:[`API key, OAuth token, or exported JSON — one or many`,(0,$.jsxs)(`span`,{className:`font-normal text-text-tertiary`,children:[` `,`·`,` `,`also supports `,(0,$.jsx)(`code`,{className:`font-mono text-micro`,children:`name|credential`}),` per line`]})]}),b?(0,$.jsxs)(q,{tone:`accent`,children:[`Detected: `,y.length,` accounts`]}):x?(0,$.jsxs)(q,{tone:S===`oauth`||S===`jwt`?`accent`:`default`,children:[`Detected:`,` `,S===`oauth`?`OAuth`:S===`jwt`?`Static JWT`:`API key`,x.identity?` · ${x.identity}`:``]}):null,x&&S===`jwt`?(0,$.jsxs)(`p`,{className:`text-micro text-text-tertiary`,children:[`Static JWT · no refresh token`,C?` · expires ${new Date(C).toLocaleString()}`:` · no expiry claim`]}):null]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-control border-2 border-dashed p-3 transition-colors`,"data-drag-active":p?`true`:void 0,onDragOver:e=>{e.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:e=>{e.preventDefault(),m(!1);let t=[...e.dataTransfer.files].filter(e=>e.name.endsWith(`.json`)||e.name.endsWith(`.jsonl`)||e.name.endsWith(`.ndjson`)||e.name.endsWith(`.txt`)||e.type.startsWith(`application/json`)||e.type.startsWith(`text/plain`));if(t.length>0){k(t);return}let n=e.dataTransfer.getData(`text/plain`);if(!n||!n.trim())return;let r=n.trim();c(r);let i=cr(r);if(i.length>1)g.success(`Dropped credential text`,`Detected ${i.length} credentials`);else{let e=i[0]?.kind??`api_key`;g.success(`Dropped credential text`,e===`oauth`?`Detected: OAuth export`:e===`jwt`?`Detected: Static JWT`:`Detected: API key`)}},children:[(0,$.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`Paste one credential, or many — one per line, a JSON array, or newline-delimited OAuth exports. Prefix a line with name| to name that account (e.g. onlybougieclan|pt-…). Kind and account naming are detected automatically…`,rows:6,spellCheck:!1,className:`font-mono tabular-nums w-full min-w-0 min-h-65 rounded-control border border-inner-border bg-input-bg px-6 py-5 text-caption text-text-primary resize-y box-border`}),(0,$.jsx)(`p`,{className:`text-micro text-text-tertiary text-center`,children:`Or drop credential files here — JSON, .txt, .jsonl, .ndjson — several at once, merged and detected together. Selecting a credential text and dragging it here works too.`})]}),(0,$.jsxs)(Z,{gap:`8px`,className:`justify-end`,children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:()=>void O(),children:`Paste`}),(0,$.jsxs)(`label`,{className:v({size:`sm`,className:`cursor-pointer`}),children:[(0,$.jsx)(`input`,{ref:_,type:`file`,accept:`.json,.txt,.jsonl,.ndjson,application/json,text/plain`,multiple:!0,"aria-label":`Import credentials from files`,className:`hidden`,onChange:e=>{let t=[...e.target.files??[]];e.target.value=``,t.length>0&&k(t)}}),`Import files`]})]})]}),b&&(0,$.jsx)(`div`,{className:`flex flex-col gap-2 max-h-75 overflow-y-auto rounded-control border border-inner-border bg-surface-2 px-4 py-5`,children:y.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4 text-badge`,children:[(0,$.jsx)(`span`,{className:`truncate min-w-0`,children:T[t]}),(0,$.jsx)(q,{tone:e.kind===`oauth`?`accent`:`default`,children:e.kind===`oauth`?`OAuth`:`API key`})]},t))})]})})}function _r(e){if(e.kind===`pool`||e.status===`disabled`)return!1;if(e.status===`cooldown`)return!0;if(e.cooldownUntil!==void 0&&e.cooldownUntil!==null){let t=Date.parse(e.cooldownUntil);if(Number.isFinite(t)&&t>Date.now())return!0}return Object.keys(e.modelCooldowns??{}).length>0}function vr(e){return e.kind!==`pool`&&e.status===`disabled`&&e.lastErrorCategory===`policy_blocked_banned`}function yr(e){return e===`active`?0:e===`cooldown`?2:3}var br=[{value:`added-asc`,label:`Added · oldest`},{value:`added-desc`,label:`Added · newest`},{value:`label-asc`,label:`Name · A–Z`},{value:`label-desc`,label:`Name · Z–A`},{value:`status-asc`,label:`Status · active first`},{value:`status-desc`,label:`Status · disabled first`},{value:`lastCheck-desc`,label:`Last check · newest`},{value:`lastCheck-asc`,label:`Last check · oldest`}];function xr(e,t,n){let r=e=>e.createdAt??``,i=e=>e.id??``,a=(e,t)=>(e.label||e.id).localeCompare(t.label||t.id)||r(e).localeCompare(r(t))||i(e).localeCompare(i(t));if(n===`added`)return e.sortIndex-t.sortIndex||r(e).localeCompare(r(t))||i(e).localeCompare(i(t));if(n===`label`)return a(e,t);if(n===`status`){let n=yr(e.status)-yr(t.status);return n===0?a(e,t):n}let o=new Date(e.lastSuccessAt??e.createdAt).getTime();return new Date(t.lastSuccessAt??t.createdAt).getTime()-o||a(e,t)}function Sr({label:e,disabled:t=!1,title:n,children:r}){let[i,a]=(0,Q.useState)(!1),o=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!i)return;let e=e=>{o.current?.contains(e.target)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[i]),(0,$.jsxs)(`div`,{className:`relative shrink-0`,ref:o,children:[(0,$.jsxs)(h,{size:`sm`,variant:`secondary`,disabled:t,title:n,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(e=>!e),children:[e,(0,$.jsx)(je,{size:12,className:i?`rotate-180`:``,"aria-hidden":`true`})]}),(0,$.jsx)(`div`,{role:`menu`,hidden:!i,className:`absolute right-0 top-full z-popover mt-1 min-w-56 rounded-card border border-border-strong bg-popover-bg p-1 shadow-popout`,children:r})]})}function Cr({label:e,hint:t,icon:n,disabled:r=!1,danger:i=!1,title:a,onClick:o}){return(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,disabled:r,title:a,className:`flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-caption font-semibold disabled:cursor-not-allowed disabled:opacity-40 ${i?`text-red hover:bg-red-soft`:`text-text-primary hover:bg-hover`}`,onClick:o,children:[(0,$.jsx)(`span`,{className:`inline-flex shrink-0`,"aria-hidden":`true`,children:n}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:e}),t?(0,$.jsx)(`span`,{className:`text-badge font-medium text-text-tertiary`,children:t}):null]})}function wr({providerId:e,accounts:t,onDelete:n,showGrokProbe:r=!1,grokProbePending:i=!1,onGrokProbe:a}){let o=le(),s=xt(),c=Oe(),l=H(),u=we(),f=ze(),m=dt(e).data??new Map,_=bt(),v=(0,Q.useMemo)(()=>{let t=new Map;for(let n of _.data?.accounts??[])n.provider===e&&n.quota&&t.set(n.id,n.quota.windows);return t},[_.data,e]),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)(new Set),[C,w]=(0,Q.useState)(`added-asc`),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(!1),[ee,j]=(0,Q.useState)(!1),M=y.trim().toLowerCase(),N=(0,Q.useMemo)(()=>M?t.filter(e=>{let t=`${e.label??``} ${e.id} ${e.credentialKind} ${e.status}`.toLowerCase();return M.split(/\s+/).every(e=>t.includes(e))}):t,[t,M]),ne=(0,Q.useMemo)(()=>{let e=C.slice(0,C.lastIndexOf(`-`)),t=C.endsWith(`-desc`)?-1:1,n=[...N];return n.sort((n,r)=>t*xr(n,r,e)),n},[N,C]),P=(0,Q.useMemo)(()=>t.filter(e=>e.kind!==`pool`&&x.has(e.id)),[t,x]),F=N.length>0&&N.every(e=>x.has(e.id)),ie=P.some(e=>e.status===`disabled`),I=P.some(e=>e.status!==`disabled`),L=P.length===0,R=(0,Q.useMemo)(()=>t.filter(_r),[t]),z=(0,Q.useMemo)(()=>t.filter(vr),[t]),ue=(e,t)=>{S(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},de=()=>{S(e=>{let t=new Set(e);if(F)for(let e of N)t.delete(e.id);else for(let e of N)e.kind!==`pool`&&t.add(e.id);return t})},fe=async(e,t)=>{if(P.length===0)return;E(!0);let n=await yn(P,me,t),r=n.filter(e=>e.status===`rejected`).length,i=n.length-r;E(!1),r===0?g.success(`${e} complete`,`${i} account${i===1?``:`s`}`):g.error(`${e} partially failed`,`${i} succeeded, ${r} failed`)},B=()=>fe(`Recover`,t=>u.mutateAsync({providerId:e,accountId:t.id})),me=3,he=async()=>{let e=t.filter(e=>e.kind!==`pool`);e.length!==0&&(E(!0),O({done:0,total:e.length}),await yn(e,3,async(e,n)=>{let r=await pe(`/accounts/${encodeURIComponent(e.id)}/quota/refresh`,{method:`POST`});return O({done:n+1,total:t.length}),r}),await Promise.all([o.invalidateQueries({queryKey:V.quota.all}),o.invalidateQueries({queryKey:V.providers.all})]),E(!1),O(null),g.success(`Test complete`,`${e.length} account${e.length===1?``:`s`} tested`))},ge=async t=>{let n=P.filter(e=>e.tenantId!==null),r=P.filter(e=>e.tenantId===null);if(n.length===0&&r.length===0)return;E(!0);let i=0;try{if(n.length>0)try{await s.mutateAsync({ids:n.map(e=>e.id),active:t})}catch{i+=n.length}let e=await yn(r,3,async e=>{try{return await pe(`/global/accounts/${encodeURIComponent(e.id)}`,{method:`PATCH`,body:JSON.stringify({active:t})}),!0}catch{return!1}});i+=e.filter(e=>e.status===`rejected`||e.value===!1).length;let a=P.length-i;i===0?g.success(`${t?`Enable`:`Disable`} complete`,`${a} account${a===1?``:`s`}`):g.error(`${t?`Enable`:`Disable`} partially failed`,`${a} succeeded, ${i} failed`)}finally{await o.invalidateQueries({queryKey:V.providers.accounts(e)}),E(!1)}},_e=async()=>{if(P.length!==0){E(!0);try{let t=await f.mutateAsync({providerId:e,accountIds:P.map(e=>e.id)}),n=new Date().toISOString().replace(/[:.]/g,`-`);G(`${e}-accounts-${n}.json`,JSON.stringify(t,null,2),`application/json`),g.success(`Accounts exported`,`${t.accounts.length} account${t.accounts.length===1?``:`s`} — contains plaintext credentials`)}catch(e){g.error(`Export failed`,e.message??`Unable to export accounts`)}finally{E(!1)}}};return(0,$.jsxs)(X,{gap:`8px`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 border border-inner-border rounded-control bg-surface-2`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 p-2`,children:[(0,$.jsxs)(`label`,{className:`relative min-w-44 flex-1`,children:[(0,$.jsx)(se,{size:13,"aria-hidden":`true`,className:`pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary`}),(0,$.jsx)(J,{id:`accounts-search`,value:y,onChange:e=>b(e.target.value),placeholder:`Search accounts...`,"aria-label":`Search accounts`,className:`pl-9 h-15 py-0`})]}),(0,$.jsx)(`label`,{className:`inline-flex h-15 shrink-0 items-center [&_.radix-select-trigger]:font-semibold [&_.radix-select-trigger]:bg-hover [&_.radix-select-trigger]:text-text-primary`,children:(0,$.jsx)(Y,{size:`sm`,value:C,onValueChange:e=>w(e),options:br,"aria-label":`Sort accounts by`})}),(0,$.jsxs)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:F,onChange:de,"aria-label":`Select accounts`}),(0,$.jsx)(`span`,{children:`Select`})]}),L?null:(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(new Set),className:`inline-flex h-15 shrink-0 items-center gap-1 rounded-control border border-inner-border px-3 text-badge font-semibold text-text-secondary hover:bg-hover`,title:`Clear selection`,children:[P.length,` selected`,(0,$.jsx)(re,{size:11,"aria-hidden":`true`})]})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-t border-inner-border p-2`,children:[(0,$.jsx)(h,{size:`sm`,variant:`primary`,icon:(0,$.jsx)(p,{size:12}),disabled:T||t.length===0,onClick:he,"aria-label":D===null?`Test all accounts`:`Testing accounts, ${D.done} of ${D.total} tested`,title:`Test every account, regardless of selection or filters`,children:D===null?`Test all`:`Tested ${D.done}/${D.total}`}),r?(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(p,{size:12,className:i?`animate-spin`:``}),disabled:i||t.length===0,onClick:()=>a?.(P.map(e=>e.id)),title:L?`Probe every Grok account with the live 407 streaming request`:`Probe only the ${P.length} selected Grok account${P.length===1?``:`s`}`,children:i?`Testing…`:`Test 407`}):null,(0,$.jsx)(`span`,{className:`min-w-2 flex-1`}),(0,$.jsxs)(`div`,{className:`hidden items-center gap-2 lg:flex`,children:[(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(oe,{size:12}),disabled:T||L,title:L?`Select at least one account`:`Clear cooldowns and retry-wait states on the selected accounts`,onClick:()=>void B(),children:`Recover`}),(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(At,{size:12}),disabled:T||!ie,title:ie?`Enable the selected accounts`:`No selected account is currently disabled`,onClick:()=>void ge(!0),children:`Enable`}),(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(ae,{size:12}),disabled:T||!I,title:I?`Disable the selected accounts`:`No selected account is currently enabled`,onClick:()=>void ge(!1),children:`Disable`}),(0,$.jsx)(h,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(d,{size:12}),disabled:T||L,title:L?`Select at least one account`:`Download the selected accounts as JSON`,onClick:()=>void _e(),children:`Export`}),(0,$.jsx)(h,{size:`sm`,variant:`danger`,icon:(0,$.jsx)(ce,{size:12}),disabled:T||L,title:`Delete ${P.length} selected account${P.length===1?``:`s`}`,onClick:()=>A(!0),children:`Delete`})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-2 lg:hidden`,children:(0,$.jsxs)(Sr,{label:`Selection`,disabled:T||L,title:L?`Select at least one account`:`Actions for the selected accounts`,children:[(0,$.jsx)(Cr,{label:`Recover`,icon:(0,$.jsx)(oe,{size:12}),disabled:T||L,title:`Clear cooldowns and retry-wait states on the selected accounts`,onClick:()=>void B()}),(0,$.jsx)(Cr,{label:`Enable`,icon:(0,$.jsx)(At,{size:12}),disabled:T||!ie,title:ie?`Enable the selected accounts`:`No selected account is currently disabled`,onClick:()=>void ge(!0)}),(0,$.jsx)(Cr,{label:`Disable`,icon:(0,$.jsx)(ae,{size:12}),disabled:T||!I,title:I?`Disable the selected accounts`:`No selected account is currently enabled`,onClick:()=>void ge(!1)}),(0,$.jsx)(Cr,{label:`Export`,hint:`JSON`,icon:(0,$.jsx)(d,{size:12}),disabled:T||L,title:`Download the selected accounts as JSON`,onClick:()=>void _e()}),(0,$.jsx)(`div`,{className:`mx-2 my-1 h-px bg-inner-border`}),(0,$.jsx)(Cr,{label:`Delete`,icon:(0,$.jsx)(ce,{size:12}),danger:!0,disabled:T||L,title:`Delete ${P.length} selected account${P.length===1?``:`s`}`,onClick:()=>A(!0)})]})}),(0,$.jsxs)(Sr,{label:R.length+z.length>0?`Cleanup (${R.length+z.length})`:`Cleanup`,disabled:T||R.length===0&&z.length===0,title:`Provider-wide actions. Counts ignore the current search and selection.`,children:[(0,$.jsx)(Cr,{label:`Disable cooldown`,hint:String(R.length),icon:(0,$.jsx)(ae,{size:12}),disabled:T||c.isPending||R.length===0,title:R.length===0?`No account is currently cooling down`:`Disable ${R.length} account(s) in cooldown (account-wide or per-model)`,onClick:()=>{c.mutateAsync({providerId:e})}}),(0,$.jsx)(Cr,{label:`Delete banned`,hint:String(z.length),icon:(0,$.jsx)(ce,{size:12}),danger:!0,disabled:T||l.isPending||z.length===0,title:z.length===0?`No policy-banned account to delete`:`Permanently delete ${z.length} policy-banned account(s)`,onClick:()=>j(!0)})]})]})]}),(0,$.jsx)(`div`,{className:`account-list flex flex-col gap-3 max-h-230 overflow-y-auto pr-1 [container-type:inline-size] [container-name:account-list]`,role:`list`,"aria-label":`Provider accounts`,children:ne.length===0?(0,$.jsx)(te,{compact:!0,icon:(0,$.jsx)(se,{size:20}),title:`No matching accounts`,message:M?`Nothing matches “${M}”. Clear the filter to see all ${t.length} account${t.length===1?``:`s`}.`:`This provider has no accounts yet.`}):ne.map(t=>(0,$.jsx)(Hn,{providerId:e,account:t,inflight:m.get(t.id)??t.inflight,quota:v.get(t.id),selected:x.has(t.id),onToggleSelect:ue,onDelete:n},t.id))}),(0,$.jsx)(`div`,{className:`flex items-center justify-between text-badge text-text-tertiary`,children:(0,$.jsxs)(`span`,{children:[`Showing `,N.length,` account`,N.length===1?``:`s`,M?` (filtered from ${t.length})`:``]})}),(0,$.jsx)(ve,{open:k,onClose:()=>{T||A(!1)},onConfirm:async()=>{let t=P.filter(e=>e.tenantId!==null),n=P.filter(e=>e.tenantId===null),r=e=>{for(let t of e)o.removeQueries({queryKey:V.quota.account(t),exact:!0})};try{t.length>0&&r((await pe(`/accounts/batch-delete`,{method:`POST`,body:JSON.stringify({accountIds:t.map(e=>e.id)})})).deleted),n.length>0&&r((await pe(`/global/accounts/batch-delete`,{method:`POST`,body:JSON.stringify({accountIds:n.map(e=>e.id)})})).deleted),S(new Set),A(!1),g.success(`Deleted accounts`,`${P.length} account${P.length===1?``:`s`}`)}catch(e){g.error(`Delete partially failed`,e.message??`Unable to delete accounts`)}finally{await Promise.all([o.invalidateQueries({queryKey:V.providers.accounts(e)}),o.invalidateQueries({queryKey:V.providers.all}),o.invalidateQueries({queryKey:V.quota.all})])}},title:`Delete ${P.length} account${P.length===1?``:`s`}?`,message:`This permanently removes the selected accounts and their credentials. This cannot be undone.`,confirmLabel:`Delete`,danger:!0}),(0,$.jsx)(ve,{open:ee,onClose:()=>{l.isPending||j(!1)},onConfirm:async()=>{try{await l.mutateAsync({providerId:e}),j(!1)}catch{}},title:`Delete ${z.length} banned account${z.length===1?``:`s`}?`,message:`This permanently removes ${z.length} disabled account(s) whose last failure was policy_blocked_banned, including their credentials and quota history. This cannot be undone. Accounts disabled for other reasons are left alone.`,confirmLabel:`Delete banned`,danger:!0})]})}function Tr(e){let t=e.trim(),n=e=>{try{return new URL(e).searchParams}catch{return}},r=n(t)??new URLSearchParams(t.startsWith(`?`)?t.slice(1):t),i=r.get(`code`);if(i)return{code:i};let a=r.get(`error_description`)??r.get(`error`);return a?{error:`The provider refused the login: ${a}`}:r.has(`authCodeInfo`)||r.has(`refreshToken`)||r.has(`refresh_token`)?{code:r.toString()}:n(t)!==void 0||t.startsWith(`?`)?{error:`That redirect URL carries no authorization code — copy the full URL from the address bar.`}:{code:t}}function Er({providerId:e,authorizeUrl:t,state:n,popup:r,onClose:i}){let[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),[l,d]=(0,Q.useState)(!1),p=Pe(),m=Et(),v=le(),y=Ke(e),b=(0,Q.useRef)(null),x=(0,Q.useRef)(!1),[S,C]=(0,Q.useState)(!0);(0,Q.useEffect)(()=>{let t=setInterval(()=>{v.invalidateQueries({queryKey:V.providers.accounts(e)})},1500);return()=>clearInterval(t)},[v,e]),(0,Q.useEffect)(()=>{let t=!1;return v.invalidateQueries({queryKey:V.providers.accounts(e)}).finally(()=>{t||C(!1)}),()=>{t=!0}},[v,e]),(0,Q.useEffect)(()=>{if(S)return;let e=y.data?.map(e=>e.id)??null;if(e!==null){if(b.current===null){b.current=new Set(e);return}x.current||e.find(e=>!b.current.has(e))!==void 0&&(x.current=!0,r.close(),g.success(`Account connected`,`OAuth login completed successfully`),i(!0))}},[y.data,S,r,i]);let w=()=>{r.close(),i(!1)},[T,E]=(0,Q.useState)(!1),D=()=>{E(!0),v.invalidateQueries({queryKey:V.providers.accounts(e)}).finally(()=>E(!1))},O=async()=>{try{let e=await navigator.clipboard.readText();if(!e.trim()){g.error(`Clipboard is empty`);return}c(e),g.success(`Pasted redirect URL`)}catch{g.error(`Clipboard unavailable on this origin`)}},k=e=>{let t=new FileReader;t.onload=()=>{let n=typeof t.result==`string`?t.result.trim():``;if(!n){g.error(`Empty file`,`"${e.name}" contained no URL to connect with.`);return}let r=Tr(n);if(`error`in r){c(``),g.error(`Invalid OAuth paste`,r.error);return}c(n),g.success(`Loaded redirect URL`,`Read from ${e.name}`)},t.onerror=()=>g.error(`Could not read file`,`Failed to read "${e.name}".`),t.readAsText(e)};return(0,$.jsx)(F,{open:!0,onClose:w,title:`Connect via OAuth`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:w,disabled:p.isPending,children:`Cancel`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:D,disabled:p.isPending||T,title:`You already approved in the popup — check now instead of waiting`,children:T?`Checking…`:`Complete`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,disabled:p.isPending||s.trim().length===0,onClick:()=>{let t=Tr(s);if(`error`in t){c(``),g.error(`OAuth callback failed`,t.error);return}p.mutate({providerId:e,code:t.code,state:n},{onSuccess:()=>{r.close(),g.success(`Account connected`,`OAuth login completed successfully`),i(!0)},onError:e=>g.error(`OAuth callback failed`,e.message??`Invalid or expired authorization code`)})},children:p.isPending?`Connecting…`:`Connect`})]}),children:(0,$.jsxs)(X,{gap:`14px`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3.5 py-2.5 rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsx)(f,{size:16,className:`animate-spin text-accent shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Waiting for popup authorization…`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 1: Open this URL in your browser`}),(0,$.jsxs)(Z,{gap:`8px`,children:[(0,$.jsx)(`a`,{className:`min-w-0 flex-1 font-mono text-badge text-accent overflow-hidden text-ellipsis whitespace-nowrap px-2.5 py-2 rounded-control bg-input-bg border border-inner-border`,href:t,target:`_blank`,rel:`noreferrer`,title:t,children:t}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:a?(0,$.jsx)(_,{size:12}):(0,$.jsx)(u,{size:12}),onClick:()=>{navigator.clipboard?.writeText(t),o(!0),m(()=>o(!1),1500)},className:`shrink-0`,children:a?`Copied`:`Copy`})]}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:`A popup should open automatically. If it was blocked, open the URL above manually.`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 text-micro font-bold uppercase tracking-label text-text-tertiary`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`flex-1 h-px bg-inner-border`}),(0,$.jsx)(`span`,{children:`Or complete manually`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`flex-1 h-px bg-inner-border`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 2: Paste the redirect URL here`}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:`If the redirect lands on an unreachable address, copy that page's full URL from your browser and paste it below — this works from any machine, not just localhost.`}),(0,$.jsxs)(Z,{gap:`8px`,align:`flex-start`,children:[(0,$.jsx)(`div`,{className:`flex-1 min-w-0 rounded-control border-2 border-dashed transition-colors ${l?`border-accent bg-accent-soft`:``}`,"data-drag-active":l?`true`:void 0,onDragOver:e=>{e.preventDefault(),d(!0)},onDragLeave:()=>d(!1),onDrop:e=>{e.preventDefault(),d(!1);let t=e.dataTransfer.files[0];if(t){k(t);return}let n=e.dataTransfer.getData(`text/plain`);if(!n||!n.trim())return;let r=n.trim(),i=Tr(r);if(`error`in i){c(``),g.error(`Invalid OAuth paste`,i.error);return}c(r),g.success(`Loaded redirect URL`,`Dropped URL text`)},children:(0,$.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`http://127.0.0.1:59653/callback?code=…&state=… (or just the code)`,rows:2,spellCheck:!1,className:`w-full min-h-16 resize-y rounded-control border border-inner-border bg-input-bg px-2.5 py-2 font-mono text-badge text-text-primary box-border focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1`})}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:()=>void O(),className:`shrink-0`,children:`Paste`})]}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:`Or drag a file — or select the redirect URL and drag it here — a saved redirect URL or raw code is read straight into the field.`})]})]})})}function Dr(e){try{return new URL(e).host}catch{return e}}function Or({providerId:e,parameters:t,onClose:n}){let r=Fe(),i=Me(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,d]=(0,Q.useState)(!1),p=Et();(0,Q.useEffect)(()=>{let i=!1;return r.mutate({providerId:e,...t===void 0||Object.keys(t).length===0?{}:{parameters:t}},{onSuccess:e=>{i||o(e)},onError:e=>{i||(g.error(`Failed to start device login`,e.message??`Unable to start device authorization`),n())}}),()=>{i=!0}},[]);let m=(0,Q.useRef)(null),[v,y]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{if(!a)return;let e=window.open(a.verificationUri,`cartethyia-device`,`popup,width=720,height=820`);return e?m.current=e:y(!0),()=>{let e=m.current;m.current=null,e&&!e.closed&&e.close()}},[a]),(0,Q.useEffect)(()=>{if(!a)return;let t=Date.now(),r=Math.max(1,a.expiresInSeconds)*1e3,o=!1,s=Math.max(1,a.intervalSeconds)*1e3,c=!1,l=0,u=()=>window.clearTimeout(l),d=e=>{u(),l=window.setTimeout(f,e)},f=()=>{if(!c){if(Date.now()-t>r){u(),g.error(`Device login expired`,`Please try again.`),n();return}o||(o=!0,i.mutate({providerId:e,deviceAuthId:a.deviceAuthId},{onSuccess:e=>{if(o=!1,!c){if(e.status===`complete`){u();let e=m.current;e&&!e.closed&&e.close(),g.success(`OAuth account connected`,`Device authorization complete`),n()}else e.status===`failed`?(u(),g.error(`Device login failed`,e.reason),n()):e.status===`slow_down`?(s=(e.retryAfterSeconds===void 0?s+5e3:Math.max(1,e.retryAfterSeconds)*1e3)+1e3,d(s)):(e.status===`pending`&&e.retryAfterSeconds!==void 0&&(s=Math.max(1,e.retryAfterSeconds)*1e3+1e3),d(s))}},onError:e=>{if(o=!1,c)return;u();let t=e.message;g.error(`Device login failed`,t??`The device flow ended without a result.`),n()}}))}};return d(s+1e3),()=>{c=!0,u()}},[a]),(0,$.jsx)(F,{open:!0,onClose:n,title:`Login with OAuth (device code)`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:n,children:`Cancel`}),null]}),children:(0,$.jsx)(X,{gap:`14px`,children:a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3.5 py-2.5 rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsx)(f,{size:16,className:`animate-spin text-accent shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Waiting for authorization…`})]}),a.userCode?(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 1: Enter this code`}),(0,$.jsxs)(`div`,{className:`rounded-card border border-inner-border bg-surface-2 p-3.5 flex flex-col gap-1.5 items-center text-center`,children:[(0,$.jsx)(`div`,{className:`text-micro font-bold uppercase tracking-label text-text-tertiary`,children:`Device code`}),(0,$.jsx)(`div`,{className:`font-mono text-display font-bold tracking-code text-text-primary`,children:a.userCode}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:l?(0,$.jsx)(_,{size:12}):(0,$.jsx)(u,{size:12}),onClick:()=>{navigator.clipboard?.writeText(a.userCode),d(!0),p(()=>d(!1),1500)},children:l?`Copied`:`Copy code`})]})]}):null,(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:a.userCode?`Step 2: Open the verification page`:`Open the verification page to authorize`}),(0,$.jsxs)(Z,{gap:`8px`,children:[(0,$.jsx)(`a`,{className:`min-w-0 flex-1 font-mono text-badge text-accent overflow-hidden text-ellipsis whitespace-nowrap px-2.5 py-2 rounded-control bg-input-bg border border-inner-border`,href:a.verificationUri,target:`_blank`,rel:`noreferrer`,title:a.verificationUri,children:Dr(a.verificationUri)}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,icon:(0,$.jsx)(Ne,{size:12}),onClick:()=>window.open(a.verificationUri,`_blank`,`noopener`),className:`shrink-0`,children:`Open`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:s?(0,$.jsx)(_,{size:12}):(0,$.jsx)(u,{size:12}),onClick:()=>{navigator.clipboard?.writeText(a.verificationUri),c(!0),p(()=>c(!1),1500)},className:`shrink-0`,children:s?`Copied`:`Copy`})]}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:v?`The popup was blocked — open the page with Open above, finish signing in there, then press Check now.`:`The page opened in a popup. Finish signing in there — this dialog closes automatically once the account connects, or press Check now.`})]})]}):(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3.5 py-2.5 rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsx)(f,{size:16,className:`animate-spin text-accent shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Starting device authorization…`})]})})})}function kr({providerId:e}){let[t,n]=(0,Q.useState)(!1),r=Ce(e,t);return(0,$.jsxs)(W,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n(e=>!e),"aria-expanded":t,className:`card-header-bar w-full cursor-pointer list-none text-left`,children:[(0,$.jsxs)(`div`,{className:`card-header-left`,children:[(0,$.jsx)(`div`,{className:`card-header-icon`,children:(0,$.jsx)(i,{size:16,"aria-hidden":`true`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`font-bold text-text-primary`,children:`Activity Matrix`}),(0,$.jsxs)(`div`,{className:`text-caption text-text-secondary`,children:[`Daily token usage, last `,r.data?.days??30,` days · expand to load`]})]})]}),(0,$.jsx)(`div`,{className:`card-header-right`,children:(0,$.jsx)(je,{size:14,"aria-hidden":`true`,className:y(`transition-transform`,t&&`rotate-180`)})})]}),t?(0,$.jsx)(Vr,{matrix:r}):null]})}function Ar(e){let t=new Map,n=new Map,r={requests:0,tokens:0,cachedTokens:0,costUsd:0};for(let i of e.rows){let e=t.get(i.day)??{tokens:0,models:new Map},a=i.inputTokens+i.outputTokens;e.tokens+=a;let o=i.model??`unknown`,s=e.models.get(o)??{tokens:0,requests:0};s.tokens+=a,s.requests+=i.requests,e.models.set(o,s),t.set(i.day,e);let c=n.get(o)??{tokens:0,requests:0};c.tokens+=a,c.requests+=i.requests,n.set(o,c),r.requests+=i.requests,r.tokens+=a,r.cachedTokens+=i.cachedInputTokens,r.costUsd+=i.costUsd}let i=Math.min(Math.max(e.days,1),366),a=new Date,o=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()),s=[],c=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],l=0;for(let e of t.values())l=Math.max(l,e.tokens);let u=new Date(o-(i-1)*864e5),d=(u.getUTCDay()+6)%7,f=u.getTime()-d*864e5,p=[];for(;;){if(f>o){if(p.length>0||s.length===0){for(;p.length<7;)p.push(null);s.push({cells:p})}break}let e=new Date(f),n=e.toISOString().slice(0,10),r=t.get(n),i=r?[...r.models.entries()].map(([e,t])=>({name:e,tokens:t.tokens,requests:t.requests,color:jr(e)})).sort((e,t)=>t.tokens-e.tokens):[],a=r?{day:n,label:`${c[(e.getUTCDay()+6)%7]} ${n.slice(5)}`,total:r.tokens,color:i[0]?.color??`var(--surface-2)`,models:i}:null;p.push(a),p.length===7&&(s.push({cells:p}),p=[]),f+=864e5}let m=[...n.entries()].map(([e,t])=>({name:e,tokens:t.tokens,requests:t.requests,color:jr(e)})).sort((e,t)=>t.tokens-e.tokens);return{weeks:s,maxDay:l,totals:r,models:m}}function jr(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33^e.charCodeAt(n);let n=Math.abs(t)%360;return`hsl(${(n<60||n>110?n:n+130)%360} 65% 60%)`}function Mr(e,t){if(e<=0||t<=0)return 0;let n=e/t,r=1;for(let e=1;e<Nr.length;e++)n>e/(Nr.length-1)&&(r=e);return Math.min(r,Nr.length-1)}var Nr=[0,.18,.38,.62,.9];function Pr(e){return Nr[Math.min(Math.max(Math.trunc(e),0),Nr.length-1)]??0}function Fr(e){let t=Pr(e)*100;return t===0?`var(--surface-2)`:`color-mix(in srgb, var(--text-primary) ${t}%, transparent)`}function Ir(e,t){if(t===0)return{backgroundColor:`var(--surface-2)`,borderColor:`var(--inner-border)`};let n=Pr(t)*100;return{backgroundColor:`color-mix(in srgb, ${e.color} ${n}%, transparent)`,borderColor:`color-mix(in srgb, ${e.color} 45%, transparent)`}}function Lr(e){return[`${e.label} — ${$e(e.total)} tokens`,...e.models.map(t=>`• ${t.name}: ${$e(t.tokens)} (${Math.round(t.tokens/e.total*100)}%) · ${t.requests} req`)].join(`
4
+ `)}var Rr=`26px repeat(7, minmax(0, 1fr))`,zr=420,Br=360;function Vr({matrix:e}){let t=(0,Q.useMemo)(()=>e.data?Ar(e.data):void 0,[e.data]),n;return n=e.isPending?(0,$.jsx)(`p`,{className:`p-4 text-caption text-text-secondary`,children:`Loading activity…`}):e.isError?(0,$.jsx)(`p`,{className:`p-4 text-caption text-status-danger`,children:`Failed to load activity matrix.`}):!t||t.totals.requests===0?(0,$.jsx)(`p`,{className:`p-4 text-caption text-text-secondary`,children:`No usage recorded for this provider in the window.`}):(0,$.jsx)(Ur,{view:t}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`border-t border-inner-border`,children:(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 p-4 max-small:p-3 min-[641px]:grid-cols-4`,children:[(0,$.jsx)(Hr,{label:`Total tokens`,value:$e(t?.totals.tokens)}),(0,$.jsx)(Hr,{label:`Requests`,value:(t?.totals.requests??0).toLocaleString(`en-US`)}),(0,$.jsx)(Hr,{label:`Cached`,value:$e(t?.totals.cachedTokens)}),(0,$.jsx)(Hr,{label:`Est. cost`,value:E(t?.totals.costUsd)})]})}),(0,$.jsxs)(`div`,{className:`min-w-0 overflow-x-auto border-t border-inner-border p-4 max-small:p-3`,children:[n,t&&t.totals.requests>0?(0,$.jsxs)(`div`,{className:`mt-3 flex items-center justify-end gap-1.5 text-micro text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`Less`}),[0,1,2,3,4].map(e=>(0,$.jsx)(`span`,{className:`size-3 rounded-micro border border-inner-border`,style:{backgroundColor:Fr(e)}},e)),(0,$.jsx)(`span`,{children:`More`})]}):null,t&&t.totals.requests>0&&t.models.length>0?(0,$.jsxs)(`details`,{className:`group mt-4 border-t border-inner-border pt-3`,children:[(0,$.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center justify-between gap-3 text-caption text-text-secondary [&::-webkit-details-marker]:hidden`,children:[(0,$.jsxs)(`span`,{className:`font-semibold`,children:[`Usage by model (`,t.models.length,`) · sorted by tokens`]}),(0,$.jsx)(je,{size:14,"aria-hidden":`true`,className:`shrink-0 transition-transform group-open:rotate-180`})]}),(0,$.jsx)(`div`,{className:`mt-3 flex flex-col gap-2.5`,children:t.models.map(e=>{let n=t.totals.tokens>0?e.tokens/t.totals.tokens:0;return(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`min-w-0 shrink truncate text-caption font-semibold`,style:{color:e.color},title:e.name,children:e.name}),(0,$.jsx)(`span`,{className:`h-2.5 min-w-0 flex-1 rounded-micro`,style:{backgroundColor:`var(--surface-2)`,backgroundImage:`linear-gradient(to right, ${e.color} ${Math.max(n*100,2)}%, transparent ${Math.max(n*100,2)}%)`}}),(0,$.jsxs)(`span`,{className:`shrink-0 font-mono text-caption text-text-secondary`,children:[$e(e.tokens),` `,(0,$.jsxs)(`span`,{className:`text-text-tertiary`,children:[Math.round(n*100),`%`]}),` ·`,` `,e.requests.toLocaleString(`en-US`),` req`]})]},e.name)})})]}):null]})]})}function Hr({label:e,value:t}){return(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-micro font-semibold uppercase tracking-label text-text-tertiary`,children:e}),(0,$.jsx)(`div`,{className:`mt-0.5 font-mono text-lg font-bold text-text-primary`,children:t})]})}function Ur({view:e}){return(0,$.jsx)(`div`,{style:{minWidth:Br},children:(0,$.jsxs)(`div`,{className:`grid gap-1`,style:{gridTemplateColumns:Rr,maxWidth:zr},children:[(0,$.jsx)(`div`,{}),[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`].map(e=>(0,$.jsx)(`div`,{className:`text-center text-micro text-text-tertiary`,children:e},e)),e.weeks.map((t,n)=>(0,$.jsxs)(`div`,{className:`contents`,children:[(0,$.jsxs)(`div`,{className:`flex items-center text-micro text-text-tertiary`,children:[`W`,n+1]}),t.cells.map((t,r)=>t===null?(0,$.jsx)(`div`,{},`${n}-${r}`):(0,$.jsx)(`div`,{className:`aspect-square cursor-pointer rounded-micro border border-inner-border transition-[outline-offset] hover:outline hover:outline-2 hover:outline-accent`,style:Ir(t,Mr(t.total,e.maxDay)),title:Lr(t)},t.day))]},n))]})})}function Wr(e){let t={};for(let n of e)t[n.key]=n.defaultValue??``;return t}function Gr(e,t){return e.filter(e=>e.required===!0&&(t[e.key]??``).trim().length===0).map(e=>e.key)}function Kr({fields:e,values:t,onChange:n,idPrefix:r}){return e.length===0?null:(0,$.jsx)(X,{gap:`10px`,children:e.map(e=>{let i=`${r}-${e.key}`,a=t[e.key]??``;return e.options&&e.options.length>0?(0,$.jsx)(Y,{id:i,label:e.label,value:a,onValueChange:t=>n(e.key,t),options:e.options.map(e=>({value:e.value,label:e.label}))},e.key):(0,$.jsx)(J,{id:i,label:e.label,value:a,placeholder:e.placeholder??``,type:e.secret===!0?`password`:`text`,autoComplete:`off`,onChange:t=>n(e.key,t.target.value)},e.key)})})}function qr({providerId:e,providerName:t,fields:n,onClose:r}){let i=Ie(),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1),[d,p]=(0,Q.useState)(()=>Wr(n)),m=(0,Q.useMemo)(()=>Gr(n,d),[n,d]);return(0,$.jsx)(F,{open:!0,onClose:r,title:`Import a ${t} credential`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:r,disabled:i.isPending,children:`Cancel`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,onClick:()=>{if(a.trim().length===0){g.error(`Credential required`,`Paste the token, key or exported JSON to import.`);return}if(m.length>0){g.error(`Missing required fields`,`Fill in: ${m.join(`, `)}`);return}i.mutate({providerId:e,credential:a.trim(),...Object.keys(d).length>0?{fields:d}:{},...s.trim().length>0?{accountLabel:s.trim()}:{}},{onSuccess:()=>{g.success(`Account imported`,`The credential was validated and saved`),r()},onError:e=>g.error(`Import failed`,e.message??`The provider rejected this credential`)})},disabled:i.isPending,icon:i.isPending?(0,$.jsx)(f,{size:13,className:`animate-spin`}):void 0,children:i.isPending?`Validating…`:`Import`})]}),children:(0,$.jsxs)(X,{gap:`12px`,children:[(0,$.jsxs)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:[`The credential is checked against `,t,` before it is saved, so one that no longer works is reported here instead of being stored.`]}),(0,$.jsx)(Kr,{fields:n,values:d,idPrefix:`import`,onChange:(e,t)=>p(n=>({...n,[e]:t}))}),(0,$.jsx)(J,{id:`import-account-label`,label:`Account label`,hint:`optional`,value:s,placeholder:e,onChange:e=>c(e.target.value)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`rounded-control border-2 border-dashed transition-colors ${l?`border-accent bg-accent-soft`:``}`,"data-drag-active":l?`true`:void 0,onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:e=>{e.preventDefault(),u(!1);let t=e.dataTransfer.files[0];if(t){let e=new FileReader;e.onload=()=>{let n=typeof e.result==`string`?e.result.trim():``;n&&(o(n),g.success(`Loaded credential file`,`Read from ${t.name}`))},e.onerror=()=>g.error(`Could not read file`,`Failed to read "${t.name}".`),e.readAsText(t);return}let n=e.dataTransfer.getData(`text/plain`);n&&n.trim()&&(o(n.trim()),g.success(`Dropped credential text`))},children:(0,$.jsx)(J,{id:`import-credential`,label:`Credential`,value:a,placeholder:`Paste the token, key, or exported JSON`,type:`password`,autoComplete:`off`,onChange:e=>o(e.target.value)})}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:`Or select the token/key and drag it here — same as pasting.`})]})]})})}var Jr=2e4,Yr=1e4,Xr=`How are you?`,Zr=`What model are you, and what is your knowledge cutoff date? Answer in one sentence.`;function Qr(){let e=it(),t=rt(),[n,r]=(0,Q.useState)(!1);return{test:(0,Q.useCallback)(async(n,i,a={})=>{let o=a.fast===!0,s=(e.data??[]).find(e=>e.enabled&&e.revokedAt===void 0&&e.isDefault);if(s===void 0)return{ok:!1,latencyMs:0,error:`The default gateway API key is unavailable.`};let c;try{({secret:c}=await t.mutateAsync({keyId:s.id}))}catch(e){return{ok:!1,latencyMs:0,error:e.message??`Failed to reveal the default API key.`}}let l=new AbortController,u=setTimeout(()=>l.abort(),o?Yr:Jr),d=performance.now();r(!0);try{let e=await fetch(`/v1/chat/completions`,{method:`POST`,credentials:`same-origin`,signal:l.signal,headers:{Accept:`application/json`,"Content-Type":`application/json`,Authorization:`Bearer ${c}`},body:JSON.stringify({model:n,messages:[{role:`user`,content:o?Xr:Zr}],...o?{max_tokens:64}:i===void 0?{}:{max_tokens:i},stream:!1})}),t=await e.text(),r=null;try{r=JSON.parse(t)}catch{r=null}let a=Math.round(performance.now()-d);if(!e.ok){let t=r?.error;return{ok:!1,latencyMs:a,error:typeof t?.message==`string`?t.message:`Gateway responded with HTTP ${e.status}`}}let s=(Array.isArray(r?.choices)?r?.choices:[])[0]?.message,u=typeof s?.content==`string`?s.content.trim():``,f=o?u.slice(0,80):u,p=typeof r?.model==`string`?r.model:void 0;return{ok:!0,latencyMs:a,...f.length>0?{sample:f}:{},...p===void 0?{}:{reportedModel:p}}}catch(e){let t=e instanceof DOMException&&e.name===`AbortError`;return{ok:!1,latencyMs:Math.round(performance.now()-d),error:t?`The model test timed out.`:e.message??`Network error during model test.`}}finally{clearTimeout(u),r(!1)}},[e.data,t]),testing:n}}function $r(e){return e===`builtin`?`Built-in model`:e===`auto_free`?`Free tier, discovered from the provider`:e===`discovered`?`Fetched from provider`:`Added manually`}function ei(e){return e===`auto_free`?`Free tier`:e===`discovered`?`Fetched`:`Manual`}var ti=[{key:`builtin`,label:`Built-in models`,hint:`Compiled catalog — can be disabled, not deleted`,matches:e=>e===null||e===`builtin`},{key:`auto_free`,label:`Free models (auto)`,hint:`Discovered from the provider's free tier`,matches:e=>e===`auto_free`},{key:`manual`,label:`Manually added`,hint:`Added by hand from the Add Model dialog`,matches:e=>e===`manual`},{key:`fetched`,label:`Fetched from provider`,hint:`Listed by the provider's /v1/models`,matches:e=>e!==null&&e!==`builtin`&&e!==`auto_free`&&e!==`manual`}],ni={key:`disabled`,label:`Disabled models`,hint:`Turned off — not routable until re-enabled`};function ri(e){return e.some(e=>e.severity===`critical`)?`critical`:e.some(e=>e.severity===`warn`)?`warn`:`info`}function ii(e){return e.map(e=>`[${e.severity??`warn`}] ${e.kind}: ${e.message}`).join(`
5
+ `)}var ai={info:`text-status-info`,warn:`text-orange`,critical:`text-red`};function oi(){return Lt.map(e=>({value:e,label:e===`auto`?`Thinking: auto`:e.charAt(0).toUpperCase()+e.slice(1)}))}function si({value:e,onChange:t,disabled:n,size:r=`md`,id:i=`probe-thinking-effort`}){return(0,$.jsx)(`div`,{title:`Reasoning effort every test in this section sends. Auto leaves the model's own reasoning default in place.`,className:`min-w-74 shrink-0 max-sm:min-w-56`,children:(0,$.jsx)(Y,{id:i,"aria-label":`Thinking effort`,value:e,disabled:n,size:r,onValueChange:e=>t(e),options:oi()})})}function ci(){return[{value:`all`,label:`All models`},{value:`free`,label:`Free tier`}]}function li({value:e,onChange:t,disabled:n,size:r=`md`,id:i=`models-show-filter`}){return(0,$.jsx)(`div`,{title:`Which models to show. Free tier hides every row the provider does not publish as free.`,className:`min-w-46 shrink-0 max-sm:min-w-40`,children:(0,$.jsx)(Y,{id:i,"aria-label":`Show models`,value:e,disabled:n,size:r,onValueChange:e=>t(e),options:ci()})})}function ui(e,t){let n=t.trim();return n.toLowerCase().startsWith(`${e.toLowerCase()}/`)&&n.length>e.length+1?n.slice(e.length+1):n}function di({providerId:e,provider:t,onClose:n,onSwitchToProvider:r}){let i=We(),a=ge(),[o,s]=(0,Q.useState)(``),c=t?.supportedWireFamilies,l=t?.wireFamilyDefault!==void 0&&(c===void 0||c.includes(t.wireFamilyDefault))?t.wireFamilyDefault:c?.[0],u=(0,Q.useMemo)(()=>{let e=[`chat`,`responses`,`messages`],t=(c??[]).filter(t=>e.includes(t));return[...t,...e.filter(e=>!t.includes(e))]},[c]),[d,m]=(0,Q.useState)(l??`chat`),[_,v]=(0,Q.useState)(`auto`),[y,b]=(0,Q.useState)(`idle`),[x,S]=(0,Q.useState)(``),[C,w]=(0,Q.useState)(null),[T,E]=(0,Q.useState)(vi),D=o.trim(),O=ui(e,D),k=O!==D,A=()=>{O&&(b(`testing`),S(``),w(null),i.mutate({providerId:e,request:{modelId:O,wireFamily:d,reasoningEffort:_,serviceKind:`llm`}},{onSuccess:e=>{e.ok?(b(`passed`),w(e.providerMetadata??null)):(b(`failed`),S(e.error??`Model probe failed`))},onError:e=>{b(`failed`),S(e.message??`Model probe failed`)}}))};return(0,$.jsx)(F,{open:!0,onClose:n,title:`Add Custom Model`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[r?(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:r,children:`From provider`}):null,(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:n,disabled:a.isPending,children:`Cancel`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,disabled:a.isPending||O.length===0,onClick:()=>{if(!O)return;let t=Je(T.contextLimit),r=Je(T.outputLimit);if(t===null||r===null){g.error(`Invalid limits`,`Use a token count such as 512k, 200000, or 1.5m.`);return}a.mutate({providerId:e,modelIds:[O],wireFamily:d,metadata:{contextLimit:t??null,outputLimit:r??null,passthrough:T.passthrough,image:T.passthrough?!0:T.image,reasoning:T.passthrough?!0:T.reasoning,toolCall:T.passthrough?!0:T.toolCall}},{onSuccess:()=>{g.success(`Custom model added`,`Sent to ${e}/${O}`),n()},onError:e=>g.error(`Failed to add model`,e.message??`Unable to register model`)})},children:a.isPending?`Adding...`:`Add Model`})]}),children:(0,$.jsxs)(X,{gap:`10px`,children:[(0,$.jsxs)(Z,{gap:`8px`,align:`flex-end`,children:[(0,$.jsx)(J,{label:`Model ID`,autoFocus:!0,placeholder:`e.g. gpt-4o, free-model-id`,value:o,onChange:e=>{s(e.target.value),b(`idle`),S(``)},onKeyDown:e=>{e.key===`Enter`&&O.length>0&&A()},className:`flex-1`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:y===`testing`?(0,$.jsx)(f,{size:13,className:`animate-spin`}):(0,$.jsx)(p,{size:13}),disabled:i.isPending||O.length===0,onClick:A,className:`shrink-0`,children:y===`testing`?`Testing...`:`Test`})]}),k&&(0,$.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Using `,(0,$.jsx)(`span`,{className:`font-mono tabular-nums`,children:O}),` (provider prefix removed).`]}),(0,$.jsx)(Y,{label:`Wire family`,id:`add-model-wire-family`,value:d,onValueChange:e=>{m(e),b(`idle`),S(``)},options:u.map(e=>({value:e,label:Ti(e)}))}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Thinking`}),(0,$.jsx)(si,{id:`add-model-thinking-effort`,value:_,onChange:e=>{v(e),b(`idle`),S(``)},disabled:i.isPending}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:`Sent with the test. Auto leaves the model's own reasoning default in place.`})]}),(0,$.jsx)(yi,{draft:T,onChange:E,idPrefix:`add-model`,disabled:a.isPending}),c!==void 0&&!c.includes(d)&&(0,$.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`This provider does not declare the`,` `,(0,$.jsx)(`span`,{className:`font-mono tabular-nums`,children:Ti(d)}),` wire. The request is sent as chosen; the upstream decides whether it answers.`]}),y===`passed`&&(0,$.jsxs)(ut,{tone:`success`,live:`status`,children:[`Model test passed — ready to add.`,C!==null&&(0,$.jsx)(`span`,{className:`grid gap-1 mt-2 min-w-0`,children:Object.entries(C).filter(([,e])=>e!=null&&e!==``).map(([e,t])=>(0,$.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`shrink-0 text-micro text-text-tertiary`,children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-micro text-text-secondary`,title:String(t),children:String(t)})]},e))})]}),y===`failed`&&(0,$.jsx)(ut,{tone:`danger`,live:`alert`,children:x||`Model test failed.`})]})})}function fi(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.modelId.toLowerCase().includes(n)):e}function pi({providerId:e,onClose:t,onManual:n}){let r=ke(e),i=Be(),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)([]),l=r.data?.candidates??[],u=r.data?.supported===!1,d=(0,Q.useMemo)(()=>fi(l,a),[l,a]),f=e=>{c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},p=s.length>0&&!i.isPending&&!u,m=()=>{p&&i.mutate({providerId:e,modelIds:s},{onSuccess:()=>t(),onError:e=>g.error(`Failed to add models`,e.message??`Unable to commit models`)})},v=r.data?.accountLabel?`Using account ${r.data.accountLabel}`:`Using the first usable account`;return(0,$.jsx)(F,{open:!0,onClose:t,title:`Add Model`,size:`lg`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:n,children:`Add manually`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:t,disabled:i.isPending,children:`Cancel`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,disabled:!p,onClick:m,title:s.length===0?`Select at least one model`:`Add ${s.length} model(s)`,children:i.isPending?`Adding...`:`Add selected (${s.length})`})]}),children:(0,$.jsxs)(X,{gap:`10px`,children:[(0,$.jsxs)(`div`,{className:`text-badge text-text-tertiary`,"data-testid":`discover-account-label`,children:[v,` · configs follow the provider listing.`]}),u?(0,$.jsxs)(ut,{tone:`warning`,surface:`raised`,children:[`This provider does not publish a model directory. Use`,` `,(0,$.jsx)(h,{variant:`ghost`,size:`sm`,onClick:n,children:`Add manually`}),` `,`to add a model by id.`]}):null,(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(se,{size:14,"aria-hidden":`true`,className:`absolute left-5 top-1/2 -translate-y-1/2 text-text-tertiary`}),(0,$.jsx)(`input`,{"aria-label":`Search discovered models`,placeholder:`Search models…`,value:a,onChange:e=>o(e.target.value),className:`w-full max-w-full rounded-inset border border-inner-border bg-surface-2 py-4 pr-5 pl-16 text-caption text-text-primary`})]}),s.length>0?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-3 rounded-inset border border-inner-border bg-surface-2 p-4`,children:s.map(e=>(0,$.jsxs)(`span`,{className:`font-mono tabular-nums inline-flex items-center gap-2 text-badge bg-accent-soft text-accent py-1 px-3 rounded-chip border border-accent max-w-full overflow-hidden break-all`,children:[(0,$.jsx)(`span`,{className:`overflow-hidden truncate whitespace-nowrap`,children:e}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e}`,onClick:()=>f(e),className:`bg-transparent border-none cursor-pointer p-0 flex shrink-0`,children:(0,$.jsx)(re,{size:12})})]},e))}):null,(0,$.jsx)(`div`,{className:`flex min-h-160 max-h-320 flex-1 flex-col gap-3 overflow-y-auto rounded-control border border-inner-border bg-surface-1 p-6`,children:r.isPending?(0,$.jsx)(`div`,{className:`p-16 text-center text-caption text-text-tertiary`,children:`Fetching models from provider…`}):u?(0,$.jsx)(`div`,{className:`p-16 text-center text-caption text-text-tertiary`,children:`No provider listing available.`}):r.isError?(0,$.jsxs)(`div`,{className:`p-10 text-center text-caption`,children:[(0,$.jsx)(ut,{tone:`danger`,live:`alert`,children:`Could not fetch the provider's model list. Add manually is still available.`}),(0,$.jsxs)(`div`,{className:`flex gap-3 justify-center mt-4`,children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:()=>void r.refetch(),children:`Retry`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,onClick:n,children:`Add manually`})]})]}):d.length===0?(0,$.jsx)(`div`,{className:`p-16 text-center text-caption text-text-tertiary`,children:`No models found.`}):(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-3`,children:d.map(e=>{let t=s.includes(e.modelId),n=e.alreadyRegistered;return(0,$.jsxs)(`label`,{className:`block min-w-0 rounded-control border border-inner-border p-4 text-caption transition-colors ${n?`opacity-60`:`cursor-pointer hover:bg-hover`}`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.modelId}`,checked:t,disabled:n,onChange:()=>f(e.modelId)}),(0,$.jsx)(`span`,{className:`font-mono tabular-nums truncate flex-1 min-w-0 text-badge font-medium`,title:e.modelId,children:e.modelId}),e.freeTier===!0?(0,$.jsx)(`span`,{className:`shrink-0 rounded-pill border border-teal-soft px-3 py-0.5 text-micro text-teal`,children:`Free tier`}):null,e.proOnly===!0?(0,$.jsx)(`span`,{className:`shrink-0 rounded-tiny border border-orange bg-orange-soft px-3 py-0.5 text-micro text-orange`,children:`Pro`}):null,n?(0,$.jsx)(`span`,{className:`shrink-0 rounded-pill border border-inner-border px-3 py-0.5 text-micro font-bold text-text-tertiary`,children:`Registered`}):null,t?(0,$.jsx)(_,{size:13,"aria-hidden":`true`,className:`shrink-0 text-accent`}):null]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-x-4 gap-y-1.5 pl-2 text-micro text-text-tertiary`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`text-text-quaternary`,children:`Context`}),(0,$.jsx)(`span`,{className:`font-mono tabular-nums text-text-secondary`,children:K(e.contextLimit)})]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`text-text-quaternary`,children:`Output`}),(0,$.jsx)(`span`,{className:`font-mono tabular-nums text-text-secondary`,children:K(e.outputLimit)})]})]})]},e.modelId)})})})]})})}function mi({providerId:e,provider:t,onClose:n}){let[r,i]=(0,Q.useState)(t?.supportsModelDiscovery===!1);return r?(0,$.jsx)(di,{providerId:e,provider:t,onClose:n,onSwitchToProvider:()=>i(!1)}):(0,$.jsx)(pi,{providerId:e,onClose:n,onManual:()=>i(!0)})}function hi(){return{contextLimit:``,outputLimit:``,passthrough:!1,image:!0,reasoning:!0,toolCall:!0}}var gi=String(Ze),_i=String(Ye);function vi(){return{...hi(),contextLimit:gi,outputLimit:_i}}function yi({draft:e,onChange:t,idPrefix:n,disabled:r=!1}){let i=e.passthrough;return(0,$.jsxs)(X,{gap:`10px`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Limits`}),(0,$.jsxs)(Z,{gap:`8px`,children:[(0,$.jsx)(J,{label:`Context`,id:`${n}-context`,placeholder:gi,value:e.contextLimit,disabled:r,onChange:n=>t({...e,contextLimit:n.target.value}),className:`flex-1`}),(0,$.jsx)(J,{label:`Output`,id:`${n}-output`,placeholder:_i,value:e.outputLimit,disabled:r,onChange:n=>t({...e,outputLimit:n.target.value}),className:`flex-1`})]}),(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 mt-2 text-badge text-text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`${n}-fallback-limits`,checked:e.contextLimit===gi&&e.outputLimit===_i,disabled:r,onChange:n=>t(n.target.checked?{...e,contextLimit:gi,outputLimit:_i}:{...e,contextLimit:``,outputLimit:``})}),`Use fallback — `,K(Ze),` ctx ·`,` `,K(Ye),` out`]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Capabilities`}),(0,$.jsx)(X,{gap:`6px`,children:[[`image`,`Can image`,e.image],[`reasoning`,`Reasoning`,e.reasoning],[`toolCall`,`Tools`,e.toolCall]].map(([a,o,s])=>(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 text-badge text-text-secondary`,style:i?{opacity:.5}:void 0,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`${n}-${a}`,checked:i?!0:s,disabled:r||i,onChange:n=>t({...e,[a]:n.target.checked})}),o]},a))}),(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 mt-2 text-badge text-text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`${n}-passthrough`,checked:e.passthrough,disabled:r,onChange:n=>t({...e,passthrough:n.target.checked})}),`Passthrough — accept every capability`]}),i?(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:`Passthrough grants all of the above, so they are locked on. Uncheck it to restore your own choices.`}):null]})]})}function bi({warnings:e,onChange:t,idPrefix:n,disabled:r=!1}){let i=(n,r)=>{t(e.map((e,t)=>t===n?{...e,...r}:e))};return(0,$.jsxs)(X,{gap:`6px`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary`,children:`Warnings`}),e.length>0?(0,$.jsx)(h,{variant:`ghost`,size:`sm`,disabled:r,onClick:()=>t([]),"aria-label":`Clear all warnings`,title:`Clear all warnings`,children:`Clear`}):null]}),e.length===0?(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary`,children:`No warnings. Add one to flag a provider caveat on this model.`}):null,e.map((a,o)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-inset border border-inner-border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0`,children:[(0,$.jsx)(J,{id:`${n}-warning-kind-${o}`,"aria-label":`Warning ${o+1} kind`,placeholder:`kind (e.g. fallback_model)`,value:a.kind,disabled:r,onChange:e=>i(o,{kind:e.target.value}),className:`flex-1`}),(0,$.jsx)(Y,{id:`${n}-warning-severity-${o}`,"aria-label":`Warning ${o+1} severity`,value:a.severity??`warn`,disabled:r,size:`sm`,onValueChange:e=>i(o,{severity:e===`info`||e===`critical`?e:`warn`}),options:[{value:`info`,label:`Info`},{value:`warn`,label:`Warn — default`},{value:`critical`,label:`Critical`}]}),(0,$.jsx)(h,{variant:`ghost`,size:`sm`,icon:(0,$.jsx)(ce,{size:12}),disabled:r,onClick:()=>t(e.filter((e,t)=>t!==o)),"aria-label":`Remove warning ${o+1}`,title:`Remove warning`})]}),(0,$.jsx)(J,{id:`${n}-warning-message-${o}`,"aria-label":`Warning ${o+1} message`,placeholder:`Message shown on hover`,value:a.message,disabled:r,onChange:e=>i(o,{message:e.target.value})}),a.updatedAt?(0,$.jsxs)(`div`,{className:`text-micro text-text-tertiary`,children:[`Updated `,a.updatedAt]}):null]},o)),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,disabled:r,onClick:()=>t([...e,{kind:``,message:``,severity:`warn`}]),children:`Add warning`})]})}function xi({providerId:e,model:t,onClose:n}){let r=be(),[i,a]=(0,Q.useState)(()=>({contextLimit:t.contextLimit?String(t.contextLimit):``,outputLimit:t.outputLimit?String(t.outputLimit):``,passthrough:!1,image:t.vision===!0,reasoning:t.reasoning===!0,toolCall:t.toolCall===!0})),[o,s]=(0,Q.useState)(()=>[...t.warnings??[]]),c=JSON.stringify(o)!==JSON.stringify(t.warnings??[]);return(0,$.jsx)(F,{open:!0,onClose:n,title:`Edit Model`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:n,disabled:r.isPending,children:`Cancel`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,disabled:r.isPending,onClick:()=>{let a=Je(i.contextLimit),s=Je(i.outputLimit);if(a===null||s===null){g.error(`Invalid limits`,`Use a token count such as 512k, 200000, or 1.5m.`);return}if(o.some(e=>e.kind.trim()===``||e.message.trim()===``)){g.error(`Invalid warning`,`Every warning needs a kind and a message.`);return}let l=new Date().toISOString(),u=c?o.length===0?null:o.map(e=>({...e,updatedAt:l})):void 0;r.mutate({providerId:e,modelId:t.modelId,route:t.route??``,metadata:{contextLimit:a??null,outputLimit:s??null,passthrough:i.passthrough,image:i.passthrough?!0:i.image,reasoning:i.passthrough?!0:i.reasoning,toolCall:i.passthrough?!0:i.toolCall,...u===void 0?{}:{warnings:u}}},{onSuccess:()=>n(),onError:e=>g.error(`Failed to update model`,e.message??`Unable to update model`)})},children:r.isPending?`Saving...`:`Save`})]}),children:(0,$.jsxs)(X,{gap:`10px`,children:[(0,$.jsxs)(`div`,{className:`text-badge text-text-tertiary`,children:[`Editing `,(0,$.jsx)(`span`,{className:`font-mono tabular-nums`,children:t.modelId})]}),(0,$.jsx)(yi,{draft:i,onChange:a,idPrefix:`edit-model`,disabled:r.isPending}),(0,$.jsx)(bi,{warnings:o,onChange:s,idPrefix:`edit-model`,disabled:r.isPending})]})})}function Si({providerId:e,model:t,serviceKind:n,searchCapable:r,thinkingEffort:i,probeMode:a,onDeleteRequest:c,onEditRequest:l,deletePending:d,onRegisterProbe:v}){let y=Qr(),w=We(),E=he(),[D,O]=(0,Q.useState)(!1),[A,ee]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(null),[te,N]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(!1),P=Et(),F=t.warnings??[],I=n===`llm`?Rt(t.modelId,i===`auto`?null:i):t.modelId,L=`${e}/${I}`,oe=n===`websearch`?`Searching…`:`Thinking…`,se=()=>{if(N(!1),e===`qoder`||e===`qodercn`){w.mutate({providerId:e,request:{modelId:t.modelId,serviceKind:`llm`,mode:a}},{onSuccess:t=>{if(ee({ok:t.ok,latencyMs:t.latencyMs}),M(t.providerMetadata??null),!t.ok){g.error(`${e}/${I} test failed`,t.error??`Unknown error`);return}let n=t.sample??``,r=t.reportedModel?.trim()??``,i=t.providerMetadata,a=i?Object.entries(i).filter(([,e])=>e!=null&&e!==``):[];g.successRich(`${I} · END ${m(t.latencyMs)}`,(0,$.jsxs)(`span`,{className:`grid gap-2 min-w-0`,children:[r?(0,$.jsxs)(Z,{gap:`6px`,align:`center`,className:`min-w-0`,children:[(0,$.jsx)(T,{size:12,"aria-hidden":`true`,className:`shrink-0 text-text-tertiary`}),(0,$.jsx)(`span`,{className:`truncate font-mono text-badge text-text-secondary`,title:r,children:r})]}):null,a.length>0?(0,$.jsx)(`span`,{className:`grid gap-1 min-w-0`,children:a.map(([e,t])=>(0,$.jsxs)(Z,{gap:`6px`,align:`center`,className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`shrink-0 text-micro text-text-tertiary`,children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-micro text-text-secondary`,title:String(t),children:String(t)})]},e))}):null,(0,$.jsx)(`span`,{children:n||`No sample text in the response.`})]}),[r,n].filter(Boolean).join(`
6
+ `)||`No sample text in the response.`)},onError:t=>{ee({ok:!1,latencyMs:0}),M(null),g.error(`${e}/${I} test failed`,t.message??`Model probe failed`)}});return}y.test(L,t.outputLimit??void 0,{fast:a===`fast`}).then(t=>{if(ee({ok:t.ok,latencyMs:t.latencyMs}),M(null),!t.ok){g.error(`${e}/${I} test failed`,t.error??`Unknown error`);return}let n=t.sample??``,r=t.reportedModel?.trim()??``;g.successRich(`${I} · END ${m(t.latencyMs)}`,(0,$.jsxs)(`span`,{className:`grid gap-2 min-w-0`,children:[r?(0,$.jsxs)(Z,{gap:`6px`,align:`center`,className:`min-w-0`,children:[(0,$.jsx)(T,{size:12,"aria-hidden":`true`,className:`shrink-0 text-text-tertiary`}),(0,$.jsx)(`span`,{className:`truncate font-mono text-badge text-text-secondary`,title:r,children:r})]}):null,(0,$.jsx)(`span`,{children:n||`No sample text in the response.`})]}),[r,n].filter(Boolean).join(`
7
+ `)||`No sample text in the response.`)})};(0,Q.useEffect)(()=>{v?.(t.modelId,se)});let R=()=>{let n=!t.enabled;E.mutate({providerId:e,request:{modelId:t.modelId,route:t.route,enabled:n}},{onSuccess:()=>g.success(n?`Model enabled`:`Model disabled`,t.modelId),onError:e=>g.error(`Failed to update model`,e.message??`Unable to update model`)})};return(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`model-card box-border flex w-full min-w-0 flex-1-auto flex-col gap-5 rounded-panel border border-inner-border p-6 ${t.enabled?`bg-surface-2`:`bg-surface-1 opacity-72`}`,"data-model-id":t.modelId,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-4 min-w-0`,children:[(0,$.jsx)(`span`,{className:`inline-flex items-center justify-center w-13 h-13 rounded-inset bg-teal-soft text-teal shrink-0`,children:(0,$.jsx)(o,{size:14})}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{title:L,className:`font-mono tabular-nums min-w-0 truncate text-caption font-semibold leading-[1.35]`,children:I}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-micro text-text-tertiary`,children:[(0,$.jsx)(`span`,{title:`${t.wireFamily} · ${t.route??e}`,className:`shrink-0 rounded-tiny px-3.5 py-0.5 text-micro font-bold`,style:{...wi(t.wireFamily)},children:Ti(t.wireFamily)}),t.source!==null&&t.source!==`builtin`?(0,$.jsx)(`span`,{title:$r(t.source),className:`shrink-0 rounded-pill border border-teal-soft px-3 py-0.5 text-micro font-bold tracking-[0.04em] text-teal`,children:ei(t.source)}):null,t.proOnly===!0?(0,$.jsx)(`span`,{title:`Refused on a free plan. Nothing in the provider's model directory predicts it, so this comes from a real dispatch: the upstream answers that the model is not allowed for a free user type.`,className:`shrink-0 rounded-tiny border border-orange bg-orange-soft px-3.5 py-0.5 text-micro font-bold uppercase tracking-[0.04em] text-orange`,children:`Pro`}):null,t.freeTier===!0&&t.source!==`auto_free`?(0,$.jsx)(`span`,{title:`Free on this provider's plan. Taken from the provider's own model directory, not a hardcoded list, so it tracks plan changes.`,className:`shrink-0 rounded-pill border border-teal-soft px-3 py-0.5 text-micro font-bold text-teal`,children:`Free tier`}):null,F.length>0?(0,$.jsx)(`span`,{role:`button`,tabIndex:0,"aria-label":`Model warnings: ${F.length}`,"aria-expanded":ne,title:ii(F),onClick:()=>re(e=>!e),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),re(e=>!e))},className:`estimate-dot inline-flex items-center justify-center rounded-full border border-inner-border bg-surface-2 cursor-help shrink-0 ${ai[ri(F)]}`,"data-severity":ri(F),children:(0,$.jsx)(x,{size:9,"aria-hidden":`true`})}):null,t.enabled?null:(0,$.jsx)(`span`,{className:`shrink-0 rounded-pill bg-red-soft px-3 py-0.5 text-micro font-bold tracking-[0.04em] text-red`,children:`Off`})]})]}),(0,$.jsx)(h,{variant:`ghost`,size:`sm`,icon:D?(0,$.jsx)(_,{size:12}):(0,$.jsx)(u,{size:12}),"aria-label":`Copy ${L}`,title:`Copy ${L}`,onClick:()=>{navigator.clipboard?.writeText(L),O(!0),P(()=>O(!1),1500)},className:`shrink-0 p-2 opacity-70`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-badge text-text-secondary`,children:[(0,$.jsxs)(`span`,{className:`inline-flex gap-2.5`,children:[t.reasoning?(0,$.jsx)(`span`,{title:`Reasoning`,"aria-label":`Reasoning`,className:`inline-flex text-purple`,children:(0,$.jsx)(s,{size:12})}):null,t.vision?(0,$.jsx)(`span`,{title:`Vision`,"aria-label":`Vision`,className:`inline-flex text-status-info`,children:(0,$.jsx)(k,{size:12})}):null,t.toolCall?(0,$.jsx)(`span`,{title:`Tool calling`,"aria-label":`Tool calling`,className:`inline-flex text-orange`,children:(0,$.jsx)(z,{size:12})}):null,r?(0,$.jsx)(`span`,{title:`Web search`,"aria-label":`Web search`,className:`inline-flex text-teal`,children:(0,$.jsx)(b,{size:12})}):null]}),(0,$.jsxs)(`span`,{className:`whitespace-nowrap`,children:[t.limitsEstimated?(0,$.jsx)(`span`,{title:Xe,"aria-label":`Limits are a fallback estimate`,className:`estimate-dot inline-flex items-center justify-center rounded-full border border-inner-border bg-surface-2 text-orange cursor-help mr-1 align-middle`,children:(0,$.jsx)(S,{size:9,"aria-hidden":`true`})}):null,t.contextLimit?`${K(t.contextLimit)} ctx`:(0,$.jsx)(`span`,{title:Qe,className:`cursor-help`,children:`n/a ctx`}),t.outputLimit?` · ${K(t.outputLimit)} out`:(0,$.jsx)(`span`,{title:Qe,className:`cursor-help`,children:` · n/a out`})]}),l?(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 grid place-items-center w-6 h-6 p-0 border-0 bg-transparent text-text-tertiary cursor-pointer rounded-tiny hover:bg-inner-border hover:text-text-primary`,title:`Edit limits and capabilities`,"aria-label":`Edit ${t.modelId} limits and capabilities`,onClick:()=>l(t),children:(0,$.jsx)(ie,{size:11})}):null]}),(0,$.jsxs)(`div`,{className:`flex gap-3 items-center flex-wrap`,children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,disabled:y.testing||w.isPending,onClick:se,"aria-label":`Test ${I}`,title:y.testing||w.isPending?`Probing ${I}…`:A?.ok?`Last probe OK in ${m(A.latencyMs)} — click to re-test${j?`\n${Object.entries(j).filter(([,e])=>e!=null&&e!==``).map(([e,t])=>`${e}: ${String(t)}`).join(`
8
+ `)}`:``}`:A?`Last probe failed — click to retry`:`Test ${I}`,className:`flex-1 justify-center`,icon:y.testing||w.isPending?(0,$.jsx)(f,{size:12,className:`animate-spin`}):A?A.ok?(0,$.jsx)(`span`,{className:`inline-flex text-green`,children:(0,$.jsx)(C,{size:12})}):(0,$.jsx)(`span`,{className:`inline-flex text-red`,children:(0,$.jsx)(x,{size:12})}):(0,$.jsx)(p,{size:12}),children:y.testing||w.isPending?oe:A?.ok?m(A.latencyMs):A?`Fail`:`Test`}),(0,$.jsx)(h,{variant:`ghost`,size:`sm`,disabled:E.isPending,onClick:R,icon:t.enabled?(0,$.jsx)(ae,{size:12}):(0,$.jsx)(At,{size:12}),"aria-label":t.enabled?`Disable ${t.modelId}`:`Enable ${t.modelId}`,title:t.enabled?`Disable model`:`Enable model`,className:`flex-1 justify-center ${t.enabled?`text-red`:`text-green`}`,children:t.enabled?`Disable`:`Enable`}),t.source===`builtin`?null:(0,$.jsx)(h,{variant:`ghost`,size:`sm`,disabled:d,onClick:()=>c(t),icon:(0,$.jsx)(ce,{size:12}),"aria-label":`Delete ${t.modelId}`,title:`Delete model`,className:`model-card-delete shrink-0 px-4 py-3 text-text-tertiary`})]}),ne?(0,$.jsx)(`div`,{className:`grid gap-1 pt-1 min-w-0`,"data-testid":`model-warning-details`,children:F.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`text-micro font-semibold text-text-secondary`,children:[e.kind,` · `,e.severity??`warn`,e.updatedAt?` · ${e.updatedAt}`:``]}),(0,$.jsx)(`span`,{className:`text-micro text-text-tertiary wrap-break-word`,children:e.message})]},`${e.kind}-${t}`))}):null,j!==null&&(0,$.jsx)(`div`,{className:`grid gap-1 pt-1 min-w-0`,children:(()=>{let e=Object.entries(j).filter(([,e])=>e!=null&&e!==``);if(e.length===0)return null;let t=te?e:e.slice(0,1);return(0,$.jsxs)($.Fragment,{children:[t.map(([e,t])=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`shrink-0 text-micro text-text-tertiary`,children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-micro text-text-secondary`,title:String(t),children:String(t)})]},e)),e.length>1?(0,$.jsx)(`button`,{type:`button`,className:`mt-0.5 w-fit text-micro font-semibold text-text-tertiary hover:text-text-primary cursor-pointer bg-transparent border-0 p-0`,"aria-expanded":te,onClick:()=>N(e=>!e),children:te?`(close)`:`(show more · ${e.length-1} more)`}):null]})})()})]})})}var Ci=(0,Q.memo)(Si);function wi(e){return e===`responses`?{color:`var(--purple)`,background:`var(--purple-soft)`}:e===`messages`?{color:`var(--orange)`,background:`color-mix(in srgb, var(--orange) 14%, transparent)`}:{color:`var(--teal)`,background:`var(--teal-soft)`}}function Ti(e){let t=e.toLowerCase();return t===`responses`?`Responses`:t===`messages`?`Messages`:`Chat`}function Ei({results:e}){let[t,n]=(0,Q.useState)(!0),r=e.filter(e=>e.ok).length;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-control border border-inner-border bg-surface-2 p-4`,children:[(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":t,onClick:()=>n(e=>!e),className:`flex items-center justify-between gap-4 text-caption font-semibold text-text-secondary bg-transparent border-0 p-0 cursor-pointer`,children:[(0,$.jsx)(`span`,{children:`Test all models · ${r}/${e.length} passed`}),(0,$.jsx)(`span`,{className:`text-badge text-text-tertiary`,children:t?`(close)`:`(show)`})]}),t?(0,$.jsx)(`div`,{className:`grid gap-1 max-h-160 overflow-y-auto`,"data-testid":`test-all-models-results`,children:e.length===0?(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary`,children:`No models returned by the probe.`}):e.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-badge`,children:[(0,$.jsx)(`span`,{className:`shrink-0 font-bold ${e.ok?`text-green`:`text-red`}`,children:e.ok?`OK`:`Fail`}),(0,$.jsx)(`span`,{className:`font-mono tabular-nums truncate min-w-0 flex-1`,title:e.modelId,children:e.modelId}),(0,$.jsx)(`span`,{className:`shrink-0 tabular-nums text-text-tertiary`,children:m(e.latencyMs)}),e.error?(0,$.jsx)(`span`,{className:`truncate max-w-100 text-micro text-text-tertiary`,title:e.error,children:e.error}):null]},e.modelId))}):null]})}function Di({providerId:e,models:t,thinkingEffort:n,probeMode:r=`detail`,showFilter:i=`all`,serviceKind:a=`llm`,searchCapable:o=!1,testAll:s,onReady:c}){let l=Ue(),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),m=e=>e.enabled!==!1,h=(0,Q.useRef)(new Map),_=(0,Q.useCallback)((e,t)=>{h.current.set(e,t)},[]),v=(0,Q.useCallback)(()=>{for(let e of h.current.values())try{e()}catch{}},[]);(0,Q.useEffect)(()=>{c!==void 0&&c(v)},[c,v]);let y=i===`free`?t.filter(e=>e.freeTier===!0):t,b=ti.map(e=>({...e,rows:y.filter(t=>m(t)&&e.matches(t.source))})).filter(e=>e.rows.length>0),x=y.filter(e=>!m(e)),S=t=>(0,$.jsx)(Ci,{providerId:e,model:t,serviceKind:a,searchCapable:o,thinkingEffort:n,probeMode:r,deletePending:l.isPending,onDeleteRequest:d,onEditRequest:t.source===`builtin`?void 0:p,onRegisterProbe:_},`${t.modelId}::${t.route}`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(X,{gap:`16px`,children:[b.map(e=>(0,$.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline gap-4 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-caption font-bold text-text-secondary`,children:e.label}),(0,$.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:e.rows.length}),(0,$.jsxs)(`span`,{title:e.hint,className:`text-micro text-text-tertiary overflow-hidden truncate`,children:[`· `,e.hint]})]}),(0,$.jsx)(`div`,{className:`provider-grid grid gap-4 items-stretch`,children:e.rows.map(S)})]},e.key)),s?.results?(0,$.jsx)(Ei,{results:s.results}):null,x.length===0?null:(0,$.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline gap-4 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-caption font-bold text-text-secondary`,children:ni.label}),(0,$.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:x.length}),(0,$.jsxs)(`span`,{title:ni.hint,className:`text-micro text-text-tertiary overflow-hidden truncate`,children:[`· `,ni.hint]})]}),(0,$.jsx)(`div`,{className:`provider-grid grid gap-4 items-stretch`,children:x.map(S)})]})]}),(0,$.jsx)(ve,{open:u!==null,onClose:()=>{l.isPending||d(null)},onConfirm:async()=>{u!==null&&(await l.mutateAsync({providerId:e,request:{modelId:u.modelId,route:u.route}}),g.success(`Model deleted`,`${e}/${u.modelId}`),d(null))},title:`Delete model?`,message:`Delete ${e}/${u?.modelId??``} from the provider catalog?`,confirmLabel:`Delete`,danger:!0}),f===null?null:(0,$.jsx)(xi,{providerId:e,model:f,onClose:()=>p(null)})]})}function Oi(e){return e===`llm`?`LLM`:e===`websearch`?`Search`:e===`imageGeneration`?`Image`:e===`videoGeneration`?`Video`:e}function ki(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}function Ai(){let{providerId:e}=He(),[t]=De(),n=e??``,r=t.get(`service`),[i,a]=(0,Q.useState)(r===`websearch`||r===`imageGeneration`||r===`videoGeneration`?r:`llm`),o=Ee(n),s=Ge(n),l=Ke(n),u=me(),f=me({silent:!0}),[m,_]=(0,Q.useState)(!1),y=Te(),x=ye(),S=xe(),C=le(),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(!1),O=We(),[k,A]=(0,Q.useState)(``),[ne,re]=(0,Q.useState)(``),[P,ie]=(0,Q.useState)(null),oe=e=>`cartethyia:provider:${e}:thinking-effort`,se=e=>{if(typeof window>`u`||!window.localStorage)return`auto`;let t=window.localStorage.getItem(oe(e));if(t===null)return`auto`;let n=t.trim().toLowerCase();return Lt.includes(n)?n:`auto`},[R,z]=(0,Q.useState)(()=>se(n));(0,Q.useEffect)(()=>{if(!n)return;let e=se(n);e!==R&&z(e)},[n]),(0,Q.useEffect)(()=>{typeof window>`u`||!window.localStorage||!n||window.localStorage.setItem(oe(n),R)},[n,R]);let ue=e=>`cartethyia:provider:${e}:show-filter`,de=e=>typeof window>`u`||!window.localStorage?`all`:window.localStorage.getItem(ue(e))===`free`?`free`:`all`,fe=lt().data?.modelProbeMode??`detail`,B=Ae(),he=(0,Q.useRef)(void 0),[ge,_e]=(0,Q.useState)(()=>de(n));(0,Q.useEffect)(()=>{if(!n)return;let e=de(n);e!==ge&&_e(e)},[n]),(0,Q.useEffect)(()=>{typeof window>`u`||!window.localStorage||!n||window.localStorage.setItem(ue(n),ge)},[n,ge]);let[be,Se]=(0,Q.useState)(!1),[Ce,we]=(0,Q.useState)(!1),[Oe,ke]=(0,Q.useState)(null),[je,Me]=(0,Q.useState)({}),[Pe,Fe]=(0,Q.useState)({}),[H,Ie]=(0,Q.useState)(null),[Le,Re]=(0,Q.useState)(!1),[ze,Be]=(0,Q.useState)(null),Ve=(0,Q.useRef)(null),Ue=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{let e=Ve.current;Ve.current=null,e&&!e.closed&&e.close()},[]);let G=o.data,Je=n===`opencode`||n===`cline`,Ye=G===void 0?[`llm`]:ki(G),K=[];for(let e of Ye)(e===`llm`||e===`websearch`||e===`imageGeneration`||e===`videoGeneration`)&&K.push(e);(0,Q.useEffect)(()=>{if(G===void 0)return;let e=r===`websearch`||r===`imageGeneration`||r===`videoGeneration`||r===`llm`?r:void 0,t=K[0];if(e!==void 0&&K.includes(e)){i!==e&&a(e);return}!K.includes(i)&&t!==void 0&&a(t)},[G,r,i,K.join(`|`)]),(0,Q.useEffect)(()=>{Je&&G!==void 0&&G.supportsModelDiscovery!==!1&&Ue.current!==n&&(Ue.current=n,f.mutate(n))},[Je,f,n,G?.supportsModelDiscovery]);let Xe=l.data??[],Ze=s.data??[],Qe=(()=>{let e=new Map;for(let t of Ze){if(!t.modelId)continue;let n=`${t.serviceKind??`llm`}:${t.modelId}`,r=e.get(n);if(!r)e.set(n,t);else{let i=r.contextLimit??0;(t.contextLimit??0)>i&&e.set(n,t)}}return[...e.values()].sort((e,t)=>e.modelId.localeCompare(t.modelId))})(),$e=Qe.filter(e=>e.serviceKind===`llm`||e.serviceKind===void 0),et=Qe.filter(e=>e.serviceKind===`websearch`),q=Qe.filter(e=>e.serviceKind===`imageGeneration`),J=Qe.filter(e=>e.serviceKind===`videoGeneration`),Y=K.includes(i)?i:K[0],rt=ne||et[0]?.modelId||``,it=()=>{let e=k.trim();rt&&e&&(ie(null),O.mutate({providerId:n,request:{modelId:rt,serviceKind:`websearch`,prompt:e}},{onSuccess:e=>ie({ok:e.ok,latencyMs:e.latencyMs,...e.searchResults?{results:e.searchResults,count:e.searchResults.length}:{},...e.error?{error:e.error}:{}}),onError:e=>ie({ok:!1,error:e instanceof Error?e.message:`Search test failed`})}))};if(o.isPending)return(0,$.jsx)(M,{label:`Loading provider...`});if(o.isError)return(0,$.jsx)(j,{title:`Unable to load providers`,message:`The provider details could not be read, so this page cannot resolve its endpoint settings.`,onRetry:()=>void o.refetch(),retrying:o.isFetching,action:(0,$.jsx)(zt,{to:`/providers`,label:`Back to providers`})});if(!G)return(0,$.jsx)(te,{icon:(0,$.jsx)(jt,{size:20}),title:`Provider not found`,message:`No provider named “${n}”. It may have been removed, or the link is stale.`,action:(0,$.jsx)(zt,{to:`/providers`,label:`Back to providers`})});let at=Xe.filter(e=>e.status===`active`).length,ot=e=>{let t=e===`browser`?G?.oauthFlows?.browserLoginFields??[]:G?.oauthFlows?.deviceLoginFields??[];if(t.length===0){e===`browser`?ct():Se(!0);return}Me(Wr(t)),ke(e)},st=()=>{if(Oe===null)return;let e=Gr(Oe===`browser`?G?.oauthFlows?.browserLoginFields??[]:G?.oauthFlows?.deviceLoginFields??[],je);if(e.length>0){g.error(`Missing required fields`,`Fill in: ${e.join(`, `)}`);return}let t=Oe;ke(null),t===`browser`?ct(je):(Fe(je),Se(!0))},ct=e=>{let t=Ve.current;t&&!t.closed&&t.close();let r=`cartethyia-oauth-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=window.open(`about:blank`,r,`popup,width=720,height=820`);i&&(i.opener=null,Ve.current=i),S.mutate({providerId:n,...e===void 0?{}:{parameters:e}},{onSuccess:({authorizeUrl:e,state:t})=>{let n=null;if(i&&!i.closed?(i.location.href=e,n=i):(n=window.open(e,r,`popup,width=720,height=820`),n&&(n.opener=null,Ve.current=n)),!n){g.error(`Popup blocked`,`Allow popups to complete OAuth login.`);return}Be({authorizeUrl:e,state:t,popup:n})},onError:e=>{i&&!i.closed&&i.close(),Ve.current===i&&(Ve.current=null),g.error(`Failed to start OAuth`,e.message??`Unable to start authorization`)}})};return(0,$.jsxs)(X,{gap:`16px`,children:[(0,$.jsx)(Bt,{title:`${G.label||G.displayName}${Y?` (${Oi(Y)})`:``}`,description:`${G.providerId}/${G.baseUrl?` · ${G.baseUrl}`:``}`,icon:(0,$.jsx)(tt,{icon:G.providerId,name:G.label||G.displayName,size:28}),back:{to:`/providers`,label:`Back to Providers`},actions:(0,$.jsxs)(Z,{gap:`8px`,className:`flex-wrap w-full max-w-full min-w-0`,children:[n===`inferhub`?(0,$.jsxs)(`a`,{href:`https://inferhub.dev/`,target:`_blank`,rel:`noreferrer`,className:v({size:`sm`,variant:`secondary`,className:`no-underline`}),title:`Open InferHub — create a config_read key`,children:[(0,$.jsx)(Ne,{size:13,"aria-hidden":`true`}),`inferhub.dev`]}):null,G.isBuiltIn?(0,$.jsx)(h,{variant:G.enabled?`danger`:`secondary`,icon:G.enabled?(0,$.jsx)(ae,{size:13}):(0,$.jsx)(At,{size:13}),loading:x.isPending,onClick:()=>x.mutate({providerId:n,enabled:!G.enabled},{onSuccess:e=>g.success(e.enabled?`Provider enabled`:`Provider disabled`,G.label||G.displayName),onError:e=>g.error(`Provider update failed`,e.message??`Unable to change provider availability`)}),title:G.enabled?`Disable provider globally`:`Enable provider globally`,children:G.enabled?`Disable`:`Enable`}):null]})}),(0,$.jsx)(_n,{provider:G}),G.isBuiltIn?null:(0,$.jsx)(vn,{provider:G}),Y===`llm`?(0,$.jsx)(Zt,{providerId:n,clientVersion:G.clientVersion,userAgentEditable:Vt(G)}):null,(0,$.jsx)(kr,{providerId:n}),(0,$.jsx)(`div`,{id:`provider-accounts`,tabIndex:-1,children:G.requiresAccount===!1&&Xe.length===0?(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`Accounts`,icon:(0,$.jsx)(Dt,{size:16})}),(0,$.jsx)(U,{children:(0,$.jsx)(`p`,{className:`text-caption text-text-secondary`,children:`This provider is a public, unauthenticated route — no account or credential is needed. Routing already works without any setup here.`})})]}):(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`Accounts`,subtitle:`${Xe.length} total · ${at} active · ${Xe.length-at} disabled`,icon:(0,$.jsx)(Dt,{size:16}),action:(0,$.jsxs)(nt,{children:[G.oauthFlows?.browser&&(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(Ne,{size:13}),disabled:S.isPending,onClick:()=>ct(),title:`Social login — Google / GitHub / OIDC via the provider's sign-in portal`,children:S.isPending?`Starting...`:`Social login`}),G.oauthFlows?.device&&(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(N,{size:13}),onClick:()=>ot(`device`),title:`Device Code — enter the shown code on the provider site`,children:`Device Code`}),G.oauthFlows?.import&&(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(d,{size:13}),onClick:()=>we(!0),title:G.oauthFlows.browser||G.oauthFlows.device||G.oauthFlows.refreshable?`Import a credential you already hold — a refresh token, an exported auth blob, or an API key`:`Add and validate an API key`,children:G.oauthFlows.browser||G.oauthFlows.device||G.oauthFlows.refreshable?`Import credential`:`Add API key`}),G.requiresAccount?(0,$.jsx)(h,{variant:`primary`,size:`sm`,icon:(0,$.jsx)(I,{size:13}),onClick:()=>T(!0),children:`Add Account`}):null]})}),(0,$.jsxs)(U,{className:`flex flex-col gap-5`,children:[(0,$.jsx)(pn,{providerId:n}),l.isPending?(0,$.jsx)(M,{label:`Loading accounts...`}):l.isError?(0,$.jsx)(j,{message:`Failed to load accounts`,onRetry:()=>l.refetch()}):Xe.length===0?(0,$.jsx)(te,{title:`No accounts connected`,message:`Add an API key or OAuth credential to route requests to this provider.`}):(0,$.jsx)(wr,{providerId:n,accounts:Xe,onDelete:e=>Ie(e),showGrokProbe:Y===`llm`&&n===`grok`,grokProbePending:y.isPending,onGrokProbe:e=>{let t={modelId:`grok-4.6`,prompt:`Type the number 407.`,stream:!0,serviceKind:`llm`};e.length>0&&(t.accountIds=e),y.mutate({providerId:n,request:t},{onSuccess:t=>{let n=t.results.filter(e=>e.ok).length,r=t.results.filter(e=>e.statusCode===202).length,i=t.results.length-n-r,a=e.length>0?`${e.length} selected account${e.length===1?``:`s`}`:`all accounts`;g.success(`Grok account probe complete`,`${a} probed · ${n} passed · ${r} returned 202 and were parked in cooldown · ${i} other failures`)},onError:e=>g.error(`Grok account probe failed`,e.message??`Unable to probe Grok accounts`)})}})]})]})}),Y===`llm`?(0,$.jsxs)($.Fragment,{children:[n===`inferhub`?(0,$.jsx)(un,{}):null,(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`Models`,subtitle:`${$e.length} model${$e.length===1?``:`s`} registered`,icon:(0,$.jsx)(c,{size:16}),action:(0,$.jsxs)(Z,{gap:`6px`,className:`flex-wrap items-center`,children:[(0,$.jsx)(li,{id:`models-section-show-filter`,value:ge,onChange:_e,size:`sm`}),(0,$.jsx)(si,{id:`models-section-thinking-effort`,value:R,onChange:z,size:`sm`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(p,{size:13,className:B.isPending?`animate-spin`:``}),disabled:B.isPending||$e.length===0,onClick:()=>{let e=he.current;e===void 0?B.mutate({providerId:n,mode:fe},{onError:e=>g.error(`Test all models failed`,e.message??`Probe failed`)}):e()},title:`Test every registered model in ${fe} mode`,children:B.isPending?`Testing…`:`Test all models`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(L,{size:13,className:u.isPending||f.isPending?`animate-spin`:``}),disabled:u.isPending||f.isPending,onClick:()=>u.mutate(n),children:u.isPending||f.isPending?`Fetching...`:`Fetch models`}),(0,$.jsx)(h,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(ce,{size:13,className:m?`animate-spin`:``}),disabled:u.isPending||f.isPending||m||$e.filter(e=>e.source!==`builtin`&&e.source!==null).length===0,onClick:async()=>{let e=$e.filter(e=>e.source!==`builtin`&&e.source!==null);if(e.length!==0&&confirm(`Delete ${e.length} fetched/manual model(s) for ${n}?`)){_(!0);try{let t=await pe(`/providers/${encodeURIComponent(n)}/models/bulk`,{method:`DELETE`,body:JSON.stringify({items:e.map(e=>({modelId:e.modelId,route:e.route}))})});await Promise.all([C.invalidateQueries({queryKey:V.providers.models(n)}),C.invalidateQueries({queryKey:V.providers.all})]);let r=t.failures.length;g.success(`Fetched models deleted`,r>0?`${t.deleted}/${t.total} removed, ${r} failed`:`${t.deleted}/${t.total} removed`)}catch(e){g.error(`Failed to delete fetched models`,e.message??`Unable to delete models`)}finally{_(!1)}}},children:m?`Deleting…`:`Delete fetched`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,icon:(0,$.jsx)(I,{size:13}),onClick:()=>D(!0),children:`Add Model`})]})}),(0,$.jsx)(U,{className:`flex flex-col gap-8`,children:s.isPending?(0,$.jsx)(M,{label:`Loading models...`}):s.isError?(0,$.jsx)(j,{message:`Failed to load models`,onRetry:()=>s.refetch()}):$e.length===0?(0,$.jsx)(te,{title:`No LLM models found`,message:`No LLM models published by this provider yet. Sync or add a custom model above.`}):(0,$.jsx)(Di,{providerId:n,models:$e,serviceKind:`llm`,thinkingEffort:R,probeMode:fe,showFilter:ge,searchCapable:G?.supportsWebSearch===!0,testAll:{pending:B.isPending,onRun:()=>B.mutate({providerId:n,mode:fe}),results:B.data?.results??null},onReady:e=>{he.current=e}})})]})]}):Y===`websearch`?(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:`Web Search`,subtitle:`Run a real search request through the selected provider.`,icon:(0,$.jsx)(b,{size:16})}),(0,$.jsx)(U,{className:`flex flex-col gap-6`,children:s.isPending?(0,$.jsx)(M,{label:`Loading search models...`}):s.isError?(0,$.jsx)(j,{message:`Failed to load search models`,onRetry:()=>s.refetch()}):et.length===0?(0,$.jsx)(te,{title:`No Search models found`,message:`This provider advertises Search, but no websearch model is registered yet.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`flex flex-col gap-2.5 text-badge text-text-secondary`,children:[`Search model`,(0,$.jsx)(`select`,{value:rt,onChange:e=>{re(e.target.value),ie(null)},className:`w-full min-h-17 rounded-inset border border-inner-border bg-surface-1 text-text-primary px-4.5 py-0`,children:et.map(e=>(0,$.jsx)(`option`,{value:e.modelId,children:e.modelId},`${e.modelId}:${e.route}`))})]}),(0,$.jsxs)(`label`,{className:`flex flex-col gap-2.5 text-badge text-text-secondary`,children:[`Query`,(0,$.jsx)(`input`,{value:k,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),it())},placeholder:`What is the latest news about AI?`,className:`w-full min-h-17 rounded-inset border border-inner-border bg-surface-1 text-text-primary px-4.5 py-0`})]}),(0,$.jsxs)(Z,{gap:`8px`,className:`items-center flex-wrap`,children:[(0,$.jsx)(h,{variant:`primary`,size:`sm`,disabled:O.isPending||k.trim().length===0,loading:O.isPending,onClick:it,children:`Test search`}),P?(0,$.jsx)(`span`,{className:`text-badge`,style:{color:P.ok?`var(--green)`:`var(--red)`},children:P.ok?`Search ok · ${P.latencyMs}ms · ${P.count??0} result(s)`:P.error??`Search failed.`}):null]}),P&&P.results&&P.results.length>0?(0,$.jsx)(`div`,{className:`flex max-h-110 flex-col gap-4 overflow-y-auto rounded-inset border border-inner-border bg-surface-1 p-4`,children:P.results.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-caption text-text-primary font-semibold`,children:e.title||e.url}),(0,$.jsx)(`span`,{className:`text-badge text-text-tertiary break-all`,children:e.url}),e.snippet?(0,$.jsx)(`span`,{className:`text-badge text-text-secondary`,children:e.snippet}):null]},`${e.url}:${t}`))}):null]})})]}):Y===`imageGeneration`||Y===`videoGeneration`?(0,$.jsxs)(W,{children:[(0,$.jsx)(qe,{title:Oi(Y),subtitle:Y===`imageGeneration`?`Models that return an image rather than text.`:`Models that return a video. Wired and routable; not yet verified against a live account.`,icon:Y===`imageGeneration`?(0,$.jsx)(ee,{size:16}):(0,$.jsx)(Ft,{size:16})}),(0,$.jsx)(U,{className:`flex flex-col gap-6`,children:s.isPending?(0,$.jsx)(M,{label:`Loading ${Oi(Y).toLowerCase()} models...`}):s.isError?(0,$.jsx)(j,{message:`Failed to load ${Oi(Y).toLowerCase()} models`,onRetry:()=>s.refetch()}):(Y===`imageGeneration`?q:J).length===0?(0,$.jsx)(te,{title:`No ${Oi(Y)} models found`,message:`This provider advertises ${Oi(Y)}, but no ${Y} model is registered yet.`}):(0,$.jsx)(Di,{providerId:n,models:Y===`imageGeneration`?q:J,serviceKind:`llm`,searchCapable:!1,thinkingEffort:`auto`})})]}):(0,$.jsx)(W,{children:(0,$.jsx)(U,{children:(0,$.jsx)(te,{title:`Service not available`,message:`This provider advertises ${Ye.map(Oi).join(`, `)}, but the dashboard has no controls for the selected service yet.`})})}),w&&(0,$.jsx)(gr,{providerId:n,accounts:Xe,onClose:()=>T(!1)}),Y===`llm`&&E?(0,$.jsx)(mi,{providerId:n,provider:G,onClose:()=>D(!1)}):null,(0,$.jsx)(ve,{open:H!==null,onClose:()=>{Le||Ie(null)},onConfirm:async()=>{if(H){Re(!0);try{let e=H.tenantId===null?`/global/accounts/${encodeURIComponent(H.id)}`:`/accounts/${encodeURIComponent(H.id)}`;await pe(e,{method:`DELETE`}),C.removeQueries({queryKey:V.quota.account(H.id),exact:!0}),await Promise.all([C.invalidateQueries({queryKey:V.providers.accounts(n)}),C.invalidateQueries({queryKey:V.providers.healthEvents(n,H.id)}),C.invalidateQueries({queryKey:V.providers.all}),C.invalidateQueries({queryKey:V.quota.all})]),g.success(`Account deleted`,H.label||H.id.slice(0,8)),Ie(null)}catch(e){throw g.error(`Failed to delete account`,e.message??`Unable to delete account`),e}finally{Re(!1)}}},title:`Delete account?`,message:`Delete "${H?.label||H?.id.slice(0,8)}"? This cannot be undone.`,confirmLabel:`Delete`,danger:!0}),be&&(0,$.jsx)(Or,{providerId:n,parameters:Pe,onClose:()=>{Se(!1),Fe({})}}),Oe!==null&&(0,$.jsx)(F,{open:!0,onClose:()=>ke(null),title:Oe===`browser`?`Sign in with`:`Device sign-in details`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{variant:`secondary`,size:`sm`,onClick:()=>ke(null),children:`Cancel`}),(0,$.jsx)(h,{variant:`primary`,size:`sm`,onClick:st,children:`Continue`})]}),children:(0,$.jsxs)(X,{gap:`12px`,children:[(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:Oe===`browser`?`Choose how ${G.label||G.displayName} should identify you, then continue to its sign-in page.`:`These decide which organization the device code is issued for.`}),(0,$.jsx)(Kr,{fields:Oe===`browser`?G?.oauthFlows?.browserLoginFields??[]:G?.oauthFlows?.deviceLoginFields??[],values:je,idPrefix:`flow-${Oe}`,onChange:(e,t)=>Me(n=>({...n,[e]:t}))})]})}),Ce&&G?.oauthFlows?.import===!0&&(0,$.jsx)(qr,{providerId:n,providerName:G.label||G.displayName,fields:G.oauthFlows.importFields,onClose:()=>we(!1)}),ze&&(0,$.jsx)(Er,{providerId:n,authorizeUrl:ze.authorizeUrl,state:ze.state,popup:ze.popup,onClose:e=>{Ve.current=null,Be(null),e&&C.invalidateQueries({queryKey:V.providers.accounts(n)})}})]})}export{Ai as default};
@@ -1 +1 @@
1
- import{o as e,r as t,t as n}from"./jsx-runtime-CXUMngI_.js";var r=e(t(),1),i=n(),a=new Set,o={claude:{file:`claude-code`,ext:`svg`},anthropic:{file:`anthropics`,ext:`webp`},openai:{file:`openai-light`,ext:`svg`},codex:{file:`codex`,ext:`webp`},opencode:{file:`opencode`,ext:`webp`},"opencode-zen":{file:`opencode`,ext:`webp`},"opencode-go":{file:`opencode-go`,ext:`webp`},"google-antigravity":{file:`antigravity`,ext:`svg`},antigravity:{file:`antigravity`,ext:`svg`},blackbox:{file:`blackbox`,ext:`svg`},blackboxai:{file:`blackbox`,ext:`svg`},grok:{file:`grok-build`,ext:`webp`},"grok-build":{file:`grok-build`,ext:`webp`},xai:{file:`grok-build`,ext:`webp`},inferhub:{file:`inferhub`,ext:`svg`},gemini:{file:`gemini`,ext:`webp`},alibaba:{file:`alibaba`,ext:`svg`},alibabacp:{file:`alibaba`,ext:`svg`},dashscope:{file:`alibaba`,ext:`svg`},fireworks:{file:`fireworks`,ext:`webp`},exa:{file:`exa`,ext:`svg`},perplexity:{file:`perplexity`,ext:`webp`},tokenharbor:{file:`tokenharbor`,ext:`svg`},aihubmix:{file:`aihubmix`,ext:`svg`},zcode:{file:`zcode`,ext:`webp`},"zcode-start":{file:`zcode`,ext:`webp`},zai:{file:`zai`,ext:`webp`},"zai-plan":{file:`zai`,ext:`webp`},"zai-start":{file:`zai`,ext:`webp`},"kimi-code":{file:`kimi-code`,ext:`webp`},kimi:{file:`kimi-code`,ext:`webp`},github:{file:`github`,ext:`webp`},copilot:{file:`copilot`,ext:`webp`},xiaomipg:{file:`mimo`,ext:`webp`},xiaomitp:{file:`mimo`,ext:`webp`},mimo:{file:`mimo`,ext:`webp`},cb:{file:`codebuddy`,ext:`webp`},cbcn:{file:`codebuddy`,ext:`webp`},agentrouter:{file:`agentrouter`,ext:`svg`},parallel:{file:`parallel`,ext:`svg`},gmi:{file:`gmi-cloud`,ext:`svg`},hermes:{file:`hermes`,ext:`webp`},nous:{file:`nous-research`,ext:`svg`},inception:{file:`inception`,ext:`svg`},bai:{file:`bai`,ext:`svg`},cline:{file:`cline`,ext:`webp`},cerebras:{file:`cerebras`,ext:`webp`},qoder:{file:`qoder`,ext:`webp`},qodercn:{file:`qoder`,ext:`webp`},mistral:{file:`mistral`,ext:`webp`},muse:{file:`muse`,ext:`svg`},meta:{file:`muse`,ext:`svg`},openrouter:{file:`openrouter`,ext:`webp`},ollama:{file:`ollama`,ext:`webp`},ollamacloud:{file:`ollama-cloud`,ext:`webp`},nvidia:{file:`nvidia`,ext:`webp`},deepseek:{file:`deepseek`,ext:`webp`},"deepseek-tui":{file:`deepseek-tui`,ext:`webp`},droid:{file:`droid`,ext:`webp`},jcode:{file:`jcode`,ext:`webp`},kilo:{file:`kilocode`,ext:`webp`},"kilo-gateway":{file:`kilocode-gateway`,ext:`webp`},openclaw:{file:`openclaw`,ext:`webp`},cowork:{file:`claude`,ext:`webp`},roo:{file:`roo`,ext:`webp`},continue:{file:`continue`,ext:`webp`},amp:{file:`amp`,ext:`webp`},qwen:{file:`qwen`,ext:`webp`},kiro:{file:`kiro`,ext:`webp`},kimchi:{file:`kimchi`,ext:`webp`},commandcode:{file:`commandcode`,ext:`webp`},cursor:{file:`cursor`,ext:`webp`},devin:{file:`devin`,ext:`svg`},windsurf:{file:`windsurf`,ext:`svg`},trae:{file:`trae`,ext:`webp`},traecn:{file:`trae`,ext:`webp`},zro:{file:`zro`,ext:`svg`}};function s(e){let t=e.toLowerCase().trim();return o[t]??{file:t,ext:`webp`}}function c(e){let t=e.trim().split(/[\s-]+/).filter(Boolean);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}var l=(0,r.memo)(function({icon:e,name:t,size:n=32,imageSize:o,style:l,className:u}){let[d,f]=(0,r.useState)(()=>a.has(e)),p=s(e),m=o??n;return(0,i.jsx)(`div`,{className:u,style:{width:`${n}px`,height:`${n}px`,borderRadius:`8px`,background:`var(--surface-2)`,display:`grid`,placeItems:`center`,flexShrink:0,overflow:`hidden`,border:`1px solid var(--inner-border)`,...l},role:`img`,"aria-label":`${t} provider`,children:d?(0,i.jsx)(`span`,{style:{fontSize:`${Math.max(10,Math.floor(n*.35))}px`,fontWeight:700,color:`var(--text-secondary)`},children:c(t)}):(0,i.jsx)(`img`,{src:`/assets/providers/${p.file}.${p.ext}`,alt:``,width:m,height:m,loading:`lazy`,decoding:`async`,style:{width:`${m}px`,height:`${m}px`,objectFit:`contain`,padding:p.ext===`svg`?`1px`:`2px`},onError:()=>{a.add(e),f(!0)}})})});export{l as t};
1
+ import{o as e,r as t,t as n}from"./jsx-runtime-CXUMngI_.js";var r=e(t(),1),i=n(),a=new Set,o={claude:{file:`claude-code`,ext:`svg`},anthropic:{file:`anthropics`,ext:`webp`},openai:{file:`openai-light`,ext:`svg`},codex:{file:`codex`,ext:`webp`},opencode:{file:`opencode`,ext:`webp`},"opencode-zen":{file:`opencode`,ext:`webp`},"opencode-go":{file:`opencode-go`,ext:`webp`},"google-antigravity":{file:`antigravity`,ext:`svg`},antigravity:{file:`antigravity`,ext:`svg`},blackbox:{file:`blackbox`,ext:`svg`},blackboxai:{file:`blackbox`,ext:`svg`},grok:{file:`grok-build`,ext:`webp`},"grok-build":{file:`grok-build`,ext:`webp`},xai:{file:`grok-build`,ext:`webp`},inferhub:{file:`inferhub`,ext:`svg`},gemini:{file:`gemini`,ext:`webp`},alibaba:{file:`alibaba`,ext:`svg`},alibabacp:{file:`alibaba`,ext:`svg`},dashscope:{file:`alibaba`,ext:`svg`},fireworks:{file:`fireworks`,ext:`webp`},exa:{file:`exa`,ext:`svg`},perplexity:{file:`perplexity`,ext:`webp`},tokenharbor:{file:`tokenharbor`,ext:`svg`},aihubmix:{file:`aihubmix`,ext:`svg`},zcode:{file:`zcode`,ext:`webp`},"zcode-start":{file:`zcode`,ext:`webp`},zai:{file:`zai`,ext:`webp`},"zai-plan":{file:`zai`,ext:`webp`},"zai-start":{file:`zai`,ext:`webp`},"kimi-code":{file:`kimi-code`,ext:`webp`},kimi:{file:`kimi-code`,ext:`webp`},github:{file:`github`,ext:`webp`},copilot:{file:`copilot`,ext:`webp`},xiaomipg:{file:`mimo`,ext:`webp`},xiaomitp:{file:`mimo`,ext:`webp`},mimo:{file:`mimo`,ext:`webp`},cb:{file:`codebuddy`,ext:`webp`},cbcn:{file:`codebuddy`,ext:`webp`},agentrouter:{file:`agentrouter`,ext:`svg`},parallel:{file:`parallel`,ext:`svg`},gmi:{file:`gmi-cloud`,ext:`svg`},hermes:{file:`hermes`,ext:`webp`},nous:{file:`nous-research`,ext:`svg`},inception:{file:`inception`,ext:`svg`},bai:{file:`bai`,ext:`svg`},cline:{file:`cline`,ext:`webp`},cerebras:{file:`cerebras`,ext:`webp`},qoder:{file:`qoder`,ext:`webp`},qodercn:{file:`qoder`,ext:`webp`},mistral:{file:`mistral`,ext:`webp`},muse:{file:`muse`,ext:`svg`},meta:{file:`muse`,ext:`svg`},openrouter:{file:`openrouter`,ext:`webp`},ollama:{file:`ollama`,ext:`webp`},ollamacloud:{file:`ollama-cloud`,ext:`webp`},nvidia:{file:`nvidia`,ext:`webp`},deepseek:{file:`deepseek`,ext:`webp`},"deepseek-tui":{file:`deepseek-tui`,ext:`webp`},droid:{file:`droid`,ext:`webp`},jcode:{file:`jcode`,ext:`webp`},kilo:{file:`kilocode`,ext:`webp`},"kilo-gateway":{file:`kilocode-gateway`,ext:`webp`},openclaw:{file:`openclaw`,ext:`webp`},cowork:{file:`claude`,ext:`webp`},roo:{file:`roo`,ext:`webp`},continue:{file:`continue`,ext:`webp`},amp:{file:`amp`,ext:`webp`},qwen:{file:`qwen`,ext:`webp`},kiro:{file:`kiro`,ext:`webp`},kimchi:{file:`kimchi`,ext:`webp`},commandcode:{file:`commandcode`,ext:`webp`},cursor:{file:`cursor`,ext:`webp`},devin:{file:`devin`,ext:`svg`},windsurf:{file:`windsurf`,ext:`svg`},trae:{file:`trae`,ext:`webp`},traecn:{file:`trae`,ext:`webp`},zro:{file:`zro`,ext:`svg`},sensenova:{file:`sensenova`,ext:`png`},"sensenova-intl":{file:`sensenova-intl`,ext:`png`},clixad:{file:`clixad`,ext:`svg`},deepai:{file:`deepai`,ext:`svg`}};function s(e){let t=e.toLowerCase().trim();return o[t]??{file:t,ext:`webp`}}function c(e){let t=e.trim().split(/[\s-]+/).filter(Boolean);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}var l=(0,r.memo)(function({icon:e,name:t,size:n=32,imageSize:o,style:l,className:u}){let[d,f]=(0,r.useState)(()=>a.has(e)),p=s(e),m=o??n;return(0,i.jsx)(`div`,{className:u,style:{width:`${n}px`,height:`${n}px`,borderRadius:`8px`,background:`var(--surface-2)`,display:`grid`,placeItems:`center`,flexShrink:0,overflow:`hidden`,border:`1px solid var(--inner-border)`,...l},role:`img`,"aria-label":`${t} provider`,children:d?(0,i.jsx)(`span`,{style:{fontSize:`${Math.max(10,Math.floor(n*.35))}px`,fontWeight:700,color:`var(--text-secondary)`},children:c(t)}):(0,i.jsx)(`img`,{src:`/assets/providers/${p.file}.${p.ext}`,alt:``,width:m,height:m,loading:`lazy`,decoding:`async`,style:{width:`${m}px`,height:`${m}px`,objectFit:`contain`,padding:p.ext===`svg`?`1px`:`2px`},onError:()=>{a.add(e),f(!0)}})})});export{l as t};
@@ -1 +1 @@
1
- import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{c as i,m as a}from"./numbers-CivAk3da.js";import{t as ee}from"./eye-off-Bk5g2luF.js";import{t as te}from"./eye-C_hawfH4.js";import{n as o,r as s,t as c}from"./state-ClFzfbYp.js";import{t as l}from"./dialog-BjFR5UHy.js";import{t as u}from"./plus-DIdX_g-x.js";import{t as d}from"./trash-Cppn5c3R.js";import{l as f}from"./query-keys-IKLh0YFd.js";import{t as p}from"./dialog-actions-B1axpEg7.js";import{A as m,C as h,a as g,at as _,c as v,ct as y,dt as b,gt as x,j as S,o as C}from"./entry-BSu3gFlt.js";import{n as w,r as T,t as E}from"./card-DU3Lq5Lm.js";import{t as ne}from"./switch-CTIFxKqS.js";import{t as D}from"./badge-C83EqLB0.js";import{n as O}from"./input-iNnO1X2K.js";import{t as re}from"./select-CXbck0jG.js";import{t as k}from"./ProviderIcon-D_0PiZtg.js";import{t as A}from"./stack-DggRiCxE.js";import{n as j}from"./inline-DGvU2oLK.js";import{t as M}from"./pagination-CpzvI5ep.js";import{t as N}from"./list-row-C0w2bQjJ.js";import{t as P}from"./privacy-mode-GM8bej85.js";var F=e(`layout-grid`,[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]),I=e(`rows-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M21 9H3`,key:`1338ky`}],[`path`,{d:`M21 15H3`,key:`9uk58r`}]]),L=t(n(),1),R=r();function z(e){let t={};for(let[n,r]of e)n.trim()&&(t[n.trim()]=r);return t}function ie({pairs:e,onChange:t}){let n=(n,r)=>t(e.map((e,t)=>t===n?r:e)),r=n=>t(e.filter((e,t)=>t!==n));return(0,R.jsxs)(`div`,{className:`form-group`,children:[(0,R.jsxs)(`label`,{className:`form-label block`,children:[(0,R.jsx)(`span`,{className:`block`,children:`Custom Headers`}),(0,R.jsx)(`span`,{className:`form-hint block mt-1`,children:`Optional — sent with every request, override built-in headers on a name collision`})]}),(0,R.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e.map(([e,t],a)=>(0,R.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,R.jsx)(O,{placeholder:`Header-Name`,value:e,onChange:e=>n(a,[e.target.value,t]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,R.jsx)(O,{placeholder:`value`,value:t,onChange:t=>n(a,[e,t.target.value]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,R.jsx)(i,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Remove ${e||`header`}`,onClick:()=>r(a),children:(0,R.jsx)(d,{size:13})})]},a)),(0,R.jsxs)(i,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>t([...e,[``,``]]),children:[(0,R.jsx)(u,{size:13}),` Add header`]})]})]})}function B({children:e}){return(0,R.jsx)(`div`,{className:`provider-grid grid gap-6 w-full min-w-0`,children:e})}var V=a(`relative flex flex-col min-w-0 border border-inner-border rounded-card`,`transition-[transform,border-color,box-shadow]`),H=a(`block flex-1 p-6 no-underline text-inherit`),U=a(`text-body font-semibold overflow-hidden text-ellipsis whitespace-nowrap`);function W({label:e,title:t,tone:n}){return(0,R.jsx)(`span`,{"aria-label":t,title:t,className:`absolute top-0 right-0 z-2 w-36 h-36 overflow-hidden pointer-events-none`,children:(0,R.jsx)(`span`,{className:a(n===`danger`?`absolute top-9 -right-13 w-44 py-1 rotate-45 bg-red-soft text-red`:`absolute top-9 -right-11 w-38 py-1 rotate-45 bg-accent-soft text-accent`,`text-micro font-extrabold tracking-tight leading-[1.05]`,`text-center uppercase shadow-ribbon`),children:e})})}var G=[{kind:`imageGeneration`,label:`Image generation`},{kind:`videoGeneration`,label:`Video generation`},{kind:`embedding`,label:`Embeddings`},{kind:`audioSpeech`,label:`Speech synthesis (TTS)`},{kind:`audioTranscription`,label:`Audio transcription (STT)`},{kind:`websearch`,label:`Web search`},{kind:`systemone`,label:`System One (native routing)`}];function ae(e){return G.find(t=>t.kind===e)?.label??e}function K(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}var q=/\/(?:v\d+\/)?(?:messages|chat\/completions|responses|completions|embeddings|images\/generations)$/;function oe(e){let t=e.trim().replace(/\/+$/,``);if(t===``)return null;let n,r;try{n=new URL(t),r=n.pathname.replace(/\/+$/,``)}catch{return null}let i=q.exec(r);if(i===null)return null;let a=r.slice(0,i.index);return`${n.origin}${a}`}function J({variant:e,open:t,onClose:n}){let r=g(),ee=C(),te=m(),o=S(),[s,c]=(0,L.useState)(``),[u,d]=(0,L.useState)(``),[p,h]=(0,L.useState)(``),[_,v]=(0,L.useState)(``),[y,b]=(0,L.useState)(!1),[x,w]=(0,L.useState)(!0),[T,E]=(0,L.useState)([]),[D,k]=(0,L.useState)(null),[A,M]=(0,L.useState)(!1),[P,F]=(0,L.useState)(null),[I,B]=(0,L.useState)(!1),[V,H]=(0,L.useState)(!1),[U,W]=(0,L.useState)([`llm`]),K=e===`anthropic-compatible`,q=K?`messages`:`chat`,[J,Y]=(0,L.useState)(q),X=(0,L.useMemo)(()=>oe(p),[p]);(0,L.useEffect)(()=>{t&&(c(``),v(``),Y(q),h(``),b(!1),w(!0),E([]),k(null),F(null),H(!1),W([`llm`]))},[t]);let Z=async e=>{try{let t=await navigator.clipboard.readText();t.trim()&&e(t.trim())}catch{k(`Clipboard access denied — paste manually instead.`)}},Q=async()=>{if(!p.trim()){F({ok:!1,message:`Base URL is required to test the connection.`});return}B(!0),F(null),k(null);try{let e=z(T),t=await o.mutateAsync({baseUrl:p.trim(),apiKey:_.trim(),wireFamily:J,cliIdentity:x,...Object.keys(e).length>0?{extraHeaders:e}:{}});if(t.ok){let e=typeof t.modelCount==`number`?` — upstream advertised ${t.modelCount} model(s)`:``;F({ok:!0,message:`Connected successfully (${t.latencyMs}ms)${e}.`,...t.warning===void 0?{}:{warning:t.warning}})}else F({ok:!1,message:t.error??`Connection failed.`,...t.warning===void 0?{}:{warning:t.warning}})}catch(e){F({ok:!1,message:f(e,`Connection test failed`)})}finally{B(!1)}};return(0,R.jsx)(l,{open:t,onClose:n,title:K?`Add Custom Anthropic Provider`:`Add Custom OpenAI Provider`,footer:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(i,{variant:`secondary`,type:`button`,onClick:n,children:`Cancel`}),(0,R.jsx)(i,{variant:`primary`,type:`submit`,form:`add-compatible-provider`,disabled:A,children:A?`Creating...`:`Add Provider`})]}),children:(0,R.jsxs)(`form`,{id:`add-compatible-provider`,onSubmit:async e=>{if(e.preventDefault(),!s.trim()){k(`Display Name is required`);return}if(!u.trim()){k(`Provider ID (slug) is required`);return}if(!p.trim()){k(`Base URL is required`);return}let t=z(T),i=u.trim().toLowerCase(),a=V?U:void 0;M(!0),k(null);try{let e={providerId:i,label:s.trim(),baseUrl:p.trim(),wireFamily:J,compatibilityProfile:{cli_identity:x,...a===void 0?{}:{service_kinds:a},...Object.keys(t).length>0?{extra_headers:t}:{}}};await r.mutateAsync(e),_.trim()&&await ee.mutateAsync({providerId:i,request:{credentialKind:`api_key`,secret:_.trim()}}),y&&await te.mutateAsync(i),n()}catch(e){k(f(e,`Failed to create provider`))}finally{M(!1)}},className:`flex flex-col gap-6`,children:[D?(0,R.jsx)(`div`,{className:`text-red text-caption`,children:D}):null,(0,R.jsx)(O,{label:`Display Name`,hint:`Required. A friendly label for this node.`,id:`compat-label`,value:s,onChange:e=>c(e.target.value),placeholder:K?`Anthropic Compatible (Prod)`:`OpenAI Compatible (Prod)`,required:!0}),(0,R.jsx)(O,{label:`Provider ID / Slug`,hint:`Required. Used as the provider prefix for model IDs.`,id:`compat-slug`,value:u,onChange:e=>d(e.target.value),placeholder:K?`ac-prod`:`oc-prod`,required:!0}),(0,R.jsxs)(`div`,{className:`form-group`,children:[(0,R.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-url`,children:[(0,R.jsx)(`span`,{children:`Base URL`}),(0,R.jsxs)(`span`,{className:`form-hint`,children:[`The root only. Do not paste the full endpoint — leave off`,K?" `/v1/messages`.":" `/chat/completions`."]})]}),(0,R.jsxs)(j,{gap:`8px`,children:[(0,R.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,R.jsx)(O,{id:`compat-url`,value:p,onChange:e=>h(e.target.value),placeholder:K?`https://api.anthropic.com/v1`:`https://api.openai.com/v1`,required:!0})}),(0,R.jsx)(i,{type:`button`,variant:`secondary`,onClick:()=>Z(h),children:`Paste`})]}),X===null?null:(0,R.jsxs)(`p`,{className:`mt-1.5 text-caption text-orange`,children:[`That looks like a full endpoint. Use`,` `,(0,R.jsx)(`code`,{className:`font-mono`,children:X}),` instead — Cartethyia appends the endpoint path itself.`]})]}),K?null:(0,R.jsx)(re,{id:`compat-wire`,label:`API format`,value:J,onValueChange:e=>Y(e),options:[{value:`chat`,label:`Chat completions`},{value:`responses`,label:`Responses`}]}),(0,R.jsxs)(`div`,{className:`form-group`,children:[(0,R.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-credential`,children:[(0,R.jsx)(`span`,{children:`API Key`}),(0,R.jsx)(`span`,{className:`form-hint`,children:`Optional — saved with this provider and used to authenticate every request.`})]}),(0,R.jsxs)(j,{gap:`8px`,children:[(0,R.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,R.jsx)(O,{id:`compat-credential`,type:`password`,placeholder:`sk-...`,value:_,onChange:e=>v(e.target.value)})}),(0,R.jsx)(i,{type:`button`,variant:`secondary`,disabled:I,onClick:()=>void Q(),children:I?`Testing...`:`Test connection`}),(0,R.jsx)(i,{type:`button`,variant:`secondary`,onClick:()=>Z(v),children:`Paste`})]}),P?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:a(`mt-3 text-caption leading-[1.4] break-words`,P.ok?`text-green`:`text-red`),children:[P.ok?`✓ `:`✗ `,P.message]}),P.warning?(0,R.jsxs)(`div`,{className:`mt-2 text-caption leading-snug break-words text-orange`,children:[`⚠ `,P.warning]}):null]}):null]}),(0,R.jsx)(N,{actions:(0,R.jsx)(ne,{checked:y,onChange:b,id:`compat-autofetch`}),children:(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`text-body font-semibold`,children:`Auto-fetch models`}),(0,R.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Discover this provider's model list automatically after creation`})]})}),(0,R.jsx)(N,{actions:(0,R.jsx)(i,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>H(e=>!e),"aria-expanded":V,children:V?`Done`:`Configure`}),children:(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`text-body font-semibold`,children:`Advanced capabilities`}),(0,R.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:V?`Check the surfaces this upstream answers. Agentic (LLM) is always on.`:U.length>1?`${U.length-1} enabled · ${U.filter(e=>e!==`llm`).map(ae).join(`, `)}`:`Agentic only (LLM) — enable image, video, embeddings, and audio here`})]})}),V?(0,R.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-2 rounded-control border border-inner-border bg-surface-1 p-4`,children:G.map(e=>{let t=U.includes(e.kind);return(0,R.jsxs)(`label`,{className:`flex items-center gap-2.5 cursor-pointer text-caption text-text-secondary`,children:[(0,R.jsx)(`input`,{type:`checkbox`,className:`cursor-pointer`,checked:t,onChange:()=>W(n=>t?n.filter(t=>t!==e.kind):[...n,e.kind])}),(0,R.jsx)(`span`,{children:e.label})]},e.kind)})}):null,(0,R.jsx)(N,{actions:(0,R.jsx)(ne,{checked:x,onChange:w,id:`compat-cli-identity`}),children:(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`text-body font-semibold`,children:K?`Send request as Claude CLI`:`Send request as Codex CLI`}),(0,R.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:K?`Emits official Claude CLI User-Agent and Stainless headers to upstream`:`Emits official codex_cli_rs User-Agent and originator headers to upstream`})]})}),(0,R.jsx)(ie,{pairs:T,onChange:E})]})})}function Y({customProvider:e}){let t=v(),[n,r]=(0,L.useState)(!1);return(0,R.jsxs)(E,{className:V,children:[(0,R.jsx)(de,{clientVersion:e.clientVersion}),e.enabled?null:(0,R.jsx)(W,{label:`Disabled`,title:`Provider disabled`,tone:`danger`}),(0,R.jsx)(_,{to:`/providers/${encodeURIComponent(e.providerId)}`,className:a(H,`pr-20 min-h-38`),children:(0,R.jsxs)(j,{gap:`10px`,children:[(0,R.jsx)(k,{icon:e.wireFamilyDefault===`messages`?`anthropic`:`openai`,name:e.label||e.providerId,size:32,imageSize:24}),(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,R.jsx)(`div`,{className:U,children:e.label||e.providerId}),e.baseUrl?(0,R.jsxs)(`div`,{className:`mt-1 min-w-0 truncate font-mono text-micro text-text-tertiary`,title:e.baseUrl,children:[(0,R.jsx)(`span`,{className:`font-semibold text-text-secondary`,children:`Base URL`}),` `,e.baseUrl]}):null,(0,R.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:e.accountCount===void 0?(0,R.jsx)($,{kind:`accounts`,isPending:!1,isError:!1,hasData:!1}):e.accountCount===0?e.requiresAccount===!1?(0,R.jsx)(D,{tone:`ok`,children:`Free Endpoint`}):(0,R.jsx)(D,{children:`No connections`}):(0,R.jsx)(ue,{activeCount:e.activeAccountCount,total:e.accountCount})})]}),(0,R.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,R.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),e.modelCount!==void 0&&e.modelCount>0?(0,R.jsxs)(D,{tone:`info`,children:[e.modelCount,` models`]}):null,e.modelCount===void 0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!1}):e.modelCount===0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})}),(0,R.jsx)(i,{variant:`ghost`,size:`sm`,icon:(0,R.jsx)(d,{size:12}),onClick:()=>r(!0),className:`absolute top-2 right-2 p-2 text-text-tertiary`,title:`Delete ${e.label||e.providerId}`}),(0,R.jsx)(l,{open:n,onClose:()=>r(!1),title:`Delete Custom Provider`,children:(0,R.jsxs)(A,{gap:`12px`,children:[(0,R.jsxs)(`p`,{className:`text-body text-text-secondary`,children:[`Are you sure you want to delete custom provider`,` `,(0,R.jsx)(`strong`,{children:e.label||e.providerId}),`? Its models, accounts, and routing preferences are deleted together, and requests to this provider will no longer route.`]}),t.isError?(0,R.jsx)(`p`,{className:`text-caption text-red`,children:f(t.error,`Delete failed`)}):null,(0,R.jsxs)(p,{children:[(0,R.jsx)(i,{variant:`secondary`,onClick:()=>r(!1),children:`Cancel`}),(0,R.jsx)(i,{variant:`danger`,onClick:()=>{t.mutate(e.providerId,{onSuccess:()=>r(!1),onError:()=>void 0})},disabled:t.isPending,children:t.isPending?`Deleting...`:`Delete Provider`})]})]})})]})}function X({customProviders:e}){let[t,n]=(0,L.useState)(!1),[r,a]=(0,L.useState)(!1),[o,s]=(0,L.useState)(()=>{try{return window.localStorage.getItem(`cartethyia.customProvidersHidden`)===`1`}catch{return!1}});function c(){s(e=>{let t=!e;try{window.localStorage.setItem(`cartethyia.customProvidersHidden`,t?`1`:`0`)}catch{}return t})}return(0,R.jsxs)(`section`,{className:`flex flex-col gap-5`,children:[(0,R.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-4`,children:[(0,R.jsxs)(`button`,{type:`button`,onClick:c,"aria-expanded":!o,title:o?`Show custom providers`:`Hide custom providers`,className:`inline-flex items-center gap-3 bg-transparent border-none p-0 cursor-pointer text-inherit`,children:[(0,R.jsxs)(`h2`,{className:`text-body-lg font-bold tracking-[-0.01em]`,children:[`Custom Providers`,e.length>0?` (${e.length})`:``]}),(0,R.jsx)(x,{size:14,className:`text-text-tertiary transition-transform`,style:{transform:o?`rotate(-90deg)`:void 0}})]}),(0,R.jsxs)(j,{gap:`8px`,children:[(0,R.jsx)(i,{size:`sm`,variant:`ghost`,icon:o?(0,R.jsx)(te,{size:13}):(0,R.jsx)(ee,{size:13}),onClick:c,title:o?`Show custom providers`:`Hide custom providers`,children:o?`Show`:`Hide`}),(0,R.jsx)(i,{size:`sm`,variant:`secondary`,icon:(0,R.jsx)(u,{size:13}),onClick:()=>n(!0),children:`Custom Anthropic`}),(0,R.jsx)(i,{size:`sm`,variant:`secondary`,icon:(0,R.jsx)(u,{size:13}),onClick:()=>a(!0),children:`Custom OpenAI`})]})]}),o?null:e.length===0?(0,R.jsx)(E,{children:(0,R.jsxs)(w,{className:`text-center px-7 py-10 border border-dashed border-inner-border rounded-card`,children:[(0,R.jsx)(`p`,{className:`text-body font-semibold text-text-primary`,children:`No custom providers yet`}),(0,R.jsx)(`p`,{className:`text-badge text-text-tertiary mt-1`,children:`Add an OpenAI- or Anthropic-compatible endpoint with the buttons above.`})]})}):(0,R.jsx)(B,{children:e.map(e=>(0,R.jsx)(Y,{customProvider:e},e.providerId))}),(0,R.jsx)(J,{variant:`anthropic-compatible`,open:t,onClose:()=>n(!1)}),(0,R.jsx)(J,{variant:`openai-compatible`,open:r,onClose:()=>a(!1)})]})}var Z=new Set([`inferhub`]),Q=new Set([`grok`,`opencode`,`cline`,`hermes`,`kilo`,`inception`,`zcode-start`,`freepi`,`perch`,`zro`,`freebuff`]),se=new Set([`anthropic`,`openai`,`gemini`,`alibabacp`,`ollamacloud`,`opencode-zen`,`opencode-go`,`mistral`,`meta`,`deepseek`,`commandcode`,`dashscope`]);function ce(e){return e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0}function le(e){return e.oauthFlows?.refreshable===!0}function ue({activeCount:e,total:t}){return e===void 0?(0,R.jsxs)(D,{tone:`warn`,dot:!0,children:[t,` Connected`]}):e===0?(0,R.jsxs)(D,{tone:`warn`,dot:!0,children:[t,` Unhealthy`]}):e===t?(0,R.jsxs)(D,{tone:`ok`,dot:!0,children:[t,` Healthy`]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(D,{tone:`ok`,dot:!0,children:[e,` Healthy`]}),(0,R.jsxs)(D,{tone:`warn`,dot:!0,children:[t-e,` Unhealthy`]})]})}function $({kind:e,isPending:t,isError:n,hasData:r,isEmpty:i=!1}){let a=e===`models`?`Models`:`Connections`;return n?(0,R.jsxs)(D,{tone:`warn`,children:[a,` unavailable`]}):t&&!r?(0,R.jsxs)(D,{tone:`info`,children:[`Loading `,a.toLowerCase(),`…`]}):i?(0,R.jsx)(D,{children:e===`models`?`No models`:`No connections`}):null}function de({clientVersion:e}){return e?(0,R.jsxs)(D,{className:`provider-version-badge absolute -top-4.5 left-5 right-auto z-chip max-w-[calc(100%-var(--spacing)*10)] truncate px-3 py-1 text-micro leading-[1.15] shadow-card max-small:left-4 max-small:max-w-[calc(100%-var(--spacing)*8)]`,tone:e.source===`latest`?`teal`:`default`,title:e.source===`latest`?`Latest discovered client version`:`Pinned fallback; background discovery has not succeeded yet`,children:[`v`,e.version,` · `,e.source]}):null}var fe=(0,L.memo)(function({provider:e,serviceKind:t}){let n=Z.has(e.providerId.toLowerCase()),r=e.label||e.displayName;return(0,R.jsxs)(E,{className:V,children:[(0,R.jsx)(de,{clientVersion:e.clientVersion}),e.enabled?n?(0,R.jsx)(W,{label:`Friend`,title:`Friend sponsor`,tone:`accent`}):null:(0,R.jsx)(W,{label:`Disabled`,title:`Provider disabled`,tone:`danger`}),(0,R.jsx)(_,{to:`/providers/${encodeURIComponent(e.providerId)}${t===void 0?``:`?service=${t}`}`,className:H,children:(0,R.jsxs)(j,{gap:`10px`,children:[(0,R.jsx)(k,{icon:e.providerId,name:r,size:32,imageSize:24}),(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,R.jsx)(`div`,{className:U,children:r}),(0,R.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:e.accountCount===void 0?(0,R.jsx)($,{kind:`accounts`,isPending:!1,isError:!1,hasData:!1}):e.accountCount===0?e.requiresAccount===!1?(0,R.jsx)(D,{tone:`ok`,children:`Free Endpoint`}):(0,R.jsx)(D,{children:`No connections`}):(0,R.jsx)(ue,{activeCount:e.activeAccountCount,total:e.accountCount})})]}),(0,R.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,R.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),e.modelCount!==void 0&&e.modelCount>0?(0,R.jsxs)(D,{tone:`info`,children:[e.modelCount,` models`]}):null,e.modelCount===void 0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!1}):e.modelCount===0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})})]})});function pe(e,t){let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n}var me=`cartethyia.providerSectionsCollapsed`,he=`cartethyia:providers:display-mode`;function ge(){try{if(typeof window>`u`)return null;let e=window.localStorage.getItem(he);return e===`all`||e!==`paginated`&&null}catch{return null}}function _e(e){try{window.localStorage.setItem(he,e?`all`:`paginated`)}catch{}}var ve=`Other API Key Providers`;function ye(){try{let e=window.localStorage.getItem(me);if(e===null)return new Set([ve]);let t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set([ve])}}var be=`text-body font-bold tracking-[-0.01em]`,xe=[{title:`Founding Friend & Sponsors`,subtitle:`Super Cheap inference pool`,filter:e=>Z.has(e.providerId.toLowerCase())},{title:`Free Limited Providers`,filter:e=>Q.has(e.providerId.toLowerCase())},{title:`OAuth & Agent Providers`,filter:e=>(ce(e)||le(e))&&!Q.has(e.providerId.toLowerCase())},{title:`Well Known API Key Providers`,subtitle:`The household names — sign up with a key and go`,filter:e=>e.isBuiltIn&&se.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q.has(e.providerId.toLowerCase())&&!ce(e)&&!le(e)},{title:`Other API Key Providers`,subtitle:`Free tier friendly — no credit card`,filter:e=>e.isBuiltIn&&!se.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q.has(e.providerId.toLowerCase())&&!ce(e)&&!le(e)}];function Se(){let[e,t]=(0,L.useState)(ye),n=h(),r=P(),l=r.enabled,u=e=>!l||e.configured===!0||e.requiresAccount===!1,d=(0,L.useMemo)(()=>n.data??[],[n.data]),p=(0,L.useMemo)(()=>[...d.filter(e=>!e.isBuiltIn&&u(e))].sort(pe),[d,l]),m=(0,L.useMemo)(()=>d.filter(e=>K(e).includes(`websearch`)&&u(e)),[d,l]),g=(0,L.useMemo)(()=>d.filter(e=>K(e).includes(`llm`)&&u(e)),[d,l]),[_,v]=y(),S=_.get(`tab`),C=S===`search`||S===`media`?S:`llm`,ne=e=>{v(t=>{let n=new URLSearchParams(t);return e===`llm`?n.delete(`tab`):n.set(`tab`,e),n})},D=(0,L.useMemo)(()=>d.filter(e=>(K(e).includes(`imageGeneration`)||K(e).includes(`videoGeneration`))&&u(e)),[d,l]),O=(0,L.useMemo)(()=>[...m].sort((e,t)=>(e.label||e.displayName).localeCompare(t.label||t.displayName)),[m]),re=(e,t)=>{let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n},k=(0,L.useMemo)(()=>{if(C===`media`)return[{title:`Media Generation`,subtitle:`Providers that can return an image or a video`,providers:D}].filter(e=>e.providers.length>0);if(C===`search`)return[{title:`Search Providers`,subtitle:`Providers that can answer a web search request`,providers:O}].filter(e=>e.providers.length>0);let e=g;return xe.map(t=>({...t,providers:e.filter(t.filter).sort(re)})).filter(e=>e.providers.length>0)},[g,O,D,C]),[j,N]=(0,L.useState)({}),[z,ie]=(0,L.useState)(()=>ge()??!1),V=()=>{ie(e=>{let t=!e;return _e(t),t})},H=e=>j[e]??1,U=e=>t=>N(n=>({...n,[e]:t})),W=(e,t)=>{if(z)return{visible:e,pageCount:1,safePage:1};let n=H(t),r=Math.max(1,Math.ceil(e.length/8)),i=Math.min(n,r);return{visible:e.slice((i-1)*8,i*8),pageCount:r,safePage:i}},G=n.isPending&&!n.data?(0,R.jsx)(s,{label:`Loading providers...`}):n.isError?(0,R.jsx)(o,{message:f(n.error,`Failed to load providers`),onRetry:()=>n.refetch()}):null;return G?(0,R.jsxs)(E,{children:[(0,R.jsx)(T,{title:`Providers`,icon:(0,R.jsx)(b,{size:16})}),(0,R.jsx)(w,{className:`flex flex-1`,children:G})]}):(0,R.jsx)(A,{gap:`24px`,children:(0,R.jsxs)(E,{children:[(0,R.jsx)(T,{title:`Providers`,subtitle:`Connected pinned first · A–Z`,icon:(0,R.jsx)(b,{size:16})}),(0,R.jsxs)(w,{className:`flex flex-col gap-8`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,R.jsx)(`div`,{className:`flex gap-2`,children:[`llm`,`search`,`media`].map(e=>(0,R.jsxs)(`button`,{onClick:()=>ne(e),className:a(`px-6 py-3 rounded-inset text-caption font-semibold border cursor-pointer`,C===e?`border-accent bg-accent-soft text-accent`:`border-inner-border bg-surface-1 text-text-secondary`),children:[e===`llm`?`LLM`:e===`search`?`Search`:`Media`,e===`search`?` (${m.length})`:e===`media`?` (${D.length})`:` (${g.length})`]},e))}),(0,R.jsx)(i,{variant:`ghost`,size:`sm`,icon:l?(0,R.jsx)(ee,{size:12}):(0,R.jsx)(te,{size:12}),onClick:()=>r.setEnabled(!l),title:l?`Show providers that have no account yet`:`Hide providers that have no account yet`,children:l?`Show unconfigured`:`Hide unconfigured`}),(0,R.jsx)(i,{variant:`ghost`,size:`sm`,icon:z?(0,R.jsx)(I,{size:12}):(0,R.jsx)(F,{size:12}),onClick:V,title:z?`Paginate each section (8 per page)`:`Show every provider in each section at once`,children:z?`Paginated`:`Show All`}),(0,R.jsx)(`span`,{className:`ml-auto text-micro text-text-tertiary`,children:C===`search`?`Fallback runs only when the model invokes Websearch`:C===`media`?`Image and video generation`:`Connected pinned first · A–Z`})]}),C===`llm`?(0,R.jsx)(X,{customProviders:p}):null,k.length===0?(0,R.jsx)(E,{children:(0,R.jsx)(w,{children:(0,R.jsx)(c,{title:`No providers found`,message:`No providers available.`})})}):k.map(n=>{let r=e.has(n.title);return(0,R.jsxs)(`section`,{className:`flex flex-col gap-6`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`flex items-start gap-4 border-0 bg-transparent p-0 text-left text-inherit`,"aria-expanded":!r,onClick:()=>t(e=>{let t=new Set(e);t.has(n.title)?t.delete(n.title):t.add(n.title);try{window.localStorage.setItem(me,JSON.stringify([...t]))}catch{}return t}),children:[(0,R.jsx)(x,{size:15,className:a(`mt-1 shrink-0 transition-transform`,r&&`-rotate-90`)}),(0,R.jsxs)(A,{gap:`1px`,children:[(0,R.jsxs)(`h2`,{className:be,children:[n.title,` (`,n.providers.length,`)`,r?` (Hidden)`:``]}),!r&&n.subtitle?(0,R.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:n.subtitle}):null]})]}),r?null:(0,R.jsx)(B,{children:W(n.providers,n.title).visible.map(e=>(0,R.jsx)(fe,{provider:e,serviceKind:C===`search`?`websearch`:C===`media`?K(e).includes(`imageGeneration`)?`imageGeneration`:`videoGeneration`:`llm`},e.providerId))}),r?null:(()=>{let{pageCount:e,safePage:t}=W(n.providers,n.title);return e>1?(0,R.jsx)(M,{page:t,pageCount:e,onPageChange:U(n.title),testId:`providers-section-pagination-${n.title}`}):null})()]},n.title)})]})]})})}export{Se as default};
1
+ import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{c as i,m as a}from"./numbers-Dw6kiew-.js";import{t as ee}from"./eye-off-Bk5g2luF.js";import{t as te}from"./eye-C_hawfH4.js";import{n as o,r as s,t as c}from"./state-CArX_Iak.js";import{t as l}from"./dialog-DL0Zftwv.js";import{t as u}from"./plus-DIdX_g-x.js";import{t as d}from"./trash-Cppn5c3R.js";import{l as f}from"./query-keys-IKLh0YFd.js";import{t as p}from"./dialog-actions-B1axpEg7.js";import{A as m,C as h,a as g,at as _,c as v,ct as y,dt as b,gt as x,j as S,o as C}from"./entry-DScKYvZj.js";import{n as w,r as T,t as E}from"./card-Bto5UlL9.js";import{t as ne}from"./switch-DwlwmDO-.js";import{t as D}from"./badge-DkRUuVfz.js";import{n as O}from"./input-Bfx0EzRc.js";import{t as re}from"./select-oO1FxMVb.js";import{t as k}from"./ProviderIcon-Ddhm1InL.js";import{t as A}from"./stack-Y3pDteZr.js";import{n as j}from"./inline-Dl-cuLK0.js";import{t as M}from"./pagination-iUoI8GeE.js";import{t as N}from"./list-row-D49Y4ptn.js";import{t as P}from"./privacy-mode-GM8bej85.js";var F=e(`layout-grid`,[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]),I=e(`rows-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M21 9H3`,key:`1338ky`}],[`path`,{d:`M21 15H3`,key:`9uk58r`}]]),L=t(n(),1),R=r();function z(e){let t={};for(let[n,r]of e)n.trim()&&(t[n.trim()]=r);return t}function ie({pairs:e,onChange:t}){let n=(n,r)=>t(e.map((e,t)=>t===n?r:e)),r=n=>t(e.filter((e,t)=>t!==n));return(0,R.jsxs)(`div`,{className:`form-group`,children:[(0,R.jsxs)(`label`,{className:`form-label block`,children:[(0,R.jsx)(`span`,{className:`block`,children:`Custom Headers`}),(0,R.jsx)(`span`,{className:`form-hint block mt-1`,children:`Optional — sent with every request, override built-in headers on a name collision`})]}),(0,R.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e.map(([e,t],a)=>(0,R.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,R.jsx)(O,{placeholder:`Header-Name`,value:e,onChange:e=>n(a,[e.target.value,t]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,R.jsx)(O,{placeholder:`value`,value:t,onChange:t=>n(a,[e,t.target.value]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,R.jsx)(i,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Remove ${e||`header`}`,onClick:()=>r(a),children:(0,R.jsx)(d,{size:13})})]},a)),(0,R.jsxs)(i,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>t([...e,[``,``]]),children:[(0,R.jsx)(u,{size:13}),` Add header`]})]})]})}function B({children:e}){return(0,R.jsx)(`div`,{className:`provider-grid grid gap-6 w-full min-w-0`,children:e})}var V=a(`relative flex flex-col min-w-0 border border-inner-border rounded-card`,`transition-[transform,border-color,box-shadow]`),H=a(`block flex-1 p-6 no-underline text-inherit`),U=a(`text-body font-semibold overflow-hidden text-ellipsis whitespace-nowrap`);function W({label:e,title:t,tone:n}){return(0,R.jsx)(`span`,{"aria-label":t,title:t,className:`absolute top-0 right-0 z-2 w-36 h-36 overflow-hidden pointer-events-none`,children:(0,R.jsx)(`span`,{className:a(n===`danger`?`absolute top-9 -right-13 w-44 py-1 rotate-45 bg-red-soft text-red`:`absolute top-9 -right-11 w-38 py-1 rotate-45 bg-accent-soft text-accent`,`text-micro font-extrabold tracking-tight leading-[1.05]`,`text-center uppercase shadow-ribbon`),children:e})})}var G=[{kind:`imageGeneration`,label:`Image generation`},{kind:`videoGeneration`,label:`Video generation`},{kind:`embedding`,label:`Embeddings`},{kind:`audioSpeech`,label:`Speech synthesis (TTS)`},{kind:`audioTranscription`,label:`Audio transcription (STT)`},{kind:`websearch`,label:`Web search`},{kind:`systemone`,label:`System One (native routing)`}];function ae(e){return G.find(t=>t.kind===e)?.label??e}function K(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}var q=/\/(?:v\d+\/)?(?:messages|chat\/completions|responses|completions|embeddings|images\/generations)$/;function oe(e){let t=e.trim().replace(/\/+$/,``);if(t===``)return null;let n,r;try{n=new URL(t),r=n.pathname.replace(/\/+$/,``)}catch{return null}let i=q.exec(r);if(i===null)return null;let a=r.slice(0,i.index);return`${n.origin}${a}`}function J({variant:e,open:t,onClose:n}){let r=g(),ee=C(),te=m(),o=S(),[s,c]=(0,L.useState)(``),[u,d]=(0,L.useState)(``),[p,h]=(0,L.useState)(``),[_,v]=(0,L.useState)(``),[y,b]=(0,L.useState)(!1),[x,w]=(0,L.useState)(!0),[T,E]=(0,L.useState)([]),[D,k]=(0,L.useState)(null),[A,M]=(0,L.useState)(!1),[P,F]=(0,L.useState)(null),[I,B]=(0,L.useState)(!1),[V,H]=(0,L.useState)(!1),[U,W]=(0,L.useState)([`llm`]),K=e===`anthropic-compatible`,q=K?`messages`:`chat`,[J,Y]=(0,L.useState)(q),X=(0,L.useMemo)(()=>oe(p),[p]);(0,L.useEffect)(()=>{t&&(c(``),v(``),Y(q),h(``),b(!1),w(!0),E([]),k(null),F(null),H(!1),W([`llm`]))},[t]);let Z=async e=>{try{let t=await navigator.clipboard.readText();t.trim()&&e(t.trim())}catch{k(`Clipboard access denied — paste manually instead.`)}},Q=async()=>{if(!p.trim()){F({ok:!1,message:`Base URL is required to test the connection.`});return}B(!0),F(null),k(null);try{let e=z(T),t=await o.mutateAsync({baseUrl:p.trim(),apiKey:_.trim(),wireFamily:J,cliIdentity:x,...Object.keys(e).length>0?{extraHeaders:e}:{}});if(t.ok){let e=typeof t.modelCount==`number`?` — upstream advertised ${t.modelCount} model(s)`:``;F({ok:!0,message:`Connected successfully (${t.latencyMs}ms)${e}.`,...t.warning===void 0?{}:{warning:t.warning}})}else F({ok:!1,message:t.error??`Connection failed.`,...t.warning===void 0?{}:{warning:t.warning}})}catch(e){F({ok:!1,message:f(e,`Connection test failed`)})}finally{B(!1)}};return(0,R.jsx)(l,{open:t,onClose:n,title:K?`Add Custom Anthropic Provider`:`Add Custom OpenAI Provider`,footer:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(i,{variant:`secondary`,type:`button`,onClick:n,children:`Cancel`}),(0,R.jsx)(i,{variant:`primary`,type:`submit`,form:`add-compatible-provider`,disabled:A,children:A?`Creating...`:`Add Provider`})]}),children:(0,R.jsxs)(`form`,{id:`add-compatible-provider`,onSubmit:async e=>{if(e.preventDefault(),!s.trim()){k(`Display Name is required`);return}if(!u.trim()){k(`Provider ID (slug) is required`);return}if(!p.trim()){k(`Base URL is required`);return}let t=z(T),i=u.trim().toLowerCase(),a=V?U:void 0;M(!0),k(null);try{let e={providerId:i,label:s.trim(),baseUrl:p.trim(),wireFamily:J,compatibilityProfile:{cli_identity:x,...a===void 0?{}:{service_kinds:a},...Object.keys(t).length>0?{extra_headers:t}:{}}};await r.mutateAsync(e),_.trim()&&await ee.mutateAsync({providerId:i,request:{credentialKind:`api_key`,secret:_.trim()}}),y&&await te.mutateAsync(i),n()}catch(e){k(f(e,`Failed to create provider`))}finally{M(!1)}},className:`flex flex-col gap-6`,children:[D?(0,R.jsx)(`div`,{className:`text-red text-caption`,children:D}):null,(0,R.jsx)(O,{label:`Display Name`,hint:`Required. A friendly label for this node.`,id:`compat-label`,value:s,onChange:e=>c(e.target.value),placeholder:K?`Anthropic Compatible (Prod)`:`OpenAI Compatible (Prod)`,required:!0}),(0,R.jsx)(O,{label:`Provider ID / Slug`,hint:`Required. Used as the provider prefix for model IDs.`,id:`compat-slug`,value:u,onChange:e=>d(e.target.value),placeholder:K?`ac-prod`:`oc-prod`,required:!0}),(0,R.jsxs)(`div`,{className:`form-group`,children:[(0,R.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-url`,children:[(0,R.jsx)(`span`,{children:`Base URL`}),(0,R.jsxs)(`span`,{className:`form-hint`,children:[`The root only. Do not paste the full endpoint — leave off`,K?" `/v1/messages`.":" `/chat/completions`."]})]}),(0,R.jsxs)(j,{gap:`8px`,children:[(0,R.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,R.jsx)(O,{id:`compat-url`,value:p,onChange:e=>h(e.target.value),placeholder:K?`https://api.anthropic.com/v1`:`https://api.openai.com/v1`,required:!0})}),(0,R.jsx)(i,{type:`button`,variant:`secondary`,onClick:()=>Z(h),children:`Paste`})]}),X===null?null:(0,R.jsxs)(`p`,{className:`mt-1.5 text-caption text-orange`,children:[`That looks like a full endpoint. Use`,` `,(0,R.jsx)(`code`,{className:`font-mono`,children:X}),` instead — Cartethyia appends the endpoint path itself.`]})]}),K?null:(0,R.jsx)(re,{id:`compat-wire`,label:`API format`,value:J,onValueChange:e=>Y(e),options:[{value:`chat`,label:`Chat completions`},{value:`responses`,label:`Responses`}]}),(0,R.jsxs)(`div`,{className:`form-group`,children:[(0,R.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-credential`,children:[(0,R.jsx)(`span`,{children:`API Key`}),(0,R.jsx)(`span`,{className:`form-hint`,children:`Optional — saved with this provider and used to authenticate every request.`})]}),(0,R.jsxs)(j,{gap:`8px`,children:[(0,R.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,R.jsx)(O,{id:`compat-credential`,type:`password`,placeholder:`sk-...`,value:_,onChange:e=>v(e.target.value)})}),(0,R.jsx)(i,{type:`button`,variant:`secondary`,disabled:I,onClick:()=>void Q(),children:I?`Testing...`:`Test connection`}),(0,R.jsx)(i,{type:`button`,variant:`secondary`,onClick:()=>Z(v),children:`Paste`})]}),P?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:a(`mt-3 text-caption leading-[1.4] break-words`,P.ok?`text-green`:`text-red`),children:[P.ok?`✓ `:`✗ `,P.message]}),P.warning?(0,R.jsxs)(`div`,{className:`mt-2 text-caption leading-snug break-words text-orange`,children:[`⚠ `,P.warning]}):null]}):null]}),(0,R.jsx)(N,{actions:(0,R.jsx)(ne,{checked:y,onChange:b,id:`compat-autofetch`}),children:(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`text-body font-semibold`,children:`Auto-fetch models`}),(0,R.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Discover this provider's model list automatically after creation`})]})}),(0,R.jsx)(N,{actions:(0,R.jsx)(i,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>H(e=>!e),"aria-expanded":V,children:V?`Done`:`Configure`}),children:(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`text-body font-semibold`,children:`Advanced capabilities`}),(0,R.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:V?`Check the surfaces this upstream answers. Agentic (LLM) is always on.`:U.length>1?`${U.length-1} enabled · ${U.filter(e=>e!==`llm`).map(ae).join(`, `)}`:`Agentic only (LLM) — enable image, video, embeddings, and audio here`})]})}),V?(0,R.jsx)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-2 rounded-control border border-inner-border bg-surface-1 p-4`,children:G.map(e=>{let t=U.includes(e.kind);return(0,R.jsxs)(`label`,{className:`flex items-center gap-2.5 cursor-pointer text-caption text-text-secondary`,children:[(0,R.jsx)(`input`,{type:`checkbox`,className:`cursor-pointer`,checked:t,onChange:()=>W(n=>t?n.filter(t=>t!==e.kind):[...n,e.kind])}),(0,R.jsx)(`span`,{children:e.label})]},e.kind)})}):null,(0,R.jsx)(N,{actions:(0,R.jsx)(ne,{checked:x,onChange:w,id:`compat-cli-identity`}),children:(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`text-body font-semibold`,children:K?`Send request as Claude CLI`:`Send request as Codex CLI`}),(0,R.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:K?`Emits official Claude CLI User-Agent and Stainless headers to upstream`:`Emits official codex_cli_rs User-Agent and originator headers to upstream`})]})}),(0,R.jsx)(ie,{pairs:T,onChange:E})]})})}function Y({customProvider:e}){let t=v(),[n,r]=(0,L.useState)(!1);return(0,R.jsxs)(E,{className:V,children:[(0,R.jsx)(de,{clientVersion:e.clientVersion}),e.enabled?null:(0,R.jsx)(W,{label:`Disabled`,title:`Provider disabled`,tone:`danger`}),(0,R.jsx)(_,{to:`/providers/${encodeURIComponent(e.providerId)}`,className:a(H,`pr-20 min-h-38`),children:(0,R.jsxs)(j,{gap:`10px`,children:[(0,R.jsx)(k,{icon:e.wireFamilyDefault===`messages`?`anthropic`:`openai`,name:e.label||e.providerId,size:32,imageSize:24}),(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,R.jsx)(`div`,{className:U,children:e.label||e.providerId}),e.baseUrl?(0,R.jsxs)(`div`,{className:`mt-1 min-w-0 truncate font-mono text-micro text-text-tertiary`,title:e.baseUrl,children:[(0,R.jsx)(`span`,{className:`font-semibold text-text-secondary`,children:`Base URL`}),` `,e.baseUrl]}):null,(0,R.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:e.accountCount===void 0?(0,R.jsx)($,{kind:`accounts`,isPending:!1,isError:!1,hasData:!1}):e.accountCount===0?e.requiresAccount===!1?(0,R.jsx)(D,{tone:`ok`,children:`Free Endpoint`}):(0,R.jsx)(D,{children:`No connections`}):(0,R.jsx)(ue,{activeCount:e.activeAccountCount,total:e.accountCount})})]}),(0,R.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,R.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),e.modelCount!==void 0&&e.modelCount>0?(0,R.jsxs)(D,{tone:`info`,children:[e.modelCount,` models`]}):null,e.modelCount===void 0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!1}):e.modelCount===0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})}),(0,R.jsx)(i,{variant:`ghost`,size:`sm`,icon:(0,R.jsx)(d,{size:12}),onClick:()=>r(!0),className:`absolute top-2 right-2 p-2 text-text-tertiary`,title:`Delete ${e.label||e.providerId}`}),(0,R.jsx)(l,{open:n,onClose:()=>r(!1),title:`Delete Custom Provider`,children:(0,R.jsxs)(A,{gap:`12px`,children:[(0,R.jsxs)(`p`,{className:`text-body text-text-secondary`,children:[`Are you sure you want to delete custom provider`,` `,(0,R.jsx)(`strong`,{children:e.label||e.providerId}),`? Its models, accounts, and routing preferences are deleted together, and requests to this provider will no longer route.`]}),t.isError?(0,R.jsx)(`p`,{className:`text-caption text-red`,children:f(t.error,`Delete failed`)}):null,(0,R.jsxs)(p,{children:[(0,R.jsx)(i,{variant:`secondary`,onClick:()=>r(!1),children:`Cancel`}),(0,R.jsx)(i,{variant:`danger`,onClick:()=>{t.mutate(e.providerId,{onSuccess:()=>r(!1),onError:()=>void 0})},disabled:t.isPending,children:t.isPending?`Deleting...`:`Delete Provider`})]})]})})]})}function X({customProviders:e}){let[t,n]=(0,L.useState)(!1),[r,a]=(0,L.useState)(!1),[o,s]=(0,L.useState)(()=>{try{return window.localStorage.getItem(`cartethyia.customProvidersHidden`)===`1`}catch{return!1}});function c(){s(e=>{let t=!e;try{window.localStorage.setItem(`cartethyia.customProvidersHidden`,t?`1`:`0`)}catch{}return t})}return(0,R.jsxs)(`section`,{className:`flex flex-col gap-5`,children:[(0,R.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-4`,children:[(0,R.jsxs)(`button`,{type:`button`,onClick:c,"aria-expanded":!o,title:o?`Show custom providers`:`Hide custom providers`,className:`inline-flex items-center gap-3 bg-transparent border-none p-0 cursor-pointer text-inherit`,children:[(0,R.jsxs)(`h2`,{className:`text-body-lg font-bold tracking-[-0.01em]`,children:[`Custom Providers`,e.length>0?` (${e.length})`:``]}),(0,R.jsx)(x,{size:14,className:`text-text-tertiary transition-transform`,style:{transform:o?`rotate(-90deg)`:void 0}})]}),(0,R.jsxs)(j,{gap:`8px`,children:[(0,R.jsx)(i,{size:`sm`,variant:`ghost`,icon:o?(0,R.jsx)(te,{size:13}):(0,R.jsx)(ee,{size:13}),onClick:c,title:o?`Show custom providers`:`Hide custom providers`,children:o?`Show`:`Hide`}),(0,R.jsx)(i,{size:`sm`,variant:`secondary`,icon:(0,R.jsx)(u,{size:13}),onClick:()=>n(!0),children:`Custom Anthropic`}),(0,R.jsx)(i,{size:`sm`,variant:`secondary`,icon:(0,R.jsx)(u,{size:13}),onClick:()=>a(!0),children:`Custom OpenAI`})]})]}),o?null:e.length===0?(0,R.jsx)(E,{children:(0,R.jsxs)(w,{className:`text-center px-7 py-10 border border-dashed border-inner-border rounded-card`,children:[(0,R.jsx)(`p`,{className:`text-body font-semibold text-text-primary`,children:`No custom providers yet`}),(0,R.jsx)(`p`,{className:`text-badge text-text-tertiary mt-1`,children:`Add an OpenAI- or Anthropic-compatible endpoint with the buttons above.`})]})}):(0,R.jsx)(B,{children:e.map(e=>(0,R.jsx)(Y,{customProvider:e},e.providerId))}),(0,R.jsx)(J,{variant:`anthropic-compatible`,open:t,onClose:()=>n(!1)}),(0,R.jsx)(J,{variant:`openai-compatible`,open:r,onClose:()=>a(!1)})]})}var Z=new Set([`inferhub`]),Q=new Set([`grok`,`opencode`,`cline`,`hermes`,`kilo`,`inception`,`zcode-start`,`freepi`,`perch`,`zro`,`freebuff`,`clixad`,`vercel`,`deepai`]),se=new Set([`anthropic`,`openai`,`gemini`,`alibabacp`,`ollamacloud`,`opencode-zen`,`opencode-go`,`mistral`,`meta`,`deepseek`,`commandcode`,`dashscope`]);function ce(e){return e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0}function le(e){return e.oauthFlows?.refreshable===!0}function ue({activeCount:e,total:t}){return e===void 0?(0,R.jsxs)(D,{tone:`warn`,dot:!0,children:[t,` Connected`]}):e===0?(0,R.jsxs)(D,{tone:`warn`,dot:!0,children:[t,` Unhealthy`]}):e===t?(0,R.jsxs)(D,{tone:`ok`,dot:!0,children:[t,` Healthy`]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(D,{tone:`ok`,dot:!0,children:[e,` Healthy`]}),(0,R.jsxs)(D,{tone:`warn`,dot:!0,children:[t-e,` Unhealthy`]})]})}function $({kind:e,isPending:t,isError:n,hasData:r,isEmpty:i=!1}){let a=e===`models`?`Models`:`Connections`;return n?(0,R.jsxs)(D,{tone:`warn`,children:[a,` unavailable`]}):t&&!r?(0,R.jsxs)(D,{tone:`info`,children:[`Loading `,a.toLowerCase(),`…`]}):i?(0,R.jsx)(D,{children:e===`models`?`No models`:`No connections`}):null}function de({clientVersion:e}){return e?(0,R.jsxs)(D,{className:`provider-version-badge absolute -top-4.5 left-5 right-auto z-chip max-w-[calc(100%-var(--spacing)*10)] truncate px-3 py-1 text-micro leading-[1.15] shadow-card max-small:left-4 max-small:max-w-[calc(100%-var(--spacing)*8)]`,tone:e.source===`latest`?`teal`:`default`,title:e.source===`latest`?`Latest discovered client version`:`Pinned fallback; background discovery has not succeeded yet`,children:[`v`,e.version,` · `,e.source]}):null}var fe=(0,L.memo)(function({provider:e,serviceKind:t}){let n=Z.has(e.providerId.toLowerCase()),r=e.label||e.displayName;return(0,R.jsxs)(E,{className:V,children:[(0,R.jsx)(de,{clientVersion:e.clientVersion}),e.enabled?n?(0,R.jsx)(W,{label:`Friend`,title:`Friend sponsor`,tone:`accent`}):null:(0,R.jsx)(W,{label:`Disabled`,title:`Provider disabled`,tone:`danger`}),(0,R.jsx)(_,{to:`/providers/${encodeURIComponent(e.providerId)}${t===void 0?``:`?service=${t}`}`,className:H,children:(0,R.jsxs)(j,{gap:`10px`,children:[(0,R.jsx)(k,{icon:e.providerId,name:r,size:32,imageSize:24}),(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,R.jsx)(`div`,{className:U,children:r}),(0,R.jsx)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:e.accountCount===void 0?(0,R.jsx)($,{kind:`accounts`,isPending:!1,isError:!1,hasData:!1}):e.accountCount===0?e.requiresAccount===!1?(0,R.jsx)(D,{tone:`ok`,children:`Free Endpoint`}):(0,R.jsx)(D,{children:`No connections`}):(0,R.jsx)(ue,{activeCount:e.activeAccountCount,total:e.accountCount})})]}),(0,R.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,R.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),e.modelCount!==void 0&&e.modelCount>0?(0,R.jsxs)(D,{tone:`info`,children:[e.modelCount,` models`]}):null,e.modelCount===void 0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!1}):e.modelCount===0?(0,R.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})})]})});function pe(e,t){let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n}var me=`cartethyia.providerSectionsCollapsed`,he=`cartethyia:providers:display-mode`;function ge(){try{if(typeof window>`u`)return null;let e=window.localStorage.getItem(he);return e===`all`||e!==`paginated`&&null}catch{return null}}function _e(e){try{window.localStorage.setItem(he,e?`all`:`paginated`)}catch{}}var ve=`Other API Key Providers`;function ye(){try{let e=window.localStorage.getItem(me);if(e===null)return new Set([ve]);let t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set([ve])}}var be=`text-body font-bold tracking-[-0.01em]`,xe=[{title:`Founding Friend & Sponsors`,subtitle:`Super Cheap inference pool`,filter:e=>Z.has(e.providerId.toLowerCase())},{title:`Free Limited Providers`,filter:e=>Q.has(e.providerId.toLowerCase())},{title:`OAuth & Agent Providers`,filter:e=>(ce(e)||le(e))&&!Q.has(e.providerId.toLowerCase())},{title:`Well Known API Key Providers`,subtitle:`The household names — sign up with a key and go`,filter:e=>e.isBuiltIn&&se.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q.has(e.providerId.toLowerCase())&&!ce(e)&&!le(e)},{title:`Other API Key Providers`,subtitle:`Free tier friendly — no credit card`,filter:e=>e.isBuiltIn&&!se.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q.has(e.providerId.toLowerCase())&&!ce(e)&&!le(e)}];function Se(){let[e,t]=(0,L.useState)(ye),n=h(),r=P(),l=r.enabled,u=e=>!l||e.configured===!0||e.requiresAccount===!1,d=(0,L.useMemo)(()=>n.data??[],[n.data]),p=(0,L.useMemo)(()=>[...d.filter(e=>!e.isBuiltIn&&u(e))].sort(pe),[d,l]),m=(0,L.useMemo)(()=>d.filter(e=>K(e).includes(`websearch`)&&u(e)),[d,l]),g=(0,L.useMemo)(()=>d.filter(e=>K(e).includes(`llm`)&&u(e)),[d,l]),[_,v]=y(),S=_.get(`tab`),C=S===`search`||S===`media`?S:`llm`,ne=e=>{v(t=>{let n=new URLSearchParams(t);return e===`llm`?n.delete(`tab`):n.set(`tab`,e),n})},D=(0,L.useMemo)(()=>d.filter(e=>(K(e).includes(`imageGeneration`)||K(e).includes(`videoGeneration`))&&u(e)),[d,l]),O=(0,L.useMemo)(()=>[...m].sort((e,t)=>(e.label||e.displayName).localeCompare(t.label||t.displayName)),[m]),re=(e,t)=>{let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n},k=(0,L.useMemo)(()=>{if(C===`media`)return[{title:`Media Generation`,subtitle:`Providers that can return an image or a video`,providers:D}].filter(e=>e.providers.length>0);if(C===`search`)return[{title:`Search Providers`,subtitle:`Providers that can answer a web search request`,providers:O}].filter(e=>e.providers.length>0);let e=g;return xe.map(t=>({...t,providers:e.filter(t.filter).sort(re)})).filter(e=>e.providers.length>0)},[g,O,D,C]),[j,N]=(0,L.useState)({}),[z,ie]=(0,L.useState)(()=>ge()??!1),V=()=>{ie(e=>{let t=!e;return _e(t),t})},H=e=>j[e]??1,U=e=>t=>N(n=>({...n,[e]:t})),W=(e,t)=>{if(z)return{visible:e,pageCount:1,safePage:1};let n=H(t),r=Math.max(1,Math.ceil(e.length/8)),i=Math.min(n,r);return{visible:e.slice((i-1)*8,i*8),pageCount:r,safePage:i}},G=n.isPending&&!n.data?(0,R.jsx)(s,{label:`Loading providers...`}):n.isError?(0,R.jsx)(o,{message:f(n.error,`Failed to load providers`),onRetry:()=>n.refetch()}):null;return G?(0,R.jsxs)(E,{children:[(0,R.jsx)(T,{title:`Providers`,icon:(0,R.jsx)(b,{size:16})}),(0,R.jsx)(w,{className:`flex flex-1`,children:G})]}):(0,R.jsx)(A,{gap:`24px`,children:(0,R.jsxs)(E,{children:[(0,R.jsx)(T,{title:`Providers`,subtitle:`Connected pinned first · A–Z`,icon:(0,R.jsx)(b,{size:16})}),(0,R.jsxs)(w,{className:`flex flex-col gap-8`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,R.jsx)(`div`,{className:`flex gap-2`,children:[`llm`,`search`,`media`].map(e=>(0,R.jsxs)(`button`,{onClick:()=>ne(e),className:a(`px-6 py-3 rounded-inset text-caption font-semibold border cursor-pointer`,C===e?`border-accent bg-accent-soft text-accent`:`border-inner-border bg-surface-1 text-text-secondary`),children:[e===`llm`?`LLM`:e===`search`?`Search`:`Media`,e===`search`?` (${m.length})`:e===`media`?` (${D.length})`:` (${g.length})`]},e))}),(0,R.jsx)(i,{variant:`ghost`,size:`sm`,icon:l?(0,R.jsx)(ee,{size:12}):(0,R.jsx)(te,{size:12}),onClick:()=>r.setEnabled(!l),title:l?`Show providers that have no account yet`:`Hide providers that have no account yet`,children:l?`Show unconfigured`:`Hide unconfigured`}),(0,R.jsx)(i,{variant:`ghost`,size:`sm`,icon:z?(0,R.jsx)(I,{size:12}):(0,R.jsx)(F,{size:12}),onClick:V,title:z?`Paginate each section (8 per page)`:`Show every provider in each section at once`,children:z?`Paginated`:`Show All`}),(0,R.jsx)(`span`,{className:`ml-auto text-micro text-text-tertiary`,children:C===`search`?`Fallback runs only when the model invokes Websearch`:C===`media`?`Image and video generation`:`Connected pinned first · A–Z`})]}),C===`llm`?(0,R.jsx)(X,{customProviders:p}):null,k.length===0?(0,R.jsx)(E,{children:(0,R.jsx)(w,{children:(0,R.jsx)(c,{title:`No providers found`,message:`No providers available.`})})}):k.map(n=>{let r=e.has(n.title);return(0,R.jsxs)(`section`,{className:`flex flex-col gap-6`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`flex items-start gap-4 border-0 bg-transparent p-0 text-left text-inherit`,"aria-expanded":!r,onClick:()=>t(e=>{let t=new Set(e);t.has(n.title)?t.delete(n.title):t.add(n.title);try{window.localStorage.setItem(me,JSON.stringify([...t]))}catch{}return t}),children:[(0,R.jsx)(x,{size:15,className:a(`mt-1 shrink-0 transition-transform`,r&&`-rotate-90`)}),(0,R.jsxs)(A,{gap:`1px`,children:[(0,R.jsxs)(`h2`,{className:be,children:[n.title,` (`,n.providers.length,`)`,r?` (Hidden)`:``]}),!r&&n.subtitle?(0,R.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:n.subtitle}):null]})]}),r?null:(0,R.jsx)(B,{children:W(n.providers,n.title).visible.map(e=>(0,R.jsx)(fe,{provider:e,serviceKind:C===`search`?`websearch`:C===`media`?K(e).includes(`imageGeneration`)?`imageGeneration`:`videoGeneration`:`llm`},e.providerId))}),r?null:(()=>{let{pageCount:e,safePage:t}=W(n.providers,n.title);return e>1?(0,R.jsx)(M,{page:t,pageCount:e,onPageChange:U(n.title),testId:`providers-section-pagination-${n.title}`}):null})()]},n.title)})]})]})})}export{Se as default};