cartethyia 2.5.4 → 2.5.7

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 (395) hide show
  1. package/.env.example +13 -4
  2. package/README.md +2 -2
  3. package/dist/dashboard/assets/{BannedPage-C2orBsI2.js → BannedPage-DE2607Tb.js} +1 -1
  4. package/dist/dashboard/assets/BannedPage-DE2607Tb.js.gz +0 -0
  5. package/dist/dashboard/assets/CliToolDetailPage-Duv6mfrl.js +1 -0
  6. package/dist/dashboard/assets/CliToolDetailPage-Duv6mfrl.js.gz +0 -0
  7. package/dist/dashboard/assets/{CliToolsPage-BV6pxVQo.js → CliToolsPage-C2PNYWzk.js} +1 -1
  8. package/dist/dashboard/assets/CliToolsPage-C2PNYWzk.js.gz +0 -0
  9. package/dist/dashboard/assets/CombosPage-TXP9OfAM.js +1 -0
  10. package/dist/dashboard/assets/CombosPage-TXP9OfAM.js.gz +0 -0
  11. package/dist/dashboard/assets/{ConsoleLogPage-CW-wPmJ6.js → ConsoleLogPage-B-9xnAQN.js} +1 -1
  12. package/dist/dashboard/assets/ConsoleLogPage-B-9xnAQN.js.gz +0 -0
  13. package/dist/dashboard/assets/{CustomizationPage-0p8uX7vB.js → CustomizationPage-xeax9nJt.js} +1 -1
  14. package/dist/dashboard/assets/CustomizationPage-xeax9nJt.js.gz +0 -0
  15. package/dist/dashboard/assets/{HealthEventsModal-BjqSMfko.js → HealthEventsModal-Df4jjaHJ.js} +1 -1
  16. package/dist/dashboard/assets/HealthEventsModal-Df4jjaHJ.js.gz +0 -0
  17. package/dist/dashboard/assets/{LoginPage-BvzCx8Kr.js → LoginPage-Dyojsm84.js} +1 -1
  18. package/dist/dashboard/assets/LoginPage-Dyojsm84.js.gz +0 -0
  19. package/dist/dashboard/assets/ModelPicker-C7pDb41R.js +1 -0
  20. package/dist/dashboard/assets/ModelPicker-C7pDb41R.js.gz +0 -0
  21. package/dist/dashboard/assets/OverviewPage-BJfg4ow6.js +1 -0
  22. package/dist/dashboard/assets/OverviewPage-BJfg4ow6.js.gz +0 -0
  23. package/dist/dashboard/assets/ProviderDetailPage-ChCX1gmT.js +3 -0
  24. package/dist/dashboard/assets/ProviderDetailPage-ChCX1gmT.js.gz +0 -0
  25. package/dist/dashboard/assets/{ProvidersPage-Js9jUPSb.js → ProvidersPage-DeWSOEUO.js} +1 -1
  26. package/dist/dashboard/assets/ProvidersPage-DeWSOEUO.js.gz +0 -0
  27. package/dist/dashboard/assets/ProxyPage-CkpWln2S.js +7 -0
  28. package/dist/dashboard/assets/ProxyPage-CkpWln2S.js.gz +0 -0
  29. package/dist/dashboard/assets/QuotaPage-B3VOgQmt.js +1 -0
  30. package/dist/dashboard/assets/QuotaPage-B3VOgQmt.js.gz +0 -0
  31. package/dist/dashboard/assets/SettingsPage-C_klIZom.js +1 -0
  32. package/dist/dashboard/assets/SettingsPage-C_klIZom.js.gz +0 -0
  33. package/dist/dashboard/assets/{SetupPage-DDbMQsoo.js → SetupPage-BYph-InK.js} +1 -1
  34. package/dist/dashboard/assets/SetupPage-BYph-InK.js.gz +0 -0
  35. package/dist/dashboard/assets/{SortableList-CB3Z7VTf.js → SortableList-CvyQCYWJ.js} +1 -1
  36. package/dist/dashboard/assets/SortableList-CvyQCYWJ.js.gz +0 -0
  37. package/dist/dashboard/assets/{StudioPage-D95UCPHI.js → StudioPage-Cm1JYilI.js} +3 -3
  38. package/dist/dashboard/assets/StudioPage-Cm1JYilI.js.gz +0 -0
  39. package/dist/dashboard/assets/UsagePage-DlFnc3_S.js +56 -0
  40. package/dist/dashboard/assets/UsagePage-DlFnc3_S.js.gz +0 -0
  41. package/dist/dashboard/assets/api-keys-DQYLQxpW.js +1 -0
  42. package/dist/dashboard/assets/api-keys-DQYLQxpW.js.gz +0 -0
  43. package/dist/dashboard/assets/app-CX_Z8cMs.css +2 -0
  44. package/dist/dashboard/assets/app-CX_Z8cMs.css.gz +0 -0
  45. package/dist/dashboard/assets/{assert-Chi7pCnt.js → assert-C9FD_JwJ.js} +1 -1
  46. package/dist/dashboard/assets/assert-C9FD_JwJ.js.gz +0 -0
  47. package/dist/dashboard/assets/{badge-D4pQapKj.js → badge-CR72dasT.js} +1 -1
  48. package/dist/dashboard/assets/badge-CR72dasT.js.gz +0 -0
  49. package/dist/dashboard/assets/{banner-DH6cg-_B.js → banner-CI9_eSfO.js} +1 -1
  50. package/dist/dashboard/assets/banner-CI9_eSfO.js.gz +0 -0
  51. package/dist/dashboard/assets/{card-BKqlUOe4.js → card-DS7CQEsO.js} +1 -1
  52. package/dist/dashboard/assets/card-DS7CQEsO.js.gz +0 -0
  53. package/dist/dashboard/assets/{cli-tools-fTgljTGA.js → cli-tools-CNqzrfdb.js} +1 -1
  54. package/dist/dashboard/assets/cli-tools-CNqzrfdb.js.gz +0 -0
  55. package/dist/dashboard/assets/{clipboard-button-D5Ys_sM0.js → clipboard-button-611pSsaX.js} +1 -1
  56. package/dist/dashboard/assets/clipboard-button-611pSsaX.js.gz +0 -0
  57. package/dist/dashboard/assets/{fingerprint-pattern-BWuHtbW4.js → concurrency-BDF0ok7y.js} +1 -1
  58. package/dist/dashboard/assets/concurrency-BDF0ok7y.js.gz +0 -0
  59. package/dist/dashboard/assets/dialog-k37exjNt.js +1 -0
  60. package/dist/dashboard/assets/dialog-k37exjNt.js.gz +0 -0
  61. package/dist/dashboard/assets/drawer-CX7N8ucR.js +1 -0
  62. package/dist/dashboard/assets/drawer-CX7N8ucR.js.gz +0 -0
  63. package/dist/dashboard/assets/{entry-CQBr6U9c.js → entry-B9Xvtnfj.js} +1 -1
  64. package/dist/dashboard/assets/entry-B9Xvtnfj.js.gz +0 -0
  65. package/dist/dashboard/assets/entry-Bog0p925.js +4 -0
  66. package/dist/dashboard/assets/entry-Bog0p925.js.gz +0 -0
  67. package/dist/dashboard/assets/entry-CTP8AyiS.js +1 -0
  68. package/dist/dashboard/assets/entry-CTP8AyiS.js.gz +0 -0
  69. package/dist/dashboard/assets/{github-badge-BlptL8Uf.js → github-badge-sltk1qUi.js} +1 -1
  70. package/dist/dashboard/assets/github-badge-sltk1qUi.js.gz +0 -0
  71. package/dist/dashboard/assets/{index-js6TJvdr.js → index-CZQIrdoX.js} +2 -2
  72. package/dist/dashboard/assets/index-CZQIrdoX.js.gz +0 -0
  73. package/dist/dashboard/assets/{inline-DUWDSmDV.js → inline-BhY2sSnO.js} +1 -1
  74. package/dist/dashboard/assets/inline-BhY2sSnO.js.gz +0 -0
  75. package/dist/dashboard/assets/{input-LVjgZq4f.js → input-V1umFiBk.js} +1 -1
  76. package/dist/dashboard/assets/input-V1umFiBk.js.gz +0 -0
  77. package/dist/dashboard/assets/layout-BBOYycyS.js +1 -0
  78. package/dist/dashboard/assets/layout-BBOYycyS.js.gz +0 -0
  79. package/dist/dashboard/assets/{list-row-DupvLfDx.js → list-row-1zzZYM0B.js} +1 -1
  80. package/dist/dashboard/assets/list-row-1zzZYM0B.js.gz +0 -0
  81. package/dist/dashboard/assets/{live-C4pEJUqI.js → live-BivGfuUs.js} +1 -1
  82. package/dist/dashboard/assets/live-BivGfuUs.js.gz +0 -0
  83. package/dist/dashboard/assets/{model-bans-BRiuufkB.js → model-bans-CmffjLuG.js} +1 -1
  84. package/dist/dashboard/assets/model-bans-CmffjLuG.js.gz +0 -0
  85. package/dist/dashboard/assets/{mutation-B4ROwk8L.js → mutation-46P0oWMe.js} +1 -1
  86. package/dist/dashboard/assets/mutation-46P0oWMe.js.gz +0 -0
  87. package/dist/dashboard/assets/numbers-DkfMR5Qs.js +2 -0
  88. package/dist/dashboard/assets/numbers-DkfMR5Qs.js.gz +0 -0
  89. package/dist/dashboard/assets/{query-keys-gmjzC3RS.js → query-keys-BFhGpwR1.js} +1 -1
  90. package/dist/dashboard/assets/query-keys-BFhGpwR1.js.gz +0 -0
  91. package/dist/dashboard/assets/{routing-C7tBT5o-.js → routing-CAb4F37R.js} +1 -1
  92. package/dist/dashboard/assets/routing-CAb4F37R.js.gz +0 -0
  93. package/dist/dashboard/assets/{select-WUCXorXw.js → select-BPpSsBgL.js} +1 -1
  94. package/dist/dashboard/assets/select-BPpSsBgL.js.gz +0 -0
  95. package/dist/dashboard/assets/{settings-C_zKl1GS.js → settings-DNX9sydi.js} +1 -1
  96. package/dist/dashboard/assets/settings-DNX9sydi.js.gz +0 -0
  97. package/dist/dashboard/assets/{stack-_3O0F8Xn.js → stack-BHTfXdz_.js} +1 -1
  98. package/dist/dashboard/assets/stack-BHTfXdz_.js.gz +0 -0
  99. package/dist/dashboard/assets/{state-BgTxHcJS.js → state-mPDRlQkl.js} +1 -1
  100. package/dist/dashboard/assets/state-mPDRlQkl.js.gz +0 -0
  101. package/dist/dashboard/assets/{switch-DEjTtOWf.js → switch-DOmJxg7H.js} +1 -1
  102. package/dist/dashboard/assets/switch-DOmJxg7H.js.gz +0 -0
  103. package/dist/dashboard/assets/tokens-COzario9.js +1 -0
  104. package/dist/dashboard/assets/tokens-COzario9.js.gz +0 -0
  105. package/dist/dashboard/assets/use-modal-focus-By7oJoGd.js +1 -0
  106. package/dist/dashboard/assets/use-modal-focus-By7oJoGd.js.gz +0 -0
  107. package/dist/dashboard/assets/{useMutation-BWSC0UAS.js → useMutation-Dem0lXQj.js} +1 -1
  108. package/dist/dashboard/assets/useMutation-Dem0lXQj.js.gz +0 -0
  109. package/dist/dashboard/index.html +1 -1
  110. package/dist/dashboard/index.html.gz +0 -0
  111. package/dist/dashboard/precompressed-assets.json +54 -54
  112. package/migrations/README.md +52 -52
  113. package/migrations/lite-sqlite3/0000_baseline.sql +2 -2
  114. package/package.json +95 -95
  115. package/scripts/cli/admin.ts +125 -0
  116. package/scripts/cli/{ui/background.ts → background.ts} +1 -1
  117. package/scripts/cli/{command/console-menu.ts → console-menu.ts} +275 -244
  118. package/scripts/cli/doctor.ts +37 -0
  119. package/scripts/cli/{support/env.ts → env.ts} +99 -99
  120. package/scripts/cli/{gateway/spawn.ts → gateway.ts} +112 -24
  121. package/scripts/cli/instance.ts +224 -0
  122. package/scripts/cli/main.ts +61 -18
  123. package/scripts/cli/{support/platform.ts → platform.ts} +64 -64
  124. package/scripts/cli/port.ts +100 -0
  125. package/scripts/cli/{support/services.ts → services.ts} +88 -88
  126. package/scripts/cli/{command/setup.ts → setup.ts} +35 -34
  127. package/scripts/cli/{command/start.ts → start.ts} +10 -5
  128. package/scripts/cli/{support/startup-signal.ts → startup-signal.ts} +23 -23
  129. package/scripts/cli/tray/index.ts +62 -12
  130. package/scripts/cli/{command/tray.ts → tray.ts} +208 -208
  131. package/scripts/cli/{command/update.ts → update.ts} +39 -39
  132. package/scripts/cli/version.ts +67 -0
  133. package/scripts/cli/{ui/wordmark.ts → wordmark.ts} +58 -58
  134. package/src/boot/app.ts +697 -693
  135. package/src/boot/dependencies.ts +647 -646
  136. package/src/boot/timeout.ts +2 -13
  137. package/src/config/cooldowns.ts +186 -138
  138. package/src/config/network.ts +8 -14
  139. package/src/config/providers.ts +7 -10
  140. package/src/config/runtime.ts +76 -76
  141. package/src/config/security.ts +15 -0
  142. package/src/config/spec.ts +20 -30
  143. package/src/config/telemetry.ts +0 -20
  144. package/src/config/timeouts.ts +0 -6
  145. package/src/console/admin/model-abuse/contracts.ts +28 -6
  146. package/src/console/admin/model-abuse/routes.ts +56 -3
  147. package/src/console/api-keys/contracts.ts +410 -414
  148. package/src/console/api-keys/routes.ts +881 -880
  149. package/src/console/auth/credentials.ts +3 -3
  150. package/src/console/auth/setup-service.ts +2 -2
  151. package/src/console/backup/export-endpoint.ts +6 -2
  152. package/src/console/backup/nine-router.ts +2 -5
  153. package/src/console/backup/service.ts +4 -0
  154. package/src/console/backup/store.ts +192 -29
  155. package/src/console/backup/validate.ts +3 -45
  156. package/src/console/cli-tools/fs-ops.ts +487 -487
  157. package/src/console/console-router-guards.ts +1 -1
  158. package/src/console/data-management/contracts.ts +13 -6
  159. package/src/console/data-management/operations.ts +23 -18
  160. package/src/console/data-management/routes.ts +0 -1
  161. package/src/console/domain-registration.ts +10 -5
  162. package/src/console/observability/live.ts +22 -0
  163. package/src/console/observability/store.ts +39 -16
  164. package/src/console/observability/usage-dimensions.ts +4 -4
  165. package/src/console/providers/catalog/catalog-projections.ts +6 -7
  166. package/src/console/providers/catalog/model-operations.ts +5 -2
  167. package/src/console/providers/catalog/provider-operations.ts +4 -4
  168. package/src/console/providers/catalog/public-model-store.ts +8 -11
  169. package/src/console/providers/catalog/store.ts +1553 -1553
  170. package/src/console/providers/oauth/routes.ts +8 -12
  171. package/src/console/quota/account-quota-tenant.ts +6 -6
  172. package/src/console/quota/quota-view.ts +1 -1
  173. package/src/console/remote-support/contracts.ts +61 -0
  174. package/src/console/remote-support/routes.ts +65 -0
  175. package/src/console/remote-support/service.ts +207 -0
  176. package/src/console/response-compression.ts +0 -3
  177. package/src/console/routing/pools/probe-result.ts +3 -2
  178. package/src/console/routing/pools/probe-verdict.ts +132 -132
  179. package/src/console/routing/pools/store.ts +8 -8
  180. package/src/console/settings/contracts.ts +58 -2
  181. package/src/console/settings/store.ts +30 -3
  182. package/src/console/shared/cursor.ts +8 -8
  183. package/src/console/shared/errors.ts +1 -3
  184. package/src/network/http2-bidi.ts +2 -4
  185. package/src/network/pool/agent.ts +478 -478
  186. package/src/network/pool/selector.ts +5 -4
  187. package/src/network/retry.ts +1 -2
  188. package/src/network/ssrf.ts +5 -4
  189. package/src/observability/event-compaction.ts +80 -78
  190. package/src/observability/event-day-index.ts +13 -15
  191. package/src/observability/event-log.ts +4 -4
  192. package/src/observability/logger.ts +6 -6
  193. package/src/observability/payload-capture.ts +151 -33
  194. package/src/observability/payload-store.ts +397 -440
  195. package/src/observability/redaction.ts +5 -6
  196. package/src/observability/request-notify.ts +43 -0
  197. package/src/observability/telemetry-status.ts +8 -9
  198. package/src/observability/token-speed.ts +5 -4
  199. package/src/persistence/db-mode.ts +7 -7
  200. package/src/persistence/readiness.ts +1 -1
  201. package/src/persistence/schema.ts +1406 -1402
  202. package/src/persistence/shared-cache.ts +1 -2
  203. package/src/persistence/stores/api-key-store.ts +18 -6
  204. package/src/persistence/stores/share-store.ts +4 -3
  205. package/src/persistence/stores/telemetry-store.ts +236 -237
  206. package/src/protocol/canonical-model.ts +11 -3
  207. package/src/protocol/codecs.ts +138 -4
  208. package/src/protocol/gateway-error.ts +6 -4
  209. package/src/protocol/request/chat.ts +21 -1
  210. package/src/protocol/request/codex.ts +10 -1
  211. package/src/protocol/request/messages.ts +4 -5
  212. package/src/protocol/request/responses.ts +9 -1
  213. package/src/protocol/response/chat.ts +34 -4
  214. package/src/protocol/response/codex.ts +7 -4
  215. package/src/protocol/response/dsml.ts +140 -28
  216. package/src/protocol/response/responses.ts +11 -5
  217. package/src/protocol/stream-error-frames.ts +4 -5
  218. package/src/providers/authentication/jwt-validator.ts +9 -10
  219. package/src/providers/authentication/oauth-refresh-service.ts +9 -11
  220. package/src/providers/configured-openai-providers.ts +134 -136
  221. package/src/providers/discovery/catalog/catalog-blob.ts +18 -18
  222. package/src/providers/discovery/catalog/catalog-format.ts +3 -6
  223. package/src/providers/discovery/models-dev-catalog.ts +354 -354
  224. package/src/providers/discovery/probe-phases.ts +4 -4
  225. package/src/providers/discovery/probe-wire.ts +6 -13
  226. package/src/providers/discovery/probing-service.ts +1117 -1045
  227. package/src/providers/integrations/alibabacp/alibabacp.ts +1 -1
  228. package/src/providers/integrations/antigravity/antigravity-quota.ts +5 -7
  229. package/src/providers/integrations/buddy/buddy-chat-shared.ts +23 -2
  230. package/src/providers/integrations/buddy/buddy-checkin.ts +1 -4
  231. package/src/providers/integrations/buddy/buddy-cli-headers.ts +23 -6
  232. package/src/providers/integrations/buddy/buddy-conversation-headers.ts +0 -1
  233. package/src/providers/integrations/buddy/buddy-identity.ts +52 -0
  234. package/src/providers/integrations/buddy/buddy-media.ts +2 -2
  235. package/src/providers/integrations/buddy/buddy-usage-store.ts +3 -4
  236. package/src/providers/integrations/buddy/codebuddy/quota.ts +2 -13
  237. package/src/providers/integrations/buddy/codebuddy/shared.ts +118 -115
  238. package/src/providers/integrations/buddy/workbuddy/quota.ts +0 -11
  239. package/src/providers/integrations/buddy/workbuddy/shared.ts +5 -2
  240. package/src/providers/integrations/claude/claude.ts +608 -608
  241. package/src/providers/integrations/cline/cline-quota.ts +132 -132
  242. package/src/providers/integrations/cline/cline.ts +537 -539
  243. package/src/providers/integrations/codex/codex-oauth.ts +1 -1
  244. package/src/providers/integrations/commandcode/commandcode.ts +674 -675
  245. package/src/providers/integrations/commandcode/discovery.ts +117 -116
  246. package/src/providers/integrations/cursor/cursor-auth.ts +418 -418
  247. package/src/providers/integrations/cursor/cursor-quota.ts +309 -310
  248. package/src/providers/integrations/cursor/cursor.ts +11 -163
  249. package/src/providers/integrations/factory/factory-models.ts +3 -5
  250. package/src/providers/integrations/grok/grok-install-id.ts +2 -3
  251. package/src/providers/integrations/grok/grok.ts +6 -7
  252. package/src/providers/integrations/hermes.ts +14 -18
  253. package/src/providers/integrations/kiro/kiro-discovery.ts +1 -1
  254. package/src/providers/integrations/kiro/kiro.ts +1 -1
  255. package/src/providers/integrations/mistral.ts +6 -6
  256. package/src/providers/integrations/opencode/fingerprint.ts +3 -3
  257. package/src/providers/integrations/opencode/provider.ts +8 -8
  258. package/src/providers/integrations/qoder/qoder-catalog.ts +450 -450
  259. package/src/providers/integrations/qoder/qoder-oauth.ts +388 -310
  260. package/src/providers/integrations/qoder/qoder.ts +884 -865
  261. package/src/providers/integrations/shared/connect.ts +6 -6
  262. package/src/providers/integrations/trae/trae-catalog.ts +1 -2
  263. package/src/providers/integrations/trae/trae.ts +2 -2
  264. package/src/providers/integrations/zcode/oauth.ts +6 -1
  265. package/src/providers/operations/account-health-service.ts +1528 -1523
  266. package/src/providers/operations/account-reset-service.ts +1 -1
  267. package/src/providers/operations/client-versions.ts +6 -6
  268. package/src/providers/operations/custom-cli-headers.ts +3 -4
  269. package/src/providers/operations/provider-catalog-seeder.ts +95 -95
  270. package/src/providers/operations/provider-catalog-service.ts +3 -4
  271. package/src/providers/provider-metadata.ts +4 -8
  272. package/src/providers/provider-registry.ts +6 -7
  273. package/src/providers/provider-usage.ts +1 -1
  274. package/src/security/abuse.ts +15 -10
  275. package/src/security/access-control.ts +144 -146
  276. package/src/security/admission/contracts.ts +11 -0
  277. package/src/security/admission/in-memory-store.ts +4 -3
  278. package/src/security/admission/lease-sweep.ts +6 -6
  279. package/src/security/admission/reasons.ts +5 -1
  280. package/src/security/admission/redis-store.ts +211 -210
  281. package/src/security/admission/service.ts +4 -0
  282. package/src/security/api-key-auth.ts +504 -504
  283. package/src/security/ip-boundary.ts +155 -15
  284. package/src/security/model-abuse.ts +366 -94
  285. package/src/security/outbound-headers.ts +3 -4
  286. package/src/shared/sleep.ts +4 -0
  287. package/src/transport/dispatch/attempt-finalize.ts +47 -5
  288. package/src/transport/dispatch/attempt-loop.ts +531 -530
  289. package/src/transport/dispatch/stream-bridge.ts +1 -3
  290. package/src/transport/dispatch/streaming/finalize.ts +1 -1
  291. package/src/transport/dispatch/streaming/stream.ts +5 -6
  292. package/src/transport/failure-policy.ts +162 -8
  293. package/src/transport/guards/auth-guard.ts +7 -4
  294. package/src/transport/guards/concurrency-guard.ts +0 -5
  295. package/src/transport/guards/error-lifecycle.ts +13 -6
  296. package/src/transport/guards/pipeline.ts +15 -3
  297. package/src/transport/guards/request-context.ts +8 -2
  298. package/src/transport/request/inflight.ts +5 -6
  299. package/src/transport/request/preparer.ts +2 -2
  300. package/src/transport/request/state.ts +12 -8
  301. package/src/transport/routing/admission.ts +4 -0
  302. package/src/transport/routing/route-catalog.ts +8 -1
  303. package/src/transport/routing/route-model.ts +46 -14
  304. package/src/transport/routing/router.ts +21 -14
  305. package/src/transport/surface/completion.ts +2 -3
  306. package/src/transport/surface/dialects.ts +5 -6
  307. package/src/transport/surface/responses/encode.ts +38 -0
  308. package/src/transport/surface/responses/parse.ts +4 -0
  309. package/src/transport/translation/capabilities.ts +2 -3
  310. package/src/transport/translation/quirks.ts +3 -3
  311. package/src/workers/buddy-growth-tasks.ts +5 -10
  312. package/src/workers/daily-checkin.ts +17 -23
  313. package/src/workers/quota-refresh-sweep.ts +26 -26
  314. package/dist/dashboard/assets/BannedPage-C2orBsI2.js.gz +0 -0
  315. package/dist/dashboard/assets/CliToolDetailPage-DUcZ6pMB.js +0 -1
  316. package/dist/dashboard/assets/CliToolDetailPage-DUcZ6pMB.js.gz +0 -0
  317. package/dist/dashboard/assets/CliToolsPage-BV6pxVQo.js.gz +0 -0
  318. package/dist/dashboard/assets/CombosPage-Bsan4679.js +0 -1
  319. package/dist/dashboard/assets/CombosPage-Bsan4679.js.gz +0 -0
  320. package/dist/dashboard/assets/ConsoleLogPage-CW-wPmJ6.js.gz +0 -0
  321. package/dist/dashboard/assets/CustomizationPage-0p8uX7vB.js.gz +0 -0
  322. package/dist/dashboard/assets/HealthEventsModal-BjqSMfko.js.gz +0 -0
  323. package/dist/dashboard/assets/LoginPage-BvzCx8Kr.js.gz +0 -0
  324. package/dist/dashboard/assets/ModelPicker-BY1aKEkP.js +0 -1
  325. package/dist/dashboard/assets/ModelPicker-BY1aKEkP.js.gz +0 -0
  326. package/dist/dashboard/assets/OverviewPage-DOQpy1y0.js +0 -1
  327. package/dist/dashboard/assets/OverviewPage-DOQpy1y0.js.gz +0 -0
  328. package/dist/dashboard/assets/ProviderDetailPage-ecxyUMzt.js +0 -3
  329. package/dist/dashboard/assets/ProviderDetailPage-ecxyUMzt.js.gz +0 -0
  330. package/dist/dashboard/assets/ProvidersPage-Js9jUPSb.js.gz +0 -0
  331. package/dist/dashboard/assets/ProxyPage-J3TBi3Kx.js +0 -7
  332. package/dist/dashboard/assets/ProxyPage-J3TBi3Kx.js.gz +0 -0
  333. package/dist/dashboard/assets/QuotaPage-C1gZS6xr.js +0 -1
  334. package/dist/dashboard/assets/QuotaPage-C1gZS6xr.js.gz +0 -0
  335. package/dist/dashboard/assets/SettingsPage-CS86ho5X.js +0 -1
  336. package/dist/dashboard/assets/SettingsPage-CS86ho5X.js.gz +0 -0
  337. package/dist/dashboard/assets/SetupPage-DDbMQsoo.js.gz +0 -0
  338. package/dist/dashboard/assets/SortableList-CB3Z7VTf.js.gz +0 -0
  339. package/dist/dashboard/assets/StudioPage-D95UCPHI.js.gz +0 -0
  340. package/dist/dashboard/assets/UsagePage-Cnae9SWA.js +0 -56
  341. package/dist/dashboard/assets/UsagePage-Cnae9SWA.js.gz +0 -0
  342. package/dist/dashboard/assets/api-keys-VY68Mhd1.js +0 -1
  343. package/dist/dashboard/assets/api-keys-VY68Mhd1.js.gz +0 -0
  344. package/dist/dashboard/assets/app-COlK95oi.css +0 -2
  345. package/dist/dashboard/assets/app-COlK95oi.css.gz +0 -0
  346. package/dist/dashboard/assets/assert-Chi7pCnt.js.gz +0 -0
  347. package/dist/dashboard/assets/badge-D4pQapKj.js.gz +0 -0
  348. package/dist/dashboard/assets/banner-DH6cg-_B.js.gz +0 -0
  349. package/dist/dashboard/assets/card-BKqlUOe4.js.gz +0 -0
  350. package/dist/dashboard/assets/cli-tools-fTgljTGA.js.gz +0 -0
  351. package/dist/dashboard/assets/clipboard-button-D5Ys_sM0.js.gz +0 -0
  352. package/dist/dashboard/assets/dialog-BYj-8WuK.js +0 -1
  353. package/dist/dashboard/assets/dialog-BYj-8WuK.js.gz +0 -0
  354. package/dist/dashboard/assets/drawer-CmXIZ6H1.js +0 -1
  355. package/dist/dashboard/assets/drawer-CmXIZ6H1.js.gz +0 -0
  356. package/dist/dashboard/assets/entry-CBg5zeu8.js +0 -1
  357. package/dist/dashboard/assets/entry-CBg5zeu8.js.gz +0 -0
  358. package/dist/dashboard/assets/entry-CQBr6U9c.js.gz +0 -0
  359. package/dist/dashboard/assets/entry-CgdSAzEV.js +0 -4
  360. package/dist/dashboard/assets/entry-CgdSAzEV.js.gz +0 -0
  361. package/dist/dashboard/assets/fingerprint-pattern-BWuHtbW4.js.gz +0 -0
  362. package/dist/dashboard/assets/github-badge-BlptL8Uf.js.gz +0 -0
  363. package/dist/dashboard/assets/index-js6TJvdr.js.gz +0 -0
  364. package/dist/dashboard/assets/inline-DUWDSmDV.js.gz +0 -0
  365. package/dist/dashboard/assets/input-LVjgZq4f.js.gz +0 -0
  366. package/dist/dashboard/assets/layout-CPfxpsfy.js +0 -1
  367. package/dist/dashboard/assets/layout-CPfxpsfy.js.gz +0 -0
  368. package/dist/dashboard/assets/list-row-DupvLfDx.js.gz +0 -0
  369. package/dist/dashboard/assets/live-C4pEJUqI.js.gz +0 -0
  370. package/dist/dashboard/assets/model-bans-BRiuufkB.js.gz +0 -0
  371. package/dist/dashboard/assets/mutation-B4ROwk8L.js.gz +0 -0
  372. package/dist/dashboard/assets/numbers-YNcHvRY7.js +0 -2
  373. package/dist/dashboard/assets/numbers-YNcHvRY7.js.gz +0 -0
  374. package/dist/dashboard/assets/query-keys-gmjzC3RS.js.gz +0 -0
  375. package/dist/dashboard/assets/routing-C7tBT5o-.js.gz +0 -0
  376. package/dist/dashboard/assets/select-WUCXorXw.js.gz +0 -0
  377. package/dist/dashboard/assets/settings-C_zKl1GS.js.gz +0 -0
  378. package/dist/dashboard/assets/stack-_3O0F8Xn.js.gz +0 -0
  379. package/dist/dashboard/assets/state-BgTxHcJS.js.gz +0 -0
  380. package/dist/dashboard/assets/switch-DEjTtOWf.js.gz +0 -0
  381. package/dist/dashboard/assets/tokens-DDxMbSRL.js +0 -1
  382. package/dist/dashboard/assets/tokens-DDxMbSRL.js.gz +0 -0
  383. package/dist/dashboard/assets/use-presence-BSZEBx7U.js +0 -1
  384. package/dist/dashboard/assets/use-presence-BSZEBx7U.js.gz +0 -0
  385. package/dist/dashboard/assets/useMutation-BWSC0UAS.js.gz +0 -0
  386. package/scripts/cli/command/admin.ts +0 -65
  387. package/scripts/cli/command/doctor.ts +0 -257
  388. package/scripts/cli/gateway/drain-token.ts +0 -78
  389. package/scripts/cli/gateway/instance-lock.ts +0 -105
  390. package/scripts/cli/gateway/stop.ts +0 -51
  391. package/scripts/cli/support/bun.ts +0 -27
  392. package/scripts/cli/support/version.ts +0 -37
  393. /package/dist/dashboard/assets/{app-DCQZRmHY.js → app-BIt446yE.js} +0 -0
  394. /package/dist/dashboard/assets/{app-DCQZRmHY.js.gz → app-BIt446yE.js.gz} +0 -0
  395. /package/scripts/cli/{ui/prompt.ts → prompt.ts} +0 -0
@@ -1 +0,0 @@
1
- import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{n as i}from"./terminal-0_IjPWTk.js";import{a,i as o,n as s,r as c}from"./model-bans-BRiuufkB.js";import{n as l,t as u}from"./fingerprint-pattern-BWuHtbW4.js";import{D as d,T as f,b as p,c as m,k as h,s as g}from"./numbers-YNcHvRY7.js";import{t as _}from"./chevron-right-BXIy5l3h.js";import{t as v}from"./SortableList-CB3Z7VTf.js";import{t as y}from"./database-Dz9N3zGd.js";import{t as b}from"./eye-off-Bk5g2luF.js";import{t as x}from"./eye-C_hawfH4.js";import{t as S}from"./gauge-BbIMy7MB.js";import{n as C,r as w,t as ee}from"./state-BgTxHcJS.js";import{t as te}from"./key-round-UkavsGxp.js";import{n as T,r as E,t as D}from"./clipboard-button-D5Ys_sM0.js";import{t as O}from"./dialog-BYj-8WuK.js";import{t as ne}from"./pencil-768ysRAr.js";import{t as k}from"./plus-DIdX_g-x.js";import{t as A}from"./refresh-cw-BqJFk4sU.js";import{t as j}from"./route-CNSNj9Zm.js";import{t as M}from"./search-JOKus9rb.js";import{t as re}from"./shield-check-DVS0Foqh.js";import{n as ie,r as ae,t as N}from"./settings-C_zKl1GS.js";import{t as oe}from"./trash-Cppn5c3R.js";import{b as se,x as ce}from"./assert-Chi7pCnt.js";import{l as P}from"./query-keys-gmjzC3RS.js";import{it as F,j as le,lt as I,ot as ue,ut as de,z as L}from"./entry-CgdSAzEV.js";import{n as R,r as z,t as B}from"./card-BKqlUOe4.js";import{t as fe}from"./use-clipboard-B0Sy03fE.js";import{n as pe}from"./download-dRFo5_Wu.js";import{c as V,d as H}from"./tokens-DDxMbSRL.js";import{t as me}from"./badge-D4pQapKj.js";import{n as U,t as he}from"./input-LVjgZq4f.js";import{t as W}from"./select-WUCXorXw.js";import{t as ge}from"./ModelPicker-BY1aKEkP.js";import{t as G}from"./switch-DEjTtOWf.js";import{t as K}from"./stack-_3O0F8Xn.js";import{n as q}from"./inline-DUWDSmDV.js";import{a as _e,c as ve,d as J,f as ye,i as be,l as xe,n as Se,o as Ce,r as we,s as Te,t as Y,u as Ee}from"./api-keys-VY68Mhd1.js";import{a as X,i as Z,n as De,r as Oe}from"./cli-tools-fTgljTGA.js";import{t as ke}from"./layout-CPfxpsfy.js";import{s as Ae}from"./quota-DZGyp0N5.js";var je=e(`lock-keyhole`,[[`circle`,{cx:`12`,cy:`16`,r:`1`,key:`1au0dj`}],[`rect`,{x:`3`,y:`10`,width:`18`,height:`12`,rx:`2`,key:`6s8ecr`}],[`path`,{d:`M7 10V7a5 5 0 0 1 10 0v3`,key:`1pqi11`}]]),Me=e(`repeat-2`,[[`path`,{d:`m2 9 3-3 3 3`,key:`1ltn5i`}],[`path`,{d:`M13 18H7a2 2 0 0 1-2-2V6`,key:`1r6tfw`}],[`path`,{d:`m22 15-3 3-3-3`,key:`4rnwn2`}],[`path`,{d:`M11 6h6a2 2 0 0 1 2 2v10`,key:`2f72bc`}]]),Ne=e(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),Pe=e(`scissors`,[[`circle`,{cx:`6`,cy:`6`,r:`3`,key:`1lh9wr`}],[`path`,{d:`M8.12 8.12 12 12`,key:`1alkpv`}],[`path`,{d:`M20 4 8.12 15.88`,key:`xgtan2`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M14.8 14.8 20 20`,key:`ptml3r`}]]),Fe=e(`share-2`,[[`circle`,{cx:`18`,cy:`5`,r:`3`,key:`gq8acd`}],[`circle`,{cx:`6`,cy:`12`,r:`3`,key:`w7nqdw`}],[`circle`,{cx:`18`,cy:`19`,r:`3`,key:`1xt0gg`}],[`line`,{x1:`8.59`,x2:`15.42`,y1:`13.51`,y2:`17.49`,key:`47mynk`}],[`line`,{x1:`15.41`,x2:`8.59`,y1:`6.51`,y2:`10.49`,key:`1n3mei`}]]),Ie=e(`shield-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71`,key:`1jlk70`}],[`path`,{d:`M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264`,key:`18rp1v`}]]),Le=e(`shield-x`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m14.5 9.5-5 5`,key:`17q4r4`}],[`path`,{d:`m9.5 9.5 5 5`,key:`18nt4w`}]]),Re=e(`undo-2`,[[`path`,{d:`M9 14 4 9l5-5`,key:`102s5s`}],[`path`,{d:`M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11`,key:`f3b9sd`}]]),ze=e(`user-round`,[[`circle`,{cx:`12`,cy:`8`,r:`5`,key:`1hypcn`}],[`path`,{d:`M20 21a8 8 0 0 0-16 0`,key:`rfgkzh`}]]),Be=e(`users-round`,[[`path`,{d:`M18 21a8 8 0 0 0-16 0`,key:`3ypg7q`}],[`circle`,{cx:`10`,cy:`8`,r:`5`,key:`o932ke`}],[`path`,{d:`M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3`,key:`10s06x`}]]),Ve=[`routing:invoke`,`routing:cli_mapping`,`search:invoke`,`dashboard:read`,`dashboard:write`,`providers:read`,`providers:write`,`models:read`,`models:write`],He=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],Q=t(n(),1),$=r(),Ue={"routing:invoke":`Call /v1/* gateway routes within this tenant.`,"routing:cli_mapping":`Resolve persisted CLI source→target model mappings.`,"search:invoke":`Call POST /v1/search with exa.`,"dashboard:read":`Read this tenant's configuration and usage.`,"dashboard:write":`Modify this tenant's configuration.`,"providers:read":`Read provider rows, including accounts.`,"providers:write":`Add, modify, or delete provider rows and their credentials.`,"models:read":`Read catalog model rows.`,"models:write":`Add, modify, or delete catalog model rows.`},We={"routing:invoke":j,"routing:cli_mapping":j,"search:invoke":M,"dashboard:read":x,"dashboard:write":ne,"providers:read":F,"providers:write":je,"models:read":l,"models:write":y},Ge={k:1e3,m:1e6,b:1e9,t:0xe8d4a51000},Ke=[{label:`1M`,amount:1e6,description:`1 million`},{label:`100M`,amount:1e8,description:`100 million`},{label:`1B`,amount:1e9,description:`1 billion`},{label:`1T`,amount:0xe8d4a51000,description:`1 trillion`}];function qe(e){let t=e.trim().toLowerCase();if(!t)return;let n=t.match(/^([\d.]+)\s*([kmbt])?$/);if(!n)return;let r=Number(n[1]);if(!Number.isFinite(r)||r<=0)return;let i=n[2]?Ge[n[2]]??1:1;return Math.round(r*i)}function Je(e){if(e==null)return``;let t=Ke.find(t=>t.amount===e);return t?t.label:e>=1e9?`${(e/1e9).toFixed(1).replace(/\.0$/,``)}B`:e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}K`:String(e)}function Ye(e){let t=Number(e.trim());return Number.isFinite(t)&&t>0?Math.round(t):void 0}function Xe(e){let t=Ye(e);return e.trim()===``?null:t}function Ze({label:e,value:t,onChange:n,disabled:r}){let i=qe(t),a=Ke.find(e=>e.amount===i)?.label;return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(U,{label:e,value:t,onChange:e=>n(e.target.value),placeholder:`e.g. 1M, 500K`,disabled:r}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-3 mt-3`,role:`group`,"aria-label":`${e} presets`,children:Ke.map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":a===e.label,"aria-label":`${e.label}, ${e.description} tokens`,onClick:()=>n(e.label),disabled:r,className:`py-1 px-4 rounded-chip text-micro font-semibold`,style:{cursor:r?`not-allowed`:`pointer`,border:`1px solid ${a===e.label?`var(--accent)`:`var(--inner-border)`}`,background:a===e.label?`var(--accent-soft)`:`transparent`,color:a===e.label?`var(--accent)`:`var(--text-tertiary)`},children:e.label},e.label))})]})}function Qe({tool:e,keyId:t,busy:n,scopeGranted:r,onScopeChange:i}){let a=Z(e.id,t),o=Oe(),s=De(),c=a.data?.enabled??!1,l=r&&c,u=a.data?.mappings.length??0,d=o.isPending||s.isPending;return(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 py-2 px-5 rounded-inset`,style:{minHeight:`44px`,border:`1px solid var(--inner-border)`,background:l?`var(--accent-soft)`:`var(--surface-1)`},children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-start gap-3`,children:[(0,$.jsx)(j,{size:16,className:`mt-1 shrink-0 text-accent`,"aria-hidden":`true`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-caption font-semibold text-text-primary`,children:e.name}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:l?`Remote routing on — ${u} route${u===1?``:`s`} active, routing:cli_mapping granted.`:`Remote routing off — this key's requests go straight to the provider.`})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,$.jsx)(G,{checked:l,disabled:n||d||a.isLoading,"aria-label":`Enable remote routing for ${e.name}`,onChange:n=>{n!==r&&i(n),o.mutate({toolId:e.id,keyId:t,input:{enabled:n,mappings:a.data?.mappings??[]}},{onSuccess:()=>g.success(`Saved remote routing for ${e.name}.`),onError:e=>g.error(P(e,`Could not save remote routing.`))})}}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,disabled:n||d||!c&&u===0,onClick:()=>s.mutate({toolId:e.id,keyId:t},{onSuccess:()=>g.success(`Cleared remote routes for ${e.name}.`),onError:e=>g.error(P(e,`Could not reset remote routes.`))}),children:s.isPending?`Resetting…`:`Reset`})]})]})}function $e({keyId:e,busy:t,scopeGranted:n,onScopeChange:r,persistScope:i}){let a=(X().data??[]).filter(e=>e.mappingSupported);return e.length===0||a.length===0?null:(0,$.jsxs)(`section`,{"aria-labelledby":`remote-routing-heading`,className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h4`,{id:`remote-routing-heading`,className:`inline-flex items-center gap-2 text-caption font-bold text-text-primary`,children:[(0,$.jsx)(j,{size:15,className:`text-accent`,"aria-hidden":`true`}),`Remote routing`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:`Route this key's CLI model calls through persisted mappings and grant routing:cli_mapping. Applies immediately — no save needed.`})]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-3`,children:a.map(a=>(0,$.jsx)(Qe,{tool:a,keyId:e,busy:t,scopeGranted:n,onScopeChange:e=>{r(e),i(e)}},a.id))})]})}function et(e,t,n){let r=e===`personal`?t.trim():``;return{keyMode:e,keyPrefix:n.trim()||void 0,...r?{key:r}:{}}}function tt(e,t){return e===`personal`?t??null:null}function nt(e){if(e?.isDefault)return[...Ve];let t=e?.scopes;return t&&t.length>0?[...t]:[`routing:invoke`,`search:invoke`]}function rt({mode:e,record:t,busy:n,onDone:r,onClose:i,actionsRef:o}){let[s,c]=(0,Q.useState)(t?.label??``),[d,f]=(0,Q.useState)(t?.keyPrefix??``),[p,h]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(t?.requestsPerMinute?.toString()??``),[y,b]=(0,Q.useState)(Je(t?.dailyTokenLimit??null)),[x,C]=(0,Q.useState)(Je(t?.monthlyTokenLimit??null)),[w,ee]=(0,Q.useState)(Je(t?.lifetimeTokenBudget??null)),[E,D]=(0,Q.useState)(t?.lifetimeTokenBudget==null?`recurring`:`one-time`),[O,ne]=(0,Q.useState)(t?.maxConcurrentRequests?.toString()??``),[k,A]=(0,Q.useState)(()=>nt(t)),[M,ie]=(0,Q.useState)(t?.modelAccessMode??`whitelist`),[N,oe]=(0,Q.useState)(()=>{let e=t?.modelList;return e?[...e]:[]}),[F,le]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(()=>{let e=t?.clientRouterDenylist;return e?[...new Set(e.map(ce).filter(e=>e!==void 0))]:[]}),[R,z]=(0,Q.useState)(()=>t?.notesTitle??``),[B,fe]=(0,Q.useState)(()=>t?.notesSubtitle??``),[pe,V]=(0,Q.useState)(()=>t?.notesBody??``),[H,me]=(0,Q.useState)(t?.sharePopupEnabled??!1),[W,K]=(0,Q.useState)(null),[q,_e]=(0,Q.useState)(!1),[ve,J]=(0,Q.useState)(null),be=t?.sharePopupImageMime!==void 0,xe=W??(be&&!q&&t!==null?`/console/api/api-keys/${t.id}/share-popup-image`:null),[Se,Ce]=(0,Q.useState)(t?.sharePopupTitle??``),[we,Te]=(0,Q.useState)(t?.sharePopupBody??``),[Y,Ee]=(0,Q.useState)(t?.keyMode??`personal`),X=E===`one-time`,Z=e===`edit`,De=ye(),Oe=e=>A(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),ke=()=>{r({label:s.trim(),...et(Y,p,d),scopes:k,modelAccessMode:M,modelList:N,clientRouterDenylist:I,requestsPerMinute:Xe(_),maxConcurrentRequests:Xe(O),dailyTokenLimit:X?null:qe(y)??null,monthlyTokenLimit:X?null:qe(x)??null,lifetimeTokenBudget:X?qe(w)??null:null,notesTitle:R.trim(),notesSubtitle:B.trim(),notesBody:pe.trim(),sharePopupEnabled:H,...W===null?q?{sharePopupImage:null}:{}:{sharePopupImage:W},sharePopupTitle:Se.trim(),sharePopupBody:we.trim()})};return(0,Q.useEffect)(()=>{o?.((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(m,{variant:`secondary`,size:`sm`,onClick:i,disabled:n,children:`Cancel`}),(0,$.jsx)(m,{variant:`primary`,size:`sm`,disabled:n||e===`create`&&!s.trim(),onClick:ke,children:n?`Saving…`:e===`create`?`Create API key`:`Save changes`})]}))}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-6 min-w-0 pb-2`,children:[(0,$.jsxs)(`section`,{className:`flex flex-col gap-4 min-w-0 p-6 border border-inner-border rounded-card bg-surface-2 col-span-full`,children:[(0,$.jsxs)(`h3`,{className:`inline-flex items-center gap-2 text-body font-bold text-text-primary`,children:[(0,$.jsx)(te,{size:16,className:`text-accent`,"aria-hidden":`true`}),`Credential mode`]}),(0,$.jsx)(`div`,{role:`group`,"aria-label":`Credential mode`,className:`flex gap-4`,children:[`personal`,`share`].map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":Y===e,disabled:n||Z,onClick:()=>Ee(e),title:Z?`Credential mode cannot change after creation`:void 0,className:`rounded-inset py-2 px-6`,style:{border:`1px solid var(--inner-border)`,color:Y===e?`var(--accent)`:`var(--text-secondary)`,background:Y===e?`var(--accent-soft)`:`var(--surface-2)`,cursor:Z?`not-allowed`:`pointer`,opacity:Z&&Y!==e?.5:1},children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[e===`personal`?(0,$.jsx)(ze,{size:14,"aria-hidden":`true`}):(0,$.jsx)(Be,{size:14,"aria-hidden":`true`}),e===`personal`?`Personal`:`Share template`]})},e))}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:Y===`share`?`A share template does not authenticate requests. Recipients generate their own child key from its public enrollment page.`:`A personal key authenticates requests directly; its secret is shown once when created or rotated.`})]}),(0,$.jsxs)(`div`,{className:`columns-2 gap-6 min-w-0 max-medium:columns-1`,children:[e===`create`&&(0,$.jsxs)(`section`,{className:`flex flex-col gap-4 min-w-0 p-6 border border-inner-border rounded-card bg-surface-2 break-inside-avoid mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h3`,{className:`inline-flex items-center gap-2 text-body font-bold text-text-primary`,children:[(0,$.jsx)(u,{size:16,className:`text-accent`,"aria-hidden":`true`}),`Identity`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:`Give this credential a recognizable name.`})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 items-start min-w-0 max-medium:grid-cols-1`,children:[(0,$.jsx)(U,{label:`Name`,value:s,onChange:e=>c(e.target.value),placeholder:`ci-key…`,disabled:n,autoFocus:!0}),(0,$.jsx)(U,{label:`Key prefix`,value:d,onChange:e=>f(e.target.value),placeholder:`pn-carte- (default)…`,disabled:n||p.trim().length>0})]}),Y===`personal`&&(0,$.jsx)(U,{label:`Custom API key value (optional)`,value:p,onChange:e=>h(e.target.value),placeholder:`Leave blank to generate…`,disabled:n})]}),e===`edit`&&(0,$.jsxs)(`section`,{className:`flex flex-col gap-4 min-w-0 p-6 border border-inner-border rounded-card bg-surface-2 break-inside-avoid mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h3`,{className:`text-body font-bold text-text-primary`,children:[(0,$.jsx)(u,{size:16,className:`mr-2 inline text-accent`,"aria-hidden":`true`}),`Identity`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:t?.isDefault?`The default key's name is fixed. Limits, access, and everything else can still change.`:`Update the label for this credential.`})]}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-4 items-start min-w-0 max-medium:grid-cols-1`,children:(0,$.jsx)(U,{label:`Name`,value:s,onChange:e=>c(e.target.value),placeholder:`ci-key…`,disabled:n||t?.isDefault===!0,title:t?.isDefault?`The default gateway key keeps its name`:void 0,autoFocus:!0})})]}),(0,$.jsxs)(`section`,{className:`flex flex-col gap-4 min-w-0 p-6 border border-inner-border rounded-card bg-surface-2 break-inside-avoid mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h3`,{className:`text-body font-bold text-text-primary`,children:[(0,$.jsx)(T,{size:16,className:`mr-2 inline text-accent`,"aria-hidden":`true`}),`Share notes`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:`Optional copy shown on the public share page.`})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 items-start min-w-0 max-medium:grid-cols-1`,children:[(0,$.jsx)(U,{label:`Title`,value:R,onChange:e=>z(e.target.value),placeholder:`e.g. Bansos Token`,disabled:n}),(0,$.jsx)(U,{label:`Subtitle`,value:B,onChange:e=>fe(e.target.value),placeholder:`e.g. Come and save your tokens`,disabled:n}),(0,$.jsx)(U,{label:`Body`,value:pe,onChange:e=>V(e.target.value),placeholder:`Free-form notes for the recipient`,disabled:n})]})]}),(0,$.jsxs)(`section`,{className:`flex flex-col gap-4 min-w-0 p-6 border border-inner-border rounded-card bg-surface-2 break-inside-avoid mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h3`,{className:`text-body font-bold text-text-primary`,children:[(0,$.jsx)(S,{size:16,className:`mr-2 inline text-accent`,"aria-hidden":`true`}),`Limits`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:`Keep this credential predictable under load.`})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 items-start min-w-0 max-medium:grid-cols-1`,children:[(0,$.jsx)(U,{label:`Requests per minute`,type:`number`,min:`0`,value:_,onChange:e=>v(e.target.value),placeholder:`Unlimited…`,disabled:n}),(0,$.jsx)(U,{label:`Max concurrent requests`,type:`number`,min:`0`,value:O,onChange:e=>ne(e.target.value),placeholder:`Unlimited…`,disabled:n})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 rounded-panel border border-inner-border px-6 py-5 bg-surface-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`text-caption font-bold text-text-primary`,children:[(0,$.jsx)(S,{size:14,className:`mr-2 inline text-accent`,"aria-hidden":`true`}),`Token budget`]}),(0,$.jsx)(`p`,{className:`mt-1 text-text-tertiary text-micro`,children:X?`One-time cap; it does not reset.`:`Daily and monthly limits reset automatically.`})]}),(0,$.jsxs)(`div`,{className:`flex gap-2 rounded-inset border border-inner-border bg-surface-1 p-1`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(`recurring`),disabled:n,className:`py-2 px-5 rounded-chip font-semibold border-0 cursor-pointer`,style:{fontSize:`10.5px`,background:X?`transparent`:`var(--accent-soft)`,color:X?`var(--text-tertiary)`:`var(--accent)`},children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsx)(Me,{size:13,"aria-hidden":`true`}),`Recurring`]})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(`one-time`),disabled:n,className:`py-2 px-5 rounded-chip font-semibold border-0 cursor-pointer`,style:{fontSize:`10.5px`,background:X?`var(--accent-soft)`:`transparent`,color:X?`var(--accent)`:`var(--text-tertiary)`},children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsx)(je,{size:13,"aria-hidden":`true`}),`One-time`]})})]})]}),X?(0,$.jsx)(Ze,{label:`One-time token limit`,value:w,onChange:ee,disabled:n}):(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 items-start min-w-0 max-medium:grid-cols-1`,children:[(0,$.jsx)(Ze,{label:`Daily token limit`,value:y,onChange:b,disabled:n}),(0,$.jsx)(Ze,{label:`Monthly token limit`,value:x,onChange:C,disabled:n})]})]})]}),(0,$.jsxs)(`section`,{className:`flex flex-col gap-4 min-w-0 p-6 border border-inner-border rounded-card bg-surface-2 col-span-full`,"aria-labelledby":`share-popup-heading`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h3`,{id:`share-popup-heading`,className:`text-body font-bold text-text-primary`,children:[(0,$.jsx)(Fe,{size:16,className:`mr-2 inline text-accent`,"aria-hidden":`true`}),`Share page popup`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:`Optional card visitors open from the Base URL card on your share page.`})]}),(0,$.jsx)(G,{checked:H,onChange:e=>me(e),disabled:n,label:`Enable popup`})]}),H?(0,$.jsxs)(`div`,{className:`flex gap-7 items-start mt-2 min-w-0 max-medium:flex-col max-medium:items-stretch`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 min-w-0 w-100 shrink-0 max-medium:w-auto`,children:[xe?(0,$.jsx)(`img`,{className:`block w-full h-66 object-cover border border-inner-border rounded-control bg-surface-1 max-medium:h-80`,src:xe,alt:`Popup image preview`}):(0,$.jsx)(`div`,{className:`flex items-center justify-center w-full h-66 object-cover border border-dashed border-inner-border rounded-control bg-surface-1 text-text-tertiary text-badge max-medium:h-80`,"aria-hidden":`true`,children:(0,$.jsx)(`span`,{children:`No image`})}),(0,$.jsx)(he,{id:`share-popup-image`,accept:He.join(`,`),"aria-label":`Popup image`,disabled:n,onChange:e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;if(J(null),t.size>2097152){K(null),J(`Image must be 2 MB or smaller.`);return}let n=new FileReader;n.onload=()=>{K(String(n.result)),_e(!1)},n.onerror=()=>J(`Could not read that file.`),n.readAsDataURL(t)}}),xe?(0,$.jsx)(m,{variant:`secondary`,size:`sm`,type:`button`,disabled:n,className:`h-14 px-5 text-badge self-start`,onClick:()=>{K(null),_e(!0),J(null)},children:`Remove image`}):null,ve?(0,$.jsx)(`p`,{className:`form-error`,children:ve}):null,(0,$.jsx)(`p`,{className:`m-0 text-text-tertiary text-badge leading-normal`,children:`PNG, JPEG, WebP, or GIF up to 2 MB.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 min-w-0 flex-1 [&_.form-group]:gap-2`,children:[(0,$.jsx)(U,{label:`Popup title`,value:Se,onChange:e=>Ce(e.target.value),maxLength:120,placeholder:`Support this gateway`,disabled:n}),(0,$.jsxs)(`div`,{className:`form-group`,children:[(0,$.jsx)(`label`,{className:`form-label`,htmlFor:`share-popup-copy`,children:`Message`}),(0,$.jsx)(`textarea`,{className:`form-textarea`,id:`share-popup-copy`,value:we,onChange:e=>Te(e.target.value),maxLength:1200,rows:3,placeholder:`If this service helps you, consider supporting its upkeep…`,disabled:n})]})]})]}):null]}),(0,$.jsxs)(`details`,{className:`group min-w-0 col-span-full rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center justify-between gap-4 p-6 [&::-webkit-details-marker]:hidden`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-start gap-3`,children:[(0,$.jsx)(`span`,{className:`grid size-10 shrink-0 place-items-center rounded-inset bg-accent-soft text-accent`,children:(0,$.jsx)(ae,{size:18,"aria-hidden":`true`})}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block text-body font-bold text-text-primary`,children:`Access`}),(0,$.jsx)(`span`,{className:`mt-1 block text-badge text-text-tertiary`,children:t?.isDefault?`Default gateway key · all tenant permissions, including gateway routing and remote debugging.`:`Choose model, router, and dashboard permissions for this key.`})]})]}),(0,$.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-2 rounded-control border border-inner-border bg-surface-1 px-3 py-2 text-micro font-semibold text-text-secondary`,children:[k.length,`/`,Ve.length,` grants`,(0,$.jsx)(de,{size:14,className:`transition-transform group-open:rotate-180`,"aria-hidden":`true`})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-5 border-t border-inner-border p-6`,children:[t?.isDefault?(0,$.jsxs)(`div`,{className:`flex items-start gap-3 rounded-control border border-accent/30 bg-accent-soft p-4 text-badge text-text-secondary`,children:[(0,$.jsx)(re,{size:16,className:`mt-0.5 shrink-0 text-accent`,"aria-hidden":`true`}),(0,$.jsxs)(`p`,{className:`m-0`,children:[`This default API key is provisioned with every tenant permission, including `,(0,$.jsx)(`code`,{children:`routing:invoke`}),` and`,` `,(0,$.jsx)(`code`,{children:`routing:cli_mapping`}),`. Those grant gateway access and authorization to use remote CLI mappings; each client's mapping toggle below still controls whether those routes are active. You can remove individual grants here.`]})]}):null,(0,$.jsxs)(`div`,{className:`columns-2 gap-6 min-w-0 max-medium:columns-1`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 text-badge font-semibold text-text-secondary block mb-3`,children:[(0,$.jsx)(l,{size:14,className:`text-accent`,"aria-hidden":`true`}),`Model access`]}),(0,$.jsx)(`div`,{role:`group`,"aria-label":`Model access mode`,className:`flex gap-3 mb-4`,children:[`whitelist`,`blacklist`].map(e=>(0,$.jsxs)(`button`,{type:`button`,"aria-pressed":M===e,disabled:n,onClick:()=>ie(e),title:e===`whitelist`?`Only the listed models may be used. An empty list allows every model.`:`The listed models are refused. Everything else is allowed.`,className:`flex-1 py-2.5 px-4 text-badge font-semibold`,style:{borderRadius:`7px`,border:`1px solid ${M===e?`var(--accent)`:`var(--inner-border)`}`,background:M===e?`var(--accent-soft)`:`var(--surface-2)`,color:M===e?`var(--accent)`:`var(--text-secondary)`,cursor:n?`not-allowed`:`pointer`,opacity:n?.6:1},children:[e===`whitelist`?`Whitelist`:`Blacklist`,e===`whitelist`?(0,$.jsx)(re,{size:13,className:`ml-2 inline`,"aria-hidden":`true`}):(0,$.jsx)(Le,{size:13,className:`ml-2 inline`,"aria-hidden":`true`})]},e))}),(0,$.jsx)(`label`,{className:`text-badge font-semibold text-text-secondary block mb-3`,children:M===`whitelist`?`Allowed models`:`Blocked models`}),(0,$.jsx)(`div`,{className:`flex gap-3 flex-wrap mb-4`,children:N.length===0?(0,$.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:M===`whitelist`?`All models allowed`:`No models blocked`}):N.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-4 rounded-chip border border-accent`,children:[e,(0,$.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e} from the model list`,onClick:()=>oe(t=>t.filter(t=>t!==e)),disabled:n,className:`bg-transparent border-0 cursor-pointer p-0 flex`,children:`×`})]},e))}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,type:`button`,onClick:()=>le(!0),disabled:n,children:`Browse models`}),(0,$.jsx)(ge,{open:F,onClose:()=>le(!1),selected:N,onToggle:e=>oe(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),title:M===`whitelist`?`Select allowed models`:`Select blocked models`,multi:!0})]}),(0,$.jsxs)(`section`,{"aria-labelledby":`blocked-routers-heading`,className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h4`,{id:`blocked-routers-heading`,className:`inline-flex items-center gap-2 text-caption font-bold text-text-primary`,children:[(0,$.jsx)(a,{size:15,className:`text-accent`,"aria-hidden":`true`}),`Blocked client routers`]}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:`Matching fingerprints are rejected with 403 before routing. Detection is best-effort; clients without a fingerprint are not matched. This may also block bazaar probe links that share the same fingerprint.`})]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-3`,children:se.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 py-2 px-5 rounded-inset`,style:{minHeight:`44px`,border:`1px solid var(--inner-border)`,background:I.includes(e.id)?`var(--accent-soft)`:`var(--surface-1)`},children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-start gap-3`,children:[(0,$.jsx)(a,{size:15,className:`mt-1 shrink-0 text-orange`,"aria-hidden":`true`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`text-caption text-text-primary`,children:[`Block `,e.label,` Client`]}),(0,$.jsxs)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Reject requests fingerprinted as `,e.label,`.`]})]})]}),(0,$.jsx)(G,{checked:I.includes(e.id),onChange:t=>L(n=>t?[...n,e.id]:n.filter(t=>t!==e.id)),disabled:n,"aria-label":`Block ${e.label} client`})]},e.id))})]}),(0,$.jsxs)(`section`,{"aria-labelledby":`routing-scopes-heading`,className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`h4`,{id:`routing-scopes-heading`,className:`inline-flex items-center gap-2 text-caption font-bold text-text-primary`,children:[(0,$.jsx)(j,{size:15,className:`text-accent`,"aria-hidden":`true`}),`Routing`]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-3`,children:Ve.filter(e=>e===`routing:invoke`).map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 py-2 px-5 rounded-inset`,style:{minHeight:`44px`,border:`1px solid var(--inner-border)`,background:k.includes(e)?`var(--accent-soft)`:`var(--surface-1)`},children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,$.jsx)(j,{size:16,className:`mt-1 shrink-0 text-accent`,"aria-hidden":`true`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-caption font-semibold text-text-primary`,children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:Ue[e]})]})]}),(0,$.jsx)(G,{checked:k.includes(e),onChange:()=>Oe(e),disabled:n,"aria-label":`Grant ${e}`})]},e))})]}),(0,$.jsx)($e,{keyId:e===`edit`&&t?t.id:``,busy:n,scopeGranted:k.includes(`routing:cli_mapping`),onScopeChange:e=>{e!==k.includes(`routing:cli_mapping`)&&Oe(`routing:cli_mapping`)},persistScope:n=>{if(e!==`edit`||!t)return;let r=n?[...new Set([...k,`routing:cli_mapping`])]:k.filter(e=>e!==`routing:cli_mapping`);De.mutate({keyId:t.id,request:{scopes:r}},{onError:e=>g.error(P(e,`Could not update the key's routing scope.`))})}}),(0,$.jsxs)(`section`,{"aria-labelledby":`dashboard-scopes-heading`,className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`h4`,{id:`dashboard-scopes-heading`,className:`inline-flex items-center gap-2 text-caption font-bold text-text-primary`,children:[(0,$.jsx)(ue,{size:15,className:`text-accent`,"aria-hidden":`true`}),`Dashboard / Resources`]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-3`,children:Ve.filter(e=>!e.startsWith(`routing:`)).map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 py-2 px-5 rounded-inset`,style:{minHeight:`44px`,border:`1px solid var(--inner-border)`,background:k.includes(e)?`var(--accent-soft)`:`var(--surface-1)`},children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(()=>{let t=We[e];return(0,$.jsx)(t,{size:16,className:`mt-1 shrink-0 text-accent`,"aria-hidden":`true`})})(),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-caption font-semibold text-text-primary`,children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:Ue[e]})]})]}),(0,$.jsx)(G,{checked:k.includes(e),onChange:()=>Oe(e),disabled:n,"aria-label":`Grant ${e}`})]},e))})]})]})]})]})]})}function it({secret:e,onClose:t}){return(0,$.jsx)(O,{open:e!==null,onClose:t,title:`New API key`,description:`Copy it now, or reveal it again later from the key's Share button.`,size:`md`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-7`,children:[(0,$.jsx)(`p`,{className:`text-body text-text-secondary m-0 leading-normal`,children:`A personal key stays recoverable. Open the key's Share button and choose Reveal to see it again and copy it. Rotating the key replaces this secret, and any client still using it starts getting 401s.`}),(0,$.jsx)(`code`,{className:`block rounded-inset border border-inner-border bg-surface-1 py-5 px-6 text-caption text-text-primary break-all`,children:e}),(0,$.jsxs)(`div`,{className:`flex gap-4 flex-wrap`,children:[(0,$.jsx)(D,{value:e??``,size:`sm`,variant:`primary`,label:`Copy key`,copiedLabel:`Copied`}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(I,{size:13}),onClick:()=>{e!==null&&(pe(`cartethyia-api-key.txt`,`Cartethyia API key\n\n${e}\n\nKeep this secret. Reveal it again from the key's Share button.\n`,`text/plain;charset=utf-8`),g.success(`Key saved to your downloads.`))},children:`Save this key`})]})]})})}function at(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return`—`;let n=e-Date.now(),r=t.toLocaleString();if(n<=0)return`${r} (lapsed)`;let i=Math.ceil(n/6e4);if(i<60)return`${r} (in ${i}m)`;let a=Math.floor(i/60);return a<24?`${r} (in ${a}h)`:`${r} (in ${Math.floor(a/24)}d)`}function ot({onClose:e}){let t=s(!0),n=c(),[r,i]=(0,Q.useState)(null),a=t.data??[];return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(O,{open:!0,onClose:e,title:`Banned Users`,description:`A client address is banned after repeated invalid-model requests. The ban applies to every API key used from that address, not just one credential.`,size:`lg`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-7 min-w-0`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`h4`,{className:`text-caption font-semibold text-text-secondary mb-4`,children:[`Active bans (`,a.length,`)`]}),t.isPending?(0,$.jsx)(w,{compact:!0,label:`Loading banned users…`}):t.isError?(0,$.jsx)(C,{compact:!0,message:P(t.error,`Could not load banned users.`),onRetry:()=>void t.refetch()}):a.length===0?(0,$.jsx)(ee,{compact:!0,title:`No banned users`,message:`No client address is currently banned for model abuse.`,icon:(0,$.jsx)(Ie,{size:20})}):(0,$.jsx)(`div`,{className:`rounded-inset border border-inner-border`,children:(0,$.jsx)(ke,{maxHeight:480,scrollRegion:!0,headers:[`Client IP`,`Reason`,`Applies to`,`Lapses`,``],children:a.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`font-mono tabular-nums text-badge text-text-primary whitespace-nowrap`,children:e.ip}),(0,$.jsx)(`td`,{className:`text-badge text-text-secondary`,children:e.reason===`repeated_invalid_model_requests`?`Repeated invalid-model requests`:e.reason}),(0,$.jsx)(`td`,{className:`text-badge text-text-secondary whitespace-nowrap`,children:`All API keys from this IP`}),(0,$.jsx)(`td`,{className:`text-badge text-text-secondary whitespace-nowrap`,children:at(e.expiresAt)}),(0,$.jsx)(`td`,{className:`text-right whitespace-nowrap`,children:(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(Re,{size:13}),disabled:n.isPending,onClick:()=>i(e),children:`Unban`})})]},e.ip))})})]}),(0,$.jsx)(q,{justify:`flex-end`,gap:`0px`,children:(0,$.jsx)(m,{variant:`secondary`,size:`sm`,onClick:e,children:`Close`})})]})}),(0,$.jsx)(L,{open:r!==null,onClose:()=>i(null),onConfirm:async()=>{r&&(await n.mutateAsync(r.ip),g.success(`Unbanned ${r.ip}.`),i(null))},title:`Lift this ban?`,message:r?`Lift the ban on ${r.ip}? The address can reach the gateway again immediately.`:`Lift this ban?`,confirmLabel:`Unban`,danger:!0})]})}var st=e=>(e??0).toLocaleString(),ct=e=>e?new Date(e).toLocaleString():`—`;function lt({keyId:e}){let t=_e(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!1);return(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-4 rounded-control border border-inner-border bg-surface-2 px-5 py-4 text-text-tertiary`,children:[(0,$.jsx)(`code`,{title:i&&n?n:void 0,className:`min-w-0 flex-auto overflow-hidden font-mono text-caption text-text-primary text-ellipsis whitespace-nowrap`,children:i&&n?n:`••••••••••••••••`}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:i?(0,$.jsx)(b,{size:13}):(0,$.jsx)(x,{size:13}),loading:t.isPending,disabled:t.isPending,onClick:()=>{if(n!==null){a(e=>!e);return}t.mutate({keyId:e},{onSuccess:e=>{r(e.secret),a(!0)},onError:e=>g.error(P(e,`Could not reveal the key.`))})},children:i?`Hide`:`Reveal`}),i&&n?(0,$.jsx)(D,{value:n,size:`sm`,variant:`secondary`,label:`Copy`,copiedLabel:`Copied`}):null]})}function ut({label:e,value:t}){return(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 basis-60 rounded-control border border-inner-border bg-surface-2 px-5 py-3`,children:[(0,$.jsx)(`dt`,{className:`text-badge font-normal tracking-label text-text-tertiary uppercase`,children:e}),(0,$.jsx)(`dd`,{className:`mt-1 text-caption font-normal text-text-primary tabular-nums`,children:t==null?`Unlimited`:st(t)})]})}function dt(e){return e?{title:`Regenerate this key?`,message:`This rotates the key credential. Any client still using the current secret starts getting 401s immediately, and the old secret cannot be recovered. The handoff link is re-pointed to reveal the new key.`,confirmLabel:`Regenerate key`}:{title:`Regenerate this link?`,message:`This replaces the link URL; the current URL stops resolving immediately. Recipients keep the keys they already generated and keep working — but no one can enroll through the old link again.`,confirmLabel:`Regenerate link`}}function ft({consumed:e,budget:t}){let n=t==null||t<=0,r=n?100:Math.min(100,e/t*100),i=!n&&e>=t;return(0,$.jsxs)(`div`,{className:`grid flex-auto basis-full gap-2.5 rounded-control border border-inner-border bg-surface-2 px-5 py-3.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 text-badge tracking-label text-text-tertiary uppercase`,children:[(0,$.jsx)(`span`,{children:`Lifetime budget`}),(0,$.jsx)(`span`,{className:`text-caption font-normal text-text-primary tabular-nums normal-case tracking-normal`,children:n?`${V(e)} · Unlimited`:`${V(e)} / ${V(t)}`})]}),(0,$.jsx)(`div`,{className:`h-3 overflow-hidden rounded bg-inner-border`,role:`progressbar`,"aria-label":`Lifetime token budget consumed`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(r),"aria-valuetext":n?`${V(e)} tokens consumed, no lifetime budget set`:`${V(e)} of ${V(t)} tokens consumed`,children:(0,$.jsx)(`div`,{className:i?`h-full rounded bg-status-danger`:`h-full rounded bg-status-success`,style:{width:`${r}%`}})})]})}function pt(e){return e.filter(e=>e.revokedAt===null).length}function mt(e){return e.reduce((e,t)=>e+t.allTime.totalTokens,0)}function ht({consumed:e,budget:t}){if(t==null)return(0,$.jsx)(`div`,{className:`grid flex-auto basis-full gap-2.5 rounded-control border border-inner-border bg-surface-2 px-5 py-3.5`,children:(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 text-badge tracking-label text-text-tertiary uppercase`,children:[(0,$.jsx)(`span`,{children:`Total quota used`}),(0,$.jsx)(`span`,{className:`text-caption font-normal text-text-primary tabular-nums normal-case tracking-normal`,children:V(e)})]})});let n=t>0?Math.min(100,e/t*100):0,r=t>0?Math.max(0,100-e/t*100):100,i=Math.max(0,t-e),a=Ae(e>=t?0:r),o=e>=t;return(0,$.jsxs)(`div`,{className:`grid flex-auto basis-full gap-2.5 rounded-control border border-inner-border bg-surface-2 px-5 py-3.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 text-badge tracking-label text-text-tertiary uppercase`,children:[(0,$.jsx)(`span`,{children:`Total quota`}),(0,$.jsxs)(`span`,{className:`text-caption font-normal text-text-primary tabular-nums normal-case tracking-normal`,children:[V(e),` / `,V(t)]}),(0,$.jsx)(`span`,{className:`border rounded-chip px-4 py-0.5 text-caption font-bold whitespace-nowrap tabular-nums`,style:{color:a.text,borderColor:a.text},children:o?`Exhausted`:`${V(i)} left`})]}),(0,$.jsx)(`div`,{className:`h-3 overflow-hidden rounded bg-inner-border`,role:`progressbar`,"aria-label":`Total quota consumed`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(n),"aria-valuetext":`${V(e)} of ${V(t)} tokens consumed`,children:(0,$.jsx)(`div`,{className:o?`h-full rounded bg-status-danger`:`h-full rounded`,style:{width:`${n}%`,background:o?void 0:a.bar}})})]})}function gt({parentId:e,childId:t}){let n=Ee(e,t);if(n.isPending)return(0,$.jsx)(w,{label:`Loading activity…`,compact:!0});if(n.isError)return(0,$.jsx)(C,{compact:!0,message:P(n.error,`Could not load activity.`),onRetry:()=>void n.refetch()});let r=n.data;return r?(0,$.jsxs)(`div`,{className:`grid min-w-0 gap-6 border-t border-inner-border bg-surface-1 px-6 py-5`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h4`,{className:`mb-3 text-caption font-bold text-text-primary`,children:`Top models`}),r.models.length?(0,$.jsx)(`div`,{className:`data-table-container`,children:(0,$.jsxs)(`table`,{className:`data-table text-caption`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Model`}),(0,$.jsx)(`th`,{scope:`col`,children:`Today`}),(0,$.jsx)(`th`,{scope:`col`,children:`Errors`}),(0,$.jsx)(`th`,{scope:`col`,children:`Tokens`})]})}),(0,$.jsx)(`tbody`,{children:r.models.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.modelId}),(0,$.jsx)(`td`,{children:st(e.todayRequests)}),(0,$.jsx)(`td`,{children:st(e.todayErrors)}),(0,$.jsx)(`td`,{children:V(e.todayTokens)})]},`${e.providerId??``}-${e.modelId}-${t}`))})]})}):(0,$.jsx)(`p`,{className:`py-3 text-caption text-text-tertiary`,children:`No model activity yet.`})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h4`,{className:`mb-3 text-caption font-bold text-text-primary`,children:`Recent requests`}),r.requests.length?(0,$.jsx)(`div`,{className:`data-table-container`,children:(0,$.jsxs)(`table`,{className:`data-table text-caption`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Model`}),(0,$.jsx)(`th`,{scope:`col`,children:`Status`}),(0,$.jsx)(`th`,{scope:`col`,children:`Tokens`}),(0,$.jsx)(`th`,{scope:`col`,children:`Time`})]})}),(0,$.jsx)(`tbody`,{children:r.requests.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`td`,{children:[e.providerId??`Provider`,`/`,e.modelId??`Model`]}),(0,$.jsxs)(`td`,{children:[e.status,e.httpStatus?` · ${e.httpStatus}`:``]}),(0,$.jsx)(`td`,{children:V(e.totalTokens)}),(0,$.jsx)(`td`,{children:ct(e.startedAt)})]},e.requestId))})]})}):(0,$.jsx)(`p`,{className:`py-3 text-caption text-text-tertiary`,children:`No recent requests.`})]})]}):null}function _t({parent:e,onSecretRevealed:t}){let[n,r]=(0,Q.useState)(null),[i,o]=(0,Q.useState)(`active`),[s,c]=(0,Q.useState)(null),l=ve(),u=we(),d=Te(),f=xe(e.id),p=e.keyMode!==`share`,h=J(p?null:e.id),v=h.data??[],y=i===`active`?v.filter(e=>e.revokedAt===null):v.filter(e=>e.revokedAt!==null),b=v.filter(e=>e.revokedAt===null&&e.allTime.totalTokens===0);(0,Q.useEffect)(()=>{r(null)},[e.id]);let x=async(t,n)=>{let r=0;for(let n of t)try{await d.mutateAsync({parentKeyId:e.id,childKeyId:n.id}),r+=1}catch{}await h.refetch();let i=t.length-r;i>0?g.error(`Revoked ${r} of ${t.length} ${n}; ${i} failed.`):g.success(`Revoked ${r} ${n}.`)},S=l.isPending||u.isPending,[te,T]=(0,Q.useState)(!1),O=async()=>{if(p){let n=await u.mutateAsync({keyId:e.id});t?.(n.secret);return}await l.mutateAsync({keyId:e.id,regenerate:!0}),g.success(`Link regenerated; the previous URL no longer works.`)},ne=()=>{l.mutate({keyId:e.id},{onError:e=>g.error(P(e,`Could not create link.`))})},k=f.data?.url??null,j=dt(p);return(0,$.jsxs)(`div`,{className:`grid min-w-0 gap-6`,children:[(0,$.jsx)(`section`,{"aria-label":`Link`,children:f.isPending?(0,$.jsx)(w,{label:`Loading link…`,compact:!0}):f.isError?(0,$.jsx)(C,{compact:!0,message:P(f.error,`Could not load the link.`),onRetry:()=>void f.refetch()}):k?(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-4 rounded-control border border-inner-border bg-surface-2 px-5 py-4 text-text-tertiary`,children:[(0,$.jsx)(E,{size:14,"aria-hidden":`true`,className:`shrink-0`}),(0,$.jsx)(`code`,{title:k,className:`min-w-0 flex-auto overflow-hidden font-mono text-caption text-text-primary text-ellipsis whitespace-nowrap`,children:k}),(0,$.jsx)(D,{value:k,size:`sm`,variant:`secondary`,label:`Copy`,copiedLabel:`Copied`}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(Ne,{size:13}),loading:S,disabled:S,onClick:()=>T(!0),children:`Regenerate`})]}):(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-4 rounded-control border border-inner-border bg-surface-2 px-5 py-4 text-text-tertiary`,children:[(0,$.jsx)(E,{size:14,"aria-hidden":`true`,className:`shrink-0`}),(0,$.jsx)(`span`,{className:`flex-auto text-caption text-text-tertiary`,children:`No link yet.`}),(0,$.jsx)(m,{variant:`primary`,size:`sm`,loading:S,disabled:S,onClick:ne,children:`Create link`})]})}),p?(0,$.jsxs)(`section`,{"aria-label":`API key`,className:`grid gap-3`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between gap-4`,children:(0,$.jsx)(`strong`,{className:`text-caption`,children:`API key`})}),(0,$.jsx)(lt,{keyId:e.id})]}):null,p?(0,$.jsxs)(`section`,{"aria-label":`Usage`,className:`grid gap-3`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between gap-4`,children:(0,$.jsx)(`strong`,{className:`text-caption`,children:`Usage`})}),(0,$.jsxs)(`dl`,{className:`m-0 flex flex-wrap gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 basis-60 rounded-control border border-inner-border bg-surface-2 px-5 py-3`,children:[(0,$.jsx)(`dt`,{className:`text-badge font-normal tracking-label text-text-tertiary uppercase`,children:`Lifetime tokens`}),(0,$.jsx)(`dd`,{className:`mt-1 text-caption font-normal text-text-primary tabular-nums`,children:V(e.tokensConsumed)})]}),(0,$.jsx)(ut,{label:`Requests / min`,value:e.requestsPerMinute}),(0,$.jsx)(ut,{label:`Daily tokens`,value:e.dailyTokenLimit}),(0,$.jsx)(ut,{label:`Monthly tokens`,value:e.monthlyTokenLimit}),(0,$.jsx)(ft,{consumed:e.tokensConsumed,budget:e.lifetimeTokenBudget})]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{"aria-label":`Total quota`,className:`grid gap-3`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between gap-4`,children:(0,$.jsx)(`strong`,{className:`text-caption`,children:`Total quota`})}),(0,$.jsx)(ht,{consumed:mt(v),budget:e.lifetimeTokenBudget})]}),(0,$.jsxs)(`section`,{"aria-label":`Recipients`,className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsx)(`strong`,{className:`text-caption`,children:`Recipients`}),(0,$.jsxs)(`span`,{className:`mr-2 ml-auto text-caption text-text-tertiary tabular-nums`,children:[`Active users: `,pt(v)]}),(0,$.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-chip border border-inner-border p-0.5`,role:`group`,"aria-label":`Filter recipients by status`,children:[`active`,`revoked`].map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":i===e,onClick:()=>o(e),className:`rounded-chip border-0 px-3 py-1 text-badge font-semibold capitalize cursor-pointer ${i===e?`bg-surface-1 text-text-primary`:`bg-transparent text-text-secondary hover:text-text-primary`}`,children:e},e))}),s===null?null:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2 rounded-chip border border-danger-border bg-surface-2 px-3 py-1`,children:[(0,$.jsx)(`span`,{className:`text-badge text-text-secondary`,children:s===`all`?`Revoke ${y.length}?`:`Revoke ${b.length} unused?`}),(0,$.jsx)(m,{variant:`danger`,size:`sm`,loading:d.isPending,onClick:()=>{let e=s===`all`?y:b,t=s===`all`?`recipients`:`unused recipients`;c(null),x(e,t)},children:`Confirm`}),(0,$.jsx)(m,{variant:`ghost`,size:`sm`,onClick:()=>c(null),children:`Cancel`})]}),(0,$.jsx)(m,{variant:`ghost`,size:`sm`,disabled:b.length===0||d.isPending,title:b.length===0?`No active recipient has spent zero tokens`:`Revoke ${b.length} recipient${b.length===1?``:`s`} that never spent a token`,onClick:()=>c(`unused`),icon:(0,$.jsx)(a,{size:13}),children:`Revoke no-usage`}),(0,$.jsx)(m,{variant:`ghost`,size:`sm`,disabled:y.length===0||d.isPending,title:y.length===0?`Nothing to revoke in this view`:`Revoke all ${y.length} listed recipient${y.length===1?``:`s`}`,onClick:()=>c(`all`),icon:(0,$.jsx)(a,{size:13}),children:`Revoke all`}),(0,$.jsx)(m,{variant:`ghost`,size:`sm`,onClick:()=>void h.refetch(),icon:(0,$.jsx)(A,{size:13,className:h.isFetching?`animate-spin`:void 0}),children:`Refresh`})]}),h.isPending&&!h.data?(0,$.jsx)(w,{label:`Loading recipients…`,compact:!0}):h.isError?(0,$.jsx)(C,{compact:!0,message:P(h.error,`Could not load recipients.`),onRetry:()=>void h.refetch()}):y.length===0?(0,$.jsx)(ee,{compact:!0,title:i===`revoked`?`No revoked recipients`:`No active recipients`,message:i===`revoked`?`Revoked keys appear here once a recipient's key is revoked.`:`Keys generated through this link appear here with their masked client IP and token usage.`}):(0,$.jsx)(`div`,{className:`data-table-container max-h-[46vh]`,children:(0,$.jsxs)(`table`,{className:`data-table text-caption`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`w-12`,"aria-label":`Expand`}),(0,$.jsx)(`th`,{scope:`col`,children:`Key`}),(0,$.jsx)(`th`,{scope:`col`,children:`Status`}),(0,$.jsx)(`th`,{scope:`col`,children:`Today`}),(0,$.jsx)(`th`,{scope:`col`,children:`Lifetime`}),(0,$.jsx)(`th`,{scope:`col`,children:`Last activity`}),(0,$.jsx)(`th`,{scope:`col`,className:`text-right whitespace-nowrap`,children:`Actions`})]})}),(0,$.jsx)(`tbody`,{children:y.map(t=>{let i=n===t.id;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.jsx)(`button`,{type:`button`,className:`grid h-11 w-11 place-items-center rounded-chip border-0 bg-transparent p-0 text-text-secondary hover:bg-hover hover:text-text-primary`,"aria-expanded":i,"aria-label":i?`Collapse recipient`:`Expand recipient`,onClick:()=>r(i?null:t.id),children:i?(0,$.jsx)(de,{size:14}):(0,$.jsx)(_,{size:14})})}),(0,$.jsxs)(`td`,{children:[(0,$.jsxs)(`code`,{children:[t.label||t.keyPrefix||`key`,`…`]}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary wrap-anywhere`,children:t.issuedClientIp??`IP hidden`})]}),(0,$.jsx)(`td`,{children:t.revokedAt?`revoked`:`active`}),(0,$.jsx)(`td`,{children:V(t.today.totalTokens)}),(0,$.jsx)(`td`,{children:V(t.allTime.totalTokens)}),(0,$.jsx)(`td`,{children:ct(t.lastUsedAt)}),(0,$.jsx)(`td`,{className:`text-right whitespace-nowrap`,children:(0,$.jsx)(m,{variant:`danger`,size:`sm`,disabled:d.isPending||!!t.revokedAt,onClick:()=>d.mutate({parentKeyId:e.id,childKeyId:t.id},{onError:e=>g.error(P(e,`Could not revoke key.`))}),children:`Revoke`})})]}),i?(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:7,className:`p-0`,children:(0,$.jsx)(gt,{parentId:e.id,childId:t.id})})}):null]},t.id)})})]})})]})]}),(0,$.jsx)(L,{open:te,onClose:()=>T(!1),onConfirm:O,title:j.title,message:j.message,confirmLabel:j.confirmLabel,danger:!0})]})}function vt({parent:e,onClose:t,onSecretRevealed:n}){let r=e.keyMode!==`share`;return(0,$.jsx)(O,{open:!0,onClose:t,title:`Sharing — ${e.label||`API key`}`,description:r?`One stable handoff link for this key. Regenerating rotates the key itself.`:`One stable enrollment link. Regenerating replaces the URL; recipients keep the keys they already generated.`,size:`lg`,children:(0,$.jsx)(_t,{parent:e,onSecretRevealed:n})})}function yt(){let e=Y(),t=le(),n=Se(),r=ye(),i=Ce(),a=we(),o=_e(),s=be(),{copy:c}=fe(),[l,u]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),[h,_]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[T,E]=(0,Q.useState)(null),[D,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(null),[re,ie]=(0,Q.useState)(null),ae=e.data??[],N=t.data?.isPlatformAdmin??!1,se=e=>{S(null),E(e)},ce=async e=>{try{let{secret:t}=await o.mutateAsync({keyId:e.id});await c(t)?g.success(`API key copied`):g.error(`Clipboard unavailable on this origin`)}catch(e){g.error(P(e,`Could not reveal API key.`))}},F=dt(!0);return(0,$.jsxs)(B,{children:[(0,$.jsx)(z,{title:`API Credentials`,subtitle:`Manage tenant API keys, model access, budgets, and sharing.`,icon:(0,$.jsx)(te,{size:16}),action:(0,$.jsxs)(`div`,{className:`flex items-center gap-4`,children:[N?(0,$.jsx)(m,{variant:`secondary`,size:`sm`,onClick:()=>A(!0),icon:(0,$.jsx)(Ie,{size:13}),children:`Banned Users`}):null,(0,$.jsx)(m,{variant:`primary`,size:`sm`,onClick:()=>{S(null),u(!0)},icon:(0,$.jsx)(k,{size:13}),children:`Create Key`})]})}),(0,$.jsx)(R,{children:e.isPending&&!e.data?(0,$.jsx)(w,{label:`Loading API keys…`}):e.isError&&!e.data?(0,$.jsx)(C,{message:P(e.error,`Could not load credentials.`),onRetry:()=>void e.refetch()}):ae.length===0?(0,$.jsx)(ee,{title:`No API keys issued`,message:`Generate a secret key to authenticate your SDK or CLI client against the gateway.`,icon:(0,$.jsx)(te,{size:20})}):(0,$.jsx)(`div`,{className:`scroll-region max-h-280 pr-1`,children:(0,$.jsx)(v,{items:ae,label:`API credentials`,disabled:s.isPending,onReorder:e=>s.mutate(e,{onError:e=>g.error(P(e,`Could not save the new order.`))}),renderItem:e=>(0,$.jsxs)(`div`,{className:`api-key-card flex items-start justify-between gap-6 px-6 py-4 rounded-chip border border-inner-border bg-surface-2 max-medium:flex-col max-medium:items-stretch max-medium:gap-4 max-medium:p-5 [&>div:last-child]:flex-wrap`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,$.jsx)(`strong`,{className:`text-body`,children:e.label||`Unnamed credential`}),(0,$.jsx)(me,{tone:e.revokedAt?`err`:e.enabled?`ok`:`warn`,children:e.revokedAt?`revoked`:e.enabled?`enabled`:`disabled`}),(0,$.jsx)(me,{tone:e.keyMode===`share`?`accent`:`default`,children:e.keyMode===`share`?`share template`:`personal`}),e.isDefault?(0,$.jsx)(me,{tone:`warn`,title:`Required by the gateway. Rotate it; it cannot be deleted.`,children:`default · rotate only`}):null]}),(0,$.jsxs)(`div`,{className:`api-key-facts flex items-center flex-wrap gap-2 mt-3 min-w-0 max-medium:grid max-medium:grid-cols-3 max-medium:gap-2 max-medium:mt-0`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Created`}),new Date(e.createdAt).toLocaleDateString()]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:e.keyMode===`share`?`Total usage`:`Usage`}),V(e.tokensConsumed)]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`RPM`}),H(e.requestsPerMinute)]})]}),(0,$.jsxs)(`div`,{className:`api-key-facts flex items-center flex-wrap gap-2 mt-3 min-w-0 max-medium:grid max-medium:grid-cols-3 max-medium:gap-2 max-medium:mt-0`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Daily`}),H(e.dailyTokenLimit)]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Monthly`}),H(e.monthlyTokenLimit)]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`One-time`}),H(e.lifetimeTokenBudget)]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Concurrent`}),H(e.maxConcurrentRequests)]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap max-medium:justify-between`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:e.modelAccessMode===`blacklist`?`Blocked`:`Models`}),e.modelAccessMode===`blacklist`?e.modelList?.length??0:e.modelList?.length?e.modelList.length:`All`]})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-3 shrink-0 flex-wrap`,children:[e.revokedAt?null:(0,$.jsx)(G,{checked:e.enabled,disabled:r.isPending,id:`api-key-enabled-${e.id}`,label:``,"aria-label":`${e.enabled?`Disable`:`Enable`} ${e.label||`API credential`}`,onChange:t=>r.mutate({keyId:e.id,request:{enabled:t}},{onSuccess:()=>g.success(`${e.label||`API credential`} ${t?`enabled`:`disabled`}`),onError:e=>g.error(P(e,`Could not update credential state.`))})}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(ne,{size:13}),onClick:()=>{S(null),p(e)},children:`Edit`}),!e.revokedAt&&e.keyMode!==`share`?(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(d,{size:13}),onClick:()=>void ce(e),disabled:o.isPending,children:`Copy`}):null,!e.revokedAt&&(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(Fe,{size:13}),onClick:()=>se(e),children:e.keyMode===`share`?`Recipients`:`Share`}),!e.revokedAt&&e.keyMode!==`share`&&(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(Ne,{size:13}),onClick:()=>{S(null),b(e)},disabled:a.isPending,children:`Rotate`}),!e.revokedAt&&!e.isDefault&&(0,$.jsx)(m,{variant:`danger`,size:`sm`,icon:(0,$.jsx)(oe,{size:13}),onClick:()=>_(e),disabled:i.isPending,children:`Revoke`})]})]})})})}),(0,$.jsx)(O,{open:l,onClose:()=>u(!1),title:`Create API Key`,description:`Create a tenant-scoped credential. Choose model access, permissions, limits, and optional blocked client routers.`,size:`lg`,footer:j,children:(0,$.jsx)(rt,{mode:`create`,record:null,busy:n.isPending,onClose:()=>u(!1),actionsRef:M,onDone:e=>{n.mutate(e,{onSuccess:t=>{u(!1),S(tt(e.keyMode,t.secret)),g.success(`API key created`)},onError:e=>g.error(P(e,`Could not create API key.`))})}})}),(0,$.jsx)(O,{open:f!==null,onClose:()=>p(null),title:`Edit API Key`,description:`Update the key's model access, permissions, limits, share notes, and optional public popup.`,size:`lg`,footer:re,children:(0,$.jsx)(rt,{mode:`edit`,record:f,busy:r.isPending,onClose:()=>p(null),actionsRef:ie,onDone:e=>{f&&r.mutate({keyId:f.id,request:e},{onSuccess:t=>{p(null),S(tt(e.keyMode,t.secret)),g.success(`API key updated`)},onError:e=>g.error(P(e,`Could not update API key.`))})}})}),T?(0,$.jsx)(vt,{parent:T,onClose:()=>E(null),onSecretRevealed:e=>{E(null),S(e)}}):null,(0,$.jsx)(L,{open:y!==null,onClose:()=>b(null),onConfirm:async()=>{if(!y)return;let e=await a.mutateAsync({keyId:y.id});S(e.secret),g.success(`Rotated ${y.label||y.id}.`),b(null)},title:F.title,message:F.message,confirmLabel:F.confirmLabel,danger:!0}),(0,$.jsx)(L,{open:h!==null,onClose:()=>_(null),onConfirm:async()=>{h&&(await i.mutateAsync(h.id),g.success(`Revoked ${h.label||h.id}.`),_(null))},title:`Revoke API key?`,message:h?`Revoke ${h.label||h.id}? Clients using it will be rejected.${h.keyMode===`share`?` All child keys and enrollment links will also be revoked.`:``}`:`Revoke this API key?`,confirmLabel:`Revoke`,danger:!0}),D?(0,$.jsx)(ot,{onClose:()=>A(!1)}):null,(0,$.jsx)(it,{secret:x,onClose:()=>S(null)})]})}function bt(){let e=N(),t=ie(),n=e.data;if(e.isPending)return(0,$.jsx)(w,{label:`Loading compression settings…`});if(e.isError||!n)return(0,$.jsx)(C,{message:P(e.error,`Failed to load compression settings`),onRetry:()=>void e.refetch()});let r=n.rtkPruneEnabled,a=n.ponyTailEnabled;return(0,$.jsxs)(B,{children:[(0,$.jsx)(z,{title:`Compression`,subtitle:`Shrink requests before they reach the provider`,icon:(0,$.jsx)(o,{size:16})}),(0,$.jsx)(R,{children:(0,$.jsxs)(K,{gap:`14px`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-x-8 gap-y-5`,children:[(0,$.jsxs)(`div`,{className:`flex gap-5 min-w-0 flex-auto`,children:[(0,$.jsx)(Pe,{size:16,className:`shrink-0 mt-1 text-text-secondary`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`compression-rtk`,children:(0,$.jsx)(q,{gap:`6px`,className:`text-body font-semibold`,children:`Prune tool output (RTK)`})}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary wrap-anywhere max-w-full`,children:`Compact bulky tool results (diffs, grep dumps, listings) in the message history so a long conversation stops re-sending megabytes of raw output. Higher strength compresses more aggressively.`})]})]}),(0,$.jsxs)(q,{gap:`8px`,className:`shrink-0 items-center ml-auto`,children:[(0,$.jsx)(W,{id:`compression-rtk-level`,"aria-label":`RTK strength`,value:n.rtkPruneLevel,onValueChange:e=>t.mutate({rtkPruneLevel:e===`lite`||e===`full`||e===`ultra`?e:`full`},{onError:e=>g.error(P(e,`Could not update RTK strength.`))}),options:[{value:`lite`,label:`Lite`},{value:`full`,label:`Full`},{value:`ultra`,label:`Ultra`}]}),(0,$.jsx)(G,{id:`compression-rtk`,"aria-label":`Enable RTK prune`,checked:r,onChange:e=>t.mutate({rtkPruneEnabled:e},{onError:e=>g.error(P(e,`Could not update RTK prune.`))})})]})]}),(0,$.jsxs)(`div`,{className:`flex items-start gap-x-8 gap-y-5`,children:[(0,$.jsxs)(`div`,{className:`flex gap-5 min-w-0 flex-auto`,children:[(0,$.jsx)(i,{size:16,className:`shrink-0 mt-1 text-text-secondary`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`compression-ponytail`,children:(0,$.jsx)(q,{gap:`6px`,className:`text-body font-semibold`,children:`PonyTail (system directive)`})}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary wrap-anywhere max-w-full`,children:`Appends a minimal-code directive to the system content, biasing the model toward the smallest working change. Higher strength pushes harder toward deletion over addition.`})]})]}),(0,$.jsxs)(q,{gap:`8px`,className:`shrink-0 items-center ml-auto`,children:[(0,$.jsx)(W,{id:`compression-ponytail-level`,"aria-label":`PonyTail strength`,value:n.ponyTailLevel,onValueChange:e=>t.mutate({ponyTailLevel:e===`lite`||e===`full`||e===`ultra`?e:`full`},{onError:e=>g.error(P(e,`Could not update PonyTail strength.`))}),options:[{value:`lite`,label:`Lite`},{value:`full`,label:`Full`},{value:`ultra`,label:`Ultra`}]}),(0,$.jsx)(G,{id:`compression-ponytail`,"aria-label":`Enable PonyTail`,checked:a,onChange:e=>t.mutate({ponyTailEnabled:e},{onError:e=>g.error(P(e,`Could not update PonyTail.`))})})]})]}),r||a?(0,$.jsxs)(`p`,{role:`note`,className:`flex gap-4 items-start m-0 py-4 px-5 rounded-inset border border-orange bg-orange-soft text-text-secondary text-badge`,children:[(0,$.jsx)(p,{size:14,className:`shrink-0 mt-0.5 text-orange`}),(0,$.jsx)(`span`,{children:`Your AI may produce degraded quality while compression is active: it sees a shortened history and a minimal-code directive, so fewer tokens but a chance of missing detail. Turn it off if answers get worse.`})]}):null]})})]})}function xt(){let{copied:e,copy:t}=fe(2e3),n=`${window.location.origin}/v1`,r=async()=>{if(await t(n)){g.success(`Gateway endpoint copied`,n);return}g.error(`Clipboard unavailable on this origin`)};return(0,$.jsxs)(B,{children:[(0,$.jsx)(z,{title:`Gateway Endpoint`,subtitle:`Universal OpenAI & Anthropic Wire API Endpoint Compatible`,icon:(0,$.jsx)(f,{size:16})}),(0,$.jsx)(R,{children:(0,$.jsxs)(K,{gap:`10px`,children:[(0,$.jsxs)(`div`,{className:`nested-panel flex items-center gap-4 rounded-control border border-inner-border bg-code-surface px-7 py-5 font-mono text-body font-semibold tabular-nums`,children:[(0,$.jsx)(`code`,{className:`min-w-0 flex-1 truncate`,title:n,children:n}),(0,$.jsx)(m,{variant:`secondary`,size:`sm`,icon:e?(0,$.jsx)(h,{size:13}):(0,$.jsx)(d,{size:13}),"aria-label":`Copy endpoint`,title:`Copy endpoint`,onClick:()=>void r(),className:`shrink-0`,children:e?`Copied`:`Copy`})]}),(0,$.jsxs)(`p`,{className:`text-caption leading-normal text-text-secondary`,children:[`Point any SDK, CLI, or agent (e.g. OpenCode, Pi, OMP, Kilo, Cline, Droid and more clients) to this same-origin base URL.`,(0,$.jsxs)(`span`,{className:`mt-1 block text-text-tertiary`,children:[`You may not put `,(0,$.jsx)(`code`,{className:`font-mono`,children:`/v1`}),` on Claude Code — the CLI appends it itself.`]})]})]})})]})}function St(){return(0,$.jsxs)(K,{gap:`16px`,children:[(0,$.jsx)(xt,{}),(0,$.jsx)(bt,{}),(0,$.jsx)(yt,{})]})}export{St as default};
@@ -1,3 +0,0 @@
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{C as u,D as d,E as f,T as p,a as m,b as h,c as g,k as _,l as v,m as y,s as b,y as x}from"./numbers-YNcHvRY7.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"./cog-CdWhsajs.js";import{t as T}from"./eye-off-Bk5g2luF.js";import{t as E}from"./eye-C_hawfH4.js";import{t as D}from"./gauge-BbIMy7MB.js";import{t as O}from"./image-BPaouViG.js";import{n as k,r as A,t as j}from"./state-BgTxHcJS.js";import{t as M}from"./key-round-UkavsGxp.js";import{t as N}from"./layers-2-glBbjl.js";import{n as ee,t as P}from"./dialog-BYj-8WuK.js";import{t as F}from"./pencil-768ysRAr.js";import{t as te}from"./plus-DIdX_g-x.js";import{t as ne}from"./power-off-Yjw9GMJh.js";import{t as re}from"./refresh-cw-BqJFk4sU.js";import{t as ie}from"./rotate-ccw-CufcqITi.js";import{t as ae}from"./search-JOKus9rb.js";import{t as oe}from"./trash-Cppn5c3R.js";import{t as se}from"./wrench-B6E1oEuY.js";import{T as ce}from"./assert-Chi7pCnt.js";import{l as le,o as ue,t as I}from"./query-keys-gmjzC3RS.js";import{$ as de,C as fe,D as pe,E as me,O as he,S as ge,a as _e,b as L,c as ve,ct as ye,d as be,et as xe,f as Se,g as Ce,h as we,k as Te,l as Ee,lt as De,m as Oe,o as ke,p as Ae,r as R,t as je,tt as Me,u as Ne,ut as Pe,w as Fe,x as Ie,y as Le,z as Re}from"./entry-CgdSAzEV.js";import{n as z,r as ze,t as B}from"./card-BKqlUOe4.js";import{n as V}from"./download-dRFo5_Wu.js";import{f as Be,i as H,l as Ve,n as He,r as U,s as W}from"./tokens-DDxMbSRL.js";import{t as G}from"./badge-D4pQapKj.js";import{n as K}from"./input-LVjgZq4f.js";import{t as q}from"./select-WUCXorXw.js";import{t as Ue}from"./ProviderIcon-CmfzxpVM.js";import{t as We}from"./switch-DEjTtOWf.js";import{t as J}from"./stack-_3O0F8Xn.js";import{n as Y,t as Ge}from"./inline-DUWDSmDV.js";import{i as Ke}from"./quota-DZGyp0N5.js";import{t as qe}from"./list-row-DupvLfDx.js";import{c as X,l as Je,m as Ye}from"./routing-C7tBT5o-.js";import{o as Xe,s as Ze,t as Qe}from"./HealthEventsModal-BjqSMfko.js";import{r as $e}from"./privacy-mode-GM8bej85.js";import{n as et,t as tt}from"./AccountCooldown-Bjo92Qat.js";import{t as nt}from"./use-timeout-BwcBBRrT.js";import{t as rt}from"./banner-DH6cg-_B.js";var it=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`}]]),at=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`}]]),ot=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`}]]),st=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`}]]),ct=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`}]]),lt=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`}]]),ut=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`}]]),dt=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`}]]),ft=[`auto`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function pt(e,t){return t===null?e:`${e}(${t})`}var Z=t(n(),1),Q=r();function mt({to:e,label:t}){let n=de();return(0,Q.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,Q.jsx)(a,{size:14,"aria-hidden":`true`}),t]})}function ht({title:e,description:t,icon:n,badges:r,actions:i,back:a}){return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[a?(0,Q.jsx)(mt,{...a}):null,(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-6 flex-wrap`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-5 min-w-0`,children:[n?(0,Q.jsx)(`div`,{className:`card-header-icon`,children:n}):null,(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,Q.jsx)(`h1`,{className:`text-lead font-bold`,children:e}),r]}),t?(0,Q.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:t}):null]})]}),i?(0,Q.jsx)(`div`,{className:y(`flex items-center gap-4 flex-wrap min-w-0 max-w-full`),children:i}):null]})]})}function gt(e){return e.isBuiltIn&&e.requiresAccount&&e.oauthFlows===void 0&&!e.hasAdapterUserAgent}function _t(e,t=600){let n=(0,Z.useRef)(void 0);return(0,Z.useEffect)(()=>()=>clearTimeout(n.current),[]),r=>{clearTimeout(n.current),n.current=setTimeout(()=>e(r),t)}}var vt={fallback:`Failover`,roundRobin:`Round robin`},yt=new Set([`inferhub`,`cline`]);function bt(e,t){let n=Je(e),r=Ye(),[i,a]=(0,Z.useState)(`fallback`),[o,s]=(0,Z.useState)(1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(`percent`),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(``);(0,Z.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.userAgent))},[n.data]);let b=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,...t?{userAgent:i.userAgent}:{}}},{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.userAgent))}})},x=_t(e=>b({strategy:i,rotateCount:o,maxInflight:e,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),S=_t(e=>b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:e,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),C=_t(e=>b({strategy:i,rotateCount:e,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),w=_t(e=>b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:e}));return{strategy:i,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,setUsageFloor:(e,t)=>{p(e),h(t),b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:e,usageFloorUnit:t,skipProxy:g,userAgent:v})},skipProxy:g,userAgent:v,isLoading:n.isPending,isError:n.isError,isSaving:r.isPending,saveFailed:r.isError,refetch:()=>n.refetch(),setMaxInflight:e=>{l(e),x(e)},setMaxInflightPerProxy:e=>{d(e),S(e)},setUserAgent:e=>{y(e),w(e)},setSkipProxy:e=>{_(e),b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:e,userAgent:v})},roundRobinEnabled:i===`round_robin`,setRoundRobinEnabled:e=>{let t=e?`round_robin`:`fallback`;a(t),b({strategy:t,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})},rotateCount:o,setRotateCount:e=>{s(e),C(e)}}}var xt=50,St=100;function Ct(e,t,n){return[{value:``,label:`None`},{value:`Cartethyia/${e}`,label:`Cartethyia ${e}`},{value:`codex_cli_rs/${t}`,label:`Codex`},{value:`claude-cli/${n} (external, cli)`,label:`Claude Code`}]}function wt({children:e,action:t}){return(0,Q.jsx)(qe,{actions:t,children:e})}function Tt({providerId:e,clientVersion:t,routeIdentityVersions:n,userAgentEditable:r}){let i=bt(e,r),[a,o]=(0,Z.useState)(!1),s=yt.has(e),c=Ct(je,n.codex,n.claude),u=c.some(e=>e.value===i.userAgent)?c:[...c,{value:i.userAgent,label:`Custom`}];if(i.isLoading)return(0,Q.jsx)(A,{label:`Loading routing...`});if(i.isError)return(0,Q.jsx)(k,{message:`Failed to load routing`,onRetry:i.refetch});let d=i.roundRobinEnabled?`${vt.roundRobin} · ${i.rotateCount} account${i.rotateCount===1?``:`s`} per rotation`:vt.fallback,f=i.isSaving?`Saving...`:i.saveFailed?`Save failed — reverted to last saved value`:`Active: ${d}`,p=i.maxInflight===null,m=p?51:Math.min(51,Math.max(1,i.maxInflight)),h=p?`∞`:String(i.maxInflight),_=i.maxInflightPerProxy===null,v=_?51:Math.min(51,Math.max(1,i.maxInflightPerProxy)),y=_?`∞`:String(i.maxInflightPerProxy),x=i.skipProxy,S=e=>{i.setRotateCount(Math.min(1e3,Math.max(1,i.rotateCount+e)))},C=e=>{if(e===i.userAgent)return;i.setUserAgent(e);let t=u.find(t=>t.value===e)?.label??e;b.success(`Client identity updated`,t)},w=t?`${t.client} ${t.version}`:`Provider default`;return(0,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:`Routing Strategy`,subtitle:f,icon:(0,Q.jsx)(N,{size:16})}),(0,Q.jsx)(z,{children:(0,Q.jsxs)(`div`,{className:`grid gap-5 w-full min-w-0`,children:[(0,Q.jsx)(wt,{action:(0,Q.jsxs)(Q.Fragment,{children:[i.roundRobinEnabled?(0,Q.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,Q.jsx)(`span`,{className:`px-2 text-badge text-text-secondary`,children:`Accounts/rotation`}),(0,Q.jsx)(g,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Decrease accounts per rotation`,disabled:i.rotateCount<=1,icon:(0,Q.jsx)(ee,{size:14}),onClick:()=>S(-1)}),(0,Q.jsx)(`output`,{className:`min-w-8 text-center text-body font-semibold tabular-nums`,"aria-live":`polite`,children:i.rotateCount}),(0,Q.jsx)(g,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Increase accounts per rotation`,disabled:i.rotateCount>=1e3,icon:(0,Q.jsx)(te,{size:14}),onClick:()=>S(1)})]}):null,(0,Q.jsx)(We,{checked:i.roundRobinEnabled,onChange:i.setRoundRobinEnabled,id:`routing-round-robin`})]}),children:(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`label`,{htmlFor:`routing-round-robin`,children:(0,Q.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,Q.jsx)(ct,{size:15,"aria-hidden":`true`,className:`shrink-0 ${i.roundRobinEnabled?`text-accent`:`text-text-tertiary`}`}),`Round robin`]})}),(0,Q.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,Q.jsx)(wt,{action:(0,Q.jsx)(We,{checked:i.skipProxy,onChange:i.setSkipProxy,id:`routing-skip-proxy`}),children:(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`label`,{htmlFor:`routing-skip-proxy`,children:(0,Q.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,Q.jsx)(it,{size:15,"aria-hidden":`true`,className:`shrink-0 ${i.skipProxy?`text-accent`:`text-text-tertiary`}`}),`Always direct`]})}),(0,Q.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Bypass automatic proxy-pool routing for this provider and always dial direct`})]})}),(0,Q.jsxs)(`div`,{className:`routing-controls-grid grid gap-5 min-w-0 w-full`,children:[(0,Q.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,Q.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold mb-3`,children:[(0,Q.jsx)(l,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Client identity`]}),r?(0,Q.jsx)(q,{id:`routing-user-agent-preset`,"aria-label":`Client identity`,value:i.userAgent,options:u,onValueChange:C}):(0,Q.jsx)(q,{id:`routing-user-agent-fixed`,"aria-label":`Client identity`,disabled:!0,value:w,options:[{value:w,label:w}]}),(0,Q.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:r?`None sends the request as-is — whatever the runtime or egress sets, with no identity stamped by the gateway. A chosen value overrides it.`:`Set by the provider. It cannot be changed.`})]}),(0,Q.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,Q.jsx)(`label`,{htmlFor:`routing-max-inflight`,className:`form-label`,children:(0,Q.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,Q.jsx)(D,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / account`]})}),(0,Q.jsxs)(`div`,{className:`text-badge text-text-tertiary mb-3`,children:[`Shared provider ceiling. One step past `,xt,` is unlimited.`]}),(0,Q.jsxs)(Y,{gap:`10px`,className:`mt-3`,children:[(0,Q.jsx)(`input`,{id:`routing-max-inflight`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":p?`true`:void 0,min:1,max:51,step:1,value:m,"aria-valuetext":p?`Unlimited`:String(i.maxInflight),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&i.setMaxInflight(t>xt?null:Math.round(t))},style:{"--slider-pct":`${m/51*100}%`}}),(0,Q.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per account`,value:h,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){i.setMaxInflight(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&i.setMaxInflight(Math.min(St,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${p?`text-status-success`:``}`})]})]})]}),(0,Q.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0${x?` opacity-60`:``}`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Q.jsxs)(`label`,{htmlFor:`routing-max-inflight-per-proxy`,className:`min-w-0`,children:[(0,Q.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,Q.jsx)(dt,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / proxy`]}),(0,Q.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,Q.jsx)(g,{variant:`ghost`,size:`sm`,className:`shrink-0`,"aria-label":`How per-proxy limits work`,onClick:()=>o(!0),children:`How it works`})]}),(0,Q.jsxs)(Y,{gap:`10px`,className:`mt-3`,children:[(0,Q.jsx)(`input`,{id:`routing-max-inflight-per-proxy`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":_?`true`:void 0,min:1,max:51,step:1,disabled:x,value:v,"aria-valuetext":_?`Unlimited`:String(i.maxInflightPerProxy),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&i.setMaxInflightPerProxy(t>xt?null:Math.round(t))},style:{"--slider-pct":`${v/51*100}%`}}),(0,Q.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per proxy`,disabled:x,value:y,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){i.setMaxInflightPerProxy(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&i.setMaxInflightPerProxy(Math.min(St,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${_?`text-status-success`:``}`})]}),(0,Q.jsx)(`div`,{className:`mt-2 text-badge text-text-tertiary`,children:x?`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 ${xt} is unlimited.`})]}),(0,Q.jsx)(P,{open:a,onClose:()=>o(!1),title:`How concurrency limits stack`,size:`md`,children:(0,Q.jsxs)(`div`,{className:`grid gap-4 text-body`,children:[(0,Q.jsx)(`p`,{className:`text-text-secondary`,children:`Three limits apply at once. Each one bounds a different thing; none replaces another.`}),(0,Q.jsxs)(`dl`,{className:`grid gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / account`}),(0,Q.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`One account of this provider, across every proxy. Set here, above.`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / proxy`}),(0,Q.jsxs)(`dd`,{className:`text-badge text-text-tertiary`,children:[`One proxy pool's concurrent requests `,(0,Q.jsx)(`em`,{children:`for this provider`}),`. The same number applies to every pool; each pool counts separately. This is the field above.`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`font-semibold`,children:`Pool capacity`}),(0,Q.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,Q.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,Q.jsx)(`code`,{children:`429`}),` when every pool is full.`]}),(0,Q.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.`})]})}),s&&(0,Q.jsxs)(Y,{gap:`6px`,align:`flex-start`,className:`mt-1 text-badge text-text-tertiary`,children:[(0,Q.jsx)(at,{size:12,className:`shrink-0 mt-0.5`}),(0,Q.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 Et({providerId:e}){let t=bt(e,!1),n=Xe(),r=X(e),i=(0,Z.useMemo)(()=>Ot(n.data?.accounts??[],e),[n.data,e]),a=(0,Z.useRef)(null),o=(0,Z.useMemo)(()=>[...r.data?.values()??[]].reduce((e,t)=>e+t,0),[r.data]);(0,Z.useEffect)(()=>{if(a.current===null){a.current=o;return}a.current!==o&&(a.current=o,n.refetch())},[o,n]);let[s,c]=(0,Z.useState)(`40`),[l,u]=(0,Z.useState)(`percent`),d=t.usageFloor!==null;(0,Z.useEffect)(()=>{t.usageFloor!==null&&c(String(t.usageFloor)),u(t.usageFloorUnit)},[t.usageFloor,t.usageFloorUnit]);let f=Number(s),p=Number.isInteger(f)&&f>=0&&f<=1e6,m=i===null||i.remaining<=0?`text-status-danger`:i.percent<=10?`text-status-warning`:`text-status-success`,h=(e,n)=>{(e===null||p)&&t.setUsageFloor(e,n)};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Q.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,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,Q.jsx)(D,{size:14}),(0,Q.jsx)(`span`,{children:`Usage floor`}),(0,Q.jsx)(`span`,{className:`badge border border-warning-line bg-surface-2 text-micro tracking-label text-status-warning`,children:`BETA`})]}),(0,Q.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,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4`,children:[i!==null&&(0,Q.jsxs)(`div`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2`,children:[(0,Q.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,Q.jsx)(`span`,{children:`Pooled credits`}),(0,Q.jsx)(`span`,{className:`text-text-primary`,children:i.accounts}),(0,Q.jsx)(`span`,{children:i.accounts===1?`active account`:`active accounts`})]}),(0,Q.jsxs)(`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:[(0,Q.jsx)(`strong`,{className:`font-bold ${m}`,children:kt(i.remaining)}),(0,Q.jsx)(`span`,{className:`font-medium text-text-secondary`,children:`credits available`}),(0,Q.jsxs)(`span`,{className:`font-medium opacity-75`,children:[`of `,kt(i.total)]}),(0,Q.jsxs)(`span`,{className:`font-bold ${m}`,children:[i.percent,`%`]})]}),(0,Q.jsx)(`p`,{className:`text-micro leading-normal text-text-tertiary`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${kt(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),i===null&&(0,Q.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,Q.jsx)(`span`,{children:`No combined credit balance is available. Separate quota windows are not added together, and exhausted windows are still skipped.`}),(0,Q.jsx)(`span`,{className:`text-micro`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${kt(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),(0,Q.jsxs)(`div`,{className:`ml-auto flex max-w-full shrink-0 flex-col items-end justify-center gap-2`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-x-3 gap-y-2`,children:[(0,Q.jsx)(`span`,{className:`text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:`Floor threshold`}),(0,Q.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,Q.jsx)(`input`,{type:`number`,min:0,max:1e6,value:d?s:``,placeholder:`40`,disabled:!d,"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=>c(e.target.value),onBlur:()=>{d&&h(f,l)}}),(0,Q.jsxs)(`select`,{value:l,disabled:!d,"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`;u(t),d&&h(f,t)},children:[(0,Q.jsx)(`option`,{value:`percent`,children:`%`}),(0,Q.jsx)(`option`,{value:`credit`,children:`credits`})]})]}),(0,Q.jsx)(We,{checked:d,label:`Enabled`,"aria-label":`Usage floor`,className:`usage-floor-switch`,onChange:e=>h(e?p?f:40:null,l)})]}),t.saveFailed?(0,Q.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,Q.jsx)(Dt,{providerId:e})]})}function Dt({providerId:e}){let{enabled:t,setEnabled:n}=$e(e);return(0,Q.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,Q.jsxs)(`div`,{className:`min-w-0 flex-auto basis-110`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,Q.jsx)(T,{size:14}),(0,Q.jsx)(`span`,{children:`Mysterious accounts`})]}),(0,Q.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,Q.jsx)(`div`,{className:`flex items-center gap-4 shrink-0`,children:(0,Q.jsx)(We,{checked:t,"aria-label":`Mysterious accounts`,onChange:n})})]})}function Ot(e,t){let n=0,r=0,i=0,a=!1;for(let o of e)if(o.provider===t&&o.active&&(i+=1,o.quota!==null))for(let e of o.quota.windows){if(e.accounting!==`pooled`)continue;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;i!==null&&(n+=Math.min(t,Math.max(0,i)),r+=t,a=!0)}return i>0&&a?{accounts:i,remaining:n,total:r,percent:r>0?Math.round(n/r*100):0}:null}function kt(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function At({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,Q.jsx)(B,{density:`compact`,children:(0,Q.jsx)(z,{children:(0,Q.jsxs)(Y,{gap:`12px`,className:`items-center flex-wrap`,children:[(0,Q.jsxs)(`span`,{className:`min-w-110 flex-1 text-caption text-text-secondary`,children:[a,r?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),r]}):null]}),t?(0,Q.jsxs)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,title:t,className:v({size:`sm`,className:`shrink-0 no-underline`}),children:[(0,Q.jsx)(`span`,{className:`btn-icon-wrapper`,"aria-hidden":`true`,children:(0,Q.jsx)(ye,{size:13})}),i?`Sign in`:`Get API Key`]}):null]})})})}function jt({provider:e}){let t=he(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(e.baseUrl??``);(0,Z.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,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:`Custom Provider Endpoint`,subtitle:`Upstream base URL`,icon:(0,Q.jsx)(p,{size:16})}),(0,Q.jsx)(z,{children:(0,Q.jsxs)(J,{gap:`12px`,children:[n?(0,Q.jsx)(K,{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,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`div`,{className:`text-micro font-semibold uppercase tracking-label text-text-tertiary`,children:`Base URL`}),(0,Q.jsx)(`code`,{className:`mt-1 block min-w-0 break-all font-mono text-caption text-text-primary`,children:e.baseUrl??`Not configured`})]}),(0,Q.jsxs)(Y,{gap:`8px`,className:`w-full flex-wrap`,justify:`end`,children:[n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{size:`sm`,variant:`primary`,icon:(0,Q.jsx)(lt,{size:13}),disabled:!l,loading:t.isPending,onClick:()=>{l&&t.mutate({providerId:e.providerId,request:{baseUrl:s}},{onSuccess:()=>r(!1)})},children:`Save endpoint`}),(0,Q.jsx)(g,{size:`sm`,variant:`secondary`,icon:(0,Q.jsx)(x,{size:13}),disabled:t.isPending,onClick:()=>{a(e.baseUrl??``),r(!1)},children:`Cancel`})]}):(0,Q.jsx)(g,{size:`sm`,variant:`secondary`,icon:(0,Q.jsx)(F,{size:13}),onClick:()=>r(!0),children:`Edit endpoint`}),e.requiresAccount?(0,Q.jsx)(g,{size:`sm`,variant:`secondary`,icon:(0,Q.jsx)(M,{size:13}),onClick:()=>{let e=document.getElementById(`provider-accounts`);e?.scrollIntoView({behavior:`smooth`,block:`start`}),e?.focus({preventScroll:!0})},children:`Manage API keys`}):null]})]})})]})}var Mt={quota_fetch_failed:`Quota unreachable`,quota_exhausted:`Quota exhausted`,policy_blocked:`Policy blocked`,rate_limit_transient:`Rate limited`,missing_credential:`No credential`},Nt=new Set([`quota_fetch_failed`]);function Pt(e){return e===void 0||e.length===0?!1:!Nt.has(e)}function Ft(e){return e===`oauth`?`Re-login required`:`Replace API key`}function It(e,t){return e===`auth_invalidated`?Ft(t):Mt[e]??e}async function Lt(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}var Rt=[`access`,`accessToken`,`access_token`,`sessionToken`,`session_token`,`token`,`apiKey`,`api_key`,`key`,`credential`,`pat`,`secret`],zt=[`refresh`,`refreshToken`,`refresh_token`],Bt=[`credentialKind`,`providerId`,`accessToken`],Vt=[`accounts`,`items`,`connections`],Ht=[`email`,`name`,`accountId`,`account_id`,`id`,`login`,`username`];function $(e){if(typeof e==`object`&&e&&!Array.isArray(e))return Object.fromEntries(Object.entries(e))}function Ut(e){let t=e.data;if(typeof t==`string`)try{return $(JSON.parse(t))}catch{return}return $(t)}function Wt(e){for(let t of Rt){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:t}}let t=Ut(e);if(t)for(let e of Rt){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:`data.${e}`}}}function Gt(e){for(let t of Ht){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return n.trim()}let t=Ut(e);if(t)for(let e of Ht){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function Kt(e){let t=(e,t)=>t.some(t=>typeof e[t]==`string`||typeof e[t]==`number`),n=e=>t(e,zt);if(n(e))return!0;let r=Ut(e);return r?n(r):!1}function qt(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 $(JSON.parse(atob(n)))}catch{return}}function Jt(e){let t=qt(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 Yt(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 Xt(e){if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return}}function Zt(e){let t=e.trim(),n=$(Xt(t))??Yt(t);return n&&Kt(n)?`oauth`:qt((n?Wt(n)?.value:void 0)??t)===void 0?`api_key`:`jwt`}function Qt(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 $t(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 en(e){let t=e.credentialKind;if(typeof t==`string`&&typeof e.accessToken==`string`&&Bt.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`&&Kt(e);return{value:i?JSON.stringify(e):r,kind:i?`oauth`:`api_key`,...n?{identity:n}:{}}}let n=Wt(e),r=Kt(e)?`oauth`:Zt(n?.value??JSON.stringify(e)),i=r===`oauth`?JSON.stringify(e):n?.value??JSON.stringify(e),a=Gt(e);return a?{value:i,kind:r,identity:a}:{value:i,kind:r}}function tn(e){for(let t of Vt){let n=e[t];if(!Array.isArray(n))continue;let r=n.map(e=>$(e)).filter(e=>e!==void 0);if(r.length>0)return r}}function nn(e){let t=e.trim();if(!t)return[];let n=Xt(t);if(Array.isArray(n)){let e=n.map(e=>$(e)).filter(e=>e!==void 0);if(e.length>0)return Qt(e)?[$t(t,e)]:e.map(en)}else{let e=$(n);if(e){let t=tn(e);return t?t.map(en):[en(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=Yt(r[0]);return e?[en(e)]:rn(r[0])}let i=Yt(t);return i&&(Wt(i)||Object.keys(i).length===r.length)?[en(i)]:r.flatMap(rn)}function rn(e){let t=$(Xt(e));if(t){let e=tn(t);return e?e.map(en):[en(t)]}return[{value:e,kind:Zt(e)}]}function an(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 on(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}function sn(e){return e===`active`?0:e===`cooldown`?2:3}function cn(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()}`:Ke(e,!1)}function ln({cooldowns:e,reason:t}){if(!e)return null;let n=Ke(e.until),r=`Soonest: ${e.modelId} — ${n}`;return(0,Q.jsxs)(G,{tone:`warn`,dot:!0,title:t?`${t} — ${r}`:r,children:[e.count,` model`,e.count===1?``:`s`,` cooling · `,n]})}function un(e){if(e.credentialKind===`oauth`)return`OAuth`;if(e.credentialMode===`jwt`)return`JWT`}function dn(e){return e.credentialKind===`oauth`?`blue`:`ok`}function fn({account:e}){let t=e.cooldownUntil?new Date(e.cooldownUntil).getTime():NaN,n=Number.isFinite(t)&&t>Date.now(),r=tt(e);if(e.status===`disabled`){let t=un(e),n=e.lastErrorCategory===`auth_invalidated`;return(0,Q.jsxs)(Y,{gap:`4px`,children:[(0,Q.jsxs)(G,{tone:`disabled`,dot:!0,title:e.lastError,children:[`Disabled`,t?` - ${t}`:``]}),n?(0,Q.jsx)(G,{tone:`warn`,title:e.lastError,children:Ft(e.credentialKind)}):Pt(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,Q.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:It(e.lastErrorCategory,e.credentialKind)}):null,(0,Q.jsx)(ln,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]})}return e.status===`active`?(0,Q.jsxs)(Y,{gap:`4px`,children:[(0,Q.jsxs)(G,{tone:dn(e),dot:!0,children:[`Active`,un(e)?` - ${un(e)}`:``]}),Pt(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,Q.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:It(e.lastErrorCategory,e.credentialKind)}):null,(0,Q.jsx)(ln,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):e.status===`cooldown`||n?(0,Q.jsxs)(Y,{gap:`4px`,children:[(0,Q.jsxs)(G,{tone:`warn`,dot:!0,children:[`Cooldown`,un(e)?` - ${un(e)}`:``,` `,e.cooldownUntil?`(${Ke(e.cooldownUntil)})`:``]}),Pt(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,Q.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:It(e.lastErrorCategory,e.credentialKind)}):null,(0,Q.jsx)(ln,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):(0,Q.jsx)(G,{tone:`disabled`,children:`Disabled`})}function pn({windows:e}){if(e===void 0||e.length===0)return null;let t=0,n=0,r=!1,i=null;for(let a of e){if(a.accounting!==`pooled`){typeof a.remainingPercent==`number`&&Number.isFinite(a.remainingPercent)&&(i=i===null?a.remainingPercent:Math.min(i,a.remainingPercent));continue}let e=typeof a.limit==`number`&&Number.isFinite(a.limit)?a.limit:null,o=typeof a.remaining==`number`&&Number.isFinite(a.remaining)?a.remaining:e!==null&&typeof a.used==`number`&&Number.isFinite(a.used)?e-a.used:null;o!==null&&e!==null&&(t+=Math.max(0,o),n+=e,r=!0)}let a=null;return r?a=`${mn(t)} of ${mn(n)}`:i!==null&&(a=`${Math.round(i)}% left`),a===null?null:(0,Q.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&&t<=0||(i??100)<=10?`warn`:void 0,title:r?`${mn(t)} credits available of ${mn(n)}`:`Lowest remaining percent across this account's quota windows`,children:[(0,Q.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Quota`}),a]})}function mn(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function hn({providerId:e,account:t,onClose:n}){let r=Te(),[i,a]=(0,Z.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{b.error(`Clipboard access denied`)}};return(0,Q.jsx)(P,{open:!0,onClose:n,title:`Replace API key — ${o}`,width:560,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:n,disabled:s,children:`Cancel`}),(0,Q.jsx)(g,{size:`sm`,variant:`primary`,disabled:!c,onClick:()=>{let a=i.trim();a&&r.mutate({providerId:e,accountId:t.id,request:{secret:a}},{onSuccess:()=>{b.success(`API key replaced`,o),n()},onError:e=>{let t=e instanceof Error?e.message:`Unable to update account`;b.error(`Failed to replace key`,t)}})},children:s?`Saving…`:`Replace key`})]}),children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,Q.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,Q.jsxs)(J,{gap:`6px`,className:`min-w-0`,children:[(0,Q.jsx)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:`New API key`}),(0,Q.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,Q.jsx)(Y,{gap:`8px`,className:`justify-end`,children:(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:()=>void l(),children:`Paste`})})]})]})})}function gn({providerId:e,account:t,inflight:n,quota:r,selected:a,onToggleSelect:o,onDelete:s}){let c=Te(),l=Le(),d=Ze(t.id),p=t.status===`disabled`,m=t.cooldownUntil?new Date(t.cooldownUntil).getTime():NaN,h=Number.isFinite(m)&&m>Date.now(),_=t.status===`cooldown`||h,[v,y]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(!1),[,C]=(0,Z.useState)(0),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(``),O=$e(e),k=(t.label?.match(/[^\s@]+@[^\s@]+/)?.[0]??t.label)||t.id.slice(0,8),A=O.enabled?`Mysterious accounts`:k,j=cn(t.tokenExpiresAt),N=et(t),ee=Math.max(h&&t.cooldownUntil?m:0,N??0);(0,Z.useEffect)(()=>{if(ee<=Date.now())return;let e=setInterval(()=>C(e=>e+1),1e3);return()=>clearInterval(e)},[ee]);let P=()=>{let n=E.trim();T(!1),n&&n!==(t.label??``)&&c.mutate({providerId:e,accountId:t.id,request:{label:n}},{onSuccess:()=>b.success(`Account renamed`,n),onError:e=>b.error(`Rename failed`,e.message??`Unable to rename account`)})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.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:p?.62:1},children:[(0,Q.jsx)(`div`,{className:`flex items-center`,children:(0,Q.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(t.id,e.target.checked),"aria-label":`Select ${A}`,className:`cursor-pointer`})}),(0,Q.jsxs)(`div`,{className:`min-w-0 flex flex-col gap-1.5`,children:[(0,Q.jsx)(`div`,{className:`flex items-center gap-3 min-w-0`,children:w?(0,Q.jsx)(K,{value:E,onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&P(),e.key===`Escape`&&T(!1)},onBlur:P,autoFocus:!0,"aria-label":`Account label`,className:`text-body max-w-120`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.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:A}),(0,Q.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 ${A}`,onClick:()=>{D(t.label??``),T(!0)},children:(0,Q.jsx)(F,{size:11})})]})}),(0,Q.jsxs)(`div`,{className:`flex items-center flex-nowrap gap-2 min-w-0 overflow-hidden`,children:[(0,Q.jsx)(fn,{account:t}),j?(0,Q.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:j,children:j}):null]}),(0,Q.jsxs)(`div`,{className:`flex items-center flex-wrap gap-2 min-w-0`,children:[(0,Q.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,Q.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,Q.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,Q.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,Q.jsx)(pn,{windows:r}),(0,Q.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 no longer carry manual ceilings.`,children:[(0,Q.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`In flight`}),n?.toLocaleString()??`—`]})]})]}),(0,Q.jsxs)(`div`,{className:`account-row-actions flex items-center justify-end gap-3 flex-wrap`,children:[(0,Q.jsx)(g,{size:`icon`,variant:`secondary`,icon:(0,Q.jsx)(i,{size:12}),label:`Health`,"aria-label":`Health for ${A}`,onClick:()=>y(!0),title:`View Health & Error History`}),(0,Q.jsx)(g,{size:`icon`,variant:`secondary`,icon:d.isPending?(0,Q.jsx)(u,{size:12,className:`animate-spin`}):(0,Q.jsx)(f,{size:12}),label:d.isPending?`Testing…`:`Test`,"aria-label":`Test ${A}`,disabled:d.isPending,onClick:()=>{d.mutate(void 0,{onSuccess:e=>{e?.ok?b.success(`Account test passed`,A):b.error(`Account test failed`,e?.message??`Provider reported an error`)},onError:e=>b.error(`Account test failed`,e.message??`Unable to test account`)})},title:`Refresh quota and health for this account`}),(0,Q.jsx)(g,{size:`icon`,variant:`secondary`,icon:(0,Q.jsx)(M,{size:12}),label:`Edit key`,"aria-label":`Replace API key for ${A}`,onClick:()=>S(!0),title:`Replace API key`}),(0,Q.jsx)(g,{size:`icon`,variant:`secondary`,icon:p?(0,Q.jsx)(ot,{size:12}):(0,Q.jsx)(ne,{size:12}),label:p?`Enable`:`Disable`,"aria-label":p?`Enable ${A}`:`Disable ${A}`,disabled:c.isPending,onClick:()=>{let n=p;c.mutate({providerId:e,accountId:t.id,request:{status:n?`active`:`disabled`}},{onSuccess:()=>b.success(n?`Account enabled`:`Account disabled`,A),onError:e=>b.error(`Update failed`,e.message??`Unable to update account`)})},title:p?`Enable account`:`Disable account`}),_?(0,Q.jsx)(g,{size:`icon`,variant:`secondary`,icon:(0,Q.jsx)(ie,{size:12,className:l.isPending?`animate-spin`:``}),label:l.isPending?`Recovering…`:`Recover`,"aria-label":`Recover ${A}`,disabled:l.isPending,onClick:()=>l.mutate({providerId:e,accountId:t.id}),title:`Clear cooldown / restore active status`}):null,(0,Q.jsx)(g,{size:`icon`,variant:`danger`,icon:(0,Q.jsx)(oe,{size:12}),label:`Delete`,"aria-label":`Delete ${A}`,onClick:()=>s(t),title:`Delete account`})]})]}),v&&(0,Q.jsx)(Qe,{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},onClose:()=>y(!1)}),x&&(0,Q.jsx)(hn,{providerId:e,account:t,onClose:()=>S(!1)})]})}var _n=[{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 vn(e,t,n){let r=(e,t)=>(e.label||e.id).localeCompare(t.label||t.id)||e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);if(n===`added`)return e.sortIndex-t.sortIndex||e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);if(n===`label`)return r(e,t);if(n===`status`){let n=sn(e.status)-sn(t.status);return n===0?r(e,t):n}let i=new Date(e.lastSuccessAt??e.createdAt).getTime();return new Date(t.lastSuccessAt??t.createdAt).getTime()-i||r(e,t)}function yn({providerId:e,accounts:t,onDelete:n,showGrokProbe:r=!1,grokProbePending:i=!1,onGrokProbe:a}){let o=ce(),s=Te(),c=Le(),l=Ee(),u=X(e).data??new Map,d=Xe(),p=(0,Z.useMemo)(()=>{let t=new Map;for(let n of d.data?.accounts??[])n.provider===e&&n.quota&&t.set(n.id,n.quota.windows);return t},[d.data,e]),[m,h]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(new Set),[y,x]=(0,Z.useState)(`added-asc`),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(!1),A=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!O)return;let e=e=>{A.current&&!A.current.contains(e.target)&&k(!1)},t=e=>{e.key===`Escape`&&k(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[O]);let M=m.trim().toLowerCase(),N=(0,Z.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]),ee=(0,Z.useMemo)(()=>{let e=y.slice(0,y.lastIndexOf(`-`)),t=y.endsWith(`-desc`)?-1:1,n=[...N];return n.sort((n,r)=>t*vn(n,r,e)),n},[N,y]),P=(0,Z.useMemo)(()=>t.filter(e=>_.has(e.id)),[t,_]),F=N.length>0&&N.every(e=>_.has(e.id)),te=P.some(e=>e.status===`disabled`),re=P.some(e=>e.status!==`disabled`),se=P.length===0,le=(e,t)=>{v(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},de=()=>{v(e=>{let t=new Set(e);if(F)for(let e of N)t.delete(e.id);else for(let e of N)t.add(e.id);return t})},fe=async(e,t)=>{if(P.length===0)return;C(!0);let n=await Promise.allSettled(P.map(e=>t(e))),r=n.filter(e=>e.status===`rejected`).length,i=n.length-r;C(!1),r===0?b.success(`${e} complete`,`${i} account${i===1?``:`s`}`):b.error(`${e} partially failed`,`${i} succeeded, ${r} failed`)},pe=()=>fe(`Recover`,t=>c.mutateAsync({providerId:e,accountId:t.id})),me=async()=>{t.length!==0&&(C(!0),T({done:0,total:t.length}),await Lt(t,3,async(e,n)=>{let r=await ue(`/accounts/${encodeURIComponent(e.id)}/quota/refresh`,{method:`POST`});return T({done:n+1,total:t.length}),r}),await Promise.all([o.invalidateQueries({queryKey:I.quota.all}),o.invalidateQueries({queryKey:I.providers.all})]),C(!1),T(null),b.success(`Test complete`,`${t.length} account${t.length===1?``:`s`} tested`))},he=t=>fe(t?`Enable`:`Disable`,n=>s.mutateAsync({providerId:e,accountId:n.id,request:{status:t?`active`:`disabled`}})),ge=async()=>{if(P.length!==0){C(!0);try{let t=await l.mutateAsync({providerId:e,accountIds:P.map(e=>e.id)}),n=new Date().toISOString().replace(/[:.]/g,`-`);V(`${e}-accounts-${n}.json`,JSON.stringify(t,null,2),`application/json`),b.success(`Accounts exported`,`${t.accounts.length} account${t.accounts.length===1?``:`s`} — contains plaintext credentials`)}catch(e){b.error(`Export failed`,e.message??`Unable to export accounts`)}finally{C(!1)}}};return(0,Q.jsxs)(J,{gap:`8px`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 p-3 border border-inner-border rounded-control bg-surface-2`,children:[(0,Q.jsxs)(`label`,{className:`relative min-w-20 flex-[1_1_10rem]`,children:[(0,Q.jsx)(ae,{size:13,"aria-hidden":`true`,className:`pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary`}),(0,Q.jsx)(K,{id:`accounts-search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search accounts...`,"aria-label":`Search accounts`,className:`pl-9`})]}),(0,Q.jsx)(g,{size:`sm`,variant:`primary`,icon:(0,Q.jsx)(f,{size:12}),disabled:S||t.length===0,onClick:me,"aria-label":w===null?`Test all accounts`:`Testing accounts, ${w.done} of ${w.total} tested`,title:`Test every account, regardless of selection or filters`,children:w===null?`Test all`:`Tested ${w.done}/${w.total}`}),(0,Q.jsxs)(`div`,{ref:A,className:`relative`,children:[(0,Q.jsxs)(g,{size:`sm`,variant:`secondary`,disabled:S||se,"aria-expanded":O,"aria-haspopup":`menu`,"aria-label":se?`Select accounts to enable bulk actions`:`Bulk actions for ${P.length} selected accounts`,onClick:()=>k(e=>!e),children:[`Actions`,se?``:` (${P.length})`,(0,Q.jsx)(Pe,{size:12,"aria-hidden":`true`,className:`transition-transform ${O?`rotate-180`:``}`})]}),O&&!se?(0,Q.jsxs)(`div`,{role:`menu`,"aria-label":`Selected account actions`,className:`absolute left-0 top-full z-50 mt-1 flex w-64 popover-max flex-col gap-1 rounded-control border border-inner-border bg-popover-bg p-2 shadow-popout sm:left-auto sm:right-0`,children:[(0,Q.jsx)(g,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,Q.jsx)(ie,{size:12}),disabled:S,onClick:()=>{k(!1),pe()},children:`Recover`}),te?(0,Q.jsx)(g,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,Q.jsx)(ot,{size:12}),disabled:S,onClick:()=>{k(!1),he(!0)},children:`Enable`}):null,re?(0,Q.jsx)(g,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,Q.jsx)(ne,{size:12}),disabled:S,onClick:()=>{k(!1),he(!1)},children:`Disable`}):null,(0,Q.jsx)(g,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,Q.jsx)(De,{size:12}),disabled:S,onClick:()=>{k(!1),ge()},children:`Export JSON`}),(0,Q.jsx)(g,{role:`menuitem`,size:`sm`,variant:`danger`,className:`w-full justify-start`,icon:(0,Q.jsx)(oe,{size:12}),disabled:S,onClick:()=>{k(!1),D(!0)},children:`Delete`}),(0,Q.jsx)(g,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,disabled:S,onClick:()=>{v(new Set),k(!1)},children:`Clear selection`})]}):null]}),(0,Q.jsx)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary [&_.radix-select-trigger]:font-semibold [&_.radix-select-trigger]:bg-hover [&_.radix-select-trigger]:text-text-primary`,children:(0,Q.jsx)(q,{size:`sm`,value:y,onValueChange:e=>x(e),options:_n,"aria-label":`Sort accounts by`})}),(0,Q.jsxs)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:F,onChange:de,"aria-label":`Select accounts`}),(0,Q.jsx)(`span`,{children:`Select`})]}),r?(0,Q.jsx)(g,{size:`sm`,variant:`secondary`,icon:(0,Q.jsx)(f,{size:12,className:i?`animate-spin`:``}),disabled:i||t.length===0,onClick:a,title:`Probe every Grok account with the live 407 streaming request`,children:i?`Testing…`:`Test 407`}):null]}),(0,Q.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:ee.length===0?(0,Q.jsx)(j,{compact:!0,icon:(0,Q.jsx)(ae,{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.`}):ee.map(t=>(0,Q.jsx)(gn,{providerId:e,account:t,inflight:u.get(t.id)??t.inflight,quota:p.get(t.id),selected:_.has(t.id),onToggleSelect:le,onDelete:n},t.id))}),(0,Q.jsx)(`div`,{className:`flex items-center justify-between text-badge text-text-tertiary`,children:(0,Q.jsxs)(`span`,{children:[`Showing `,N.length,` account`,N.length===1?``:`s`,M?` (filtered from ${t.length})`:``]})}),(0,Q.jsx)(Re,{open:E,onClose:()=>{S||D(!1)},onConfirm:async()=>{await fe(`Delete`,async e=>{let t=e.tenantId===null?`/global/accounts/${encodeURIComponent(e.id)}`:`/accounts/${encodeURIComponent(e.id)}`;await ue(t,{method:`DELETE`}),o.removeQueries({queryKey:I.quota.account(e.id),exact:!0})}),v(new Set),D(!1),await Promise.all([o.invalidateQueries({queryKey:I.providers.accounts(e)}),o.invalidateQueries({queryKey:I.providers.all}),o.invalidateQueries({queryKey:I.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})]})}var bn=2097152,xn=bn/1048576;function Sn({providerId:e,accounts:t,onClose:n}){let r=_e(),i=ke(),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(`auto`),p=nn(s),m=p.length>1,h=p.length===1?p[0]:void 0,_=d===`auto`?h?.kind:d,y=h&&_===`jwt`?Jt(h.value):void 0,x=t.map(e=>e.label),S=m?an(p,e,x):[],C=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}},w=r.isPending||l,T=async()=>{try{let e=await navigator.clipboard.readText();c(e);let t=nn(e);if(t.length>1)b.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`;b.success(`Pasted from clipboard`,`Detected: ${n}`)}}catch{b.error(`Clipboard access denied`)}},E=e=>{if(e.size>bn){b.error(`File too large`,`Credential files must be ${xn} MB or smaller.`);return}let t=new FileReader;t.onload=()=>{let n=typeof t.result==`string`?t.result:``;c(n);let r=nn(n);if(r.length===0){b.error(`Nothing to import`,`That file held no credential the gateway recognises.`);return}b.success(`Imported ${e.name}`,r.length>1?`Detected ${r.length} credentials`:r[0]?.kind===`oauth`?`Detected: OAuth export`:`Detected: API key`)},t.onerror=()=>b.error(`Could not read that file`),t.readAsText(e)},D=async()=>{if(p.length!==0){if(p.length===1){let t=p[0];r.mutate({providerId:e,request:{label:(a.trim()||t.identity)??void 0,...C(t)}},{onSuccess:()=>{b.success(`Account connected`,`New ${t.kind===`oauth`?`OAuth`:t.kind===`jwt`?`Static JWT`:`API key`} account registered successfully`),n()},onError:e=>b.error(`Failed to add account`,e.message??`Invalid credentials`)});return}u(!0);try{let t=on(p.map((e,t)=>({label:S[t],...C(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(`${S[o+e.index]??o+e.index}: ${e.error??`rejected`}`)}catch(e){o=!0,a.push(`chunk ${n+1}/${t.length}: ${le(e,`request failed`)}`);break}let s=a.length;r>0&&b.success(`${r} account${r===1?``:`s`} added`,o?`stopped partway; ${s} failed`:s>0?`${s} skipped`:void 0),s>0&&b.error(`${s} account${s===1?``:`s`} skipped`,a.slice(0,5).join(`
2
- `)+(s>5?`\n…and ${s-5} more`:``)),r>0&&n()}finally{u(!1)}}};return(0,Q.jsx)(P,{open:!0,onClose:n,title:`Add Account (API key / JSON)`,width:560,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:n,disabled:w,children:`Cancel`}),(0,Q.jsx)(g,{size:`sm`,variant:`primary`,disabled:w||p.length===0,onClick:()=>void D(),children:w?`Connecting...`:m?`Add ${p.length} Accounts`:`Add Account`})]}),children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[!m&&(0,Q.jsx)(K,{label:`Account label (optional)`,value:a,onChange:e=>o(e.target.value),placeholder:h?.identity??`${e} account`}),(0,Q.jsx)(q,{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,Q.jsxs)(J,{gap:`6px`,className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Q.jsx)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:`API key, OAuth token, or exported JSON — one or many`}),m?(0,Q.jsxs)(G,{tone:`accent`,children:[`Detected: `,p.length,` accounts`]}):h?(0,Q.jsxs)(G,{tone:_===`oauth`||_===`jwt`?`accent`:`default`,children:[`Detected:`,` `,_===`oauth`?`OAuth`:_===`jwt`?`Static JWT`:`API key`,h.identity?` · ${h.identity}`:``]}):null,h&&_===`jwt`?(0,Q.jsxs)(`p`,{className:`text-micro text-text-tertiary`,children:[`Static JWT · no refresh token`,y?` · expires ${new Date(y).toLocaleString()}`:` · no expiry claim`]}):null]}),(0,Q.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. 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,Q.jsxs)(Y,{gap:`8px`,className:`justify-end`,children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:()=>void T(),children:`Paste`}),(0,Q.jsxs)(`label`,{className:v({size:`sm`,className:`cursor-pointer`}),children:[(0,Q.jsx)(`input`,{type:`file`,accept:`.json,.txt,.jsonl,.ndjson,application/json,text/plain`,"aria-label":`Import credentials from a file`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&E(t)}}),`Import file`]})]})]}),m&&(0,Q.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:p.map((e,t)=>(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-4 text-badge`,children:[(0,Q.jsx)(`span`,{className:`truncate min-w-0`,children:S[t]}),(0,Q.jsx)(G,{tone:e.kind===`oauth`?`accent`:`default`,children:e.kind===`oauth`?`OAuth`:`API key`})]},t))})]})})}function Cn(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 wn({providerId:e,authorizeUrl:t,state:n,popup:r,onClose:i}){let[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(``),l=R(),f=nt(),p=ce(),m=Oe(e),h=(0,Z.useRef)(null),v=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let t=setInterval(()=>{p.invalidateQueries({queryKey:I.providers.accounts(e)})},1500);return()=>clearInterval(t)},[p,e]),(0,Z.useEffect)(()=>{let e=m.data?.map(e=>e.id)??null;if(e!==null){if(h.current===null){h.current=new Set(e);return}v.current||e.find(e=>!h.current.has(e))!==void 0&&(v.current=!0,r.close(),b.success(`Account connected`,`OAuth login completed successfully`),i(!0))}},[m.data,r,i]);let y=()=>{r.close(),i(!1)},[x,S]=(0,Z.useState)(!1),C=()=>{S(!0),p.invalidateQueries({queryKey:I.providers.accounts(e)}).finally(()=>S(!1))},w=async()=>{try{let e=await navigator.clipboard.readText();if(!e.trim()){b.error(`Clipboard is empty`);return}c(e),b.success(`Pasted redirect URL`)}catch{b.error(`Clipboard unavailable on this origin`)}};return(0,Q.jsx)(P,{open:!0,onClose:y,title:`Connect via OAuth`,size:`sm`,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:y,disabled:l.isPending,children:`Cancel`}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:C,disabled:l.isPending||x,title:`You already approved in the popup — check now instead of waiting`,children:x?`Checking…`:`Complete`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,disabled:l.isPending||s.trim().length===0,onClick:()=>{let t=Cn(s);if(`error`in t){b.error(`OAuth callback failed`,t.error);return}l.mutate({providerId:e,code:t.code,state:n},{onSuccess:()=>{r.close(),b.success(`Account connected`,`OAuth login completed successfully`),i(!0)},onError:e=>b.error(`OAuth callback failed`,e.message??`Invalid or expired authorization code`)})},children:l.isPending?`Connecting…`:`Connect`})]}),children:(0,Q.jsxs)(J,{gap:`14px`,children:[(0,Q.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,Q.jsx)(u,{size:16,className:`animate-spin text-accent shrink-0`}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,children:`Waiting for popup authorization…`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Q.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 1: Open this URL in your browser`}),(0,Q.jsxs)(Y,{gap:`8px`,children:[(0,Q.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,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:a?(0,Q.jsx)(_,{size:12}):(0,Q.jsx)(d,{size:12}),onClick:()=>{navigator.clipboard?.writeText(t),o(!0),f(()=>o(!1),1500)},className:`shrink-0`,children:a?`Copied`:`Copy`})]}),(0,Q.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,Q.jsxs)(`div`,{className:`flex items-center gap-2.5 text-micro font-bold uppercase tracking-label text-text-tertiary`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`flex-1 h-px bg-inner-border`}),(0,Q.jsx)(`span`,{children:`Or complete manually`}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`flex-1 h-px bg-inner-border`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Q.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 2: Paste the redirect URL here`}),(0,Q.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,Q.jsxs)(Y,{gap:`8px`,align:`flex-start`,children:[(0,Q.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 flex-1`}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:()=>void w(),className:`shrink-0`,children:`Paste`})]})]})]})})}function Tn(e){try{return new URL(e).host}catch{return e}}function En({providerId:e,parameters:t,onClose:n}){let r=fe(),i=be(),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,f]=(0,Z.useState)(!1),p=nt();(0,Z.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||(b.error(`Failed to start device login`,e.message??`Unable to start device authorization`),n())}}),()=>{i=!0}},[]);let m=(0,Z.useRef)(null),[h,v]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{if(!a)return;let e=window.open(a.verificationUri,`cartethyia-device`,`popup,width=720,height=820`);return e?m.current=e:v(!0),()=>{let e=m.current;m.current=null,e&&!e.closed&&e.close()}},[a]),(0,Z.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(),b.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(),b.success(`OAuth account connected`,`Device authorization complete`),n()}else e.status===`failed`?(u(),b.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:()=>{o=!1,c||d(s)}}))}};return d(s+1e3),()=>{c=!0,u()}},[a]),(0,Q.jsx)(P,{open:!0,onClose:n,title:`Login with OAuth (device code)`,size:`sm`,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:n,children:`Cancel`}),null]}),children:(0,Q.jsx)(J,{gap:`14px`,children:a?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.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,Q.jsx)(u,{size:16,className:`animate-spin text-accent shrink-0`}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,children:`Waiting for authorization…`})]}),a.userCode?(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Q.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 1: Enter this code`}),(0,Q.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,Q.jsx)(`div`,{className:`text-micro font-bold uppercase tracking-label text-text-tertiary`,children:`Device code`}),(0,Q.jsx)(`div`,{className:`font-mono text-display font-bold tracking-code text-text-primary`,children:a.userCode}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:l?(0,Q.jsx)(_,{size:12}):(0,Q.jsx)(d,{size:12}),onClick:()=>{navigator.clipboard?.writeText(a.userCode),f(!0),p(()=>f(!1),1500)},children:l?`Copied`:`Copy code`})]})]}):null,(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Q.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,Q.jsxs)(Y,{gap:`8px`,children:[(0,Q.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:Tn(a.verificationUri)}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,icon:(0,Q.jsx)(ye,{size:12}),onClick:()=>window.open(a.verificationUri,`_blank`,`noopener`),className:`shrink-0`,children:`Open`}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:s?(0,Q.jsx)(_,{size:12}):(0,Q.jsx)(d,{size:12}),onClick:()=>{navigator.clipboard?.writeText(a.verificationUri),c(!0),p(()=>c(!1),1500)},className:`shrink-0`,children:s?`Copied`:`Copy`})]}),(0,Q.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:h?`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,Q.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,Q.jsx)(u,{size:16,className:`animate-spin text-accent shrink-0`}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,children:`Starting device authorization…`})]})})})}function Dn(e){let t={};for(let n of e)t[n.key]=n.defaultValue??``;return t}function On(e,t){return e.filter(e=>e.required===!0&&(t[e.key]??``).trim().length===0).map(e=>e.key)}function kn({fields:e,values:t,onChange:n,idPrefix:r}){return e.length===0?null:(0,Q.jsx)(J,{gap:`10px`,children:e.map(e=>{let i=`${r}-${e.key}`,a=t[e.key]??``;return e.options&&e.options.length>0?(0,Q.jsx)(q,{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,Q.jsx)(K,{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 An({providerId:e,providerName:t,fields:n,onClose:r}){let i=Ne(),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,d]=(0,Z.useState)(()=>Dn(n)),f=(0,Z.useMemo)(()=>On(n,l),[n,l]);return(0,Q.jsx)(P,{open:!0,onClose:r,title:`Import a ${t} credential`,size:`sm`,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:r,disabled:i.isPending,children:`Cancel`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,onClick:()=>{if(a.trim().length===0){b.error(`Credential required`,`Paste the token, key or exported JSON to import.`);return}if(f.length>0){b.error(`Missing required fields`,`Fill in: ${f.join(`, `)}`);return}i.mutate({providerId:e,credential:a.trim(),...Object.keys(l).length>0?{fields:l}:{},...s.trim().length>0?{accountLabel:s.trim()}:{}},{onSuccess:()=>{b.success(`Account imported`,`The credential was validated and saved`),r()},onError:e=>b.error(`Import failed`,e.message??`The provider rejected this credential`)})},disabled:i.isPending,icon:i.isPending?(0,Q.jsx)(u,{size:13,className:`animate-spin`}):void 0,children:i.isPending?`Validating…`:`Import`})]}),children:(0,Q.jsxs)(J,{gap:`12px`,children:[(0,Q.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,Q.jsx)(kn,{fields:n,values:l,idPrefix:`import`,onChange:(e,t)=>d(n=>({...n,[e]:t}))}),(0,Q.jsx)(K,{id:`import-account-label`,label:`Account label`,hint:`optional`,value:s,placeholder:e,onChange:e=>c(e.target.value)}),(0,Q.jsx)(K,{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)})]})})}function jn(e,t,n){let r=n?.trim()??``,i=r.indexOf(` — `),a=i>0?r.slice(0,i):``,o=i>0?r.slice(i+3):r;return{title:`${e}/${t} probe failed${a.length>0?` via ${a}`:``}`,detail:o.length>0?o:`Unknown error`}}function Mn(e,t,n){let{title:r,detail:i}=jn(e,t,n);return[r,i]}function Nn(e){return e===`builtin`?`Built-in model`:e===`auto_free`?`Free tier, discovered from the provider`:e===`discovered`?`Fetched from provider`:`Added manually`}function Pn(e){return e===`auto_free`?`Free tier`:e===`discovered`?`Fetched`:`Manual`}var Fn=[{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`}],In={key:`disabled`,label:`Disabled models`,hint:`Turned off — not routable until re-enabled`};function Ln(){return ft.map(e=>({value:e,label:e===`auto`?`Thinking: auto`:e.charAt(0).toUpperCase()+e.slice(1)}))}function Rn({value:e,onChange:t,disabled:n,id:r=`probe-thinking-effort`}){return(0,Q.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`,children:(0,Q.jsx)(q,{id:r,"aria-label":`Thinking effort`,value:e,disabled:n,onValueChange:e=>t(e),options:Ln()})})}function zn({providerId:e,provider:t,onClose:n}){let r=Ae(),i=L(),[a,o]=(0,Z.useState)(``),s=t?.supportedWireFamilies,c=t?.wireFamilyDefault!==void 0&&(s===void 0||s.includes(t.wireFamilyDefault))?t.wireFamilyDefault:s?.[0],l=(0,Z.useMemo)(()=>{let e=[`chat`,`responses`,`messages`],t=(s??[]).filter(t=>e.includes(t));return[...t,...e.filter(e=>!t.includes(e))]},[s]),[d,p]=(0,Z.useState)(c??`chat`),[m,h]=(0,Z.useState)(`auto`),[_,v]=(0,Z.useState)(`idle`),[y,x]=(0,Z.useState)(``),[S,C]=(0,Z.useState)(Un),w=a.trim(),T=w.toLowerCase().startsWith(`${e.toLowerCase()}/`)&&w.length>e.length+1?w.slice(e.length+1):w,E=T!==w,D=()=>{T&&(v(`testing`),x(``),r.mutate({providerId:e,request:{modelId:T,wireFamily:d,reasoningEffort:m,serviceKind:`llm`}},{onSuccess:e=>{e.ok?v(`passed`):(v(`failed`),x(e.error??`Model probe failed`))},onError:e=>{v(`failed`),x(e.message??`Model probe failed`)}}))};return(0,Q.jsx)(P,{open:!0,onClose:n,title:`Add Custom Model`,size:`sm`,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:n,disabled:i.isPending,children:`Cancel`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,disabled:i.isPending||T.length===0,onClick:()=>{if(!T)return;let t=Be(S.contextLimit),r=Be(S.outputLimit);if(t===null||r===null){b.error(`Invalid limits`,`Use a token count such as 512k, 200000, or 1.5m.`);return}i.mutate({providerId:e,modelIds:[T],wireFamily:d,metadata:{contextLimit:t??null,outputLimit:r??null,passthrough:S.passthrough,image:S.passthrough?!0:S.image,reasoning:S.passthrough?!0:S.reasoning,toolCall:S.passthrough?!0:S.toolCall}},{onSuccess:()=>{b.success(`Custom model added`,`Sent to ${e}/${T}`),n()},onError:e=>b.error(`Failed to add model`,e.message??`Unable to register model`)})},children:i.isPending?`Adding...`:`Add Model`})]}),children:(0,Q.jsxs)(J,{gap:`10px`,children:[(0,Q.jsxs)(Y,{gap:`8px`,align:`flex-end`,children:[(0,Q.jsx)(K,{label:`Model ID`,autoFocus:!0,placeholder:`e.g. gpt-4o, free-model-id`,value:a,onChange:e=>{o(e.target.value),v(`idle`),x(``)},onKeyDown:e=>{e.key===`Enter`&&T.length>0&&D()},className:`flex-1`}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:_===`testing`?(0,Q.jsx)(u,{size:13,className:`animate-spin`}):(0,Q.jsx)(f,{size:13}),disabled:r.isPending||T.length===0,onClick:D,className:`shrink-0`,children:_===`testing`?`Testing...`:`Test`})]}),E&&(0,Q.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Using `,(0,Q.jsx)(`span`,{className:`font-mono tabular-nums`,children:T}),` (provider prefix removed).`]}),(0,Q.jsx)(q,{label:`Wire family`,id:`add-model-wire-family`,value:d,onValueChange:e=>{p(e),v(`idle`),x(``)},options:l.map(e=>({value:e,label:Yn(e)}))}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Thinking`}),(0,Q.jsx)(Rn,{id:`add-model-thinking-effort`,value:m,onChange:e=>{h(e),v(`idle`),x(``)},disabled:r.isPending}),(0,Q.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,Q.jsx)(Wn,{draft:S,onChange:C,idPrefix:`add-model`,disabled:i.isPending}),s!==void 0&&!s.includes(d)&&(0,Q.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`This provider does not declare the`,` `,(0,Q.jsx)(`span`,{className:`font-mono tabular-nums`,children:Yn(d)}),` wire. The request is sent as chosen; the upstream decides whether it answers.`]}),_===`passed`&&(0,Q.jsx)(rt,{tone:`success`,live:`status`,children:`Model test passed — ready to add.`}),_===`failed`&&(0,Q.jsx)(rt,{tone:`danger`,live:`alert`,children:y||`Model test failed.`})]})})}function Bn(){return{contextLimit:``,outputLimit:``,passthrough:!1,image:!0,reasoning:!0,toolCall:!0}}var Vn=String(U),Hn=String(H);function Un(){return{...Bn(),contextLimit:Vn,outputLimit:Hn}}function Wn({draft:e,onChange:t,idPrefix:n,disabled:r=!1}){let i=e.passthrough;return(0,Q.jsxs)(J,{gap:`10px`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Limits`}),(0,Q.jsxs)(Y,{gap:`8px`,children:[(0,Q.jsx)(K,{label:`Context`,id:`${n}-context`,placeholder:Vn,value:e.contextLimit,disabled:r,onChange:n=>t({...e,contextLimit:n.target.value}),className:`flex-1`}),(0,Q.jsx)(K,{label:`Output`,id:`${n}-output`,placeholder:Hn,value:e.outputLimit,disabled:r,onChange:n=>t({...e,outputLimit:n.target.value}),className:`flex-1`})]}),(0,Q.jsxs)(`label`,{className:`inline-flex items-center gap-2 mt-2 text-badge text-text-secondary cursor-pointer`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,id:`${n}-fallback-limits`,checked:e.contextLimit===Vn&&e.outputLimit===Hn,disabled:r,onChange:n=>t(n.target.checked?{...e,contextLimit:Vn,outputLimit:Hn}:{...e,contextLimit:``,outputLimit:``})}),`Use fallback — `,Ve(U),` ctx ·`,` `,Ve(H),` out`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Capabilities`}),(0,Q.jsx)(J,{gap:`6px`,children:[[`image`,`Can image`,e.image],[`reasoning`,`Reasoning`,e.reasoning],[`toolCall`,`Tools`,e.toolCall]].map(([a,o,s])=>(0,Q.jsxs)(`label`,{className:`inline-flex items-center gap-2 text-badge text-text-secondary`,style:i?{opacity:.5}:void 0,children:[(0,Q.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,Q.jsxs)(`label`,{className:`inline-flex items-center gap-2 mt-2 text-badge text-text-secondary cursor-pointer`,children:[(0,Q.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,Q.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 Gn({providerId:e,model:t,onClose:n}){let r=pe(),[i,a]=(0,Z.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}));return(0,Q.jsx)(P,{open:!0,onClose:n,title:`Edit Model`,size:`sm`,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:n,disabled:r.isPending,children:`Cancel`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,disabled:r.isPending,onClick:()=>{let a=Be(i.contextLimit),o=Be(i.outputLimit);if(a===null||o===null){b.error(`Invalid limits`,`Use a token count such as 512k, 200000, or 1.5m.`);return}r.mutate({providerId:e,modelId:t.modelId,route:t.route??``,metadata:{contextLimit:a??null,outputLimit:o??null,passthrough:i.passthrough,image:i.passthrough?!0:i.image,reasoning:i.passthrough?!0:i.reasoning,toolCall:i.passthrough?!0:i.toolCall}},{onSuccess:()=>n(),onError:e=>b.error(`Failed to update model`,e.message??`Unable to update model`)})},children:r.isPending?`Saving...`:`Save`})]}),children:(0,Q.jsxs)(J,{gap:`10px`,children:[(0,Q.jsxs)(`div`,{className:`text-badge text-text-tertiary`,children:[`Editing `,(0,Q.jsx)(`span`,{className:`font-mono tabular-nums`,children:t.modelId})]}),(0,Q.jsx)(Wn,{draft:i,onChange:a,idPrefix:`edit-model`,disabled:r.isPending})]})})}function Kn({providerId:e,model:t,serviceKind:n,searchCapable:r,thinkingEffort:i,onDeleteRequest:a,onEditRequest:c,deletePending:l}){let v=Ae(),y=Ie(),[x,T]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),k=nt(),A=n===`llm`?pt(t.modelId,i===`auto`?null:i):t.modelId,j=`${e}/${A}`,M=n===`websearch`?`Searching…`:`Thinking…`,N=()=>{v.mutate({providerId:e,request:{modelId:t.modelId,route:t.route,...n===`llm`?{reasoningEffort:i}:{},serviceKind:n}},{onSuccess:t=>{if(O({ok:t.ok,latencyMs:t.latencyMs}),!t.ok){let{title:n,detail:r}=jn(e,A,t.error);b.error(n,r);return}let n=t.sample?.trim()??``,r=t.reportedModel?.trim()??``;b.successRich(`${A} · END ${m(t.latencyMs)}`,(0,Q.jsxs)(`span`,{className:`grid gap-2 min-w-0`,children:[r?(0,Q.jsxs)(Y,{gap:`6px`,align:`center`,className:`min-w-0`,children:[(0,Q.jsx)(w,{size:12,"aria-hidden":`true`,className:`shrink-0 text-text-tertiary`}),(0,Q.jsx)(`span`,{className:`truncate font-mono text-badge text-text-secondary`,title:r,children:r})]}):null,(0,Q.jsx)(`span`,{children:n||`No sample text in the response.`})]}),[r,n].filter(Boolean).join(`
3
- `)||`No sample text in the response.`)},onError:t=>{O({ok:!1,latencyMs:0}),b.error(...Mn(e,A,t.message))}})},ee=()=>{let n=!t.enabled;y.mutate({providerId:e,request:{modelId:t.modelId,route:t.route,enabled:n}},{onSuccess:()=>b.success(n?`Model enabled`:`Model disabled`,t.modelId),onError:e=>b.error(`Failed to update model`,e.message??`Unable to update model`)})};return(0,Q.jsx)(Q.Fragment,{children:(0,Q.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`}`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start gap-4 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`inline-flex items-center justify-center w-13 h-13 rounded-inset bg-teal-soft text-teal shrink-0`,children:(0,Q.jsx)(o,{size:14})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0 flex flex-col gap-1`,children:[(0,Q.jsx)(`div`,{title:j,className:`font-mono tabular-nums min-w-0 truncate text-caption font-semibold leading-[1.35]`,children:A}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-micro text-text-tertiary`,children:[(0,Q.jsx)(`span`,{title:`${t.wireFamily} · ${t.route??e}`,className:`shrink-0 rounded-tiny px-3.5 py-0.5 text-micro font-bold`,style:{...Jn(t.wireFamily)},children:Yn(t.wireFamily)}),t.source!==null&&t.source!==`builtin`?(0,Q.jsx)(`span`,{title:Nn(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:Pn(t.source)}):null,t.proOnly===!0?(0,Q.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,Q.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,t.enabled?null:(0,Q.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,Q.jsx)(g,{variant:`ghost`,size:`sm`,icon:x?(0,Q.jsx)(_,{size:12}):(0,Q.jsx)(d,{size:12}),"aria-label":`Copy ${j}`,title:`Copy ${j}`,onClick:()=>{navigator.clipboard?.writeText(j),T(!0),k(()=>T(!1),1500)},className:`shrink-0 p-2 opacity-70`})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-badge text-text-secondary`,children:[(0,Q.jsxs)(`span`,{className:`inline-flex gap-2.5`,children:[t.reasoning?(0,Q.jsx)(`span`,{title:`Reasoning`,"aria-label":`Reasoning`,className:`inline-flex text-purple`,children:(0,Q.jsx)(s,{size:12})}):null,t.vision?(0,Q.jsx)(`span`,{title:`Vision`,"aria-label":`Vision`,className:`inline-flex text-status-info`,children:(0,Q.jsx)(E,{size:12})}):null,t.toolCall?(0,Q.jsx)(`span`,{title:`Tool calling`,"aria-label":`Tool calling`,className:`inline-flex text-orange`,children:(0,Q.jsx)(se,{size:12})}):null,r?(0,Q.jsx)(`span`,{title:`Web search`,"aria-label":`Web search`,className:`inline-flex text-teal`,children:(0,Q.jsx)(p,{size:12})}):null]}),(0,Q.jsxs)(`span`,{className:`whitespace-nowrap`,children:[t.limitsEstimated?(0,Q.jsx)(`span`,{title:He,"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,Q.jsx)(S,{size:9,"aria-hidden":`true`})}):null,t.contextLimit?`${Ve(t.contextLimit)} ctx`:(0,Q.jsx)(`span`,{title:W,className:`cursor-help`,children:`n/a ctx`}),t.outputLimit?` · ${Ve(t.outputLimit)} out`:(0,Q.jsx)(`span`,{title:W,className:`cursor-help`,children:` · n/a out`})]}),c?(0,Q.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:()=>c(t),children:(0,Q.jsx)(F,{size:11})}):null]}),(0,Q.jsxs)(`div`,{className:`flex gap-3 items-center flex-wrap`,children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,disabled:v.isPending,onClick:N,"aria-label":`Test ${A}`,title:v.isPending?`Probing ${A}…`:D?.ok?`Last probe OK in ${m(D.latencyMs)} — click to re-test`:D?`Last probe failed — click to retry`:`Test ${A}`,className:`flex-1 justify-center`,icon:v.isPending?(0,Q.jsx)(u,{size:12,className:`animate-spin`}):D?D.ok?(0,Q.jsx)(`span`,{className:`inline-flex text-green`,children:(0,Q.jsx)(C,{size:12})}):(0,Q.jsx)(`span`,{className:`inline-flex text-red`,children:(0,Q.jsx)(h,{size:12})}):(0,Q.jsx)(f,{size:12}),children:v.isPending?M:D?.ok?m(D.latencyMs):D?`Fail`:`Test`}),(0,Q.jsx)(g,{variant:`ghost`,size:`sm`,disabled:y.isPending,onClick:ee,icon:t.enabled?(0,Q.jsx)(ne,{size:12}):(0,Q.jsx)(ot,{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,Q.jsx)(g,{variant:`ghost`,size:`sm`,disabled:l,onClick:()=>a(t),icon:(0,Q.jsx)(oe,{size:12}),"aria-label":`Delete ${t.modelId}`,title:`Delete model`,className:`model-card-delete shrink-0 px-4 py-3 text-text-tertiary`})]})]})})}var qn=(0,Z.memo)(Kn);function Jn(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 Yn(e){let t=e.toLowerCase();return t===`responses`?`Responses`:t===`messages`?`Messages`:`Chat`}function Xn({providerId:e,models:t,thinkingEffort:n,serviceKind:r=`llm`,searchCapable:i=!1}){let a=ve(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),u=e=>e.enabled!==!1,d=Fn.map(e=>({...e,rows:t.filter(t=>u(t)&&e.matches(t.source))})).filter(e=>e.rows.length>0),f=t.filter(e=>!u(e)),p=t=>(0,Q.jsx)(qn,{providerId:e,model:t,serviceKind:r,searchCapable:i,thinkingEffort:n,deletePending:a.isPending,onDeleteRequest:s,onEditRequest:t.source===`builtin`?void 0:l},`${t.modelId}::${t.route}`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(J,{gap:`16px`,children:[d.map(e=>(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-baseline gap-4 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`text-caption font-bold text-text-secondary`,children:e.label}),(0,Q.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:e.rows.length}),(0,Q.jsxs)(`span`,{title:e.hint,className:`text-micro text-text-tertiary overflow-hidden truncate`,children:[`· `,e.hint]})]}),(0,Q.jsx)(`div`,{className:`provider-grid grid gap-4 items-stretch`,children:e.rows.map(p)})]},e.key)),f.length===0?null:(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-baseline gap-4 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`text-caption font-bold text-text-secondary`,children:In.label}),(0,Q.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:f.length}),(0,Q.jsxs)(`span`,{title:In.hint,className:`text-micro text-text-tertiary overflow-hidden truncate`,children:[`· `,In.hint]})]}),(0,Q.jsx)(`div`,{className:`provider-grid grid gap-4 items-stretch`,children:f.map(p)})]})]}),(0,Q.jsx)(Re,{open:o!==null,onClose:()=>{a.isPending||s(null)},onConfirm:async()=>{o!==null&&(await a.mutateAsync({providerId:e,request:{modelId:o.modelId,route:o.route}}),b.success(`Model deleted`,`${e}/${o.modelId}`),s(null))},title:`Delete model?`,message:`Delete ${e}/${o?.modelId??``} from the provider catalog?`,confirmLabel:`Delete`,danger:!0}),c===null?null:(0,Q.jsx)(Gn,{providerId:e,model:c,onClose:()=>l(null)})]})}function Zn(e){return e===`llm`?`LLM`:e===`websearch`?`Search`:e===`imageGeneration`?`Image`:e===`videoGeneration`?`Video`:e}function Qn(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}function $n(){let{providerId:e}=xe(),[t]=Me(),n=e??``,r=t.get(`service`),[i,a]=(0,Z.useState)(r===`websearch`||r===`imageGeneration`||r===`videoGeneration`?r:`llm`),o=we(n),s=Ce(n),l=Oe(n),u=Fe(),d=Fe({silent:!0}),[f,m]=(0,Z.useState)(!1),h=Se(),_=me(),v=ge(),y=ce(),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(!1),T=Ae(),[E,D]=(0,Z.useState)(``),[N,ee]=(0,Z.useState)(``),[F,ie]=(0,Z.useState)(null),ae=e=>`cartethyia:provider:${e}:thinking-effort`,se=e=>{if(typeof window>`u`||!window.localStorage)return`auto`;let t=window.localStorage.getItem(ae(e));if(t===null)return`auto`;let n=t.trim().toLowerCase();return ft.includes(n)?n:`auto`},[le,de]=(0,Z.useState)(()=>se(n));(0,Z.useEffect)(()=>{if(!n)return;let e=se(n);e!==le&&de(e)},[n]),(0,Z.useEffect)(()=>{typeof window>`u`||!window.localStorage||!n||window.localStorage.setItem(ae(n),le)},[n,le]);let[fe,pe]=(0,Z.useState)(!1),[he,_e]=(0,Z.useState)(!1),[L,ve]=(0,Z.useState)(null),[be,Te]=(0,Z.useState)({}),[Ee,ke]=(0,Z.useState)({}),[R,je]=(0,Z.useState)(null),[Ne,Pe]=(0,Z.useState)(!1),[Ie,Le]=(0,Z.useState)(null),V=(0,Z.useRef)(null),Be=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{let e=V.current;V.current=null,e&&!e.closed&&e.close()},[]);let H=o.data,Ve=n===`opencode`||n===`cline`,He=H===void 0?[`llm`]:Qn(H),U=[];for(let e of He)(e===`llm`||e===`websearch`||e===`imageGeneration`||e===`videoGeneration`)&&U.push(e);(0,Z.useEffect)(()=>{if(H===void 0)return;let e=r===`websearch`||r===`imageGeneration`||r===`videoGeneration`||r===`llm`?r:void 0,t=U[0];if(e!==void 0&&U.includes(e)){i!==e&&a(e);return}!U.includes(i)&&t!==void 0&&a(t)},[H,r,i,U.join(`|`)]),(0,Z.useEffect)(()=>{Ve&&H!==void 0&&H.supportsModelDiscovery!==!1&&Be.current!==n&&(Be.current=n,d.mutate(n))},[Ve,d,n,H?.supportsModelDiscovery]);let W=l.data??[],G=s.data??[],K=(()=>{let e=new Map;for(let t of G){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))})(),q=K.filter(e=>e.serviceKind===`llm`||e.serviceKind===void 0),We=K.filter(e=>e.serviceKind===`websearch`),Ke=K.filter(e=>e.serviceKind===`imageGeneration`),qe=K.filter(e=>e.serviceKind===`videoGeneration`),X=U.includes(i)?i:U[0],Je=N||We[0]?.modelId||``,Ye=()=>{let e=E.trim();Je&&e&&(ie(null),T.mutate({providerId:n,request:{modelId:Je,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,Q.jsx)(A,{label:`Loading provider...`});if(o.isError)return(0,Q.jsx)(k,{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,Q.jsx)(mt,{to:`/providers`,label:`Back to providers`})});if(!H)return(0,Q.jsx)(j,{icon:(0,Q.jsx)(st,{size:20}),title:`Provider not found`,message:`No provider named “${n}”. It may have been removed, or the link is stale.`,action:(0,Q.jsx)(mt,{to:`/providers`,label:`Back to providers`})});let Xe=W.filter(e=>e.status===`active`).length,Ze=e=>{let t=e===`browser`?H?.oauthFlows?.browserLoginFields??[]:H?.oauthFlows?.deviceLoginFields??[];if(t.length===0){e===`browser`?$e():pe(!0);return}Te(Dn(t)),ve(e)},Qe=()=>{if(L===null)return;let e=On(L===`browser`?H?.oauthFlows?.browserLoginFields??[]:H?.oauthFlows?.deviceLoginFields??[],be);if(e.length>0){b.error(`Missing required fields`,`Fill in: ${e.join(`, `)}`);return}let t=L;ve(null),t===`browser`?$e(be):(ke(be),pe(!0))},$e=e=>{let t=window.open(`about:blank`,`cartethyia-oauth`,`popup,width=720,height=820`);t&&(t.opener=null,V.current=t),v.mutate({providerId:n,...e===void 0?{}:{parameters:e}},{onSuccess:({authorizeUrl:e,state:n})=>{let r=null;if(t&&!t.closed?(t.location.href=e,r=t):(r=window.open(e,`cartethyia-oauth`,`popup,width=720,height=820`),r&&(r.opener=null,V.current=r)),!r){b.error(`Popup blocked`,`Allow popups to complete OAuth login.`);return}Le({authorizeUrl:e,state:n,popup:r})},onError:e=>{t&&!t.closed&&t.close(),V.current===t&&(V.current=null),b.error(`Failed to start OAuth`,e.message??`Unable to start authorization`)}})};return(0,Q.jsxs)(J,{gap:`16px`,children:[(0,Q.jsx)(ht,{title:`${H.label||H.displayName}${X?` (${Zn(X)})`:``}`,description:`${H.providerId}/${H.baseUrl?` · ${H.baseUrl}`:``}`,icon:(0,Q.jsx)(Ue,{icon:H.providerId,name:H.label||H.displayName,size:28}),back:{to:`/providers`,label:`Back to Providers`},actions:(0,Q.jsx)(Y,{gap:`8px`,className:`flex-wrap w-full max-w-full min-w-0`,children:H.isBuiltIn?(0,Q.jsx)(g,{variant:H.enabled?`danger`:`secondary`,icon:H.enabled?(0,Q.jsx)(ne,{size:13}):(0,Q.jsx)(ot,{size:13}),loading:_.isPending,onClick:()=>_.mutate({providerId:n,enabled:!H.enabled},{onSuccess:e=>b.success(e.enabled?`Provider enabled`:`Provider disabled`,H.label||H.displayName),onError:e=>b.error(`Provider update failed`,e.message??`Unable to change provider availability`)}),title:H.enabled?`Disable provider globally`:`Enable provider globally`,children:H.enabled?`Disable`:`Enable`}):null})}),(0,Q.jsx)(At,{provider:H}),H.isBuiltIn?null:(0,Q.jsx)(jt,{provider:H}),X===`llm`?(0,Q.jsx)(Tt,{providerId:n,clientVersion:H.clientVersion,routeIdentityVersions:H.routeIdentityVersions,userAgentEditable:gt(H)}):null,(0,Q.jsx)(`div`,{id:`provider-accounts`,tabIndex:-1,children:H.requiresAccount===!1?(0,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:`Accounts`,icon:(0,Q.jsx)(it,{size:16})}),(0,Q.jsx)(z,{children:(0,Q.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,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:`Accounts`,subtitle:`${W.length} total · ${Xe} active · ${W.length-Xe} disabled`,icon:(0,Q.jsx)(it,{size:16}),action:(0,Q.jsxs)(Ge,{children:[H.oauthFlows?.browser&&(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:(0,Q.jsx)(ye,{size:13}),disabled:v.isPending,onClick:()=>Ze(`browser`),title:`Browser OAuth login — opens the provider authorize page in a popup`,children:v.isPending?`Starting...`:`Login with browser`}),H.oauthFlows?.device&&(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:(0,Q.jsx)(M,{size:13}),onClick:()=>Ze(`device`),title:`Device-code login — enter the shown code on the provider site`,children:`Login with device code`}),H.oauthFlows?.import&&(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:(0,Q.jsx)(De,{size:13}),onClick:()=>_e(!0),title:H.oauthFlows.browser||H.oauthFlows.device||H.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:H.oauthFlows.browser||H.oauthFlows.device||H.oauthFlows.refreshable?`Import credential`:`Add API key`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,icon:(0,Q.jsx)(te,{size:13}),onClick:()=>S(!0),children:`Add Account`})]})}),(0,Q.jsxs)(z,{className:`flex flex-col gap-5`,children:[(0,Q.jsx)(Et,{providerId:n}),l.isPending?(0,Q.jsx)(A,{label:`Loading accounts...`}):l.isError?(0,Q.jsx)(k,{message:`Failed to load accounts`,onRetry:()=>l.refetch()}):W.length===0?(0,Q.jsx)(j,{title:`No accounts connected`,message:`Add an API key or OAuth credential to route requests to this provider.`}):(0,Q.jsx)(yn,{providerId:n,accounts:W,onDelete:e=>je(e),showGrokProbe:X===`llm`&&n===`grok`,grokProbePending:h.isPending,onGrokProbe:()=>{h.mutate({providerId:n,request:{modelId:`grok-4.6`,prompt:`reply my message with exact number 407`,stream:!0,serviceKind:`llm`}},{onSuccess:e=>{let t=e.results.filter(e=>e.ok).length,n=e.results.filter(e=>e.statusCode===202).length,r=e.results.length-t-n;b.success(`Grok account probe complete`,`${t} passed · ${n} returned 202 and were parked in cooldown · ${r} other failures`)},onError:e=>b.error(`Grok account probe failed`,e.message??`Unable to probe Grok accounts`)})}})]})]})}),X===`llm`?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:`Models`,subtitle:`${q.length} model${q.length===1?``:`s`} registered`,icon:(0,Q.jsx)(c,{size:16}),action:(0,Q.jsxs)(Y,{gap:`6px`,className:`flex-wrap items-center`,children:[(0,Q.jsx)(Rn,{id:`models-section-thinking-effort`,value:le,onChange:de}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:(0,Q.jsx)(re,{size:13,className:u.isPending||d.isPending?`animate-spin`:``}),disabled:u.isPending||d.isPending,onClick:()=>u.mutate(n),children:u.isPending||d.isPending?`Fetching...`:`Fetch models`}),(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,icon:(0,Q.jsx)(oe,{size:13,className:f?`animate-spin`:``}),disabled:u.isPending||d.isPending||f||q.filter(e=>e.source!==`builtin`&&e.source!==null).length===0,onClick:async()=>{let e=q.filter(e=>e.source!==`builtin`&&e.source!==null);if(e.length!==0&&confirm(`Delete ${e.length} fetched/manual model(s) for ${n}?`)){m(!0);try{let t=await ue(`/providers/${encodeURIComponent(n)}/models/bulk`,{method:`DELETE`,body:JSON.stringify({items:e.map(e=>({modelId:e.modelId,route:e.route}))})});await Promise.all([y.invalidateQueries({queryKey:I.providers.models(n)}),y.invalidateQueries({queryKey:I.providers.all})]);let r=t.failures.length;b.success(`Fetched models deleted`,r>0?`${t.deleted}/${t.total} removed, ${r} failed`:`${t.deleted}/${t.total} removed`)}catch(e){b.error(`Failed to delete fetched models`,e.message??`Unable to delete models`)}finally{m(!1)}}},children:f?`Deleting…`:`Delete fetched`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,icon:(0,Q.jsx)(te,{size:13}),onClick:()=>w(!0),children:`Add Model`})]})}),(0,Q.jsx)(z,{className:`flex flex-col gap-8`,children:s.isPending?(0,Q.jsx)(A,{label:`Loading models...`}):s.isError?(0,Q.jsx)(k,{message:`Failed to load models`,onRetry:()=>s.refetch()}):q.length===0?(0,Q.jsx)(j,{title:`No LLM models found`,message:`No LLM models published by this provider yet. Sync or add a custom model above.`}):(0,Q.jsx)(Xn,{providerId:n,models:q,serviceKind:`llm`,thinkingEffort:le,searchCapable:H?.supportsWebSearch===!0})})]})}):X===`websearch`?(0,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:`Web Search`,subtitle:`Run a real search request through the selected provider.`,icon:(0,Q.jsx)(p,{size:16})}),(0,Q.jsx)(z,{className:`flex flex-col gap-6`,children:s.isPending?(0,Q.jsx)(A,{label:`Loading search models...`}):s.isError?(0,Q.jsx)(k,{message:`Failed to load search models`,onRetry:()=>s.refetch()}):We.length===0?(0,Q.jsx)(j,{title:`No Search models found`,message:`This provider advertises Search, but no websearch model is registered yet.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`flex flex-col gap-2.5 text-badge text-text-secondary`,children:[`Search model`,(0,Q.jsx)(`select`,{value:Je,onChange:e=>{ee(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:We.map(e=>(0,Q.jsx)(`option`,{value:e.modelId,children:e.modelId},`${e.modelId}:${e.route}`))})]}),(0,Q.jsxs)(`label`,{className:`flex flex-col gap-2.5 text-badge text-text-secondary`,children:[`Query`,(0,Q.jsx)(`input`,{value:E,onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Ye())},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,Q.jsxs)(Y,{gap:`8px`,className:`items-center flex-wrap`,children:[(0,Q.jsx)(g,{variant:`primary`,size:`sm`,disabled:T.isPending||E.trim().length===0,loading:T.isPending,onClick:Ye,children:`Test search`}),F?(0,Q.jsx)(`span`,{className:`text-badge`,style:{color:F.ok?`var(--green)`:`var(--red)`},children:F.ok?`Search ok · ${F.latencyMs}ms · ${F.count??0} result(s)`:F.error??`Search failed.`}):null]}),F&&F.results&&F.results.length>0?(0,Q.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:F.results.map((e,t)=>(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Q.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-caption text-text-primary font-semibold`,children:e.title||e.url}),(0,Q.jsx)(`span`,{className:`text-badge text-text-tertiary break-all`,children:e.url}),e.snippet?(0,Q.jsx)(`span`,{className:`text-badge text-text-secondary`,children:e.snippet}):null]},`${e.url}:${t}`))}):null]})})]}):X===`imageGeneration`||X===`videoGeneration`?(0,Q.jsxs)(B,{children:[(0,Q.jsx)(ze,{title:Zn(X),subtitle:X===`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:X===`imageGeneration`?(0,Q.jsx)(O,{size:16}):(0,Q.jsx)(ut,{size:16})}),(0,Q.jsx)(z,{className:`flex flex-col gap-6`,children:s.isPending?(0,Q.jsx)(A,{label:`Loading ${Zn(X).toLowerCase()} models...`}):s.isError?(0,Q.jsx)(k,{message:`Failed to load ${Zn(X).toLowerCase()} models`,onRetry:()=>s.refetch()}):(X===`imageGeneration`?Ke:qe).length===0?(0,Q.jsx)(j,{title:`No ${Zn(X)} models found`,message:`This provider advertises ${Zn(X)}, but no ${X} model is registered yet.`}):(0,Q.jsx)(Xn,{providerId:n,models:X===`imageGeneration`?Ke:qe,serviceKind:`llm`,searchCapable:!1,thinkingEffort:`auto`})})]}):(0,Q.jsx)(B,{children:(0,Q.jsx)(z,{children:(0,Q.jsx)(j,{title:`Service not available`,message:`This provider advertises ${He.map(Zn).join(`, `)}, but the dashboard has no controls for the selected service yet.`})})}),x&&(0,Q.jsx)(Sn,{providerId:n,accounts:W,onClose:()=>S(!1)}),X===`llm`&&C?(0,Q.jsx)(zn,{providerId:n,provider:H,onClose:()=>w(!1)}):null,(0,Q.jsx)(Re,{open:R!==null,onClose:()=>{Ne||je(null)},onConfirm:async()=>{if(R){Pe(!0);try{let e=R.tenantId===null?`/global/accounts/${encodeURIComponent(R.id)}`:`/accounts/${encodeURIComponent(R.id)}`;await ue(e,{method:`DELETE`}),y.removeQueries({queryKey:I.quota.account(R.id),exact:!0}),await Promise.all([y.invalidateQueries({queryKey:I.providers.accounts(n)}),y.invalidateQueries({queryKey:I.providers.healthEvents(n,R.id)}),y.invalidateQueries({queryKey:I.providers.all}),y.invalidateQueries({queryKey:I.quota.all})]),b.success(`Account deleted`,R.label||R.id.slice(0,8)),je(null)}catch(e){throw b.error(`Failed to delete account`,e.message??`Unable to delete account`),e}finally{Pe(!1)}}},title:`Delete account?`,message:`Delete "${R?.label||R?.id.slice(0,8)}"? This cannot be undone.`,confirmLabel:`Delete`,danger:!0}),fe&&(0,Q.jsx)(En,{providerId:n,parameters:Ee,onClose:()=>{pe(!1),ke({})}}),L!==null&&(0,Q.jsx)(P,{open:!0,onClose:()=>ve(null),title:L===`browser`?`Sign in with`:`Device sign-in details`,size:`sm`,footer:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(g,{variant:`secondary`,size:`sm`,onClick:()=>ve(null),children:`Cancel`}),(0,Q.jsx)(g,{variant:`primary`,size:`sm`,onClick:Qe,children:`Continue`})]}),children:(0,Q.jsxs)(J,{gap:`12px`,children:[(0,Q.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:L===`browser`?`Choose how ${H.label||H.displayName} should identify you, then continue to its sign-in page.`:`These decide which organization the device code is issued for.`}),(0,Q.jsx)(kn,{fields:L===`browser`?H?.oauthFlows?.browserLoginFields??[]:H?.oauthFlows?.deviceLoginFields??[],values:be,idPrefix:`flow-${L}`,onChange:(e,t)=>Te(n=>({...n,[e]:t}))})]})}),he&&H?.oauthFlows?.import===!0&&(0,Q.jsx)(An,{providerId:n,providerName:H.label||H.displayName,fields:H.oauthFlows.importFields,onClose:()=>_e(!1)}),Ie&&(0,Q.jsx)(wn,{providerId:n,authorizeUrl:Ie.authorizeUrl,state:Ie.state,popup:Ie.popup,onClose:e=>{V.current=null,Le(null),e&&y.invalidateQueries({queryKey:I.providers.accounts(n)})}})]})}export{$n as default};
@@ -1,7 +0,0 @@
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{C as a,E as o,b as s,c,s as l,t as u}from"./numbers-YNcHvRY7.js";import{t as d}from"./eye-off-Bk5g2luF.js";import{t as f}from"./eye-C_hawfH4.js";import{t as p}from"./gauge-BbIMy7MB.js";import{n as m,r as h,t as g}from"./state-BgTxHcJS.js";import{t as _}from"./dialog-BYj-8WuK.js";import{t as v}from"./pencil-768ysRAr.js";import{t as y}from"./plus-DIdX_g-x.js";import{t as ee}from"./power-off-Yjw9GMJh.js";import{t as b}from"./rotate-ccw-CufcqITi.js";import{t as x}from"./shield-check-DVS0Foqh.js";import{t as S}from"./trash-Cppn5c3R.js";import{C,T as w,c as T,v as E,y as D}from"./assert-Chi7pCnt.js";import{a as O,i as k,l as A,o as j,t as M}from"./query-keys-gmjzC3RS.js";import{t as N}from"./useMutation-BWSC0UAS.js";import{it as te,lt as ne,z as re}from"./entry-CgdSAzEV.js";import{n as ie,r as ae,t as oe}from"./card-BKqlUOe4.js";import{n as se}from"./download-dRFo5_Wu.js";import{t as P}from"./badge-D4pQapKj.js";import{n as F}from"./input-LVjgZq4f.js";import{t as ce}from"./select-WUCXorXw.js";import{t as I}from"./switch-DEjTtOWf.js";import{t as le}from"./stack-_3O0F8Xn.js";import{n as ue}from"./inline-DUWDSmDV.js";import{r as L,t as de}from"./layout-CPfxpsfy.js";import{i as fe,n as pe}from"./privacy-mode-GM8bej85.js";import{n as R}from"./live-C4pEJUqI.js";var me=e(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),he=e(`power`,[[`path`,{d:`M12 2v10`,key:`mnfbl`}],[`path`,{d:`M18.4 6.6a9 9 0 1 1-12.77.04`,key:`obofu9`}]]),ge=1e6,z=1e8,_e=5e6,ve=`sin1`,ye=[{label:`Asia Pacific`,regions:[{id:`sin1`,label:`Singapore`},{id:`hkg1`,label:`Hong Kong`},{id:`icn1`,label:`Seoul`},{id:`hnd1`,label:`Tokyo`},{id:`kix1`,label:`Osaka`},{id:`bom1`,label:`Mumbai`},{id:`syd1`,label:`Sydney`}]},{label:`Europe`,regions:[{id:`fra1`,label:`Frankfurt`},{id:`cdg1`,label:`Paris`},{id:`lhr1`,label:`London`},{id:`arn1`,label:`Stockholm`},{id:`dub1`,label:`Dublin`}]},{label:`North America`,regions:[{id:`iad1`,label:`Washington, D.C.`},{id:`sfo1`,label:`San Francisco`},{id:`pdx1`,label:`Portland`},{id:`cle1`,label:`Cleveland`},{id:`yul1`,label:`Montréal`}]},{label:`Other`,regions:[{id:`gru1`,label:`São Paulo`},{id:`cpt1`,label:`Cape Town`},{id:`dxb1`,label:`Dubai`}]}];function be(){return C({queryKey:M.network.pools,queryFn:e=>j(`/network/pools`,{signal:E(e)}).then(T),staleTime:k.staleTime,gcTime:k.gcTime})}function B(){let e=w();return N({mutationFn:e=>j(`/network/pools`,{method:`POST`,body:JSON.stringify(e)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools}),l.success(`Proxy pool created`)},onError:e=>{l.error(`Could not create the proxy pool.`,A(e))}})}function xe(){let e=w();return N({mutationFn:e=>j(`/network/pools/relay/deploy`,{method:`POST`,body:JSON.stringify(e)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools})}})}function Se(){return N({mutationFn:e=>j(`/network/pools/test-batch`,{method:`POST`,body:JSON.stringify({targets:e})})})}function Ce(){let e=w();return N({mutationFn:({poolId:e,request:t})=>j(`/network/pools/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools}),l.success(`Proxy updated`)},onError:e=>{l.error(`Could not update the proxy pool.`,A(e))}})}function we(e){return C({queryKey:[...M.network.pools,e,`health-events`],queryFn:t=>j(`/network/pools/${encodeURIComponent(e??``)}/health-events`,{signal:E(t)}),enabled:!!e,...k,refetchInterval:O.status})}function Te(){let e=w();return N({mutationFn:e=>j(`/network/pools/${encodeURIComponent(e)}/recover`,{method:`POST`,body:`{}`}),onSuccess:async(t,n)=>{await Promise.all([e.invalidateQueries({queryKey:M.network.pools}),e.invalidateQueries({queryKey:[...M.network.pools,n,`health-events`]})]),l.success(`Proxy pool recovered`)},onError:e=>{l.error(`Could not recover the proxy pool.`,A(e))}})}function Ee(){let e=w();return N({mutationFn:e=>j(`/network/pools/${encodeURIComponent(e)}`,{method:`DELETE`}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools}),l.success(`Proxy pool deleted`)},onError:e=>{l.error(`Could not delete the proxy pool.`,A(e))}})}function De(){let e=w();return N({mutationFn:({poolId:e,providerId:t})=>j(`/network/pools/${encodeURIComponent(e)}/provider-probe`,{method:`POST`,body:JSON.stringify({providerId:t})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools})}})}function Oe(){return N({mutationFn:({providerId:e,targets:t})=>j(`/network/pools/test-batch/provider`,{method:`POST`,body:JSON.stringify({providerId:e,targets:t})})})}function ke(){let e=w();return N({mutationFn:e=>j(`/network/pools/${encodeURIComponent(e)}/health-check`,{method:`POST`,body:`{}`}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools}),l.success(`Health check complete`)},onError:e=>{l.error(`Health check failed.`,A(e))}})}function Ae(){let e=w();return N({mutationFn:({poolId:e,bytes:t})=>j(`/network/pools/${encodeURIComponent(e)}/speed-test`,{method:`POST`,body:JSON.stringify({bytes:t})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools})}})}function je(){let e=w();return N({mutationFn:({poolId:e,providerId:t})=>j(`/network/pools/${encodeURIComponent(e)}/cooldowns/clear`,{method:`POST`,body:JSON.stringify(t?{providerId:t}:{})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:M.network.pools}),l.success(`Provider cooldowns cleared`)},onError:e=>{l.error(`Could not clear provider cooldowns.`,A(e))}})}var V=t(n(),1),H=r(),U={cloudflare:{label:`Cloudflare Workers`,tokenLabel:`Cloudflare API token`,needsAccount:!0,host:`*.workers.dev`,hasRegion:!1},vercel:{label:`Vercel`,tokenLabel:`Vercel API token`,needsAccount:!1,host:`*.vercel.app`,hasRegion:!0},deno:{label:`Deno Deploy`,tokenLabel:`Deno Deploy token`,needsAccount:!1,host:`*.deno.dev`,hasRegion:!1}},Me=ye.flatMap(e=>e.regions.map(t=>({value:t.id,label:`${e.label} — ${t.label}`})));function Ne({onClose:e}){let t=xe(),[n,r]=(0,V.useState)(`cloudflare`),[i,a]=(0,V.useState)(ve),[o,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)(``),[h,g]=(0,V.useState)(null),v=U[n],y=o.trim().length>0&&(!v.needsAccount||d.trim().length>0);return(0,H.jsx)(_,{open:!0,onClose:e,title:`Deploy Relay`,description:`Run outbound traffic through a hosted relay (Cloudflare, Vercel, Deno).`,size:`md`,children:(0,H.jsxs)(le,{gap:`12px`,children:[(0,H.jsxs)(`p`,{className:`text-badge text-text-tertiary m-0 flex gap-3`,children:[(0,H.jsx)(te,{size:13,className:`shrink-0 mt-0.5`}),(0,H.jsxs)(`span`,{children:[`Deploys a small relay worker to your own `,v.label,` account and registers its URL (`,(0,H.jsx)(`code`,{children:v.host}),`) as an active HTTP pool. Your API token is used only for the deploy and is never stored.`]})]}),(0,H.jsx)(ce,{label:`Relay host`,id:`relay-target`,value:n,onValueChange:e=>r(e),options:D.map(e=>({value:e,label:U[e].label}))}),(0,H.jsx)(F,{label:v.tokenLabel,id:`relay-token`,type:`password`,value:o,placeholder:`Paste a deploy token`,onChange:e=>u(e.target.value)}),v.needsAccount?(0,H.jsx)(F,{label:`Account ID`,id:`relay-account`,value:d,placeholder:`Cloudflare account id`,onChange:e=>f(e.target.value)}):null,(0,H.jsx)(F,{label:`Project name (optional)`,id:`relay-project`,value:p,placeholder:`e.g. cartethyia-relay`,onChange:e=>m(e.target.value)}),v.hasRegion?(0,H.jsx)(ce,{label:`Deploy region`,id:`relay-region`,value:i,onValueChange:e=>a(e),options:Me}):null,v.hasRegion?(0,H.jsx)(`p`,{className:`text-badge text-text-tertiary m-0`,children:`Sets the region on the Vercel project, which is what decides the country outbound traffic leaves from. A region sent on the deployment alone is accepted but does not move the Function.`}):null,(0,H.jsxs)(`div`,{className:`flex items-center gap-5`,children:[(0,H.jsx)(c,{variant:`primary`,size:`sm`,onClick:()=>{y&&t.mutate({target:n,token:o.trim(),...v.needsAccount&&d.trim()?{accountId:d.trim()}:{},...p.trim()?{projectName:p.trim()}:{},...v.hasRegion?{region:i}:{}},{onSuccess:e=>{g(e.relayUrl),u(``),l.success(`Relay deployed to ${e.relayUrl} and registered as a pool.`)},onError:e=>l.error(A(e,`Relay deploy failed.`))})},disabled:!y||t.isPending,children:t.isPending?`Deploying…`:`Deploy relay`}),h?(0,H.jsxs)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Registered pool at `,(0,H.jsx)(`code`,{children:h})]}):null]}),t.isError?(0,H.jsxs)(`p`,{className:`text-badge text-red m-0 flex gap-3`,children:[(0,H.jsx)(s,{size:13,className:`shrink-0 mt-0.5`}),(0,H.jsx)(`span`,{children:A(t.error,`Relay deploy failed.`)})]}):null]})})}function Pe(e,t){if(e!==void 0)return e.endpoint===``||e.endpoint===(t??``)?e.result:void 0}function Fe(e,t,n){switch(t){case`name`:return(e.label||e.endpoint).toLowerCase();case`family`:return e.family===void 0||e.family===null||e.family===``?null:e.family.toLowerCase();case`address`:return e.egressIp??null;case`load`:return n??null}}function Ie(e,t,n,r){let i=n===`asc`?1:-1;return[...e].sort((e,n)=>{let a=Fe(e,t,r(e)),o=Fe(n,t,r(n));return a===null&&o===null?0:a===null?1:o===null?-1:typeof a==`number`&&typeof o==`number`?(a-o)*i:String(a).localeCompare(String(o))*i})}function W(e,t){let n=e.filter(e=>e.status===`active`),r=n.reduce((e,t)=>e+t.maxInflight,0),i=t===void 0?n.reduce((e,t)=>e+(t.inflight??0),0):n.reduce((e,n)=>e+(t.get(n.id)??0),0),a=0,o=0;for(let e of n)(t===void 0?e.inflight??0:t.get(e.id)??0)>=e.maxInflight?o+=1:a+=1;let s=null,c=Date.now(),l=e=>{if(!e)return;let t=Date.parse(e);if(Number.isNaN(t))return;let n=t-c;n<=0||(s===null||n<s)&&(s=n)};for(let t of e){l(t.cooldownUntil);for(let e of t.providerCooldowns??[])l(e.until)}let u=n.filter(e=>e.lastLatencyMs!==void 0&&Number.isFinite(e.lastLatencyMs)),d=u.length===0?null:Math.round(u.reduce((e,t)=>e+(t.lastLatencyMs??0),0)/u.length);return{totalPools:e.length,active:n.length,cooldown:e.filter(e=>e.status===`cooldown`).length,totalMaxConcurrency:r,usedInflight:i,availableCapacity:Math.max(0,r-i),routablePools:a,saturatedPools:o,soonestCooldownMs:s,avgLatencyMs:d,measuredPools:u.length}}var G=[`http`,`https`,`socks5`];function K(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function Le(e,t){let n=e.trim();return t===null||K(n)?n:`${t}://${n}`}function q(e){return e.find(e=>e.trim()!==``)}function J(e){let t=e.trim().toLowerCase();return t.startsWith(`https://`)?`https`:t.startsWith(`socks5://`)||t.startsWith(`socks://`)?`socks5`:`http`}var Re=1024**3;function ze(e){let t=e.trim();if(t===``)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:Math.max(1,Math.round(n*Re))}function Y(e,t,n){let r=new Map;if(t.trim().toLowerCase()===``||n<=0)return r;let i=Math.floor(e/n),a=e-i*n;for(let e=0;e<n;e+=1){let t=e===n-1?a:0;r.set(e,i+t)}return r}var Be=4,Ve=`cartethyia_proxy_test_payload`,He=`cartethyia_proxy_check_results`,Ue=[{value:`url`,label:`Test URL`},{value:`opencode`,label:`Test OpenCode`}],We=`opencode`,Ge=4,Ke=`Mysterious Proxy`;function X(e){return e.avgLatencyMs===null?`no measurement yet`:`avg across ${e.measuredPools} enabled ${e.measuredPools===1?`pool`:`pools`}`}function qe(e){let t=e.endpoint||``,n=t.includes(`://`)?t:`${e.kind}://${t}`,r={"https:":`443`,"http:":`80`,"socks5:":`1080`,"socks:":`1080`};try{let e=new URL(n),t=e.port||r[e.protocol]||``,i=`${e.hostname}${t?`:${t}`:``}`;return{name:i,endpoint:`${e.protocol}//${i}${e.pathname===`/`?``:e.pathname}${e.search}`}}catch{return{name:e.label||t,endpoint:t}}}function Z(e){return e.label||qe(e).name||e.id}var Q=1024**3;function Je(e){if(e.lastSpeedtestStatus===void 0||e.lastSpeedtestAt===void 0)return;let t=e.lastSpeedtestDurationMs??0,n=e.lastSpeedtestBytes??0,r=t>0?n/(t/1e3):void 0;return{poolId:e.id,status:e.lastSpeedtestStatus,bytes:n,durationMs:t,...r===void 0?{}:{bytesPerSecond:r,megabitsPerSecond:r*8/1e6},...e.lastSpeedtestError?{errorMessage:e.lastSpeedtestError}:{},measuredAt:e.lastSpeedtestAt}}function Ye(e,t){if(!e)return t;if(!t)return e;let n=e.measuredAt?new Date(e.measuredAt).getTime():0;return(t.measuredAt?new Date(t.measuredAt).getTime():0)>=n?t:e}var Xe=[{value:String(ge),label:`1 MB`},{value:String(_e),label:`5 MB`},{value:`50000000`,label:`50 MB`},{value:String(z),label:`100 MB`}];function Ze({pool:e,onClose:t,actionsRef:n}){let r=Ce(),i=Oe(),s=ke(),[d,f]=(0,V.useState)(e.label??``),[p,m]=(0,V.useState)(e.family??``),[h,g]=(0,V.useState)(e.endpoint??``),[_,v]=(0,V.useState)(String(e.maxInflight??10)),[y,ee]=(0,V.useState)(String(e.weight??100)),[b,x]=(0,V.useState)(e.quotaBytes?String(Math.round(e.quotaBytes/Q*1e3)/1e3):``),[S,C]=(0,V.useState)(null),[w,T]=(0,V.useState)(!1),E=h.trim()===e.endpoint,D=async()=>{T(!0),C(null);try{if(E){let t=await s.mutateAsync(e.id),n=t.status===`healthy`||t.status===`reachable`;C({ok:n,message:t.status===`healthy`?`Connected in ${t.latencyMs??0}ms`:t.errorMessage??`Connection failed`});return}let t=[{kind:e.kind,endpoint:h.trim(),...e.family===null||e.family===void 0?{}:{family:e.family}}],[n]=await i.mutateAsync({providerId:We,targets:t}),r=n?.result;if(!r){C({ok:!1,message:`Probe returned no result`});return}let a=r.status===`allowed`||r.status===`throttled`;C({ok:a,message:r.reason??(r.status===`allowed`?`Reachable${r.latencyMs===void 0?``:` in ${r.latencyMs}ms`}`:r.status===`throttled`?`Reachable; rate limit spent`:`Probe could not complete`)})}catch(e){C({ok:!1,message:A(e,`Connection failed`)})}finally{T(!1)}},O=ze(b),k=async()=>{await r.mutateAsync({poolId:e.id,request:{...d.trim()===e.label?{}:{label:d.trim()||void 0},...p.trim()===(e.family??``)?{}:{family:p.trim()||null},...h.trim()!==e.endpoint&&h.trim()!==``?{endpoint:h.trim()}:{},...Number(_)===e.maxInflight?{}:{maxInflight:Number(_)},...Number(y)===e.weight?{}:{weight:Number(y)},...O===(e.quotaBytes??null)?{}:{quotaBytes:O}}}),l.success(`Proxy updated`),t()};return(0,V.useEffect)(()=>{n?.((0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(c,{variant:`secondary`,size:`sm`,onClick:t,children:`Cancel`}),(0,H.jsx)(c,{variant:`primary`,size:`sm`,disabled:r.isPending||!h.trim(),onClick:()=>void k(),children:`Save`})]}))}),(0,H.jsxs)(le,{gap:`12px`,children:[(0,H.jsx)(`div`,{children:(0,H.jsx)(F,{label:`Name`,value:d,onChange:e=>f(e.target.value)})}),(0,H.jsx)(`div`,{children:(0,H.jsx)(F,{label:`Family`,value:p,placeholder:`e.g. residential-id`,onChange:e=>m(e.target.value)})}),(0,H.jsx)(`div`,{children:(0,H.jsx)(F,{label:`Endpoint`,value:h,onChange:e=>g(e.target.value),className:`font-mono tabular-nums`})}),(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-5`,children:[(0,H.jsx)(`div`,{children:(0,H.jsx)(F,{label:`Max concurrent`,type:`number`,min:1,value:_,onChange:e=>v(e.target.value)})}),(0,H.jsx)(`div`,{children:(0,H.jsx)(F,{label:`Weight`,type:`number`,min:1,value:y,onChange:e=>ee(e.target.value)})})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(F,{label:`Bandwidth quota (GB, blank = unmetered)`,type:`number`,min:.001,step:`0.1`,value:b,onChange:e=>x(e.target.value)}),(0,H.jsx)(`div`,{className:`text-micro text-text-tertiary mt-2`,children:O===null?`No quota — the bar shows a running total only.`:`Bar turns orange at 80% and red once ${u(O)} is exceeded.`})]}),S&&(0,H.jsx)(`div`,{className:`rounded-inset px-6 py-4 text-badge font-semibold ${S.ok?`bg-green-soft text-green`:`bg-red-soft text-red`}`,children:S.message}),(0,H.jsx)(`div`,{children:(0,H.jsx)(c,{variant:`secondary`,size:`sm`,disabled:w,icon:w?(0,H.jsx)(a,{size:13,className:`animate-spin`}):(0,H.jsx)(o,{size:13}),onClick:()=>void D(),children:w?`Testing…`:`Test connection`})})]})}function Qe({endpoint:e,chip:t,onChipChange:n}){return(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,role:`group`,"aria-label":`Scheme for the first endpoint`,children:[(0,H.jsx)(`span`,{className:`text-badge text-text-secondary`,children:`Scheme`}),G.map(r=>{let i=t===r;return(0,H.jsxs)(c,{type:`button`,variant:i?`primary`:`secondary`,size:`sm`,disabled:e===void 0,"aria-pressed":i,"data-scheme":r,onClick:()=>n(i?null:r),className:`font-mono`,children:[r,`://`]},r)}),t!==null&&(0,H.jsxs)(`span`,{className:`text-badge text-text-tertiary`,children:[`→ `,Le(e??``,t)]})]})}function $e({onClose:e,actionsRef:t,onProbeResult:n,onHealthResult:r}){let i=B(),a=Se(),o=Oe(),[s,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)(``),[h,g]=(0,V.useState)(null),[_,v]=(0,V.useState)([]),[y,ee]=(0,V.useState)({}),[b,x]=(0,V.useState)({}),[S,C]=(0,V.useState)(!1),[w,T]=(0,V.useState)(null),E=s.split(`
2
- `).map(e=>e.trim()).filter(Boolean),D=q(E),O=(0,V.useMemo)(()=>w===null||D===void 0?E:E.map((e,t)=>e===D&&t===0?Le(e,w):e),[E,w,D]),k=E.length>100,j=ze(p),M=(0,V.useMemo)(()=>O.map(e=>({kind:J(e),endpoint:e})),[O]),N=async()=>{try{let e=await navigator.clipboard.readText();e&&u(t=>t?`${t}\n${e}`:e)}catch{l.error(`Paste failed`,`Clipboard access denied`)}},te=async()=>{if(M.length!==0){v([`Testing ${M.length} proxy target(s)…`]);try{let e=await a.mutateAsync(M),t=e.map(e=>{let t=e.result.status===`healthy`||e.result.status===`reachable`,n=e.result.latencyMs===void 0?``:` · ${e.result.latencyMs}ms`,r=e.result.egressIp?` · ${e.result.egressIp}`:``,i=t?``:` · ${e.result.errorMessage??e.result.status}`;return`${t?`OK `:`FAIL`} ${e.endpoint}${n}${r}${i}`}),n=e.filter(e=>e.result.status===`healthy`||e.result.status===`reachable`).length;x(t=>{let n={...t};for(let t of e)n[t.endpoint]=t.result;return n}),v([`${n}/${e.length} reachable`,...t]),n===e.length?l.success(`All ${e.length} proxies reachable`):l.error(`${e.length-n} of ${e.length} proxies failed`)}catch(e){v([`Test failed: ${A(e,`batch probe failed`)}`]),l.error(`Test failed`,A(e,`batch probe failed`))}}},ne=async()=>{if(M.length!==0){v([`Testing ${M.length} proxy target(s) against OpenCode…`]);try{let e=await o.mutateAsync({providerId:We,targets:M}),t=e.map(e=>{let{status:t,latencyMs:n,reason:r}=e.result,i=n===void 0?``:` · ${n}ms`,a=r===void 0?``:` · ${r}`;return`${t===`allowed`?`OK `:t===`blocked`?`BLOCK`:`FAIL`} ${e.endpoint}${i}${a}`});ee(t=>{let n={...t};for(let t of e)n[t.endpoint]=t.result;return n});let n=e.filter(e=>e.result.status===`allowed`).length,r=e.filter(e=>e.result.status===`blocked`).length;v([`${n}/${e.length} allowed · ${r} blocked`,...t]),r===0&&n===e.length?l.success(`OpenCode accepted all ${e.length} proxies`):l.error(`OpenCode: ${n} allowed · ${r} blocked`)}catch(e){v([`Test failed: ${A(e,`provider probe failed`)}`]),l.error(`Test failed`,A(e,`provider probe failed`))}}};return(0,V.useEffect)(()=>{t?.((0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(c,{variant:`secondary`,type:`button`,onClick:e,children:`Cancel`}),(0,H.jsx)(c,{variant:`primary`,type:`submit`,form:`add-proxy-form`,disabled:S||E.length===0,children:S?`Adding…`:`Add ${E.length} Prox${E.length===1?`y`:`ies`}`})]}))},[t,S,E.length,e]),(0,H.jsxs)(`form`,{id:`add-proxy-form`,onSubmit:async t=>{if(t.preventDefault(),E.length!==0){g(null),C(!0);try{let t=j===null?new Map:Y(j,d,O.length),a=Array(E.length),o=0,s=async()=>{for(;o<E.length;){let e=o++,s=O[e];try{let o=await i.mutateAsync({kind:J(s),endpoint:s,...t.has(e)?{quotaBytes:t.get(e)}:{},...d.trim()===``?{}:{family:d.trim()}}),c=y[s],l=b[s];o?.id&&(l!==void 0&&r?.(o.id,l),c!==void 0&&n?.(o.id,c)),a[e]={ok:!0}}catch(t){a[e]={ok:!1,error:A(t,`Proxy pool creation failed`)}}}};await Promise.all(Array.from({length:Math.min(Be,E.length)},()=>s()));let c=[],f=0;for(let[e,t]of a.entries())t.ok?f++:c.length<3&&c.push(`${E[e].slice(0,48)}…: ${t.error}`);let p=E.length-f,m=a.find(e=>!e.ok)?.error;f>0&&l.success(`Added ${f} proxy pool(s)`,p?`${p} failed: ${m??`see the import details`}`:void 0),p>0&&f===0&&l.error(`Failed to create pool`,m??`See the import details`),p>0&&g(c.join(`
3
- `)),f>0&&(u(``),e())}finally{C(!1)}}},className:`flex flex-col gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,H.jsx)(`label`,{htmlFor:`proxy-endpoints`,className:`text-caption font-semibold text-text-primary`,children:`Proxy endpoints`}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,type:`button`,onClick:N,children:`Paste`})]}),(0,H.jsx)(`textarea`,{id:`proxy-endpoints`,value:s,onChange:e=>u(e.target.value),placeholder:`http://proxy.example:8080
4
- https://proxy.example:8443
5
- socks5://proxy.example:1080`,rows:5,"aria-describedby":`proxy-format-hint proxy-line-count`,"aria-invalid":!!h,className:`w-full min-h-32 max-h-64 resize-y overflow-y-auto rounded-control border border-inner-border bg-surface-1 p-3 font-mono text-caption text-text-primary outline-none transition-[border-color,box-shadow] duration-(--dur-micro) ease-spring focus:border-accent focus:shadow-focus`}),(0,H.jsx)(Qe,{endpoint:D,chip:w,onChipChange:T}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2`,children:[(0,H.jsx)(`p`,{id:`proxy-format-hint`,className:`m-0 text-badge leading-normal text-text-secondary`,children:`HTTP, HTTPS, or SOCKS5 | one per line | authentication optional`}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,H.jsxs)(`span`,{id:`proxy-line-count`,role:`status`,"aria-live":`polite`,className:`text-badge ${k?`text-red`:`text-text-tertiary`}`,children:[E.length===1?`1 proxy detected`:`${E.length} proxies detected`,k?` · max 100 per test`:``]}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,type:`button`,onClick:()=>void te(),disabled:a.isPending||o.isPending||E.length===0||k,children:a.isPending?`Testing…`:`Test URL`}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,type:`button`,onClick:()=>void ne(),disabled:a.isPending||o.isPending||E.length===0||k,children:o.isPending?`Testing…`:`Test OpenCode`})]})]}),h&&(0,H.jsx)(`div`,{role:`alert`,className:`max-h-28 overflow-y-auto rounded-inset bg-red-soft px-4 py-3 text-badge text-red whitespace-pre-wrap break-words`,children:h}),_.length>0&&(0,H.jsx)(`div`,{role:`log`,"aria-label":`Proxy test results`,"aria-live":`polite`,className:`scroll-region max-h-40 overflow-y-auto whitespace-pre-wrap break-all rounded-inset border border-inner-border bg-surface-1 px-3 py-2 font-mono text-badge leading-[1.5] text-text-secondary`,children:_.join(`
6
- `)}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 sm:grid-cols-2`,children:[(0,H.jsx)(F,{id:`proxy-family`,label:`Family`,hint:`Optional`,value:d,placeholder:`e.g. residential-id`,onChange:e=>f(e.target.value),className:`w-full`}),(0,H.jsx)(F,{id:`proxy-quota`,label:`Bandwidth quota (GB)`,hint:`Optional`,type:`number`,min:.001,step:`0.1`,value:p,onChange:e=>m(e.target.value),className:`w-full`})]})]})}function et(e,t){if(t?.status===`healthy`||t?.status===`reachable`)return t.latencyMs;if(e.lastSuccessAt)return e.lastLatencyMs??void 0}function tt(e){if(e===`proxy_payment_required`)return`HTTP 402 Payment Required`;if(e===`proxy_auth_required`)return`HTTP 407 Proxy Authentication Required`}var $=(0,V.createContext)({byId:new Map,live:!1});function nt({children:e}){let t=R(),n=(0,V.useMemo)(()=>new Map((t.pools??[]).map(e=>[e.poolId,e])),[t.pools]),r=(0,V.useMemo)(()=>({byId:n,live:t.live&&t.pools!==null}),[n,t.live,t.pools]);return(0,H.jsx)($.Provider,{value:r,children:e})}function rt({pools:e}){let{byId:t,live:n}=(0,V.useContext)($),r=(0,V.useMemo)(()=>W(e,n?new Map([...t].map(([e,t])=>[e,t.currentInflight])):void 0),[e,t,n]),a=(0,V.useMemo)(()=>{let r=0,i=0;for(let a of e){let e=n?t.get(a.id):void 0,o=(a.bytesSentTotal??0)+(a.bytesReceivedTotal??0),s=(e?.bytesSent??0)+(e?.bytesReceived??0);r+=Math.max(o,s),a.quotaBytes&&(i+=a.quotaBytes)}return{used:r,allowance:i}},[e,t,n]);return(0,H.jsxs)(`div`,{className:`signal-grid grid gap-7 w-full min-w-0 mb-7`,children:[(0,H.jsx)(L,{label:`Enabled pool`,value:String(r.active),detail:`/ ${r.totalPools} total`,tone:`accent`,icon:(0,H.jsx)(x,{size:13})}),(0,H.jsx)(L,{label:`Route capacity`,value:String(r.totalMaxConcurrency),detail:`${r.usedInflight} inflight · ${r.availableCapacity} available`,tone:r.availableCapacity===0?`orange`:`teal`,icon:(0,H.jsx)(p,{size:13})}),(0,H.jsx)(L,{label:`Latency`,value:r.avgLatencyMs===null?`—`:`${r.avgLatencyMs}ms`,detail:X(r),tone:r.avgLatencyMs===null?`accent`:r.avgLatencyMs>2e3?`orange`:`teal`,icon:(0,H.jsx)(i,{size:13})}),(0,H.jsx)(L,{label:`Quota usage`,value:u(a.used),detail:a.allowance>0?`of ${u(a.allowance)} allowance · ${e.length} pools`:`${e.length} pools · no allowance set`,tone:a.allowance>0&&a.used>a.allowance?`red`:a.allowance>0&&a.used/a.allowance>=.8?`orange`:`teal`,icon:(0,H.jsx)(me,{size:13})})]})}function it(e,t,n,r,i){let a=qe(e),o=Z(e),s=e.status!==`disabled`,c=tt(e.lastErrorCategory),l=e.status===`disabled`&&c!==void 0,u=e.lastSuccessAt?new Date(e.lastSuccessAt).getTime():0,d=e.lastErrorAt?new Date(e.lastErrorAt).getTime():0,f=!t&&(u>0||d>0)?u>=d:null,p=n?`default`:l?`warn`:t?t.status===`healthy`?`ok`:t.status===`reachable`?`warn`:`err`:f===!0?`ok`:f===!1?`err`:`default`,m=l?e.lastError??c:t?.errorMessage??(f===null?void 0:`last check ${(e.lastHealthCheckAt?new Date(e.lastHealthCheckAt):new Date).toLocaleString()}`),h=et(e,t),g=r?.currentInflight??e.inflight,_=e.maxInflight>0?Math.min(1,g/e.maxInflight):1,v=e.providerCooldowns??[],y=v.filter(e=>e.blocked===!0),ee=v.filter(e=>e.blocked!==!0),b=v.slice(0,2).map(e=>e.blocked===!0?`${e.providerId} blocked: ${e.reason}`:`${e.providerId} until ${new Date(e.until).toLocaleTimeString()}: ${e.reason}`).join(` · `),x=n?`Testing…`:l?`Proxy reachable`:t?t.status===`healthy`?`Connected`:t.status===`reachable`?`Proxy reachable`:t.status===`timeout`?`Timeout`:`Unhealthy`:f===!0?`Connected`:f===!1?e.lastErrorCategory===`timeout`?`Timeout`:`Unhealthy`:`Untested`,S=(e.bytesSentTotal??0)+(e.bytesReceivedTotal??0),C=(r?.bytesSent??0)+(r?.bytesReceived??0);return{display:a,poolLabel:o,isEnabled:s,checkTone:p,checkTooltip:m,statusText:x,latency:h,inflight:g,load:_,cooldowns:v,blocked:y,cooldownOnly:ee,cooldownText:b,...i===void 0?{}:{probe:i},metered:S,session:C,used:Math.max(S,C),proxyFailureLabel:c}}function at({pool:e,view:t,maskValues:n}){return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`block text-caption font-semibold overflow-hidden truncate whitespace-nowrap`,title:n?Ke:t.poolLabel,children:n?Ke:t.poolLabel}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3 mt-1.5 min-w-0 flex-wrap`,children:[e.status===`disabled`?(0,H.jsxs)(P,{tone:`disabled`,title:e.lastError,children:[`Disabled`,t.proxyFailureLabel?` · ${t.proxyFailureLabel}`:``]}):(0,H.jsx)(P,{tone:t.checkTone,title:t.checkTooltip,children:t.latency===void 0?t.statusText:`${t.statusText} · ${t.latency}ms`}),t.blocked.length>0?(0,H.jsxs)(P,{tone:`disabled`,title:t.cooldownText,children:[t.blocked.length,` blocked`]}):null,t.probe?(0,H.jsx)(P,{tone:t.probe.status===`blocked`?`disabled`:t.probe.status===`allowed`?`ok`:`warn`,title:t.probe.reason??(t.probe.status===`allowed`?t.probe.httpStatus!==void 0&&t.probe.httpStatus>=400?`Reachable — upstream answered ${t.probe.httpStatus} for the probe body`:`OpenCode served a probe through this pool`:t.probe.status===`throttled`?`OpenCode accepted this egress; the rate is spent`:`The probe could not complete`),children:t.probe.status===`blocked`?`OpenCode blocked`:t.probe.status===`allowed`?t.probe.httpStatus!==void 0&&t.probe.httpStatus>=400?`OpenCode reachable`:`OpenCode OK`:t.probe.status===`throttled`?`OpenCode rate-limited`:`OpenCode unreachable`}):null,t.cooldownOnly.length>0?(0,H.jsxs)(P,{tone:`warn`,title:t.cooldownText,children:[t.cooldownOnly.length,` cooldown`,t.cooldownOnly.length>1?`s`:``]}):null]})]})}function ot({pool:e,view:t,speedResult:n,isSpeedTesting:r,maskIp:i}){return(0,H.jsxs)(H.Fragment,{children:[e.egressIp?(0,H.jsx)(`span`,{className:`font-mono tabular-nums block overflow-hidden text-ellipsis whitespace-nowrap text-badge`,title:i?`IP masked`:`egress ${e.egressIp} · ${t.display.endpoint}`,children:i?`IP masked`:e.egressIp}):(0,H.jsx)(`span`,{className:`text-badge text-text-tertiary`,title:`Test the pool to read its egress address`,children:`not probed`}),(r||n)&&(0,H.jsx)(`div`,{className:`mt-1.5`,children:(0,H.jsx)(P,{tone:r?`default`:n?.status===`ok`?`ok`:`err`,title:r?`Measuring download throughput`:n?.status===`ok`?`${u(n.bytes)} in ${n.durationMs}ms${n.measuredAt?` · last measured ${new Date(n.measuredAt).toLocaleString()}`:``}`:`${n?.errorMessage??`Speed test failed`}${n?.measuredAt?` · last measured ${new Date(n.measuredAt).toLocaleString()}`:``}`,children:r?`Speed…`:n?.status===`ok`?`${(n.megabitsPerSecond??0).toFixed(1)} Mbps`:`Speed failed`})})]})}function st({pool:e,view:t}){let n=e.quotaBytes,r=n&&n>0?Math.min(1,t.used/n):0,i=n!==void 0&&n>0&&t.used>n;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{title:`${t.inflight}/${e.maxInflight} inflight`,className:`flex items-center gap-3`,children:[(0,H.jsx)(`div`,{className:`flex-1 h-3 rounded-micro overflow-hidden`,children:(0,H.jsx)(`div`,{className:`h-full rounded-micro`,style:{width:`${Math.round(t.load*100)}%`,background:t.load>=.8?`var(--orange)`:`var(--green)`}})}),(0,H.jsxs)(`span`,{className:`font-mono tabular-nums text-micro text-text-secondary whitespace-nowrap`,children:[t.inflight,`/`,e.maxInflight]})]}),(0,H.jsxs)(`div`,{title:n?`${u(t.used)} of ${u(n)} used · ${u(t.metered)} metered lifetime`:`${u(t.used)} carried (no quota set) · ${u(t.session)} this session`,className:`flex items-center gap-3 mt-2`,children:[(0,H.jsx)(`div`,{className:`flex-1 h-3 rounded-micro overflow-hidden`,children:(0,H.jsx)(`div`,{className:`h-full rounded-micro`,style:{width:`${Math.round(r*100)}%`,background:i?`var(--red)`:r>=.8?`var(--orange)`:`var(--teal)`}})}),(0,H.jsxs)(`span`,{className:`font-mono tabular-nums whitespace-nowrap text-micro ${i?`text-red`:`text-text-secondary`}`,children:[u(t.used),n?` / ${u(n)}`:``]})]})]})}function ct({pool:e,view:t,isTesting:n,onDelete:r,onEdit:s,onHealthCheck:l,onActivity:u}){let d=Ce(),f=je(),p=Te();return(0,H.jsxs)(H.Fragment,{children:[t.cooldowns.length>0&&(0,H.jsx)(c,{size:`icon`,variant:`secondary`,disabled:f.isPending,icon:f.isPending?(0,H.jsx)(a,{size:12,className:`animate-spin`}):(0,H.jsx)(b,{size:12}),onClick:()=>f.mutate({poolId:e.id}),title:`Clear provider cooldowns — ${t.cooldownText}`,label:`Clear`}),(0,H.jsx)(c,{size:`icon`,variant:`secondary`,icon:(0,H.jsx)(i,{size:12}),onClick:()=>u(e),title:`Health and error activity`,label:`Activity`}),e.status===`cooldown`&&(0,H.jsx)(c,{size:`icon`,variant:`secondary`,disabled:p.isPending,icon:(0,H.jsx)(b,{size:12,className:p.isPending?`animate-spin`:``}),onClick:()=>p.mutate(e.id),title:`Recover pool`,children:`Recover`}),!(!t.isEnabled&&t.cooldowns.length>0)&&(0,H.jsx)(c,{size:`icon`,variant:`secondary`,disabled:n,icon:n?(0,H.jsx)(a,{size:12,className:`animate-spin`}):(0,H.jsx)(o,{size:12}),onClick:()=>l(e),title:t.checkTooltip??`Run health check`,label:`Test`}),(0,H.jsx)(c,{size:`icon`,variant:`secondary`,icon:(0,H.jsx)(v,{size:12}),onClick:()=>s(e),title:`Edit pool`,label:`Edit`}),(0,H.jsx)(c,{size:`icon`,variant:`secondary`,icon:(0,H.jsx)(S,{size:12}),onClick:()=>r(e.id),title:`Delete pool`,label:`Delete`}),(0,H.jsx)(I,{className:`ml-3`,checked:t.isEnabled,disabled:d.isPending,onChange:t=>d.mutate({poolId:e.id,request:{status:t?`active`:`disabled`}})})]})}var lt=(0,V.memo)(function({pool:e,isSelected:t,onToggleSelect:n,checkResult:r,isTesting:i,onDelete:a,onEdit:o,onHealthCheck:s,onActivity:c,speedResult:l,isSpeedTesting:u,maskValues:d,maskIp:f,probe:p}){let m=(0,V.useContext)($),h=it(e,r,i,(m.live?m.byId.get(e.id):void 0)??null,p);return(0,H.jsxs)(`tr`,{className:h.isEnabled?``:`opacity-60`,children:[(0,H.jsx)(`td`,{className:`w-13`,children:(0,H.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>n(e.id),"aria-label":`Select ${h.poolLabel}`})}),(0,H.jsx)(`td`,{className:`min-w-0 max-w-150`,children:(0,H.jsx)(at,{pool:e,view:h,maskValues:d})}),(0,H.jsx)(`td`,{className:`min-w-0 max-w-90`,children:e.family?(0,H.jsx)(`span`,{className:`truncate text-caption font-semibold text-text-secondary`,title:e.family,children:e.family}):(0,H.jsx)(`span`,{className:`text-badge text-text-tertiary`,children:`—`})}),(0,H.jsx)(`td`,{className:`max-w-110`,children:(0,H.jsx)(ot,{pool:e,view:h,speedResult:l,isSpeedTesting:u,maskIp:f})}),(0,H.jsx)(`td`,{className:`min-w-55`,children:(0,H.jsx)(st,{pool:e,view:h})}),(0,H.jsx)(`td`,{className:`whitespace-nowrap pl-36 text-right`,children:(0,H.jsx)(ue,{gap:`4px`,justify:`end`,children:(0,H.jsx)(ct,{pool:e,view:h,isTesting:i,onDelete:a,onEdit:o,onHealthCheck:s,onActivity:c})})})]})});function ut({pool:e,onClose:t}){let n=we(e.id),r=Te(),i=n.data??[],a=tt(e.lastErrorCategory),o=e.status===`disabled`&&a!==void 0,s=e.status===`active`?`ok`:e.status===`disabled`?`disabled`:`warn`;return(0,H.jsx)(_,{open:!0,onClose:t,title:`Health & Activity — ${Z(e)}`,children:(0,H.jsxs)(le,{gap:`14px`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-8 rounded-panel border bg-surface-2 p-8 ${o?`border-orange`:`border-inner-border`}`,children:[(0,H.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`div`,{className:`mb-2.5 text-text-tertiary text-micro font-bold tracking-label uppercase`,children:`Proxy health`}),(0,H.jsx)(`div`,{className:`text-title font-bold leading-[1.3]`,children:o?`Proxy reachable`:`Proxy ${e.status}`}),(0,H.jsx)(`p`,{className:`mt-3 mx-0 mb-0 text-text-secondary text-caption leading-normal wrap-anywhere`,children:o?`${a} · disabled from routing`:e.lastError??`No recent proxy errors.`})]}),(0,H.jsx)(P,{tone:s,dot:!0,children:e.status})]}),e.status===`cooldown`&&(0,H.jsx)(`div`,{className:`flex justify-end`,children:(0,H.jsx)(c,{size:`sm`,variant:`secondary`,disabled:r.isPending,onClick:()=>r.mutate(e.id),icon:(0,H.jsx)(b,{size:12,className:r.isPending?`animate-spin`:``}),children:`Recover Now`})}),n.isPending?(0,H.jsx)(h,{compact:!0,label:`Loading pool activity…`}):null,n.isError?(0,H.jsx)(m,{compact:!0,message:`Failed to load pool activity`,onRetry:()=>void n.refetch()}):null,!n.isPending&&!n.isError&&i.length===0?(0,H.jsx)(g,{compact:!0,title:`No pool activity`,message:`Proxy checks, disable events, and recoveries will appear here.`}):null,i.length>0?(0,H.jsx)(`div`,{className:`grid gap-4 max-h-190 overflow-y-auto pr-1`,children:i.map(e=>(0,H.jsxs)(`div`,{className:`p-6 border border-inner-border rounded-control bg-surface-1`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-4`,children:[(0,H.jsxs)(ue,{gap:`6px`,children:[(0,H.jsxs)(P,{tone:e.toStatus===`active`?`ok`:e.toStatus===`disabled`?`disabled`:`warn`,children:[e.fromStatus??`new`,` → `,e.toStatus]}),e.errorCategory?(0,H.jsx)(P,{tone:e.errorCategory.startsWith(`proxy_`)?`warn`:`err`,children:e.errorCategory}):null]}),(0,H.jsx)(`time`,{className:`text-text-tertiary text-badge tabular-nums`,children:new Date(e.createdAt).toLocaleString()})]}),(0,H.jsx)(`p`,{className:`mt-4 mx-0 mb-0 text-text-secondary text-caption leading-normal wrap-anywhere`,children:e.reason??`No additional details`})]},e.id))}):null]})})}function dt(){let e=be(),t=Ee(),n=Ce(),r=ke(),[i,s]=(0,V.useState)(!1),u=(0,V.useCallback)(()=>s(!1),[]),[v,b]=(0,V.useState)(null),[C,w]=(0,V.useState)(null),[T,E]=(0,V.useState)(!1),[D,O]=(0,V.useState)(null),[k,j]=(0,V.useState)(new Set),M=fe(),N=M.enabled,te=pe(),F=te.enabled,[I,L]=(0,V.useState)(new Set),[R,ge]=(0,V.useState)(()=>{try{return localStorage.getItem(Ve)===`opencode`?`opencode`:`url`}catch{return`url`}});(0,V.useEffect)(()=>{try{localStorage.setItem(Ve,R)}catch{}},[R]);let[z,ve]=(0,V.useState)(new Set),[ye,B]=(0,V.useState)({}),xe=De(),Se=Ae(),[we,Te]=(0,V.useState)(_e),[Oe,je]=(0,V.useState)(()=>{try{let e=localStorage.getItem(`cartethyia_proxy_speed_results`);return e?JSON.parse(e):{}}catch{return{}}}),[U,Me]=(0,V.useState)(new Set),Fe=(0,V.useCallback)((e,t)=>{let n={...t,measuredAt:new Date().toISOString()};je(t=>{let r={...t,[e]:n};try{localStorage.setItem(`cartethyia_proxy_speed_results`,JSON.stringify(r))}catch{}return r})},[]),[W,G]=(0,V.useState)(()=>{try{let e=localStorage.getItem(He);return e?JSON.parse(e):{}}catch{return{}}}),[K,Le]=(0,V.useState)({key:`name`,direction:`asc`}),[q,J]=(0,V.useState)(null),[Re,ze]=(0,V.useState)(null),Y=e.data??[],Be=(0,V.useMemo)(()=>Ie(Y,K.key,K.direction,e=>et(e,W[e.id])),[Y,K,W]),Ke=(0,V.useCallback)(e=>{let t=e;Le(e=>e.key===t?{key:t,direction:e.direction===`asc`?`desc`:`asc`}:{key:t,direction:`asc`})},[]),X=e.isPending,Q=e.isError,Qe=Y.length>0&&Y.every(e=>k.has(e.id)),tt=()=>{j(Qe?new Set:new Set(Y.map(e=>e.id)))},$=(0,V.useCallback)(e=>{j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,V.useEffect)(()=>{try{localStorage.setItem(He,JSON.stringify(W))}catch{}},[W]);let it=Object.values(W),at=it.length,ot=it.filter(e=>e.status===`healthy`||e.status===`reachable`).length,st=it.filter(e=>e.status!==`healthy`&&e.status!==`reachable`).length,ct=(0,V.useCallback)(e=>{L(t=>new Set(t).add(e.id)),r.mutate(e.id,{onSuccess:t=>{G(n=>({...n,[e.id]:t}));let n=Z(e);t.status===`healthy`?l.success(`${n}: connected`,`${t.latencyMs??0}ms`):t.status===`reachable`?l.error(`${n}: proxy reachable · disabled`,t.errorMessage):l.error(`${n}: ${t.status===`timeout`?`timeout`:`unhealthy`}`,t.errorMessage)},onError:t=>{let n=Z(e);l.error(`${n}: check failed`,A(t,`Health check failed`))},onSettled:()=>{L(t=>{let n=new Set(t);return n.delete(e.id),n})}})},[r]),dt=async()=>{let e=Y;if(e.length===0)return;let t=0,n=0,i=0,a=async()=>{for(;;){let a=e[i++];if(!a)return;L(e=>new Set(e).add(a.id));try{let e=await r.mutateAsync(a.id);G(t=>({...t,[a.id]:e})),e.status===`healthy`?t+=1:n+=1}catch(e){n+=1;let t={poolId:a.id,status:`timeout`,errorMessage:A(e,`Health check failed`)};G(e=>({...e,[a.id]:t}))}finally{L(e=>{let t=new Set(e);return t.delete(a.id),t})}}};await Promise.all(Array.from({length:Math.min(8,e.length)},()=>a())),l.success(`Tested ${e.length} pools · ${t} healthy · ${n} failed`)},ft=async()=>{let e=Y.filter(e=>k.has(e.id));if(e.length===0)return;let t=0,n=0,i=0,a=async()=>{for(;;){let a=e[i++];if(!a)return;L(e=>new Set(e).add(a.id));try{let e=await r.mutateAsync(a.id);G(t=>({...t,[a.id]:e})),e.status===`healthy`?t+=1:n+=1}catch(e){n+=1;let t={poolId:a.id,status:`timeout`,errorMessage:A(e,`Health check failed`)};G(e=>({...e,[a.id]:t}))}finally{L(e=>{let t=new Set(e);return t.delete(a.id),t})}}};await Promise.all(Array.from({length:Math.min(8,e.length)},()=>a())),l.success(`Tested ${e.length} pools · ${t} healthy · ${n} failed`)},pt=async()=>{let e=Y.filter(e=>k.has(e.id));if(e.length===0)return;let t=0,n=0,r=0,i=0,a=0,o=async()=>{for(;;){let o=e[a++];if(!o)return;ve(e=>new Set(e).add(o.id));try{let e=await xe.mutateAsync({poolId:o.id,providerId:We});B(t=>({...t,[o.id]:{endpoint:o.endpoint??``,result:e}})),e.status===`allowed`?t+=1:e.status===`blocked`?n+=1:e.status===`throttled`?r+=1:i+=1}catch(e){i+=1,B(t=>({...t,[o.id]:{endpoint:o.endpoint??``,result:{poolId:o.id,providerId:We,status:`unreachable`,reason:A(e,`Provider probe failed`)}}}))}finally{ve(e=>{let t=new Set(e);return t.delete(o.id),t})}}};await Promise.all(Array.from({length:Math.min(Ge,e.length)},()=>o())),l.success(`OpenCode: ${t} allowed · ${n} blocked`+(r>0?` · ${r} rate-limited`:``)+(i>0?` · ${i} unreachable`:``))},mt=async()=>{let e=Y.filter(e=>k.has(e.id));if(e.length===0)return;let t=0;await(async()=>{for(;;){let n=e[t++];if(!n)return;Me(e=>new Set(e).add(n.id));try{let e=await Se.mutateAsync({poolId:n.id,bytes:we});Fe(n.id,e)}catch(e){Fe(n.id,{poolId:n.id,status:`failed`,bytes:0,durationMs:0,errorMessage:A(e,`Speed test failed`)})}finally{Me(e=>{let t=new Set(e);return t.delete(n.id),t})}}})(),l.success(`Speed tested ${e.length} pool(s)`)},ht=async()=>{let e=Y.filter(e=>k.has(e.id));e.length!==0&&(await Promise.all(e.map(e=>n.mutateAsync({poolId:e.id,request:{status:`active`}}))),j(new Set),l.success(`Enabled ${e.length} pool(s)`))},gt=async()=>{let e=Y.filter(e=>k.has(e.id));e.length!==0&&(await Promise.all(e.map(e=>n.mutateAsync({poolId:e.id,request:{status:`disabled`}}))),j(new Set),l.success(`Disabled ${e.length} pool(s)`))},_t=()=>{let e=k.size>0?Y.filter(e=>k.has(e.id)):Y;if(e.length===0)return;let t=e.map(e=>qe(e).endpoint||e.endpoint).join(`
7
- `);se(`cartethyia-proxies.txt`,t,`text/plain;charset=utf-8`),l.success(`Exported ${e.length} pool(s)`)},vt=(0,V.useCallback)(e=>{let t=Y.find(t=>t.id===e);t&&J([t])},[Y]);return(0,H.jsx)(nt,{children:(0,H.jsxs)(le,{gap:`16px`,children:[(0,H.jsx)(_,{open:i,onClose:u,title:`Add Proxy`,footer:v,children:(0,H.jsx)($e,{onClose:u,actionsRef:b,onProbeResult:(e,t)=>{let n=Y.find(t=>t.id===e);B(r=>({...r,[e]:{endpoint:n?.endpoint??``,result:t}}))},onHealthResult:(e,t)=>{G(n=>({...n,[e]:t}))}})}),(0,H.jsx)(_,{open:D!==null,onClose:()=>O(null),title:`Edit pool`,footer:C,children:D&&(0,H.jsx)(Ze,{pool:D,onClose:()=>O(null),actionsRef:w},D.id)}),(0,H.jsxs)(oe,{style:Y.length===0&&!X&&!Q?{minHeight:`min(78dvh, calc(100dvh - 160px))`,display:`flex`,flexDirection:`column`}:void 0,children:[(0,H.jsx)(ae,{title:`Proxy Pool`,subtitle:`Outbound proxy servers — HTTP, HTTPS, and SOCKS5`,icon:(0,H.jsx)(x,{size:16}),action:(0,H.jsxs)(ue,{gap:`8px`,children:[(0,H.jsx)(c,{variant:`secondary`,size:`sm`,icon:(0,H.jsx)(me,{size:13}),onClick:()=>E(!0),children:`Deploy relay`}),(0,H.jsx)(c,{variant:`primary`,size:`sm`,icon:(0,H.jsx)(y,{size:13}),onClick:()=>s(!0),children:`Add proxies`})]})}),(0,H.jsxs)(ie,{style:Y.length===0&&!X&&!Q?{flex:1,display:`flex`,flexDirection:`column`,gap:`16px`}:void 0,children:[(0,H.jsx)(rt,{pools:Y}),Y.length>0&&(0,H.jsxs)(`div`,{className:`nested-panel flex flex-wrap items-center justify-start overflow-x-auto rounded-card border border-inner-border bg-surface-2 p-4 text-badge`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-5`,children:[(0,H.jsxs)(`label`,{className:`flex items-center gap-3 cursor-pointer text-text-secondary`,children:[(0,H.jsx)(`input`,{type:`checkbox`,checked:Qe,onChange:tt,"aria-label":`Select all proxies`}),`Select all`,k.size>0&&(0,H.jsxs)(`span`,{className:`text-text-tertiary`,children:[`(`,k.size,`)`]})]}),at>0&&(0,H.jsxs)(ue,{gap:`6px`,children:[(0,H.jsxs)(`span`,{className:`text-text-tertiary`,children:[`Tested `,at,`/`,Y.length]}),ot>0&&(0,H.jsxs)(P,{tone:`ok`,children:[ot,` success`]}),st>0&&(0,H.jsxs)(P,{tone:`err`,children:[st,` errors`]})]})]}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,H.jsx)(c,{variant:`ghost`,size:`sm`,icon:N?(0,H.jsx)(d,{size:12}):(0,H.jsx)(f,{size:12}),onClick:()=>M.setEnabled(!N),title:N?`Show proxy names and addresses`:`Hide proxy names and addresses`,children:N?`Unmask`:`Mask`}),(0,H.jsx)(c,{variant:`ghost`,size:`sm`,icon:F?(0,H.jsx)(d,{size:12}):(0,H.jsx)(f,{size:12}),onClick:()=>te.setEnabled(!F),title:F?`Show egress addresses`:`Hide egress addresses`,children:F?`Show IP`:`Mask IP`}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,disabled:I.size>0||Y.length===0,icon:I.size>0?(0,H.jsx)(a,{size:12,className:`animate-spin`}):(0,H.jsx)(o,{size:12}),onClick:()=>void dt(),children:`Test all`}),(0,H.jsxs)(`div`,{className:`inline-flex items-stretch h-15`,children:[(0,H.jsx)(c,{variant:`secondary`,size:`sm`,className:`rounded-tr-none rounded-br-none`,disabled:I.size>0||z.size>0||k.size===0,icon:I.size>0||z.size>0?(0,H.jsx)(a,{size:12,className:`animate-spin`}):(0,H.jsx)(o,{size:12}),onClick:()=>void(R===`opencode`?pt():ft()),children:R===`opencode`?`Test OpenCode`:`Test URL`}),(0,H.jsx)(ce,{"aria-label":`Test payload`,value:R,onValueChange:e=>ge(e),options:Ue,disabled:I.size>0||z.size>0,className:`w-auto min-w-38 h-15 rounded-tl-none rounded-bl-none -ml-0.5`})]}),(0,H.jsxs)(`div`,{className:`inline-flex items-stretch h-15`,children:[(0,H.jsx)(c,{variant:`secondary`,size:`sm`,className:`rounded-tr-none rounded-br-none`,disabled:k.size===0||U.size>0||Se.isPending,icon:U.size>0?(0,H.jsx)(a,{size:12,className:`animate-spin`}):(0,H.jsx)(p,{size:12}),onClick:()=>void mt(),children:`Speedtest selected`}),(0,H.jsx)(ce,{"aria-label":`Speed test payload size`,value:String(we),onValueChange:e=>Te(Number(e)),options:Xe,disabled:U.size>0||Se.isPending,className:`w-auto min-w-38 h-15 rounded-tl-none rounded-bl-none -ml-0.5`})]}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,disabled:Y.length===0,icon:(0,H.jsx)(ne,{size:12}),onClick:_t,children:`Export`}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,disabled:k.size===0||n.isPending,icon:(0,H.jsx)(he,{size:12}),onClick:()=>void ht(),children:`Enable selected`}),(0,H.jsx)(c,{variant:`secondary`,size:`sm`,disabled:k.size===0||n.isPending,icon:(0,H.jsx)(ee,{size:12}),onClick:()=>void gt(),children:`Disable selected`}),(0,H.jsx)(c,{variant:`danger`,size:`sm`,disabled:k.size===0||t.isPending,icon:(0,H.jsx)(S,{size:12}),onClick:()=>{let e=Y.filter(e=>k.has(e.id));e.length!==0&&J(e)},children:`Delete selected`})]})]}),X&&(0,H.jsx)(h,{}),Q&&(0,H.jsx)(m,{title:`Error`,message:`Failed to load network pools`}),!X&&!Q&&Y.length===0&&(0,H.jsx)(`div`,{className:`flex-1 flex items-center justify-center p-12 border border-dashed border-transparent rounded-card bg-transparent text-center`,children:(0,H.jsx)(g,{title:`No proxy pools configured`,message:`The summary above is empty because nothing is routing yet. Use Add proxies or Deploy relay in the header to start one.`})}),!X&&!Q&&Y.length>0&&(0,H.jsx)(`div`,{className:`proxy-table-scroll rounded-control border border-inner-border bg-surface-1`,children:(0,H.jsx)(de,{maxHeight:460,scrollRegion:!0,headers:[``,{key:`name`,label:`Proxy`,sortable:!0},{key:`family`,label:`Family`,sortable:!0},{key:`address`,label:`Address`,sortable:!0},{key:`load`,label:`Load`,sortable:!0},`Actions`],sortKey:K.key,sortDirection:K.direction,onSort:Ke,children:Be.map(e=>(0,H.jsx)(lt,{pool:e,isSelected:k.has(e.id),onToggleSelect:$,checkResult:W[e.id],probe:e.providerProbe===void 0?Pe(ye[e.id],e.endpoint):{poolId:e.id,providerId:e.providerProbe.providerId,status:e.providerProbe.status,...e.providerProbe.httpStatus===void 0?{}:{httpStatus:e.providerProbe.httpStatus},...e.providerProbe.reason===void 0?{}:{reason:e.providerProbe.reason},...e.providerProbe.latencyMs===void 0?{}:{latencyMs:e.providerProbe.latencyMs}},isTesting:I.has(e.id),onDelete:vt,onEdit:O,onHealthCheck:ct,onActivity:ze,speedResult:Ye(Oe[e.id],Je(e)),isSpeedTesting:U.has(e.id),maskValues:N,maskIp:F},e.id))})})]})]}),(0,H.jsx)(re,{open:q!==null,onClose:()=>J(null),onConfirm:async()=>{q&&(await Promise.all(q.map(e=>t.mutateAsync(e.id))),j(new Set),l.success(`Deleted ${q.length} pool(s)`),J(null))},title:`Delete proxy pool?`,message:q&&q.length===1?`Delete "${Z(q[0])}"? This cannot be undone.`:q?`Delete ${q.length} proxy pools? This cannot be undone.`:`Delete this proxy pool? This cannot be undone.`,confirmLabel:`Delete`,danger:!0}),Re?(0,H.jsx)(ut,{pool:Re,onClose:()=>ze(null)}):null,T?(0,H.jsx)(Ne,{onClose:()=>E(!1)}):null]})})}export{$e as ProxyBulkForm,nt as ProxyLiveProvider,Qe as SchemeChipRow,dt as default};
@@ -1 +0,0 @@
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{C as a,b as o,c as s,k as c,s as l}from"./numbers-YNcHvRY7.js";import{t as u}from"./chevron-right-BXIy5l3h.js";import{t as d}from"./eye-off-Bk5g2luF.js";import{i as f,n as p,r as m,t as h}from"./state-BgTxHcJS.js";import{t as g}from"./dialog-BYj-8WuK.js";import{t as _}from"./refresh-cw-BqJFk4sU.js";import{t as v}from"./rotate-ccw-CufcqITi.js";import{t as ee}from"./trash-Cppn5c3R.js";import{t as y}from"./zap-C4EeVW4q.js";import{l as b}from"./query-keys-gmjzC3RS.js";import{z as x}from"./entry-CgdSAzEV.js";import{n as S,t as te}from"./card-BKqlUOe4.js";import{t as C}from"./badge-D4pQapKj.js";import{t as w}from"./select-WUCXorXw.js";import{t as T}from"./ProviderIcon-CmfzxpVM.js";import{t as ne}from"./switch-DEjTtOWf.js";import{t as E}from"./stack-_3O0F8Xn.js";import{n as D}from"./inline-DUWDSmDV.js";import{t as O}from"./layout-CPfxpsfy.js";import{a as k,i as A,n as j,o as M,r as N,s as P,t as F}from"./quota-DZGyp0N5.js";import{a as I,c as L,d as R,f as z,i as B,l as V,n as H,o as U,p as W,r as G,s as K,t as q,u as J}from"./HealthEventsModal-BjqSMfko.js";var re=e(`calendar-check`,[[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}],[`path`,{d:`M3 9h18`,key:`1pudct`}],[`path`,{d:`m9 15 2 2 4-4`,key:`1grp1n`}]]),ie=e(`chevron-left`,[[`path`,{d:`m15 18-6-6 6-6`,key:`1wnfg3`}]]),Y=e(`clock-3`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 6v6h4`,key:`135r8i`}]]),X=t(n(),1),Z=r();function Q(e){return!!(e.quota?.windows.length&&e.quota.windows.every(e=>e.remainingPercent!==null&&e.remainingPercent<=0))}function $(e){let t=e.quota?.windows.map(e=>e.resetsAt?new Date(e.resetsAt).getTime():1/0)??[];return Math.min(...t,1/0)}function ae({account:e,onClose:t}){let n=B(e.id,!0),r=J(e.id),i=n.data?.credits??[],a=e=>e?new Date(e).toLocaleString():`—`,o=e=>e?new Date(e).toLocaleString():`—`,c=e=>{if(!e)return``;let t=new Date(e).getTime()-Date.now();if(!Number.isFinite(t))return``;if(t<=0)return`expired`;let n=Math.floor(t/864e5);if(n>=1)return`in ${n}d`;let r=Math.floor(t/36e5);return r>=1?`in ${r}h`:`in ${Math.max(1,Math.floor(t/6e4))}m`};return(0,Z.jsx)(g,{open:!0,onClose:t,size:`lg`,title:`Saved Rate-Limit Resets — ${e.name}`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-7`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-6 rounded-control border border-inner-border bg-surface-2 px-8 py-6`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,Z.jsx)(y,{size:14,className:`text-status-success`}),(0,Z.jsx)(`span`,{className:`text-body font-semibold`,children:`Available resets`})]}),(0,Z.jsx)(`p`,{className:`mt-2 text-text-tertiary text-badge leading-normal`,children:`Each credit lifts a spent rate-limit window before its natural reset.`})]}),(0,Z.jsxs)(C,{tone:n.data&&n.data.availableCount>0?`ok`:`disabled`,dot:!0,children:[n.data?.availableCount??0,` reset`,(n.data?.availableCount??0)===1?``:`s`]})]}),n.isPending?(0,Z.jsx)(m,{compact:!0,label:`Reading saved resets…`}):n.isError?(0,Z.jsx)(p,{compact:!0,message:`Failed to read saved resets`,onRetry:()=>void n.refetch()}):i.length===0?(0,Z.jsx)(h,{compact:!0,title:`No saved resets`,message:`This account has no saved rate-limit reset credits right now.`,icon:(0,Z.jsx)(y,{size:20})}):(0,Z.jsx)(`div`,{className:`max-h-170 overflow-y-auto rounded-control border border-inner-border`,children:(0,Z.jsx)(O,{headers:[`Status`,`Title`,`Granted`,`Expires`,``],children:i.map(e=>{let t=(e.status??`available`)===`available`,n=c(e.expiresAt);return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`whitespace-nowrap align-middle`,children:(0,Z.jsx)(C,{tone:t?`ok`:e.status===`expired`?`disabled`:`warn`,children:e.status??`available`})}),(0,Z.jsx)(`td`,{className:`text-caption font-medium whitespace-nowrap align-middle text-text-primary`,children:e.title??`Rate-limit reset`}),(0,Z.jsx)(`td`,{className:`text-badge whitespace-nowrap tabular-nums align-middle text-text-secondary`,children:a(e.grantedAt)}),(0,Z.jsxs)(`td`,{className:`text-badge whitespace-nowrap tabular-nums align-middle text-text-secondary`,children:[o(e.expiresAt),n&&(0,Z.jsxs)(`span`,{className:`ml-3 text-text-tertiary`,children:[`(`,n,`)`]})]}),(0,Z.jsx)(`td`,{className:`whitespace-nowrap text-right align-middle`,children:(0,Z.jsx)(s,{size:`sm`,variant:t?`primary`:`secondary`,disabled:!t||r.isPending,onClick:()=>r.mutate({creditId:e.id},{onSuccess:e=>{e.ok?l.success(e.message??`Rate limit reset applied`):l.error(e.message??`Rate limit reset failed`)},onError:e=>{l.error(b(e,`Unable to redeem rate-limit reset`))}}),children:`Use`})})]},e.id)})})}),(0,Z.jsx)(D,{justify:`flex-end`,gap:`0px`,children:(0,Z.jsx)(s,{variant:`secondary`,size:`sm`,onClick:t,children:`Close`})})]})})}function oe({accounts:e}){let t=(0,X.useMemo)(()=>{let t=new Map;for(let n of e){if(!H(n.provider))continue;let e=t.get(n.provider);e?e.count+=1:t.set(n.provider,{id:n.provider,label:n.providerName||n.provider,count:1})}return[...t.values()]},[e]),[n,r]=(0,X.useState)(``),i=(t.find(e=>e.id===n)??t[0])?.id??``,o=z(i),c=i.length===0||o.isPending||t.length===0;return(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2.5`,"aria-label":`Daily growth actions`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 w-67.5`,children:(0,Z.jsx)(w,{"aria-label":`Provider for the daily growth pass`,value:i,onValueChange:r,className:`w-full h-16`,options:t.length>0?t.map(e=>({value:e.id,label:`${e.label} · ${e.count}`})):[{value:``,label:`No buddy providers`}]})}),(0,Z.jsx)(s,{variant:`secondary`,size:`sm`,title:`Send the activity report, then claim the daily check-in, for every account of this provider`,"aria-label":`Run the daily growth pass for this provider`,disabled:c,className:`shrink-0`,icon:o.isPending?(0,Z.jsx)(a,{size:13,className:`animate-spin`}):(0,Z.jsx)(re,{size:13}),onClick:()=>o.mutate(void 0,{onSuccess:e=>{let t=e.data.filter(e=>!e.report.ok).length;t===0?l.success(e.message):l.error(`${e.message} — ${t} report${t===1?``:`s`} failed`)},onError:e=>l.error(b(e,`Unable to run the daily growth pass`))}),children:`Daily growth`})]})}function se({account:e,onToggle:t,onDelete:n,onShowHealth:r,onShowResets:c}){let d=K(e.id),f=R(e.id),p=H(e.provider),m=G(e.provider),h=B(e.id,m),g=e.quota,[_,x]=(0,X.useState)(0),S=g?.windows??[],C=M(S,_),w=C.pageCount;(0,X.useEffect)(()=>{x(e=>Math.min(e,Math.max(0,w-1)))},[w]);let E=d.isPending||f.isPending,D=h.data?.availableCount??0,[O,I]=(0,X.useState)(null),[L,z]=(0,X.useState)(!1),V=e.checkin?.attemptedToday??!1,U=`${O?O.state===`claimed`?`Checked in${O.credit===null?``:` +${O.credit}`}${O.streakDays===null?``:` · ${O.streakDays}d streak`}`:O.state===`already_claimed`?`Check-in attempted · already claimed`:O.state===`not_eligible`?`Check-in attempted · not eligible`:O.state===`event_ended`?`Check-in attempted · event ended`:`Check-in attempted · unavailable`:V?`Check-in attempted today`:`Check-in due`}${L?` · Reported today`:``}`,W=S.reduce((e,t)=>{let n=t.limit;if(typeof n!=`number`||!Number.isFinite(n))return e;let r=typeof t.remaining==`number`&&Number.isFinite(t.remaining)?t.remaining:typeof t.used==`number`&&Number.isFinite(t.used)?n-t.used:typeof t.remainingPercent==`number`&&Number.isFinite(t.remainingPercent)?n*t.remainingPercent/100:null;return r===null?e:e+Math.max(0,r)},0),q=(d.error?b(d.error,`Unable to refresh this account`):null)??g?.refreshError??g?.error??e.health?.sanitizedMessage,J=k(q),Y=J===`Quota tracking is not supported for this provider`?null:J,Q=F(e.credentialHint,e.name),$=e.health?.status??`unknown`;return(0,Z.jsxs)(te,{className:`flex h-full flex-col overflow-hidden`,"aria-busy":E,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-5 px-7 py-4`,children:[(0,Z.jsx)(T,{icon:e.providerIcon,name:e.providerName,size:32}),(0,Z.jsxs)(`div`,{className:`flex-[1_1_160px]`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-4`,children:[(0,Z.jsx)(`div`,{className:`truncate text-caption font-bold text-text-primary text-body`,children:e.providerName}),g?.plan&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded-chip bg-accent-soft px-4 py-1 text-micro font-semibold text-accent`,children:g.plan})]}),(0,Z.jsx)(`div`,{className:`truncate text-badge text-text-secondary`,children:Q.primary}),Q.secondary!==null&&(0,Z.jsx)(`div`,{className:`truncate text-micro text-text-tertiary`,children:Q.secondary}),g&&(0,Z.jsx)(`div`,{className:`truncate text-micro text-text-tertiary`,children:j(g.lastSuccessAt??g.fetchedAt)}),m&&(0,Z.jsx)(`div`,{className:`truncate text-micro flex items-center gap-2 text-text-tertiary`,title:`Saved rate-limit reset credits available on this account`,children:h.isPending?`Checking saved resets…`:D>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(y,{size:10,className:`text-status-success shrink-0`,"aria-hidden":`true`}),(0,Z.jsxs)(`span`,{className:`reset-credit-live`,children:[D,` rate-limit reset`,D===1?``:`s`,` available`]})]}):`No rate-limit resets available`}),p&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{title:`Daily growth state: manual pass result, else the sweep ledger for today`,className:`truncate text-micro text-text-tertiary`,children:f.isPending?`Running growth pass…`:U}),S.some(e=>typeof e.limit==`number`&&Number.isFinite(e.limit))&&(0,Z.jsxs)(`div`,{className:`truncate text-micro text-text-tertiary`,children:[`Total credits: `,W.toLocaleString(void 0,{maximumFractionDigits:2})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.75 gap-3 ml-auto`,children:[m&&(0,Z.jsx)(s,{variant:`ghost`,size:`icon`,className:`w-16 h-16 p-0`,title:h.isPending?`Checking saved rate-limit resets…`:D>0?`Saved rate-limit resets (${D} available)`:`Saved rate-limit resets`,"aria-label":`Open saved rate-limit resets for ${e.name}`,disabled:E,onClick:()=>c(e),children:(0,Z.jsx)(y,{size:14})}),p&&(0,Z.jsx)(s,{variant:`ghost`,size:`icon`,className:`w-16 h-16 p-0`,title:`Daily growth pass (check-in + activity report) — ${U}`,"aria-label":`Run daily growth pass for ${e.name}`,disabled:E,onClick:()=>f.mutate(void 0,{onSuccess:e=>{let t=e.checkin.data;t&&I({state:t.state,credit:t.credit,streakDays:t.streakDays}),e.report.ok&&z(!0),e.ok?l.success(e.message):l.error(e.message)},onError:e=>{l.error(b(e,`Unable to run daily growth pass`))}}),children:f.isPending?(0,Z.jsx)(a,{size:14,className:`animate-spin`}):(0,Z.jsx)(re,{size:14})}),(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,title:$===`active`?`Health & Error Log`:`${$} — Inspect account health details`,"aria-label":$===`active`?`Health log for ${e.name}`:`Account is ${$} — inspect health details for ${e.name}`,disabled:E,onClick:()=>r(e),icon:(0,Z.jsx)(i,{size:12})}),(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,title:`Refresh quota`,"aria-label":`Refresh ${e.name} quota`,disabled:E,onClick:()=>d.mutate(),icon:d.isPending?(0,Z.jsx)(a,{size:12,className:`animate-spin`}):(0,Z.jsx)(v,{size:12})}),(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,title:`Delete account`,"aria-label":`Delete ${e.name}`,onClick:()=>n(e),className:`text-red`,icon:(0,Z.jsx)(ee,{size:12})}),(0,Z.jsx)(ne,{checked:e.active,disabled:d.isPending,onChange:n=>t(e,n),label:``,id:`switch-${e.id}`})]})]}),Y&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-center gap-4 border-t border-inner-border px-8 py-5 text-center text-badge text-red`,role:`alert`,children:[(0,Z.jsx)(o,{size:13,className:`shrink-0`}),(0,Z.jsx)(`span`,{children:Y})]}),g?.windows.length?(0,Z.jsxs)(`div`,{className:`quota-window-list flex flex-1 flex-col gap-4 border-t border-inner-border px-7 py-4.5`,children:[(0,Z.jsx)(`div`,{className:`quota-window-section-label text-micro font-bold tracking-label text-text-tertiary`,children:`QUOTA WINDOWS`}),C.items.map((e,t)=>{let n=e.remainingPercent??null,r=typeof e.limit==`number`&&Number.isFinite(e.limit)?e.limit:null,i=typeof e.used==`number`&&Number.isFinite(e.used)?e.used:r!==null&&e.usedPercent!==null&&e.usedPercent!==void 0?r*e.usedPercent/100:null,a=P(n),o=n===null?0:Math.max(0,Math.min(100,n)),s=e=>e.toLocaleString(void 0,{maximumFractionDigits:2}),c=e=>{let t=Math.round(e*10)/10;return t>0&&t<.1?`<0.1`:t.toLocaleString(void 0,{maximumFractionDigits:1})},l=N(e.label);return(0,Z.jsxs)(`div`,{className:`quota-window-row grid grid-cols-quota-window min-w-0 items-center gap-x-6 gap-y-2 max-small:grid-cols-[minmax(0,1fr)_auto] max-small:gap-x-4 max-small:gap-y-2.5`,children:[(0,Z.jsx)(`div`,{className:`quota-window-heading min-w-0 max-small:col-start-1`,children:(0,Z.jsx)(`span`,{className:`text-badge font-semibold text-text-primary`,children:l})}),(0,Z.jsx)(`div`,{className:`quota-bar-track quota-window-bar min-w-0 w-full h-5 rounded-tiny bg-inner-border overflow-hidden max-small:col-span-full max-small:row-start-2`,role:`progressbar`,"aria-label":`${l} remaining quota`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":n===null?void 0:o,"aria-valuetext":n===null?`Quota only`:`${c(n)}% remaining`,children:(0,Z.jsx)(`div`,{className:`quota-bar-fill h-full rounded-tiny transition-[width] duration-(--dur-macro) ease-spring`,style:{width:`${o}%`,background:a.bar}})}),(0,Z.jsx)(`span`,{className:`quota-window-remaining whitespace-nowrap text-badge font-bold tabular-nums max-small:col-start-2 max-small:row-start-1`,style:{color:a.text},children:n===null?`—`:`${c(n)}%`}),(0,Z.jsxs)(`div`,{className:`quota-window-details col-span-full flex min-w-0 items-center justify-end gap-6 text-micro text-text-tertiary max-small:row-start-3 max-small:flex-wrap max-small:justify-between max-small:gap-4`,children:[(0,Z.jsx)(`span`,{className:`quota-window-usage mr-auto tabular-nums max-small:min-w-0`,children:i!==null&&r!==null?`${s(i)} / ${s(r)} Credits`:`Quota only`}),e.resetsAt&&(0,Z.jsx)(`span`,{className:`quota-window-reset whitespace-nowrap tabular-nums text-right max-small:ml-auto`,children:A(e.resetsAt,e.recurring)})]})]},`${e.kind??e.label}:${e.resetsAt??`none`}:${t}`)}),C.pageCount>1&&(0,Z.jsxs)(`nav`,{"aria-label":`Quota windows for ${e.name}`,className:`quota-window-pagination mt-auto flex items-center justify-between gap-4 border-t border-inner-border pt-4 max-small:flex-wrap`,children:[(0,Z.jsxs)(`span`,{"aria-live":`polite`,className:`text-micro text-text-tertiary`,children:[`Showing `,C.startIndex+1,`–`,C.startIndex+C.items.length,` of `,S.length]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,"aria-label":`Previous quota windows for ${e.name}`,disabled:C.page===0,icon:(0,Z.jsx)(ie,{size:13}),onClick:()=>x(C.page-1),className:`h-14 px-4 py-0`,children:`Previous`}),(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,"aria-label":`Next quota windows for ${e.name}`,disabled:C.page>=C.pageCount-1,icon:(0,Z.jsx)(u,{size:13}),onClick:()=>x(C.page+1),className:`h-14 px-4 py-0`,children:`Next`})]})]})]}):Y?null:(0,Z.jsx)(`div`,{className:`border-t border-inner-border px-7 py-9 text-center text-badge text-text-tertiary`,children:E||e.pending?`Fetching quota…`:`No quota data`})]})}function ce(){let[e,t]=(0,X.useState)(`all`),[n,r]=(0,X.useState)(`all`),[i,a]=(0,X.useState)(!1),{data:o,isLoading:u,isError:p,error:m,isFetching:g,dataUpdatedAt:v,refetch:ee}=U(),y=(0,X.useMemo)(()=>[...o?.providers??[]].sort((e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`})),[o?.providers]),b=(0,X.useMemo)(()=>o?.accounts??[],[o?.accounts]),C=o?.refreshing??0,T=L(),ne=W(),D=V(),O=I(),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)(null),F=(0,X.useMemo)(()=>{let t=b.filter(t=>{if(e!==`all`&&t.provider!==e)return!1;let r=!!t.quota?.windows.length;return n===`untracked`?!r:!(!r||n===`active`&&!t.active||n===`disabled`&&t.active)}),r=(e,t)=>e.providerName.localeCompare(t.providerName,void 0,{sensitivity:`base`})||e.name.localeCompare(t.name,void 0,{sensitivity:`base`});return[...t].sort(i?(e,t)=>$(e)-$(t)||r(e,t):r)},[n,b,i,e]),R=async(e,t)=>{try{await ne.mutateAsync({id:e.id,active:t}),l.success(`${e.name} ${t?`enabled`:`disabled`}`)}catch(e){l.error(e instanceof Error?e.message:`Unable to update account`)}},z=async()=>{let e=b.filter(e=>e.active&&Q(e));await D.mutateAsync({ids:e.map(e=>e.id),active:!1}),l.success(`Disabled ${e.length} empty accounts`)},B=async()=>{let e=b.filter(e=>!e.active&&e.quota?.windows.some(e=>e.remainingPercent!==null&&e.remainingPercent>0));await D.mutateAsync({ids:e.map(e=>e.id),active:!0}),l.success(`Enabled ${e.length} available accounts`)},H=async e=>{await O.mutateAsync(e.id),l.success(`${e.name} deleted`)},G=v>0?new Date(v).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}):`Not updated`,K=b.filter(Q).length;return(0,Z.jsxs)(E,{gap:`16px`,className:`dashboard-page min-h-0 flex-1`,children:[(0,Z.jsx)(te,{children:(0,Z.jsxs)(S,{className:`flex flex-col gap-5`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-wrap items-center gap-4`,children:[(0,Z.jsx)(w,{"aria-label":`Filter quota by provider`,value:e,onValueChange:t,className:`w-full h-16 max-small:w-80`,options:[{value:`all`,label:`All Providers`},...y.map(e=>({value:e.id,label:e.name}))]}),(0,Z.jsx)(w,{"aria-label":`Filter quota by account`,value:n,onValueChange:r,className:`w-full h-16 max-small:w-67.5`,options:[{value:`all`,label:`With quota`},{value:`active`,label:`Active`},{value:`disabled`,label:`Disabled`},{value:`untracked`,label:`No quota`}]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4`,children:[(0,Z.jsx)(s,{variant:i?`secondary`:`ghost`,size:`sm`,onClick:()=>a(e=>!e),"aria-pressed":i,icon:(0,Z.jsx)(Y,{size:13}),children:`Expiring first`}),(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,className:`text-red`,disabled:K===0||g,onClick:()=>void z(),icon:(0,Z.jsx)(d,{size:13}),children:`Turn off Empty`}),(0,Z.jsx)(s,{variant:`ghost`,size:`sm`,className:`text-green`,disabled:g,onClick:()=>void B(),icon:(0,Z.jsx)(c,{size:13}),children:`Turn on Available`})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-4 border-t border-inner-border pt-5`,children:[(0,Z.jsxs)(`span`,{className:`text-badge text-text-tertiary`,children:[F.length,` shown`,K>0?` · ${K} empty`:``]}),(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-wrap items-center gap-x-5 gap-y-3 text-badge text-text-tertiary`,children:[C>0?`Refreshing ${C} account${C===1?``:`s`}…`:`Auto-refresh 60s · ${G}`,(0,Z.jsx)(oe,{accounts:b}),(0,Z.jsx)(s,{variant:`secondary`,size:`sm`,title:`Queue quota refresh`,"aria-label":`Queue quota refresh`,disabled:g||T.isPending||b.length===0,icon:(0,Z.jsx)(_,{size:13,className:T.isPending?`animate-spin`:void 0}),onClick:()=>T.mutate(b.map(e=>e.id),{onSuccess:e=>{l.success(e.failed===0?`Refreshed ${e.succeeded} quota${e.succeeded===1?``:`s`}`:`Refreshed ${e.succeeded}, ${e.failed} failed`)},onError:e=>l.error(e instanceof Error?e.message:`Unable to refresh quota`)}),children:`Refresh`})]})]})]})}),(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-6`,children:u?(0,Z.jsx)(f,{className:`min-h-0 flex flex-1 flex-col items-center justify-center`,kind:`loading`,title:`Loading quota data`,description:`Reading provider account limits…`}):p?(0,Z.jsx)(f,{className:`min-h-0 flex flex-1 flex-col items-center justify-center`,kind:`error`,title:`Unable to load quota data`,description:m instanceof Error?m.message:`Check the console session and retry.`,action:(0,Z.jsx)(s,{variant:`secondary`,onClick:()=>void ee(),children:`Retry`})}):F.length===0?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center p-12 border border-dashed border-transparent rounded-card bg-transparent text-center`,children:(0,Z.jsx)(h,{title:`No account quota data`,message:`Nothing is reporting a quota window yet. Add a provider account and its limits will appear here.`})}):(0,Z.jsx)(`div`,{className:`quota-account-grid scroll-region min-h-0 flex-1 gap-6 [align-content:start]`,children:F.map(e=>(0,Z.jsx)(se,{account:e,onToggle:(e,t)=>void R(e,t),onDelete:e=>A(e),onShowHealth:e=>M(e),onShowResets:e=>P(e)},e.id))})}),j&&(0,Z.jsx)(q,{summary:{providerId:j.provider,accountId:j.id,title:j.name,status:j.health?.status??`unknown`,errorCategory:j.health?.lastErrorCategory??void 0,errorMessage:j.health?.sanitizedMessage??void 0,emptyMessage:`Status transitions, rate limits, quota refreshes, check-ins, and auto-recoveries will appear here.`},onClose:()=>M(null)}),N&&(0,Z.jsx)(ae,{account:N,onClose:()=>P(null)}),(0,Z.jsx)(x,{open:k!==null,onClose:()=>A(null),onConfirm:async()=>{k&&await H(k)},title:`Delete account?`,message:`Delete "${k?.name}"? This cannot be undone.`,confirmLabel:`Delete`,danger:!0})]})}export{ce as default};