@bitkyc08/opencodex 2.100.5 → 2.100.6

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 (536) hide show
  1. package/README.md +1 -1
  2. package/bin/ocx.mjs +2 -0
  3. package/gui/dist/assets/App-BI8LQ7Qk.css +1 -0
  4. package/gui/dist/assets/App-CsZ1Gr7S.js +60 -0
  5. package/gui/dist/assets/Tray-CVqm4S4W.js +1 -0
  6. package/gui/dist/assets/brand-mark-BebhnAtV.js +1 -0
  7. package/gui/dist/assets/index-BtwVlpeQ.css +2 -0
  8. package/gui/dist/assets/index-CEeMegqE.js +138 -0
  9. package/gui/dist/assets/{segment-thumb-features-Bquysdn5.js → segment-thumb-features-COdzmORE.js} +1 -1
  10. package/gui/dist/classic/assets/App-BJgUWNJ8.js +59 -0
  11. package/gui/dist/classic/assets/App-CoiVLRW3.css +1 -0
  12. package/gui/dist/classic/assets/Tray-BDlcOLDK.js +1 -0
  13. package/gui/dist/classic/assets/index-B9Jgli_W.js +138 -0
  14. package/gui/dist/classic/assets/usage-companion-chart-vbzDcND0.js +1 -0
  15. package/gui/dist/classic/index.html +1 -1
  16. package/gui/dist/index.html +2 -2
  17. package/native/ocx-child/Cargo.lock +62 -0
  18. package/native/ocx-child/Cargo.toml +1 -0
  19. package/native/ocx-child/src/journal.rs +32 -10
  20. package/native/ocx-child/src/state.rs +2 -1
  21. package/native/ocx-child/src/toml_surgeon.rs +183 -72
  22. package/package.json +2 -2
  23. package/src/adapters/agy-acp/acp.ts +202 -0
  24. package/src/adapters/agy-acp/adapter.ts +554 -0
  25. package/src/adapters/agy-acp/binary.ts +79 -0
  26. package/src/adapters/agy-acp/options.ts +163 -0
  27. package/src/adapters/agy-acp/output-redaction.ts +270 -0
  28. package/src/adapters/agy-acp/policy.ts +105 -0
  29. package/src/adapters/agy-acp/process.ts +218 -0
  30. package/src/adapters/anthropic/account-metadata.ts +4 -1
  31. package/src/adapters/anthropic/advisor-tool.ts +43 -9
  32. package/src/adapters/anthropic/client-identity.ts +2 -0
  33. package/src/adapters/anthropic.ts +102 -14
  34. package/src/adapters/antigravity-refusal.ts +5 -1
  35. package/src/adapters/base.ts +25 -2
  36. package/src/adapters/claude-cli/adapter.ts +1 -0
  37. package/src/adapters/claude-cli/usage-admission.ts +12 -9
  38. package/src/adapters/codebuddy/adapter.ts +1 -0
  39. package/src/adapters/command-code.ts +2 -2
  40. package/src/adapters/cursor/http1-bidi.ts +7 -2
  41. package/src/adapters/cursor/live-transport.ts +2 -0
  42. package/src/adapters/cursor/request-builder.ts +4 -4
  43. package/src/adapters/cursor/tool-naming.ts +5 -5
  44. package/src/adapters/cursor/transport-retry.ts +14 -8
  45. package/src/adapters/cursor/transport.ts +2 -0
  46. package/src/adapters/cursor.ts +8 -2
  47. package/src/adapters/google-error-details.ts +105 -0
  48. package/src/adapters/google-errors.ts +183 -31
  49. package/src/adapters/google-http.ts +66 -22
  50. package/src/adapters/google-truncation.ts +48 -3
  51. package/src/adapters/google-vertex-endpoint.ts +12 -1
  52. package/src/adapters/google.ts +54 -26
  53. package/src/adapters/kiro/adapter.ts +39 -38
  54. package/src/adapters/kiro/stream.ts +59 -9
  55. package/src/adapters/kiro-retry.ts +5 -3
  56. package/src/adapters/m365-copilot/LICENSE +21 -0
  57. package/src/adapters/m365-copilot/fenced.ts +745 -0
  58. package/src/adapters/m365-copilot/images.ts +89 -0
  59. package/src/adapters/m365-copilot/tools.ts +284 -0
  60. package/src/adapters/m365-copilot/transport.ts +232 -0
  61. package/src/adapters/m365-copilot.ts +143 -0
  62. package/src/adapters/openai-chat/tool-schema.ts +2 -2
  63. package/src/adapters/openai-responses/passthrough.ts +1 -0
  64. package/src/adapters/openai-responses/reasoning.ts +23 -3
  65. package/src/adapters/physical-send.ts +11 -4
  66. package/src/adapters/qoder/adapter.ts +17 -3
  67. package/src/adapters/registry.ts +15 -1
  68. package/src/adapters/zed.ts +2 -1
  69. package/src/advisor/consult.ts +1 -0
  70. package/src/bridge/response-json.ts +6 -2
  71. package/src/bridge/sse.ts +21 -9
  72. package/src/chat/inbound.ts +11 -8
  73. package/src/chat/outbound.ts +28 -7
  74. package/src/claude/context-windows.ts +32 -8
  75. package/src/claude/desktop-3p.ts +18 -14
  76. package/src/claude/desktop-picker-platform.ts +1 -1
  77. package/src/claude/desktop-picker.ts +3 -3
  78. package/src/claude/inbound-content-options.ts +11 -1
  79. package/src/claude/intercept/picker-ca-cleanup.ts +17 -5
  80. package/src/claude/intercept/picker-ca.ts +162 -27
  81. package/src/claude/intercept/picker-trust-linux.ts +411 -0
  82. package/src/claude/intercept/picker-trust.ts +35 -3
  83. package/src/claude/intercept/runtime.ts +2 -2
  84. package/src/claude/subagent-force-status.ts +24 -5
  85. package/src/claude/subscription-reserve.ts +87 -0
  86. package/src/cli/account-api.ts +3 -0
  87. package/src/cli/account-auth.ts +65 -11
  88. package/src/cli/account-extended.ts +1 -1
  89. package/src/cli/account-next-actions.ts +4 -1
  90. package/src/cli/account-policy-dto.ts +1 -1
  91. package/src/cli/account-policy.ts +6 -3
  92. package/src/cli/account-probe.ts +66 -0
  93. package/src/cli/account.ts +8 -2
  94. package/src/cli/capabilities-accounts.ts +8 -1
  95. package/src/cli/capabilities-agents-routing.ts +2 -2
  96. package/src/cli/capabilities-base.ts +4 -4
  97. package/src/cli/capabilities-integrations.ts +44 -4
  98. package/src/cli/capabilities-provider-models.ts +6 -0
  99. package/src/cli/claude-context-settings.ts +60 -0
  100. package/src/cli/claude-desktop.ts +2 -2
  101. package/src/cli/claude.ts +15 -7
  102. package/src/cli/client-start-fence.ts +64 -1
  103. package/src/cli/combo-result.ts +1 -0
  104. package/src/cli/combo-stats.ts +1 -1
  105. package/src/cli/combo.ts +19 -2
  106. package/src/cli/config-command.ts +21 -8
  107. package/src/cli/connect.ts +16 -0
  108. package/src/cli/cross-home-owner.ts +65 -18
  109. package/src/cli/dispatch.ts +4 -0
  110. package/src/cli/gateway-client-command.ts +128 -0
  111. package/src/cli/index.ts +98 -97
  112. package/src/cli/init.ts +20 -4
  113. package/src/cli/integrations.ts +23 -3
  114. package/src/cli/launcher-context.ts +12 -1
  115. package/src/cli/link.ts +24 -5
  116. package/src/cli/models-runtime-subcommands.ts +1 -0
  117. package/src/cli/models-runtime.ts +32 -0
  118. package/src/cli/start-owner-fence.ts +5 -2
  119. package/src/cli/status.ts +3 -3
  120. package/src/cli/stop-client-process.ts +51 -0
  121. package/src/cli/stop-restore.ts +383 -36
  122. package/src/cli/sync-command.ts +2 -2
  123. package/src/cli/uninstall-client-state.ts +7 -0
  124. package/src/client/connect.ts +72 -13
  125. package/src/client/hub-client.ts +38 -0
  126. package/src/client/hub-relay.ts +61 -36
  127. package/src/client/hub-session.ts +106 -0
  128. package/src/client/lifecycle-lock.ts +6 -1
  129. package/src/client/link-relay.ts +2 -1
  130. package/src/client/machine-listener.ts +60 -1
  131. package/src/client/runtime-restart.ts +1 -0
  132. package/src/client/runtime.ts +104 -34
  133. package/src/client/state.ts +11 -0
  134. package/src/client/stop-darwin-process.ts +73 -0
  135. package/src/client/stop-file-routing.ts +49 -0
  136. package/src/client/stop-native-handoff.ts +108 -0
  137. package/src/client/stop-routing.ts +41 -7
  138. package/src/client/stop-teardown-owner.ts +173 -0
  139. package/src/client/sync-runtime.ts +23 -4
  140. package/src/clients/config-export/opencode-wire.ts +24 -0
  141. package/src/clients/config-export.ts +28 -19
  142. package/src/codex/auth-api/login-flow.ts +68 -33
  143. package/src/codex/auth-api/main-account-probe.ts +3 -3
  144. package/src/codex/auth-api/pool-quota-probe.ts +8 -7
  145. package/src/codex/auth-api/routes.ts +1 -1
  146. package/src/codex/catalog/aggregation.ts +22 -10
  147. package/src/codex/catalog/gather-capture.ts +11 -2
  148. package/src/codex/catalog/m365-copilot-models.ts +52 -0
  149. package/src/codex/catalog/provider-models.ts +126 -53
  150. package/src/codex/catalog/routed-gather.ts +26 -12
  151. package/src/codex/catalog-admission.ts +4 -6
  152. package/src/codex/catalog-auto-refresh.ts +4 -2
  153. package/src/codex/catalog-self-heal.ts +4 -2
  154. package/src/codex/control-plane-models.ts +6 -0
  155. package/src/codex/convergence.ts +10 -0
  156. package/src/codex/desktop-app/picker-freshness.ts +3 -14
  157. package/src/codex/desktop-app/types.ts +6 -0
  158. package/src/codex/desktop-app/windows-command-payload.ts +9 -0
  159. package/src/codex/desktop-app/windows.ts +20 -12
  160. package/src/codex/desktop-compatibility/installed-build.ts +61 -58
  161. package/src/codex/desktop-compatibility/runtime-ownership.ts +11 -5
  162. package/src/codex/desktop-compatibility/runtime.ts +51 -14
  163. package/src/codex/desktop-compatibility/windows-activation-source.ts +28 -13
  164. package/src/codex/desktop-compatibility/windows-package-command.ts +73 -33
  165. package/src/codex/desktop-compatibility/windows-package-launch.ts +41 -9
  166. package/src/codex/desktop-compatibility/windows-package-proof.ts +104 -0
  167. package/src/codex/inject/config-toml.ts +67 -73
  168. package/src/codex/inject/plan.ts +11 -10
  169. package/src/codex/inject/remove.ts +4 -1
  170. package/src/codex/inject.ts +1 -0
  171. package/src/codex/journal-config-restore.ts +31 -4
  172. package/src/codex/journal.ts +16 -4
  173. package/src/codex/model-cache.ts +98 -27
  174. package/src/codex/native-residue.ts +14 -13
  175. package/src/codex/paths.ts +65 -28
  176. package/src/codex/quota-observation-freshness.ts +4 -0
  177. package/src/codex/quota.ts +71 -8
  178. package/src/codex/routing/selection.ts +32 -8
  179. package/src/combos/capability-policy.ts +31 -0
  180. package/src/combos/failover.ts +82 -74
  181. package/src/combos/identifiers.ts +2 -2
  182. package/src/combos/index.ts +3 -0
  183. package/src/combos/jev-model-backend.ts +12 -4
  184. package/src/combos/jev-session-pin-config.ts +22 -9
  185. package/src/combos/jev.ts +15 -4
  186. package/src/combos/request-capability.ts +214 -0
  187. package/src/combos/request.ts +22 -15
  188. package/src/combos/resolve.ts +5 -2
  189. package/src/combos/suggestion-channel.ts +89 -0
  190. package/src/combos/types.ts +14 -1
  191. package/src/config/account-auto-pause-revisions.ts +33 -10
  192. package/src/config/atomic-write.ts +1 -1
  193. package/src/config/codex-ws-incremental-setting.ts +34 -0
  194. package/src/config/diagnostics.ts +47 -8
  195. package/src/config/live-topology.ts +4 -2
  196. package/src/config/load-degrade.ts +96 -2
  197. package/src/config/mutation-lock.ts +7 -3
  198. package/src/config/paths.ts +3 -0
  199. package/src/config/pending-teardown.ts +19 -3
  200. package/src/config/process-state.ts +30 -12
  201. package/src/config/provider-validation.ts +10 -0
  202. package/src/config/salvage.ts +2 -2
  203. package/src/config/schema/account-auto-pause.ts +15 -1
  204. package/src/config/schema/agy-acp-references.ts +257 -0
  205. package/src/config/schema/config-schema.ts +32 -0
  206. package/src/config/schema/leaf-validators.ts +42 -0
  207. package/src/config/schema/subscription-reserve.ts +33 -0
  208. package/src/config/windows-process-command-line.ts +27 -9
  209. package/src/config.ts +6 -0
  210. package/src/generated/compatibility-version.json +806 -402
  211. package/src/images/loop.ts +79 -39
  212. package/src/integrations/catalog-refresh.ts +19 -1
  213. package/src/integrations/gateway-clients/agy.ts +340 -0
  214. package/src/integrations/gateway-clients/antigravity.ts +224 -0
  215. package/src/integrations/gateway-clients/index.ts +89 -0
  216. package/src/integrations/gateway-clients/io.ts +278 -0
  217. package/src/integrations/gateway-clients/types.ts +80 -0
  218. package/src/integrations/route-intent-disconnect.ts +37 -21
  219. package/src/lib/app-owned-memory-stores.ts +9 -0
  220. package/src/lib/cloud-code-appeal-link.ts +30 -0
  221. package/src/lib/errors.ts +32 -0
  222. package/src/lib/executor-physical-send-receipt.ts +42 -0
  223. package/src/lib/failure-detail.ts +1 -0
  224. package/src/lib/gcp-adc.ts +5 -0
  225. package/src/lib/http-date.ts +91 -0
  226. package/src/lib/lab-passive-linker-registration.ts +2 -1
  227. package/src/lib/local-chat-completion.ts +13 -3
  228. package/src/lib/local-internal-call-capability.ts +1 -3
  229. package/src/lib/messages-error-body.ts +2 -1
  230. package/src/lib/outbound-credential-registry.ts +40 -4
  231. package/src/lib/pinned-http.ts +7 -2
  232. package/src/lib/process-control.ts +1 -0
  233. package/src/lib/provider-egress.ts +16 -0
  234. package/src/lib/provider-outbound.ts +3 -0
  235. package/src/lib/redact-folding.ts +12 -3
  236. package/src/lib/redact.ts +37 -19
  237. package/src/lib/request-execution-budget.ts +241 -32
  238. package/src/lib/request-peer-scope.ts +64 -0
  239. package/src/lib/response-send-readings.ts +41 -0
  240. package/src/lib/state-store-registrations.ts +5 -0
  241. package/src/lib/tool-envelope-echo-filter.ts +33 -5
  242. package/src/lib/upstream-condition.ts +10 -3
  243. package/src/lib/upstream-retry.ts +95 -20
  244. package/src/lib/windows-secret-acl.ts +24 -7
  245. package/src/link/child-activity.ts +60 -4
  246. package/src/link/codex-settings.ts +2 -1
  247. package/src/link/relay-auth.ts +1 -0
  248. package/src/link/route-rounds.ts +32 -9
  249. package/src/link/status-projection.ts +42 -5
  250. package/src/link/supervisor.ts +96 -11
  251. package/src/link/tunnel-history.ts +5 -0
  252. package/src/oauth/account-auto-pause-policy.ts +72 -19
  253. package/src/oauth/account-auto-pause.ts +40 -16
  254. package/src/oauth/anthropic-account-refusal.ts +7 -0
  255. package/src/oauth/anthropic-continuity.ts +70 -9
  256. package/src/oauth/anthropic-identity.ts +75 -11
  257. package/src/oauth/anthropic-login-slot.ts +258 -0
  258. package/src/oauth/anthropic-routing.ts +24 -9
  259. package/src/oauth/anthropic-send-ownership.ts +4 -3
  260. package/src/oauth/anthropic.ts +30 -11
  261. package/src/oauth/health.ts +7 -2
  262. package/src/oauth/index.ts +50 -48
  263. package/src/oauth/key-providers.ts +2 -0
  264. package/src/oauth/login-cli.ts +11 -0
  265. package/src/oauth/login-flow-state.ts +10 -4
  266. package/src/oauth/m365-copilot-browser.ts +222 -0
  267. package/src/oauth/m365-copilot-web-session.ts +25 -0
  268. package/src/oauth/m365-copilot.ts +57 -0
  269. package/src/oauth/model-discovery-auth.ts +5 -0
  270. package/src/oauth/plan.ts +44 -0
  271. package/src/oauth/pool-kernel.ts +22 -8
  272. package/src/oauth/pool-settings-capability.ts +14 -3
  273. package/src/oauth/reauth-precheck.ts +27 -0
  274. package/src/oauth/store-anthropic-instance.ts +3 -1
  275. package/src/oauth/store.ts +121 -23
  276. package/src/oauth/types.ts +27 -2
  277. package/src/protocols/codecs/chat-ir.ts +7 -4
  278. package/src/protocols/codecs/gemini-interactions.ts +770 -0
  279. package/src/protocols/codecs/gemini.ts +470 -0
  280. package/src/protocols/contract.ts +2 -0
  281. package/src/protocols/encoders/adapter-events.ts +5 -3
  282. package/src/protocols/encoders/chat.ts +23 -7
  283. package/src/protocols/settings.ts +3 -0
  284. package/src/providers/account-quota-disk.ts +26 -8
  285. package/src/providers/api-key-pause.ts +2 -2
  286. package/src/providers/api-key-response-ownership.ts +14 -4
  287. package/src/providers/claude-cli-usage-state.ts +1 -0
  288. package/src/providers/claude-cli-usage.ts +24 -7
  289. package/src/providers/default-aliases.ts +11 -5
  290. package/src/providers/derive.ts +5 -1
  291. package/src/providers/fastwire.ts +6 -5
  292. package/src/providers/free-directory.ts +2 -2
  293. package/src/providers/google-vertex-location.ts +2 -1
  294. package/src/providers/google-vertex-model-discovery.ts +22 -0
  295. package/src/providers/key-failover.ts +18 -23
  296. package/src/providers/m365-copilot-discovery-fetch.ts +17 -0
  297. package/src/providers/m365-copilot-discovery.ts +68 -0
  298. package/src/providers/m365-copilot-models.ts +32 -0
  299. package/src/providers/model-rename-fields.ts +6 -0
  300. package/src/providers/new-model-policy-runtime.ts +27 -6
  301. package/src/providers/openai-forward-destination.ts +19 -0
  302. package/src/providers/openai-tiers-destination.ts +3 -19
  303. package/src/providers/quota/account-cache.ts +183 -27
  304. package/src/providers/quota/anthropic-account-quota.ts +21 -17
  305. package/src/providers/quota/anthropic-cooldown-recovery.ts +57 -27
  306. package/src/providers/quota/anthropic-decision-windows.ts +7 -3
  307. package/src/providers/quota/anthropic-usage-windows.ts +34 -4
  308. package/src/providers/quota/antigravity-account-probe.ts +165 -0
  309. package/src/providers/quota/antigravity.ts +71 -3
  310. package/src/providers/quota/vendor-probes-oauth.ts +52 -28
  311. package/src/providers/quota-decision-publication.ts +1 -1
  312. package/src/providers/quota-decision-snapshot.ts +4 -1
  313. package/src/providers/quota-types.ts +2 -0
  314. package/src/providers/quota.ts +8 -7
  315. package/src/providers/registry/agy-acp-models.ts +3 -0
  316. package/src/providers/registry/entries-core.ts +9 -0
  317. package/src/providers/registry/entries-extended.ts +60 -0
  318. package/src/providers/registry/model-seeds.ts +51 -0
  319. package/src/providers/request-pacing.ts +37 -7
  320. package/src/providers/service-tier.ts +2 -0
  321. package/src/providers/xai-privacy-mode.ts +52 -0
  322. package/src/remote/hub-management-relay.ts +74 -0
  323. package/src/responses/id-limits.ts +2 -0
  324. package/src/responses/input-media.ts +15 -3
  325. package/src/responses/parser-tools.ts +74 -11
  326. package/src/responses/parser.ts +16 -14
  327. package/src/responses/provider-opaque-metadata.ts +10 -0
  328. package/src/responses/reasoning-envelope.ts +3 -0
  329. package/src/responses/schema.ts +2 -3
  330. package/src/responses/spill-store.ts +5 -3
  331. package/src/responses/state/connection-scope.ts +232 -0
  332. package/src/responses/state/entry-types.ts +47 -0
  333. package/src/responses/state/snapshot-codec.ts +75 -14
  334. package/src/responses/state/snapshot-select.ts +2 -0
  335. package/src/responses/state/spill-codec.ts +59 -0
  336. package/src/responses/state/spill-queue.ts +11 -2
  337. package/src/responses/state.ts +178 -159
  338. package/src/router.ts +2 -6
  339. package/src/routing/compatibility/behavior.ts +6 -2
  340. package/src/routing/compatibility/subject.ts +17 -12
  341. package/src/routing/machine-weighted-routing.ts +58 -0
  342. package/src/server/advisor-admission-scope.ts +15 -7
  343. package/src/server/auth-cors.ts +27 -0
  344. package/src/server/chat-completions.ts +37 -17
  345. package/src/server/chat-native-eligibility.ts +21 -0
  346. package/src/server/chat-native.ts +15 -6
  347. package/src/server/claude-messages.ts +54 -6
  348. package/src/server/credential-recovery-attempt.ts +32 -0
  349. package/src/server/effort-policy.ts +6 -3
  350. package/src/server/gemini-inbound.ts +267 -0
  351. package/src/server/gemini-interactions-inbound.ts +229 -0
  352. package/src/server/gemini-interactions-store.ts +129 -0
  353. package/src/server/gemini-native-catalog.ts +64 -0
  354. package/src/server/gemini-native-log.ts +33 -0
  355. package/src/server/gemini-native-paths.ts +88 -0
  356. package/src/server/gemini-native-wire.ts +201 -0
  357. package/src/server/gemini-native.ts +218 -0
  358. package/src/server/grok-upstream-envelope-echo.ts +8 -2
  359. package/src/server/hub-relay-auth.ts +87 -0
  360. package/src/server/hub-usage-windows.ts +135 -0
  361. package/src/server/hub-usage.ts +16 -3
  362. package/src/server/inbound-body-admission.ts +2 -1
  363. package/src/server/index/anthropic-model-listing.ts +75 -0
  364. package/src/server/index/gemini-routes.ts +147 -0
  365. package/src/server/index/link-management.ts +3 -22
  366. package/src/server/index/link-relay-sessions.ts +71 -13
  367. package/src/server/index/link-websocket.ts +2 -0
  368. package/src/server/index/passive-management-read.ts +55 -0
  369. package/src/server/index/serve-options.ts +93 -107
  370. package/src/server/index/websocket-handler.ts +15 -2
  371. package/src/server/index.ts +10 -0
  372. package/src/server/inference/client-encoder-delivery.ts +2 -1
  373. package/src/server/inference/context.ts +33 -6
  374. package/src/server/management/agent-settings-routes.ts +33 -16
  375. package/src/server/management/claude-code-settings-patch.ts +6 -0
  376. package/src/server/management/combo-routes.ts +21 -1
  377. package/src/server/management/combo-suggestion-routes.ts +212 -0
  378. package/src/server/management/config-routes.ts +12 -4
  379. package/src/server/management/context.ts +2 -0
  380. package/src/server/management/gateway-client-routes.ts +62 -0
  381. package/src/server/management/integration-routes.ts +5 -0
  382. package/src/server/management/link-routes.ts +5 -1
  383. package/src/server/management/m365-copilot-provider-probe.ts +23 -0
  384. package/src/server/management/model-routes.ts +32 -2
  385. package/src/server/management/model-rows.ts +36 -3
  386. package/src/server/management/oauth-account-routes.ts +68 -15
  387. package/src/server/management/protocol-settings-patch.ts +1 -0
  388. package/src/server/management/provider-omitted-fields.ts +25 -0
  389. package/src/server/management/provider-overwrite-carry.ts +33 -8
  390. package/src/server/management/provider-routes.ts +10 -16
  391. package/src/server/management/request-history-routes.ts +2 -2
  392. package/src/server/management/route-registry.ts +10 -0
  393. package/src/server/management/shared.ts +118 -30
  394. package/src/server/management/sibling-guard.ts +2 -1
  395. package/src/server/management/system-routes.ts +6 -0
  396. package/src/server/management-auth.ts +8 -1
  397. package/src/server/messages-native-scope.ts +19 -0
  398. package/src/server/messages-native.ts +156 -59
  399. package/src/server/messages-shared.ts +6 -0
  400. package/src/server/models-capabilities.ts +24 -0
  401. package/src/server/native-chat-bridge.ts +259 -0
  402. package/src/server/ollama-inbound.ts +36 -184
  403. package/src/server/passive-route-linker.ts +3 -1
  404. package/src/server/port-reclaim.ts +48 -4
  405. package/src/server/proxy-liveness.ts +79 -22
  406. package/src/server/relay.ts +16 -9
  407. package/src/server/request-log-account-rotation.ts +2 -1
  408. package/src/server/request-log-attempt-recovery.ts +24 -2
  409. package/src/server/request-log-attempt-usage.ts +5 -4
  410. package/src/server/request-log-committed-terminal.ts +87 -0
  411. package/src/server/request-log-failure-attribution.ts +3 -3
  412. package/src/server/request-log-failure-detail.ts +34 -0
  413. package/src/server/request-log-key-failure.ts +27 -0
  414. package/src/server/request-log-terminal-status.ts +25 -12
  415. package/src/server/request-log.ts +59 -63
  416. package/src/server/responses/adapter-continuation.ts +77 -44
  417. package/src/server/responses/adapter-delivery.ts +47 -22
  418. package/src/server/responses/adapter-dispatch.ts +150 -149
  419. package/src/server/responses/advisor-retention.ts +12 -4
  420. package/src/server/responses/advisor-slot.ts +97 -2
  421. package/src/server/responses/agent-task-recovery.ts +44 -11
  422. package/src/server/responses/agy-acp-preflight.ts +41 -0
  423. package/src/server/responses/anthropic-image-context.ts +44 -0
  424. package/src/server/responses/antigravity-validation-refusal.ts +25 -1
  425. package/src/server/responses/buffered-sse-json.ts +18 -1
  426. package/src/server/responses/codex-ws-correlation.ts +5 -2
  427. package/src/server/responses/codex-ws-exchange.ts +91 -8
  428. package/src/server/responses/codex-ws-incremental.ts +136 -0
  429. package/src/server/responses/codex-ws-pool.ts +22 -8
  430. package/src/server/responses/codex-ws-request.ts +5 -0
  431. package/src/server/responses/codex-ws-send-accounting.ts +8 -0
  432. package/src/server/responses/codex-ws-session.ts +14 -0
  433. package/src/server/responses/codex-ws-wire.ts +44 -22
  434. package/src/server/responses/combo-admission-snapshot.ts +93 -0
  435. package/src/server/responses/combo-required-tool-stream.ts +16 -4
  436. package/src/server/responses/combo-selection-keepalive.ts +5 -0
  437. package/src/server/responses/combo-stream-preflight.ts +182 -73
  438. package/src/server/responses/compact-response-body.ts +27 -0
  439. package/src/server/responses/compact.ts +174 -121
  440. package/src/server/responses/compaction-recovery.ts +7 -0
  441. package/src/server/responses/core-codex-account.ts +88 -62
  442. package/src/server/responses/core-combo-failure.ts +15 -0
  443. package/src/server/responses/core-combo-native.ts +12 -1
  444. package/src/server/responses/core-combo.ts +340 -94
  445. package/src/server/responses/core-normalize.ts +19 -12
  446. package/src/server/responses/core-opaque-recovery.ts +15 -4
  447. package/src/server/responses/core-options.ts +50 -5
  448. package/src/server/responses/core-pipeline.ts +11 -0
  449. package/src/server/responses/core.ts +7 -1
  450. package/src/server/responses/empty-completion-guard.ts +21 -7
  451. package/src/server/responses/estimated-usage.ts +2 -1
  452. package/src/server/responses/fetch-helpers.ts +95 -19
  453. package/src/server/responses/history-slim.ts +204 -0
  454. package/src/server/responses/hosted-advisor-spend.ts +49 -0
  455. package/src/server/responses/image-context-recovery.ts +199 -0
  456. package/src/server/responses/input-admission.ts +36 -11
  457. package/src/server/responses/jev-model-invoke.ts +23 -16
  458. package/src/server/responses/non-replayable-error.ts +12 -2
  459. package/src/server/responses/passthrough-build-error.ts +5 -3
  460. package/src/server/responses/passthrough-delivery.ts +74 -33
  461. package/src/server/responses/passthrough-dispatch.ts +170 -197
  462. package/src/server/responses/policy-fallback.ts +7 -2
  463. package/src/server/responses/policy-request-scope.ts +36 -2
  464. package/src/server/responses/replay-owner.ts +20 -0
  465. package/src/server/responses/request-prepare.ts +97 -16
  466. package/src/server/responses/request-send-budget.ts +97 -25
  467. package/src/server/responses/request-sidecar-auth.ts +138 -65
  468. package/src/server/responses/request-spend-target.ts +13 -1
  469. package/src/server/responses/request-spend.ts +228 -47
  470. package/src/server/responses/request-transport.ts +395 -70
  471. package/src/server/responses/run-turn-execution.ts +40 -9
  472. package/src/server/responses/sidecar-execution.ts +214 -67
  473. package/src/server/responses/sidecar-send-budget.ts +9 -9
  474. package/src/server/responses/terminal-guard.ts +35 -9
  475. package/src/server/responses/ws-upstream.ts +27 -6
  476. package/src/server/responses-phase-inference.ts +32 -9
  477. package/src/server/responses-terminal-repair.ts +14 -35
  478. package/src/server/system-env.ts +8 -5
  479. package/src/server/ws-bridge.ts +23 -17
  480. package/src/service/health-sentinel-linux.ts +16 -7
  481. package/src/service/systemd.ts +11 -2
  482. package/src/service/windows-checked-stop-live.ts +60 -55
  483. package/src/service/windows-checked-stop.ts +29 -11
  484. package/src/service/windows-guarded-manager.ts +14 -26
  485. package/src/service/windows-process-evidence.ts +82 -74
  486. package/src/service/windows-process-native.ts +69 -20
  487. package/src/service/windows-service-stop.ts +14 -12
  488. package/src/service/windows-stop-binding.ts +14 -5
  489. package/src/service/windows-stop-confirm.ts +1 -1
  490. package/src/service/windows-task-instance-stop.ts +98 -0
  491. package/src/service/windows-taskxml.ts +30 -7
  492. package/src/sidecar/anthropic-binding.ts +1 -1
  493. package/src/stall-timeout.ts +30 -0
  494. package/src/telemetry/aggregate.ts +6 -3
  495. package/src/types/account-auto-pause.ts +19 -1
  496. package/src/types/accounts.ts +21 -0
  497. package/src/types/anthropic-account-pool.ts +1 -1
  498. package/src/types/combo-capability-policy.ts +19 -0
  499. package/src/types/config.ts +22 -2
  500. package/src/types/provider.ts +42 -8
  501. package/src/types/request.ts +15 -0
  502. package/src/types/tools.ts +22 -5
  503. package/src/types/wire.ts +1 -0
  504. package/src/types.ts +4 -0
  505. package/src/update/check-types.ts +2 -0
  506. package/src/update/job.ts +8 -3
  507. package/src/update/managed-release.ts +6 -0
  508. package/src/update/orchestrated-entry.ts +13 -4
  509. package/src/update/refresh-scheduler.ts +17 -7
  510. package/src/usage/attempt-delivery.ts +6 -0
  511. package/src/usage/cache-provenance.ts +71 -0
  512. package/src/usage/cost.ts +216 -27
  513. package/src/usage/credit-billing.ts +88 -0
  514. package/src/usage/jev-stats.ts +13 -9
  515. package/src/usage/log.ts +5 -33
  516. package/src/usage/summary.ts +8 -43
  517. package/src/usage/user-cost-overlays.ts +13 -1
  518. package/src/vision/index.ts +8 -3
  519. package/src/vision/plan.ts +28 -14
  520. package/src/vision/routed-describe.ts +24 -36
  521. package/src/web-search/header-deadline.ts +14 -3
  522. package/src/web-search/index.ts +6 -4
  523. package/src/web-search/loop.ts +240 -78
  524. package/src/web-search/progress-stream.ts +29 -2
  525. package/src/web-search/run-turn-loop.ts +5 -1
  526. package/gui/dist/assets/App-BGP8I0V4.css +0 -1
  527. package/gui/dist/assets/App-BRExzhwL.js +0 -60
  528. package/gui/dist/assets/Tray-DHCWAn8V.js +0 -1
  529. package/gui/dist/assets/brand-mark-C70PuQ3j.js +0 -1
  530. package/gui/dist/assets/index-DJxM-imn.css +0 -2
  531. package/gui/dist/assets/index-Dy1jIGty.js +0 -138
  532. package/gui/dist/classic/assets/App-B4j-Txmb.css +0 -1
  533. package/gui/dist/classic/assets/App-CaC-E6Vl.js +0 -59
  534. package/gui/dist/classic/assets/Tray-BG253fiL.js +0 -1
  535. package/gui/dist/classic/assets/index-CR_AThOp.js +0 -138
  536. package/gui/dist/classic/assets/quota-summary-B7KQPpEC.js +0 -1
@@ -1,60 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/segment-thumb-features-Bquysdn5.js","assets/index-Dy1jIGty.js","assets/index-DJxM-imn.css"])))=>i.map(i=>d[i]);
2
- import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as m,P as h,Q as g,R as _,S as v,T as y,U as b,V as x,W as S,X as C,Y as w,Z as T,_ as E,a as D,b as O,c as k,d as A,f as j,g as M,h as N,i as P,j as F,k as I,l as L,m as R,n as z,o as B,p as V,q as H,r as U,s as W,t as ee,u as G,v as te,w as ne,x as K,y as q,z as J}from"./index-Dy1jIGty.js";import{$ as re,A as Y,At as ie,B as ae,Bt as oe,C as se,Ct as ce,D as le,Dt as ue,E as de,Et as fe,F as pe,Ft as me,G as he,Gt as ge,H as _e,Ht as ve,I as ye,It as be,J as xe,Jt as Se,K as Ce,Kt as we,L as Te,Lt as Ee,M as De,Mt as Oe,N as ke,Nt as Ae,O as je,Ot as Me,P as Ne,Pt as Pe,Q as Fe,Qt as Ie,R as Le,Rt as Re,S as ze,St as Be,T as Ve,Tt as He,U as Ue,Ut as We,V as Ge,Vt as Ke,W as qe,Wt as Je,X as Ye,Xt as Xe,Y as Ze,Yt as Qe,Z as $e,Zt as et,_ as tt,_t as nt,at as rt,b as it,bt as at,ct as ot,dt as st,et as ct,ft as lt,g as ut,gt as dt,h as ft,ht as pt,it as X,j as mt,jt as ht,k as gt,kt as _t,lt as vt,mt as yt,n as bt,nt as xt,ot as St,pt as Ct,q as wt,qt as Tt,r as Et,rt as Dt,st as Ot,t as kt,tt as At,ut as jt,v as Mt,vt as Nt,w as Pt,wt as Ft,x as It,xt as Lt,y as Rt,yt as zt,z as Bt,zt as Vt}from"./brand-mark-C70PuQ3j.js";var Z=g(C(),1);function Ht(){return typeof document<`u`&&document.visibilityState===`hidden`||typeof window<`u`&&window.__OPENCODEX_HOST_VISIBLE__===!1}function Ut(e){let t=Ht(),n=()=>{let n=Ht();n!==t&&(t=n,e())},r=e=>{let t=e.detail;typeof window<`u`&&typeof t==`boolean`&&(window.__OPENCODEX_HOST_VISIBLE__=t),n()};return typeof document<`u`&&document.addEventListener(`visibilitychange`,n),typeof window<`u`&&window.addEventListener(`opencodex:host-visibility`,r),()=>{typeof document<`u`&&document.removeEventListener(`visibilitychange`,n),typeof window<`u`&&window.removeEventListener(`opencodex:host-visibility`,r)}}var Wt=new Map,Gt=new Set,Kt=3e4,qt=`ocx-resource-deadline`,Jt={data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1};function Yt(e){let t=Wt.get(e);return t||(t={key:e,snapshot:{data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1},listeners:new Set,pollByListener:new Map,pauseWhenHiddenByListener:new Map,fetcherByListener:new Map,deadlineByListener:new Map,subscriberCount:0,pollIntervalMs:void 0,inflight:null,inflightOwner:null,generation:0,seedNeedsRevalidate:!1,lastSettledAt:void 0},Wt.set(e,t)),t}function Xt(e){for(let t of e.listeners)t()}var Zt=new Map;function Qt(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0&&e.pauseWhenHiddenByListener.get(t)===!1)return!0;return!1}function $t(e){if(e.stores.size===0)return!1;if(!on())return!0;for(let t of e.stores)if(Qt(t))return!0;return!1}function en(e){for(let t of e.stores){let e=sn(t);e&&pn(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}function tn(e,t){let n=$t(t);n&&t.timer===null?t.timer=setInterval(()=>en(t),e):(!n&&t.timer!==null&&(clearInterval(t.timer),t.timer=null),t.stores.size===0&&Zt.delete(e))}function nn(){for(let[e,t]of[...Zt])tn(e,t)}function rn(e){let t=e.pollIntervalMs;if(t===void 0)return;let n=Zt.get(t);e.pollIntervalMs=void 0,n&&(n.stores.delete(e),tn(t,n))}function an(e,t){let n=Zt.get(t);n||(n={timer:null,stores:new Set},Zt.set(t,n)),n.stores.add(e),e.pollIntervalMs=t,tn(t,n)}function on(){return Ht()}function sn(e){if(!on())return cn(e);for(let[t,n]of e.pollByListener)if(!(typeof n!=`number`||n<=0)&&e.pauseWhenHiddenByListener.get(t)===!1){let n=e.fetcherByListener.get(t);if(n)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)}}return null}function cn(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0){let n=e.fetcherByListener.get(t);if(n)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)}}for(let[t,n]of e.fetcherByListener)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)};return null}function ln(e){let t;for(let n of e.pollByListener.values())typeof n==`number`&&n>0&&(t=t===void 0?n:Math.min(t,n));if(t===void 0)rn(e),fn(e);else if(t===e.pollIntervalMs){let n=Zt.get(t);n&&tn(t,n),dn(e)}else rn(e),an(e,t),dn(e)}var un=null;function dn(e){typeof document>`u`||un||(un=Ut(()=>{if(nn(),!on())for(let e of Zt.values())for(let t of e.stores){let e=cn(t);e&&pn(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}))}function fn(e){un&&(Zt.size>0||(un(),un=null))}async function pn(e,t,n){let r=n?.replaceInflight!==!1;if(e.inflight&&!r)return;r&&e.inflight?.abort();let i=new AbortController;e.inflight=i,e.inflightOwner=n?.owner??null;let a=++e.generation,o=n?.deadlineMs??Kt,s=!1,c=setTimeout(()=>{s=!0,i.abort(qt)},o),l=e.snapshot.data===void 0||n?.forceLoading===!0;e.snapshot={...e.snapshot,loading:l?!0:e.snapshot.loading,refreshing:!0},Xt(e);try{let n=await Promise.race([t(i.signal),new Promise((e,t)=>{i.signal.addEventListener(`abort`,()=>{s?t(Error(`resource request timed out after ${o}ms`)):e(null)},{once:!0})})]);if(a!==e.generation||i.signal.aborted)return;e.seedNeedsRevalidate=!1,Gt.delete(e.key),e.lastSettledAt=Date.now(),e.snapshot={data:n,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!0,lastAttemptOk:!0}}catch(t){if(a!==e.generation||i.signal.aborted&&!s)return;e.seedNeedsRevalidate=!1,e.snapshot={...e.snapshot,error:t===void 0?Error(`resource load failed`):t,loading:!1,refreshing:!1,lastAttemptOk:!1}}finally{clearTimeout(c),e.inflight===i&&(e.inflight=null,e.inflightOwner=null),Xt(e)}}function mn(e,t){return e.inflightOwner===t&&(e.inflight?.abort(),e.inflight=null,e.inflightOwner=null,e.generation++,e.snapshot.refreshing&&(e.snapshot={...e.snapshot,refreshing:!1},Xt(e)),!0)}function hn(e,t){rn(t),fn(t),setTimeout(()=>{t.subscriberCount===0&&Wt.get(e)===t&&(t.inflight?.abort(),t.inflight=null,t.inflightOwner=null,Wt.delete(e))},0)}function gn(e,t,n){let{fetcher:r,pollMs:i,pauseWhenHidden:a=!0,deadlineMs:o,staleAfterMs:s}=n,c=Yt(e);if(c.listeners.add(t),c.pollByListener.set(t,i),c.pauseWhenHiddenByListener.set(t,a),c.fetcherByListener.set(t,r),c.deadlineByListener.set(t,o),c.subscriberCount++,c.subscriberCount===1){let n=typeof s==`number`&&c.lastSettledAt!==void 0&&Date.now()-c.lastSettledAt>s;(c.snapshot.data===void 0||c.seedNeedsRevalidate||Gt.has(e)||n)&&pn(c,r,{replaceInflight:!0,owner:t,deadlineMs:o})}return ln(c),()=>{c.listeners.delete(t),c.pollByListener.delete(t),c.pauseWhenHiddenByListener.delete(t),c.fetcherByListener.delete(t),c.deadlineByListener.delete(t),c.subscriberCount--;let n=mn(c,t);if(c.subscriberCount===0)hn(e,c);else{if(n){let e=cn(c);e&&pn(c,e.fetcher,{replaceInflight:!0,owner:e.owner,deadlineMs:e.deadlineMs})}ln(c)}}}function _n(e,t,n,r){let i=Yt(e);i.subscriberCount===0&&i.snapshot.data===void 0&&(Sn(e,t),!Gt.has(e)&&typeof r==`number`&&typeof n==`number`&&Date.now()-n<r&&(i.seedNeedsRevalidate=!1,i.lastSettledAt=n))}function vn(e,t,n){let r=n?.enabled!==!1,i=n?.pollMs,a=n?.pauseWhenHidden!==!1,o=n?.deadlineMs,s=n?.staleAfterMs;r&&n?.initialData!==void 0&&_n(e,n.initialData,n.initialDataCachedAt,s);let c=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{c.current=t});let l=(0,Z.useCallback)(e=>c.current(e),[]),u=(0,Z.useRef)(null),d=(0,Z.useCallback)(t=>r?(u.current=t,gn(e,t,{fetcher:l,pollMs:i,pauseWhenHidden:a,deadlineMs:o,staleAfterMs:s})):()=>{},[e,l,i,r,a,o,s]),f=(0,Z.useCallback)(()=>r?Yt(e).snapshot:Jt,[e,r]),p=(0,Z.useSyncExternalStore)(d,f,f),m=(0,Z.useCallback)(t=>{if(!r)return;let n=Yt(e);pn(n,l,{replaceInflight:!0,owner:u.current,forceLoading:t?.forceLoading,deadlineMs:u.current?n.deadlineByListener.get(u.current):o})},[e,l,r,o]);return{...p,refresh:m}}function yn(e,t){if(e===null)return!1;if(e.length!==t.length)return!0;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!0;return!1}function bn(e,t,n,r){let i=vn(e,n,r),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let n=a.current,r=o.current;a.current=t,o.current=e,yn(n,t)&&(r===null||r===e)&&i.refresh({forceLoading:!0})}),i}function xn(e){Gt.add(e);let t=Wt.get(e);if(!t)return;let n=cn(t);n&&pn(t,n.fetcher,{replaceInflight:!0,owner:n.owner,deadlineMs:n.deadlineMs})}function Sn(e,t){let n=Yt(e);n.inflight?.abort(),n.inflight=null,n.inflightOwner=null,n.generation++,n.snapshot={data:t,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!0,lastAttemptOk:!0},n.seedNeedsRevalidate=n.subscriberCount===0,n.lastSettledAt=Date.now(),Xt(n)}function Cn(e){return e.replace(/^#\/?/,``)}function wn(e){let t=e.indexOf(`?`);return t<0?{path:e,query:``}:{path:e.slice(0,t),query:e.slice(t+1)}}function Tn(e,t=window){let n=Cn(e);if(Cn(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function En(e,t=window){let n=Cn(e);Cn(t.location.hash)!==n&&(t.location.hash=n)}var Dn=w(),On=4,kn=8,An=8,jn=280,Mn=120,Nn=160,Pn=12;function Fn(){return typeof window<`u`?window.innerHeight:800}function In(){return typeof window<`u`?window.innerWidth:1024}function Ln(e,{align:t,placement:n=`below`,menuHeight:r=jn,maxMenuHeight:i=jn,menuWidth:a}={}){let o=Math.min(Math.max(r,Mn),i),s=Fn(),c=In();if(n===`right`){let t=s-e.top-An,n=e.top-An,r=o+kn>t&&n>t,a=Math.max(An,Math.min(e.right+Pn,c-Nn-An));return r?{position:`fixed`,left:a,bottom:s-e.top+kn,minWidth:Nn,maxHeight:Math.max(Mn,Math.min(i,e.top-An-On))}:{position:`fixed`,top:e.top,left:a,minWidth:Nn,maxHeight:Math.max(Mn,Math.min(i,s-e.top-An))}}let l=t??(e.right>c/2?`right`:`left`),u=Math.min(Math.max(a??e.width,0),Math.max(0,c-16)),d=s-e.bottom-An,f=e.top-An;if(o+On>d&&f>d){let t={position:`fixed`,bottom:s-e.top+kn,minWidth:u,maxHeight:Math.max(0,Math.min(i,f-On))};return l===`right`?t.right=Math.max(An,c-e.right):t.left=Math.max(An,Math.min(e.left,c-An-u)),t}let p={position:`fixed`,top:e.bottom+On,minWidth:u,maxHeight:Math.max(0,Math.min(i,d-On))};return l===`right`?p.right=Math.max(An,c-e.right):p.left=Math.max(An,Math.min(e.left,c-An-u)),p}var Q=U();function Rn({on:e,mixed:t,onClick:n,disabled:r,label:i,showLabel:a=!1,title:o}){let s=a&&!!i,c=t!==void 0;return(0,Q.jsxs)(`button`,{type:`button`,className:`switch${e?` on`:``}${t?` mixed`:``}${s?` switch-labeled`:``}`,onClick:n,disabled:r,role:c?void 0:`switch`,"aria-checked":c?void 0:e,"aria-pressed":c?t?`mixed`:e:void 0,"aria-label":s?void 0:i??(e?`enabled`:`disabled`),title:o,children:[(0,Q.jsx)(`span`,{className:`knob`}),s?(0,Q.jsx)(`span`,{className:`switch-labeled-text text-label muted`,children:i}):null]})}function $({tone:e,children:t}){return(0,Q.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,Q.jsx)(st,{}):(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{children:t})]})}function zn({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,Dn.createPortal)((0,Q.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,Q.jsxs)(`div`,{className:`toast-notice notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[e===`ok`?(0,Q.jsx)(st,{}):(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,Q.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function Bn(e){return e.textValue===void 0?typeof e.label==`string`||typeof e.label==`number`?String(e.label):e.value:e.textValue}function Vn({value:e,options:t,onChange:n,disabled:r,id:i,label:a,labelledBy:o,describedBy:s,invalid:c,title:l,style:u,align:d,placement:f,dropdownStyle:p,portal:m,className:h,triggerClassName:g,fullWidth:_,size:v,name:y,required:b}){let x=(0,Z.useId)(),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(),[O,k]=(0,Z.useState)(!1),A=m??!O,j=(0,Z.useRef)(null),M=(0,Z.useRef)(null),N=(0,Z.useRef)(null),P=(0,Z.useRef)({text:``,at:0}),F=(0,Z.useCallback)(e=>`${x}-${e}`,[x]),I=t.find(t=>t.value===e),L=t.length===0?0:Math.max(0,t.findIndex(t=>t.value===e)),R=!S||t.length===0?L:Math.min(w??L,t.length-1),z=(e,n,r=e)=>{for(let r=e;r>=0&&r<t.length;r+=n)if(!t[r]?.disabled)return r;return r},B=(0,Z.useCallback)((e=!1)=>{C(!1),T(null),e&&M.current?.focus()},[]),V=(0,Z.useCallback)(e=>{if(r||t.length===0)return;let n=Math.max(0,Math.min(t.length-1,e));k(!!M.current?.closest(`dialog`)),T(n),C(!0)},[r,t.length]),H=e=>{let n=Date.now(),r=P.current;r.text=n-r.at>700?e:r.text+e,r.at=n;let i=[...r.text].every(e=>e===r.text[0]),a=(i?r.text[0]:r.text).toLocaleLowerCase(),o=i?R+1:R;for(let e=0;e<t.length;e++){let n=(o+e)%t.length,r=t[n];if(!r.disabled&&Bn(r).toLocaleLowerCase().startsWith(a))return V(n),!0}return!1},U=(0,Z.useCallback)(e=>{if(!A)return;let t=M.current;t&&D(Ln(t.getBoundingClientRect(),{align:d,placement:f,menuHeight:e}))},[d,f,A]);(0,Z.useEffect)(()=>{if(!S)return;let e=e=>{let t=e.target;j.current?.contains(t)||N.current?.contains(t)||B()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[B,S]),(0,Z.useLayoutEffect)(()=>{if(!S||!A)return;U();let e=()=>U(N.current?.offsetHeight);return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[S,t.length,A,U]),(0,Z.useLayoutEffect)(()=>{if(!S||!A||!N.current||!M.current)return;let e=N.current.offsetHeight;if(!e)return;let t=Ln(M.current.getBoundingClientRect(),{align:d,placement:f,menuHeight:e});D(e=>e?.top===t.top&&e?.bottom===t.bottom&&e?.maxHeight===t.maxHeight?e:t)},[d,S,t.length,f,A]),(0,Z.useLayoutEffect)(()=>{S&&N.current&&N.current.querySelector(`[id="${F(R)}"]`)?.scrollIntoView({block:`nearest`})},[R,S,F]);let W=e=>{if(r)return;let i=t[e];i&&!i.disabled&&(n(i.value),B(!0))},ee=e=>{if(!r)switch(e.key){case`ArrowDown`:e.preventDefault(),V(S?z(Math.min(t.length-1,R+1),1,R):L);break;case`ArrowUp`:e.preventDefault(),V(S?z(Math.max(0,R-1),-1,R):L);break;case`Home`:e.preventDefault(),V(z(0,1));break;case`End`:e.preventDefault(),V(z(t.length-1,-1));break;case`Enter`:case` `:e.preventDefault(),S?W(R):V(L);break;case`Escape`:S&&(e.preventDefault(),B(!0));break;case`Tab`:if(S){let e=t[R];e&&!e.disabled&&n(e.value),C(!1)}break;default:e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&e.key!==` `&&H(e.key)&&e.preventDefault()}},G=S&&t[R]?F(R):void 0,te=S&&!r?(0,Q.jsx)(`div`,{ref:N,id:x,className:`select-dropdown${A?` select-dropdown-portal`:``}${!A&&d===`right`?` select-dropdown-right`:``}${!A&&f===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":a,style:A?{...E,zIndex:60,...p}:p,children:t.map((t,n)=>(0,Q.jsx)(`button`,{id:F(n),type:`button`,role:`option`,tabIndex:-1,disabled:r||t.disabled,"aria-disabled":t.disabled||void 0,"aria-selected":t.value===e,"data-value":t.value,className:X(`select-option`,t.value===e&&`active`,n===R&&`select-option-active`,t.disabled&&`cursor-default opacity-45`),onMouseEnter:()=>{t.disabled||T(n)},onClick:()=>W(n),children:t.label},t.value))}):null;return(0,Q.jsxs)(`div`,{ref:j,className:X(`custom-select`,_&&`w-full min-w-0`,h),style:{position:`relative`,display:_?`block`:`inline-block`,...u},children:[(0,Q.jsxs)(`button`,{ref:M,id:i,type:`button`,role:`combobox`,title:l,"aria-describedby":s,"aria-labelledby":o,"aria-invalid":c||void 0,"aria-required":b||void 0,"data-value":e,className:X(`select-trigger`,_&&`w-full min-w-0 justify-between px-[11px] py-2 text-left`,v===`sm`&&`h-[var(--ocx-control-h-sm)] min-h-0 px-2.5 py-0 text-[13px]`,g),onClick:()=>{r||(S?B():V(L))},onKeyDown:ee,disabled:r,"aria-haspopup":`listbox`,"aria-expanded":S,"aria-controls":S?x:void 0,"aria-activedescendant":G,"aria-label":a,children:[(0,Q.jsx)(`span`,{className:_?`min-w-0 truncate`:void 0,children:I?.label??e}),(0,Q.jsx)(lt,{style:{flexShrink:0,width:12,height:12,color:`var(--muted)`,transform:S?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),(b||y!==void 0)&&(0,Q.jsx)(`input`,{className:`select-form-proxy`,tabIndex:-1,"aria-hidden":`true`,name:y,required:b,disabled:r,value:e,onChange:()=>{},onFocus:()=>M.current?.focus(),style:{position:`absolute`,left:0,bottom:0,width:`100%`,height:1,opacity:0,pointerEvents:`none`,border:0,padding:0,margin:0}}),A?te&&(0,Dn.createPortal)(te,document.body):te]})}function Hn({open:e,onOpenChange:t,trigger:n,label:r,children:i,initialFocusRef:a,width:o=354,maxHeight:s=520,className:c,onKeyDown:l}){let u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)({}),g=(0,Z.useId)();(0,Z.useLayoutEffect)(()=>{if(!e)return;let t=()=>{u.current&&h(Ln(u.current.getBoundingClientRect(),{menuWidth:o,menuHeight:s,maxMenuHeight:s}))};return t(),a?.current?.focus(),window.addEventListener(`resize`,t),window.addEventListener(`scroll`,t,!0),()=>{window.removeEventListener(`resize`,t),window.removeEventListener(`scroll`,t,!0)}},[e,o,s,a]),(0,Z.useEffect)(()=>{if(!e)return;let n=e=>{let n=e.target;!u.current?.contains(n)&&!d.current?.contains(n)&&t(!1)};return document.addEventListener(`mousedown`,n),document.addEventListener(`focusin`,n),()=>{document.removeEventListener(`mousedown`,n),document.removeEventListener(`focusin`,n)}},[e,t]);let _=e?(0,Q.jsx)(`div`,{ref:d,id:g,role:`dialog`,"aria-label":r,className:X(`select-dropdown select-dropdown-portal`,c),style:f?{position:`absolute`,top:`calc(100% + 4px)`,left:0,width:`min(${o}px, calc(100vw - 16px))`,maxHeight:s}:{...m,width:`min(${o}px, calc(100vw - 16px))`,zIndex:`var(--z-popover)`},onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),e.stopPropagation(),t(!1),u.current?.focus()):l?.(e)},children:i}):null;return(0,Q.jsxs)(`div`,{className:`custom-select`,style:{position:`relative`,display:`inline-block`},children:[(0,Q.jsxs)(`button`,{ref:u,type:`button`,className:`select-trigger`,"aria-haspopup":`dialog`,"aria-expanded":e,"aria-controls":e?g:void 0,onClick:()=>{p(!!u.current?.closest(`dialog`)),t(!e)},children:[n,(0,Q.jsx)(lt,{style:{flexShrink:0,width:12,height:12,color:`var(--muted)`}})]}),f?_:_&&(0,Dn.createPortal)(_,document.body)]})}Vn.Popup=Hn;function Un({icon:e,title:t,children:n,className:r,style:i}){return(0,Q.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,Q.jsx)(`div`,{className:`title`,children:t}),n&&(0,Q.jsx)(`div`,{className:`text-control`,children:n})]})}function Wn({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,Z.useState)(!1),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=()=>{s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>a(!0),150)},l=()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null),a(!1)};return(0,Z.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-tooltip`,onMouseEnter:c,onMouseLeave:l,onFocus:c,onBlur:l,onKeyDown:e=>{e.key===`Escape`&&l()},"aria-describedby":i?o:void 0,style:{display:`inline`,border:0,background:`transparent`,padding:0,margin:0,color:`inherit`,font:`inherit`,cursor:`inherit`},children:[t,i&&(0,Q.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var Gn=45e3,Kn=2147483647;async function qn(e){if(e.status!==204){if(typeof e.text==`function`){let t=await e.text();return t.trim()?JSON.parse(t):void 0}return await e.json()}}function Jn(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function Yn(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=Jn(await e.json(),t)}catch{}throw Error(n)}return qn(e)}async function Xn(e){if(!e.ok)return null;try{return await qn(e)}catch{return null}}var Zn=[`gpt-6-luna`,`gpt-5.6-luna`];function Qn(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length===0?Zn:t.filter(e=>!e.includes(`/`))}function $n(e){return Qn(e).join(`, `)}function er(e){return Qn(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function tr(e,t){return Qn(t).some(t=>e.startsWith(t))}function nr(e,t){let n=Qn(t),r=n.find(t=>t!==e.id&&e.id.startsWith(t));if(r!==void 0)return{blocked:`covered`,prefix:r};if(!n.includes(e.id))return{sourceModels:[...n,e.id]};let i=n.filter(t=>t!==e.id);return i.length===0?{blocked:`last`}:{sourceModels:i}}function rr(e,t,n=[`gpt-6.1-terra`,`gpt-5.6-terra`]){let r=Qn(e),i=n.some(e=>e!==``&&r.some(t=>e.startsWith(t))),a=er(e);return i?a:`${a} (+ ${t})`}var ir=`dashboard/update`;function ar(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function or(){return window.location.hash.replace(/^#\/?/,``)===ir}function sr(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function cr(e,t){let n=await Yn(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var lr=[`low`,`medium`,`high`,`xhigh`];function ur(e){return e?.includes(`-preview.`)?`preview`:`latest`}function dr(e,t){switch(e){case`source_checkout`:return t(`dash.updateReason.source_checkout`);case`latest_unavailable`:return t(`dash.updateReason.latest_unavailable`);case`already_latest`:return t(`dash.updateReason.already_latest`);case`externally_managed`:return t(`dash.updateReason.externally_managed`);case`external_ownership_invalid`:return t(`dash.updateReason.external_ownership_invalid`);default:return t(`dash.updateReason.unknown`)}}function fr(e,t){switch(e){case`running`:return t(`dash.updateStatus.running`);case`restarting`:return t(`dash.updateStatus.restarting`);case`succeeded`:return t(`dash.updateStatus.succeeded`);case`failed`:return t(`dash.updateStatus.failed`)}}function pr(e,t){let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),t?.anthropicInstance===null?delete n.anthropicInstance:t?.anthropicInstance!==void 0&&(n.anthropicInstance=t.anthropicInstance),t?.backend!==void 0&&t.backend!==`anthropic`&&delete n.anthropicInstance,t?.reasoning!==void 0&&(n.reasoning=t.reasoning),t?.streamRoutedModelOutput!==void 0&&(n.streamRoutedModelOutput=t.streamRoutedModelOutput),t?.enabled!==void 0&&(n.enabled=t.enabled),t?.maxDescriptionsPerTurn!==void 0&&(n.maxDescriptionsPerTurn=t.maxDescriptionsPerTurn),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),n}function mr(e){return{vision:{reasoning:e}}}function hr(e){return{vision:{enabled:e}}}function gr(e){return{webSearch:{enabled:e}}}function _r(e){return e?.applied===!1&&e.reason!==`not_requested`}function vr(e,t){return t?.reason===`not_requested`&&_r(e)?e:t}function yr(e){return{vision:{maxDescriptionsPerTurn:e}}}function br(e){return{vision:{timeoutMs:e}}}var xr=Gn,Sr=Kn,Cr=1;function wr(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Tr(e){let t=wr(e);if(!(t===void 0||t<Cr||t>Sr))return t}var Er=[`low`,`medium`,`high`,`xhigh`,`max`];function Dr(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...Er];let r=Er.filter(e=>n.includes(e));return r.length>0?r:[...Er]}function Or(e,t){let n=kr(e,t);return e.includes(n)?e:[n,...e]}function kr(e,t){if(e.length===0||e.includes(t))return t;let n=Er.indexOf(t),r=e[0],i=Er.indexOf(r);for(let t of e){let e=Er.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function Ar(e){let t=[];for(let n of e)(n.provider===`openai`||n.provider===`anthropic`)&&t.push({value:n.id,label:`${n.provider}/${n.id}`});return t}function jr(e,t,n,r){if(e===void 0){let e=Ar(t);return n&&!e.some(e=>e.value===n)&&e.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),e}let i=e.map(e=>({value:e.value,label:e.label,backend:e.backend,model:e.model}));return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),i}function Mr(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):Ar(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function Nr(e,t,n){let r=Qn(n),i=r.flatMap(t=>{let n=e.find(e=>e.namespaced.startsWith(t))??e.find(e=>e.id.startsWith(t));return n?[{provider:n.provider,modelId:t}]:[]}),a=e.filter(e=>i.some(t=>e.provider===t.provider&&e.id.startsWith(t.modelId))),o=new Set([...r.flatMap(e=>[e,`openai/${e}`]),...a.flatMap(e=>[e.namespaced,`${e.provider}/${e.id}`])]),s=[{value:``,label:`—`},...e.filter(e=>!o.has(e.namespaced)).map(e=>({value:e.namespaced,label:e.namespaced}))];return t&&!o.has(t)&&!s.some(e=>e.value===t)&&s.push({value:t,label:t}),s}function Pr(e,t){let n=e.find(e=>e.id===t)?.provider;return n===`anthropic`||n===`anthropic2`?`anthropic`:`openai`}function Fr(e,t){function n(e,t){return t.backend!==void 0&&t.backend!==`anthropic`&&e.anthropicInstance!==void 0?{...t,anthropicInstance:null}:t}return{...t,...t.webSearch?{webSearch:n(e.webSearch,t.webSearch)}:{},...t.vision?{vision:n(e.vision,t.vision)}:{}}}function Ir(e,t,n){let r=t.find(e=>e.value===n);return{backend:r?.backend??Pr(e,n),model:r?.model??n}}function Lr(e,t,n){return t.find(e=>e.value===n)?.backend||(n.includes(`/`)?`routed`:Pr(e,n))}var Rr=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{Rr=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{Rr=!1},{capture:!0,passive:!0}));function zr(e){if(e){if(Rr)e.focus({preventScroll:!0});else try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function Br(e,t){let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let r=n.current;r&&(e?r.open||r.showModal():(r.open&&r.close(),zr(t.current)))},[e,t]),(0,Z.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),zr(t.current)},[t]),n}var Vr=`https://opencodex.me/guides/subagent-v1-default/`;function Hr(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.mode;return n!==`v1`&&n!=="default"&&n!==`v2`&&n!==`v2-plaintext`||typeof t.required!=`boolean`?null:{required:t.required,mode:n,recommended:`v1`,version:typeof t.version==`number`?t.version:0,docsUrl:typeof t.docsUrl==`string`&&t.docsUrl?t.docsUrl:Vr}}function Ur(e){return e===`v2-plaintext`?`v2 · plaintext`:e==="default"?`base`:e}function Wr(e){return e?[`v1`,`default`,`v2`,`v2-plaintext`]:[`v1`,`default`,`v2`]}function Gr(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.ok===!0&&t.multiAgentMode===`v2-plaintext`&&t.supportsPlaintextV2Mode===!0&&t.plaintextAgentMessagesEnabled===!0&&t.enabled===!1}function Kr({reason:e,mode:t,docsUrl:n,busy:r=!1,onContinue:i,onChooseV1:a,onDismiss:o}){let s=b(),c=(0,Z.useId)(),l=(0,Z.useId)(),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=u.current;e&&!e.open&&e.showModal()},[]);let d=(0,Z.useCallback)(e=>{e.preventDefault(),!r&&o()},[r,o]),f=Ur(t),p=e===`advisory`;return(0,Q.jsxs)(`dialog`,{ref:u,"aria-labelledby":c,"aria-describedby":l,className:`modal-overlay`,"data-subagent-surface-reason":e,onCancel:d,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,disabled:r,onClick:()=>{r||o()}}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:480},children:[(0,Q.jsx)(`h3`,{id:c,children:s(p?`subagentSurface.advisoryTitle`:`subagentSurface.selectionTitle`,{mode:f})}),(0,Q.jsxs)(`div`,{id:l,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(St,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:s(p?`subagentSurface.advisoryBody`:`subagentSurface.selectionBody`,{mode:f})})]}),(0,Q.jsx)(`p`,{className:`text-label`,style:{marginTop:12},children:(0,Q.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:s(`subagentSurface.learnMore`)})}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:i,children:s(`subagentSurface.continue`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:a,children:s(`subagentSurface.switchToV1`)})]})]})]})}function qr({busy:e=!1,onConfirm:t,onDismiss:n}){let r=b(),i=(0,Z.useId)(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),[s,c]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{let e=o.current;e&&!e.open&&e.showModal()},[]);let l=(0,Z.useCallback)(t=>{t.preventDefault(),!e&&n()},[e,n]);return(0,Q.jsxs)(`dialog`,{ref:o,"aria-labelledby":i,"aria-describedby":a,className:`modal-overlay`,"data-plaintext-v2-consent":!0,onCancel:l,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,disabled:e,onClick:()=>{e||n()}}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:480},children:[(0,Q.jsx)(`h3`,{id:i,children:r(`plaintextV2.title`)}),(0,Q.jsxs)(`div`,{id:a,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(St,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`modal-desc`,style:{margin:0},children:[(0,Q.jsx)(`p`,{style:{margin:0},children:r(`plaintextV2.body`)}),(0,Q.jsx)(`p`,{style:{margin:`8px 0 0`},children:r(`plaintextV2.caveat`)}),(0,Q.jsx)(`p`,{style:{margin:`8px 0 0`},children:r(`plaintextV2.scope`)})]})]}),(0,Q.jsxs)(`label`,{className:`modal-desc`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`,cursor:`pointer`},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s,disabled:e,onChange:e=>c(e.currentTarget.checked),style:{marginTop:3}}),(0,Q.jsx)(`span`,{children:r(`plaintextV2.acknowledge`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:n,children:r(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:e||!s,onClick:t,children:r(`plaintextV2.confirm`)})]})]})]})}function Jr(e){let{t,updateOpen:n,closeUpdateDialog:r,updateDialogRef:i,updateChannel:a,changeUpdateChannel:o,updateLoading:s,updateError:c,updateCheck:l,fetchUpdateCheck:u,updateRestart:d,setUpdateRestart:f,runUpdate:p,maHelpOpen:m,setMaHelpOpen:h,maHelpDialogRef:g,effortCapHelpOpen:_,setEffortCapHelpOpen:v,effortCapHelpDialogRef:y,shadowCallHelpOpen:b,setShadowCallHelpOpen:x,shadowCallHelpDialogRef:S,shadowCall:C,maAdvisory:w,maAdvisoryOpen:T,pendingMaMode:E,maBusy:D,keepMaMode:O,chooseMaV1:k,dismissMaSurfaceDialog:A}=e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dialog`,{ref:i,id:`dashboard-update-dialog`,className:`modal-overlay`,style:{display:n?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`update-title`,onCancel:e=>{e.preventDefault(),r()},children:(0,Q.jsxs)(`div`,{className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,Q.jsxs)(`div`,{className:`update-row`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,Q.jsx)(Vn,{value:a,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>o(e),disabled:s,label:t(`dash.updateChannel`),portal:!1})]}),s&&(0,Q.jsx)(Un,{className:`update-empty`,icon:(0,Q.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{children:c})]}),l&&!s&&(0,Q.jsxs)(`div`,{className:`update-box`,children:[(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,Q.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),l.command&&(0,Q.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,Q.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(St,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(St,{}),` `,t(`dash.updateUnavailable`),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,Q.jsx)(Ke,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,Q.jsxs)(`div`,{className:`update-recheck`,children:[(0,Q.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:dr(l.reason,t)})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,Q.jsx)(Ke,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,Q.jsxs)(`div`,{className:`spread update-restart`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,Q.jsxs)(`dialog`,{ref:g,id:`multi-agent-help-dialog`,className:`modal-overlay`,style:{display:m?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`multi-agent-help-title`,onCancel:e=>{e.preventDefault(),h(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,Q.jsx)(`div`,{style:{marginTop:12},children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:y,id:`effort-cap-help-dialog`,className:`modal-overlay`,style:{display:_?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`effort-cap-help-title`,onCancel:e=>{e.preventDefault(),v(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:S,id:`shadow-call-help-dialog`,className:`modal-overlay`,style:{display:b?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`shadow-call-help-title`,onCancel:e=>{e.preventDefault(),x(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:$n(C?.sourceModels)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]}),E===`v2-plaintext`?(0,Q.jsx)(qr,{busy:D,onConfirm:()=>{O()},onDismiss:A}):(E||T)&&(0,Q.jsx)(Kr,{reason:E?`selection`:`advisory`,mode:E??w?.mode??`default`,docsUrl:w?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:D,onContinue:()=>{O()},onChooseV1:()=>{k()},onDismiss:A})]})}function Yr({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,Q.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,Q.jsx)(Un,{title:e(`dash.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(We,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:e(`models.search`),value:r,onChange:e=>i(e.target.value),"aria-label":e(`models.search`)})]}),a.length===0?(0,Q.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,Q.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,Q.jsxs)(`div`,{className:`dash-model-group`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`dash-model-head`,onClick:()=>s(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),"aria-expanded":i,children:[(0,Q.jsx)(lt,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`font-semibold`,children:re(t,e)}),(0,Q.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,Q.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,Q.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}function Xr(e,t){let n=Math.max(0,Math.floor(e)),r=o(t,`uptime.day`),i=o(t,`uptime.hour`),a=o(t,`uptime.minute`),s=o(t,`uptime.second`);if(n<300)return`${n}${s}`;let c=Math.floor(n/60);if(c<60)return`${c}${a}`;let l=Math.floor(c/60);if(l<24){let e=c%60;return e>0?`${l}${i} ${e}${a}`:`${l}${i}`}let u=Math.floor(l/24),d=l%24;return d>0?`${u}${r} ${d}${i}`:`${u}${r}`}function Zr(e){return!e||typeof e!=`object`||!(`usageIncomplete`in e)||e.usageIncomplete!==!0?{}:{usageIncomplete:!0,...`usageIncompleteReason`in e&&e.usageIncompleteReason===`oversized_rows`?{usageIncompleteReason:`oversized_rows`}:{}}}function Qr(e){return!!e&&typeof e==`object`&&`error`in e&&e.error===`read_failed`}var $r=class extends Error{constructor(){super(`usage ledger read failed`),this.name=`UsageReadFailedError`}};async function ei(e,t){let n;try{n=await e.json()}catch{throw Error(t??`${e.status} ${e.statusText}`.trim())}if(Qr(n))throw new $r;if(!e.ok)throw Error(t??`${e.status} ${e.statusText}`.trim());return n}function ti(e,t=`all`,n){let r=n&&n!==e?n:e;return t===`codex`?[`usage-summary-30d`,r,`codex`].join(`:`):[`usage-summary-30d`,r,`all`].join(`:`)}function ni({data:e}){let t=b();return Zr(e).usageIncomplete?(0,Q.jsx)($,{tone:`warn`,children:t(`usage.incomplete`)}):null}var ri=(0,Z.createContext)({});function ii(e){let t=(0,Z.useRef)(null);return t.current===null&&(t.current=e()),t.current}var ai=typeof window<`u`?Z.useLayoutEffect:Z.useEffect,oi=(0,Z.createContext)(null);function si(e,t){e.indexOf(t)===-1&&e.push(t)}function ci(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var li=(e,t,n)=>n>t?t:n<e?e:n,ui={},di=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),fi=e=>/^0[^.\s]+$/u.test(e);function pi(e){let t;return()=>(t===void 0&&(t=e()),t)}var mi=e=>e,hi=class{constructor(){this.subscriptions=[]}add(e){return si(this.subscriptions,e),()=>this.remove(e)}remove(e){ci(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r){if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},gi=e=>e*1e3,_i=e=>e/1e3,vi=(e,t)=>t?1e3/t*e:0,yi=e=>Array.isArray(e)&&typeof e[0]==`number`,bi={delta:0,timestamp:0,isProcessing:!1},xi;function Si(){xi=void 0}var Ci={now:()=>(xi===void 0&&Ci.set(bi.isProcessing||ui.useManualTiming?bi.timestamp:performance.now()),xi),set:e=>{xi=e,queueMicrotask(Si)}},wi=e=>Math.round(e*1e5)/1e5,Ti=e=>t=>typeof t==`string`&&t.startsWith(e),Ei=Ti(`--`),Di=Ti(`var(--`),Oi=e=>Di(e)?ki.test(e.split(`/*`)[0].trim()):!1,ki=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Ai(e){return typeof e==`string`&&e.split(`/*`)[0].includes(`var(--`)}var ji={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Mi={...ji,transform:e=>li(0,1,e)},Ni={...ji,default:1},Pi=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Fi(e){return e==null}var Ii=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Li=(e,t)=>n=>!!(typeof n==`string`&&Ii.test(n)&&n.startsWith(e)||t&&!Fi(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ri=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Pi);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},zi=e=>li(0,255,e),Bi={...ji,transform:e=>Math.round(zi(e))},Vi={test:Li(`rgb`,`red`),parse:Ri(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Bi.transform(e)+`, `+Bi.transform(t)+`, `+Bi.transform(n)+`, `+wi(Mi.transform(r))+`)`},Hi=(e,t,n)=>{let r=e.substring(1+t*n,1+(t+1)*n);return n>1?r:r+r};function Ui(e){let t=e.length>5?2:1,n=Hi(e,3,t);return{red:parseInt(Hi(e,0,t),16),green:parseInt(Hi(e,1,t),16),blue:parseInt(Hi(e,2,t),16),alpha:n?parseInt(n,16)/255:1}}var Wi={test:Li(`#`),parse:Ui,transform:Vi.transform},Gi=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Ki=Gi(`deg`),qi=Gi(`%`),Ji=Gi(`px`),Yi=Gi(`vh`),Xi=Gi(`vw`),Zi={...qi,parse:e=>qi.parse(e)/100,transform:e=>qi.transform(e*100)},Qi={test:Li(`hsl`,`hue`),parse:Ri(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+qi.transform(wi(t))+`, `+qi.transform(wi(n))+`, `+wi(Mi.transform(r))+`)`},$i={test:e=>Vi.test(e)||Wi.test(e)||Qi.test(e),parse:e=>Vi.test(e)?Vi.parse(e):Qi.test(e)?Qi.parse(e):Wi.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Vi.transform(e):Qi.transform(e),getAnimatableNone:e=>{let t=$i.parse(e);return t.alpha=0,$i.transform(t)}},ea=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,ta=new RegExp(Pi.source),na=new RegExp(ea.source,`i`);function ra(e){return isNaN(e)&&typeof e==`string`&&(ta.test(e)||na.test(e))}var ia=`number`,aa=`color`,oa=`var`,sa=`var(`,ca="${}",la=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)(?![a-z]*\()/giu;function ua(e){let t=e.toString();return ta.test(t)||na.test(t)}function da(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(la,e=>($i.test(e)?(r.color.push(a),i.push(aa),n.push($i.parse(e))):e.startsWith(sa)?(r.var.push(a),i.push(oa),n.push(e)):(r.number.push(a),i.push(ia),n.push(parseFloat(e))),++a,ca)).split(ca),indexes:r,types:i}}function fa(e){return da(e).values}function pa({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];i+=e===ia?wi(r[a]):e===aa?$i.transform(r[a]):r[a]}return i}}function ma(e){return pa(da(e))}var ha=e=>typeof e==`number`?0:$i.test(e)?$i.getAnimatableNone(e):e,ga=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:ha(e);function _a(e){let t=da(e);return pa(t)(t.values.map((e,n)=>ga(e,t.split[n])))}var va={test:ra,parse:fa,createTransformer:ma,getAnimatableNone:_a},ya=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`];function ba(e){let t=new Set,n=new Set,r=!1,i=!1,a,o=new Set,s={delta:0,timestamp:0,isProcessing:!1};function c(t){o.has(t)&&(n.add(t),e()),(a=t)(s)}let l={schedule:(e,i=!1,s=!1)=>{let c=s&&r,l=c?t:n;return i&&o.add(e),c&&e!==a&&l.delete(e),l.add(e),e},cancel:e=>{n.delete(e),o.delete(e)},process:e=>{if(s=e,r){i=!0;return}r=!0;let o=t;t=n,n=o,t.forEach(c),t.clear(),a=void 0,r=!1,i&&(i=!1,l.process(e))}};return l}var xa=40;function Sa(e,t,n={delta:0,timestamp:0,isProcessing:!1}){let r=!1,i=!0,a=()=>r=!0,o=ya.reduce((e,t)=>(e[t]=ba(a),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=ui.useManualTiming,o=a?n.timestamp:performance.now();r=!1,a||(n.delta=i?1e3/60:Math.max(Math.min(o-n.timestamp,xa),1)),n.timestamp=o,n.isProcessing=!0,s.process(n),c.process(n),l.process(n),u.process(n),d.process(n),f.process(n),p.process(n),m.process(n),n.isProcessing=!1,r&&t&&(i=!1,e(h))},g=()=>{r=!0,i=!0,n.isProcessing||e(h)};return{schedule:ya.reduce((e,t)=>{let n=o[t];return e[t]=(e,t=!1,i=!1)=>(r||g(),n.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<ya.length;t++)o[ya[t]].cancel(e)},state:n,steps:o}}var{schedule:Ca,cancel:wa,steps:Ta}=Sa(typeof requestAnimationFrame<`u`?requestAnimationFrame:mi,!0,bi),Ea=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},Da=e=>e!==null;function Oa(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(Da),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}function ka(e,t){return{kind:e,animation:t,timestamp:Ci.now(),frameTimestamp:bi.timestamp,frameIsProcessing:bi.isProcessing}}function Aa(e,t,n){let r=globalThis.__MOTION_INSPECT__;if(r)try{r({...ka(`animation-start`,e),options:n?{...t,...n}:t})}catch{}}function ja(e,t){let n=globalThis.__MOTION_INSPECT__;if(n)try{n({...ka(`layout-animation-start`,e),node:t})}catch{}}var Ma=class{constructor(){this.isResolved=!1}get finished(){return this._finished||=this.isResolved?Promise.resolve():new Promise(e=>{this._resolve=e}),this._finished}updateFinished(){this._finished=this._resolve=void 0,this.isResolved=!1}notifyFinished(){this.isResolved=!0,this._resolve?.()}then(e,t){return this.finished.then(e,t)}},Na=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Pa(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Pi)||[];if(!r)return e;let i=n.replace(r,``),a=+!!Na.has(t);return r!==n&&(a*=100),t+`(`+a+i+`)`}var Fa=/\b([a-z-]*)\(.*?\)/gu,Ia={...va,getAnimatableNone:e=>{let t=e.match(Fa);return t?t.map(Pa).join(` `):e}},La={...va,getAnimatableNone:e=>{let t=va.parse(e);return va.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},Ra={...ji,transform:Math.round},za={rotate:Ki,pathRotation:Ki,rotateX:Ki,rotateY:Ki,rotateZ:Ki,scale:Ni,scaleX:Ni,scaleY:Ni,scaleZ:Ni,skew:Ki,skewX:Ki,skewY:Ki,distance:Ji,translateX:Ji,translateY:Ji,translateZ:Ji,x:Ji,y:Ji,z:Ji,perspective:Ji,transformPerspective:Ji,opacity:Mi,originX:Zi,originY:Zi,originZ:Ji},Ba={borderWidth:Ji,borderTopWidth:Ji,borderRightWidth:Ji,borderBottomWidth:Ji,borderLeftWidth:Ji,borderRadius:Ji,borderTopLeftRadius:Ji,borderTopRightRadius:Ji,borderBottomRightRadius:Ji,borderBottomLeftRadius:Ji,width:Ji,maxWidth:Ji,height:Ji,maxHeight:Ji,top:Ji,right:Ji,bottom:Ji,left:Ji,inset:Ji,insetBlock:Ji,insetBlockStart:Ji,insetBlockEnd:Ji,insetInline:Ji,insetInlineStart:Ji,insetInlineEnd:Ji,padding:Ji,paddingTop:Ji,paddingRight:Ji,paddingBottom:Ji,paddingLeft:Ji,paddingBlock:Ji,paddingBlockStart:Ji,paddingBlockEnd:Ji,paddingInline:Ji,paddingInlineStart:Ji,paddingInlineEnd:Ji,margin:Ji,marginTop:Ji,marginRight:Ji,marginBottom:Ji,marginLeft:Ji,marginBlock:Ji,marginBlockStart:Ji,marginBlockEnd:Ji,marginInline:Ji,marginInlineStart:Ji,marginInlineEnd:Ji,fontSize:Ji,backgroundPositionX:Ji,backgroundPositionY:Ji,...za,zIndex:Ra,fillOpacity:Mi,strokeOpacity:Mi,numOctaves:Ra},Va={...Ba,color:$i,backgroundColor:$i,outlineColor:$i,fill:$i,stroke:$i,borderColor:$i,borderTopColor:$i,borderRightColor:$i,borderBottomColor:$i,borderLeftColor:$i,filter:Ia,WebkitFilter:Ia,mask:La,WebkitMask:La},Ha=e=>Va[e],Ua=new Set([Ia,La]);function Wa(e,t){let n=Ha(e);return Ua.has(n)||(n=va),n.getAnimatableNone?n.getAnimatableNone(t):void 0}function Ga(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var Ka=e=>e*180/Math.PI,qa=e=>Ya(Ka(Math.atan2(e[1],e[0]))),Ja={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scaleZ:()=>1,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:qa,rotateZ:qa,skewX:e=>Ka(Math.atan(e[1])),skewY:e=>Ka(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ya=e=>(e%=360,e<0&&(e+=360),e),Xa=qa,Za=e=>Math.hypot(e[0],e[1]),Qa=e=>Math.hypot(e[4],e[5]),$a={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Za,scaleY:Qa,scaleZ:e=>Math.hypot(e[8],e[9],e[10]),scale:e=>(Za(e)+Qa(e))/2,rotateX:e=>Ya(Ka(Math.atan2(e[6],e[5]))),rotateY:e=>Ya(Ka(Math.atan2(-e[2],e[0]))),rotateZ:Xa,rotate:Xa,skewX:e=>Ka(Math.atan(e[4])),skewY:e=>Ka(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function eo(e){return+!!e.includes(`scale`)}function to(e,t){if(!e||e===`none`)return eo(t);let n=e.match(/^matrix(3d)?\(([-\d.e\s,]+)\)$/u);if(!n)return eo(t);let r=(n[1]?$a:Ja)[t],i=n[2].split(`,`).map(e=>parseFloat(e));return typeof r==`function`?r(i):i[r]}var no=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return to(n,t)},ro=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`scaleZ`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],io=new Set([...ro,`pathRotation`]),ao=e=>e===ji||e===Ji,oo=new Set([`x`,`y`,`z`]),so=ro.filter(e=>!oo.has(e));function co(e){let t=[];return so.forEach(n=>{let r=e.getValue(n);if(r!==void 0){let e=r.get(),i=+!!n.startsWith(`scale`);if(e===i)return;t.push([n,e]),r.set(i)}}),t}var lo=new Set([`bottom`,`right`]);function uo(e,t,n,r,i,a){let o=parseFloat(e);if(!isNaN(o))return o;let{min:s,max:c}=t()[n],l=c-s;return a===`border-box`?l:l-parseFloat(r)-parseFloat(i)}var fo=({transform:e})=>to(e,`x`),po=({transform:e})=>to(e,`y`),mo={width:({width:e,paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r},i)=>uo(e,i,`x`,t,n,r),height:({height:e,paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r},i)=>uo(e,i,`y`,t,n,r),top:({top:e})=>parseFloat(e),left:({left:e})=>parseFloat(e),bottom:({top:e},t)=>{let{y:n}=t();return parseFloat(e)+(n.max-n.min)},right:({left:e},t)=>{let{x:n}=t();return parseFloat(e)+(n.max-n.min)},x:fo,y:po,translateX:fo,translateY:po},ho=new Set,go=!1,_o=!1,vo=!1;function yo(){if(_o){let e=[],t=new Set,n=new Set;ho.forEach(r=>{r.needsMeasurement&&(e.push(r),t.add(r.element),lo.has(r.name)&&n.add(r.element))});let r=new Map;n.forEach(e=>{let t=co(e);t.length&&(r.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=r.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}_o=!1,go=!1,ho.forEach(e=>e.complete(vo)),ho.clear()}function bo(){ho.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(_o=!0)})}function xo(){vo=!0,bo(),yo(),vo=!1}function So(e,t,n){if(typeof e==`string`){if(di(e)||fi(e))return parseFloat(e);if(!va.test(e)&&va.test(n))return Wa(t,n)}return e??void 0}var Co=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(ho.add(this),go||(go=!0,Ca.read(bo),Ca.resolveKeyframes(yo))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=So(n.readValue(t,a),t,a);r!==void 0&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}Ga(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),ho.delete(this)}cancel(){this.state===`scheduled`&&(ho.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},wo=e=>e.startsWith(`--`);function To(e,t,n){wo(t)?e.style.setProperty(t,n):e.style[t]=n}var Eo={};function Do(e,t){let n=pi(e);return()=>Eo[t]??n()}var Oo=Do(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),ko=Do(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Ao=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,jo={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Ao([0,.65,.55,1]),circOut:Ao([.55,0,1,.45]),backIn:Ao([.31,.01,.66,-.59]),backOut:Ao([.33,1.53,.69,.99])};function Mo(e,t){if(e)return typeof e==`function`?ko()?Ea(e,t):`ease-out`:yi(e)?Ao(e):Array.isArray(e)?e.map(e=>Mo(e,t)||jo.easeOut):jo[e]}function No(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Mo(s,i);Array.isArray(d)&&(u.easing=d);let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};return l&&(f.pseudoElement=l),e.animate(u,f)}function Po(e){return typeof e==`function`&&`applyToOptions`in e}function Fo({type:e,...t}){return Po(e)&&ko()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Io=class extends Ma{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e;let c=Fo(e);this.animation=No(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=Oa(r,this.options,o,this.speed);this.updateMotionValue?.(e),To(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()},Aa(this,e,c)}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){this.isStopped||(this.isStopped=!0,this.state!==`idle`&&this.finishedTime===null&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||(this.animation.onfinish=null,this.cancel())))}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return _i(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+_i(e)}get time(){return _i(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=gi(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,onAttach:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&Oo()?(this.animation.timeline=e,t?.(this.animation),mi):n(this)}},Lo=new Set([`opacity`,`clipPath`,`filter`,`transform`]),Ro=(e,t)=>t&&typeof e==`number`?t.transform(e):e,zo={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},Bo=ro.length,Vo={},Ho=(e,t,n=Ro(t,za[e]))=>(Vo[e]||(Vo[e]=(zo[e]||e)+`(`))+n+`)`,Uo=(e,t)=>(typeof t==`number`?t:parseFloat(t))===+!!e.startsWith(`scale`);function Wo(e,t,n){let r=``;for(let i=0;i<Bo;i++){let a=ro[i],o=e[a];if(o===void 0)continue;let s=n&&(t[a]=Ro(o,Ba[a]));Uo(a,o)||(r+=Ho(a,o,s||void 0)+` `)}let i=e.pathRotation;return i&&(r+=Ho(`rotate`,i)),r=r.trim(),n?n(t,r):r||`none`}var Go=new WeakMap,Ko=30,qo=e=>!isNaN(parseFloat(e)),Jo={current:void 0},Yo=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Ci.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.dirty(),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Ci.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=qo(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on(`change`,e)}on(e,t){var n;return e===`change`?this.onChangeSubscribe(t):((n=this.events)[e]||(n[e]=new hi)).add(t)}onChangeSubscribe(e){let{events:t}=this;return!t.change&&!this.changeSubscriber?this.changeSubscriber=e:(t.change||(t.change=new hi,t.change.add(this.changeSubscriber),this.changeSubscriber=void 0),t.change.add(e)),()=>{this.changeSubscriber===e?this.changeSubscriber=void 0:t.change?.remove(e),this.stopIfUnobserved()}}stopIfUnobserved(){Ca.read(()=>{!this.changeSubscriber&&!this.events.change?.getSize()&&this.stop()})}clearListeners(){this.changeSubscriber=void 0;for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){t&&(this.updatedAt=Ci.now(),this.stop()),this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,this.stopPassiveEffect?.()}dirty(){let{current:e,changeSubscriber:t}=this;t?t(e):this.events.change?.notify(e)}addDependent(e){(this.dependents||=new Set).add(e)}removeDependent(e){this.dependents?.delete(e)}get(){Jo.current?.push(this);let e=this.animation?.liveValue?.();return e===void 0?this.current:e}getCurrent(){return this.current}getPrevious(){return this.prev}getVelocity(){let e=Ci.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Ko)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Ko);return vi(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0;let n=!1,r;r=e(()=>{n=!0,this.events.animationComplete?.notify(),this.animation===r&&(this.animation=void 0),t()}),n||(this.animation=r),this.events.animationStart?.notify()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel?.notify()),this.animation=void 0}isAnimating(){return!!this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect?.()}};function Xo(e,t){return new Yo(e,t)}function Zo(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function Qo(e,t,n,r){let i=t=>typeof t==`function`?t(n===void 0?e.custom:n,...Zo(r)):t;return t=i(t),typeof t==`string`&&(t=e.variants&&e.variants[t]),i(t)}var $o=e=>!!(e&&e.getVelocity),es=`data-framer-appear-id`;function ts(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(io.has(e))o=!0;else if(Ei(e))i[e]=n;else{let t=Ro(n,Ba[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=Wo(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}var ns={offset:`stroke-dashoffset`,array:`stroke-dasharray`},rs={offset:`strokeDashoffset`,array:`strokeDasharray`};function is(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?ns:rs;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var as=[`transform`,`opacity`,`clipPath`,`filter`,`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function os(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(ts(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;for(let e of as)d[e]!==void 0&&(f[e]=d[e],delete d[e]);(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox),t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&is(d,i,a,o,!1)}var{schedule:ss,cancel:cs}=Sa(queueMicrotask,!1),ls={};function us(e){return $o(e)?e.get():e}var ds=()=>({translate:0,scale:1,origin:0,originPoint:0}),fs=()=>({x:ds(),y:ds()}),ps=()=>({min:0,max:0}),ms=()=>({x:ps(),y:ps()}),hs={current:void 0},gs=new WeakMap;function _s(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function vs(e){return typeof e==`string`||Array.isArray(e)}var ys=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],bs=[`initial`].concat(ys);function xs(e){if(_s(e.animate))return!0;for(let t=0;t<bs.length;t++)if(vs(e[bs[t]]))return!0;return!1}function Ss(e){return!!(xs(e)||e.variants)}function Cs(e,t,n){for(let r in t){let i=t[r],a=n[r];if($o(i))e.addValue(r,i);else if($o(a))e.addValue(r,Xo(i,{owner:e}));else if(a!==i){if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,Xo(t===void 0?i:t,{owner:e}))}}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var ws={current:null},Ts={current:!1},Es=typeof window<`u`;function Ds(){if(Ts.current=!0,Es){if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>ws.current=e.matches;e.addEventListener(`change`,t),t()}else ws.current=!1}}var Os=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],ks={};function As(e){ks=e}function js(){return ks}var Ms=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Co,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify(`Update`,this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=Ci.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,Ca.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=xs(t),this.isVariantNode=Ss(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&$o(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted&&!this.presenceContext?.keepValuesOnRemount)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];if(this.current=e,gs.set(e,this),this.projection?.instance||this.projection?.mount(e),this.isVariantNode&&!this.isControllingVariants){let e=this;do e=e.props.inherit!==!1&&e.parent;while(e&&!e.isVariantNode);if(e){let{variantChildren:t}=e;t.add(this),this.removeFromVariantTree=()=>t.delete(this)}}this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(Ts.current||Ds(),this.shouldReduceMotion=ws.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection?.unmount(),wa(this.notifyUpdate),wa(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree?.(),this.parent?.removeChild(this);for(let e in this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),(this.enteringChildren||=new Set).add(e)}removeChild(e){this.children.delete(e),this.enteringChildren?.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.get(e)?.(),t.accelerate&&Lo.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Io({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:gi(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=io.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&Ca.preRender(this.notifyUpdate),n&&(this.projection&&(this.projection.isTransformDirty=!0),Go.get(this.current)?.check()),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i?.()})}sortNodePosition(e){return!this.current||!e.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in ks){let t=ks[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ms()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){let{transformTemplate:n,onUpdate:r}=this.props;(e.transformTemplate||n)&&this.scheduleRender(),(e.transformTemplate&&!n||e.onUpdate&&!r)&&Go.get(this.current)?.demote(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<Os.length;t++){let n=Os[t];this.propEventSubscriptions[n]?.(),delete this.propEventSubscriptions[n];let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=Cs(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue?.()}getProps(){return this.props}getVariant(e){return this.props.variants?.[e]}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}addValue(e,t){let n=this.values.get(e);if(t!==n){n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t);let r=t.get();r!==void 0&&(this.latestValues[e]=r)}}removeValue(e){this.values.delete(e),this.valueSubscriptions.get(e)?.(),this.valueSubscriptions.delete(e),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){let n=this.props.values?.[e];return n||(n=this.values.get(e),n===void 0&&t!==void 0&&(n=Xo(t??this.getDefaultValue?.(e),{owner:this}),this.addValue(e,n)),n)}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(di(n)||fi(n))?n=parseFloat(n):typeof n!=`number`&&!va.test(n)&&va.test(t)&&(n=Wa(e,t)),this.setBaseTarget(e,$o(n)?n.get():n)),$o(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}on(e,t){return(this.events[e]||(this.events[e]=new hi)).add(t)}notify(e,...t){this.events[e]?.notify(...t)}scheduleRenderMicrotask(){ss.render(this.render)}};function Ns(e,{layout:t,layoutId:n}){return io.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!ls[e]||e===`opacity`)}function Ps(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)($o(r[t])||i&&$o(i[t])||Ns(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}var Fs=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Is(e,t,n){let r=Ps(e,t,n);for(let n in e)if(n!==`children`&&($o(e[n])||$o(t[n]))){let t=ro.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Ls=(0,Z.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`}),Rs=(0,Z.createContext)({strict:!1}),zs={animation:[`variants`,...ys],exit:[`exit`],drag:[`drag`,`dragControls`],focus:[`whileFocus`],hover:[`whileHover`,`onHoverStart`,`onHoverEnd`],tap:[`whileTap`,`onTap`,`onTapStart`,`onTapCancel`],pan:[`onPan`,`onPanStart`,`onPanSessionStart`,`onPanEnd`],inView:[`whileInView`,`onViewportEnter`,`onViewportLeave`],layout:[`layout`,`layoutId`]},Bs=!1;function Vs(){if(Bs)return;let e={};for(let t in zs)e[t]={isEnabled:e=>zs[t].some(t=>!!e[t])};As(e),Bs=!0}function Hs(){return Vs(),js()}function Us(e){let t=Hs();for(let n in e)t[n]={...t[n],...e[n]};As(t)}function Ws({children:e,features:t,strict:n=!1}){let[,r]=(0,Z.useState)(!Gs(t)),i=(0,Z.useRef)(void 0);if(!Gs(t)){let{renderer:e,...n}=t;i.current=e,Us(n)}return(0,Z.useEffect)(()=>{Gs(t)&&t().then(({renderer:e,...t})=>{Us(t),i.current=e,r(!0)})},[]),(0,Q.jsx)(Rs.Provider,{value:{renderer:i.current,strict:n},children:e})}function Gs(e){return typeof e==`function`}var Ks=(0,Z.createContext)({});function qs(e,t){if(xs(e)){let{initial:t,animate:n}=e;return{initial:t===!1||vs(t)?t:void 0,animate:vs(n)?n:void 0}}return e.inherit===!1?{}:t}function Js(e){let{initial:t,animate:n}=qs(e,(0,Z.useContext)(Ks));return(0,Z.useMemo)(()=>({initial:t,animate:n}),[Ys(t),Ys(n)])}function Ys(e){return Array.isArray(e)?e.join(` `):e}var Xs=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Zs(e,t,n){for(let r in t)!$o(t[r])&&!Ns(r,n)&&(e[r]=t[r])}function Qs({transformTemplate:e},t){return(0,Z.useMemo)(()=>{let n=Xs();return ts(n,t,e),Object.assign({},n.vars,n.style)},[t])}function $s(e,t){let n=e.style||{},r={};return Zs(r,n,e),Object.assign(r,Qs(e,t)),r}function ec(e,t){let n={},r=$s(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var tc=()=>({...Xs(),attrs:{}});function nc(e,t,n,r){let i=(0,Z.useMemo)(()=>{let n=tc();return os(n,t,Fs(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};return Zs(t,e.style,e),{...i,style:{...t,...i.style}}}return i}var rc=new Set(`animate.exit.variants.initial.style.values.transition.transformTemplate.custom.inherit.onBeforeLayoutMeasure.onAnimationStart.onAnimationComplete.onUpdate.onDragStart.onDrag.onDragEnd.onMeasureDragConstraints.onDirectionLock.onDragTransitionEnd._dragX._dragY.onHoverStart.onHoverEnd.onViewportEnter.onViewportLeave.globalTapTarget.propagate.ignoreStrict.viewport`.split(`.`));function ic(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||rc.has(e)}function ac(e,t){return e.startsWith(`on`)?!ic(e):t?.(e)??!ic(e)}function oc(e,t,n,r){let i={};for(let a in e)(a!==`values`||typeof e.values!=`object`)&&($o(e[a])||(ac(a,r)||n===!0&&ic(a)||!t&&!ic(a)||e.draggable&&a.startsWith(`onDrag`))&&(i[a]=e[a]));return i}var sc=[`animate`,`circle`,`defs`,`desc`,`ellipse`,`g`,`image`,`line`,`filter`,`marker`,`mask`,`metadata`,`path`,`pattern`,`polygon`,`polyline`,`rect`,`stop`,`switch`,`symbol`,`svg`,`text`,`tspan`,`use`,`view`];function cc(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(sc.indexOf(e)>-1||/[A-Z]/u.test(e))}function lc(e,t,n,{latestValues:r},i,a=!1,o,s){let c=(o??cc(e)?nc:ec)(t,r,i,e),l=oc(t,typeof e==`string`,a,s),u=e===Z.Fragment?{}:{...l,...c,ref:n},{children:d}=t,f=(0,Z.useMemo)(()=>$o(d)?d.get():d,[d]);return(0,Z.createElement)(e,{...u,children:f})}function uc({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:dc(n,r,i,e),renderState:t()}}function dc(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=us(a[e]);let{initial:o,animate:s}=e,c=xs(e),l=Ss(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!_s(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=Qo(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var fc=e=>(t,n)=>{let r=(0,Z.useContext)(Ks),i=(0,Z.useContext)(oi),a=()=>uc(e,t,r,i);return n?a():ii(a)},pc=fc({scrapeMotionValuesFromProps:Ps,createRenderState:Xs}),mc=fc({scrapeMotionValuesFromProps:Is,createRenderState:tc}),hc=Symbol.for(`motionComponentSymbol`);function gc(e,t,n){let r=(0,Z.useRef)(n);(0,Z.useInsertionEffect)(()=>{r.current=n});let i=(0,Z.useRef)(null);return(0,Z.useCallback)(n=>{n&&e.onMount?.(n),t&&(n?t.mount(n):t.unmount());let a=r.current;if(typeof a==`function`){if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n)}else a&&(a.current=n)},[t])}var _c=(0,Z.createContext)({});function vc(e,t,n,r,i,a){let{visualElement:o}=(0,Z.useContext)(Ks),s=(0,Z.useContext)(Rs),c=(0,Z.useContext)(oi),l=(0,Z.useContext)(Ls),u=l.reducedMotion,d=l.skipAnimations,f=(0,Z.useRef)(null),p=(0,Z.useRef)(!1);r||=s.renderer,!f.current&&r&&(f.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:d,isSVG:a}),p.current&&f.current&&(f.current.manuallyAnimateOnMount=!0));let m=f.current,h=(0,Z.useContext)(_c);m&&!m.projection&&i&&(m.type===`html`||m.type===`svg`)&&i.create(m,n,h),(0,Z.useInsertionEffect)(()=>{m&&m.props!==n&&m.update(n,c)});let g=n[es],_=(0,Z.useRef)(!!g&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return ai(()=>{p.current&&m&&(m.animationState?.animateChanges(),m.enteringChildren=void 0)},[]),ai(()=>{p.current=!0,m&&(window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),_.current&&m.animationState&&m.animationState.animateChanges())}),(0,Z.useEffect)(()=>{m&&(!_.current&&m.animationState&&m.animationState.animateChanges(),_.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),!1),m.enteringChildren=void 0)}),m}function yc(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&Us(r);let a=n?n===`svg`:cc(e),o=a?mc:pc;function s(n,s){let c,l=bc(n);ii(()=>!!hs.current?.sharedNodes.get(l)?.lead&&n.initial)&&(n={...n,initial:!1});let u={...(0,Z.useContext)(Ls),...n,layoutId:l},{isStatic:d,isValidProp:f}=u,p=Js(n),m=o(n,d);if(!d&&typeof window<`u`){xc(u,r);let t=Sc(u);p.visualElement=vc(e,m,u,i,t.ProjectionNode,a),(t.isEnabled||p.visualElement?.projection?.options.layoutId)&&(c=t.MeasureLayout)}return(0,Q.jsxs)(Ks.Provider,{value:p,children:[c&&p.visualElement?(0,Q.jsx)(c,{visualElement:p.visualElement,...u}):null,lc(e,n,gc(m,p.visualElement,s),m,d,t,a,f)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,Z.forwardRef)(s);return c[hc]=e,c}function bc({layoutId:e}){let t=(0,Z.useContext)(ri).id;return t&&e!==void 0?t+`-`+e:e}function xc(e,t){(0,Z.useContext)(Rs).strict}function Sc(e){let{drag:t,layout:n}=Hs();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:r.MeasureLayout,isEnabled:t?.isEnabled(e)||n?.isEnabled(e),ProjectionNode:r.ProjectionNode}}function Cc(e,t){if(typeof Proxy>`u`)return yc;let n=new Map,r=(n,r)=>yc(n,r,e,t);return new Proxy((e,t)=>r(e,t),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,yc(a,void 0,e,t)),n.get(a))})}var wc=Cc();function Tc(){!Ts.current&&Ds();let[e]=(0,Z.useState)(ws.current);return e}var Ec=wc,Dc=()=>ee(()=>import(`./segment-thumb-features-Bquysdn5.js`).then(e=>e.default),__vite__mapDeps([0,1,2])),Oc={type:`spring`,stiffness:420,damping:36},kc={duration:0};function Ac({children:e}){return(0,Q.jsx)(Ws,{features:Dc,children:e})}function jc({layoutId:e}){let t=Tc();return(0,Q.jsx)(Ec.span,{layoutId:e,"aria-hidden":!0,transition:t?kc:Oc,className:`absolute inset-0 rounded-[inherit] bg-raised shadow-sm ring-1 ring-line dark:bg-surface-2`})}function Mc({items:e,value:t,onChange:n,"aria-label":r,size:i=`md`,className:a}){let o=(0,Z.useId)(),s=(0,Z.useRef)([]),c=Math.max(0,e.findIndex(e=>e.value===t));return(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-label":r,onKeyDown:t=>{let r=t.key===`ArrowRight`||t.key===`ArrowDown`?1:t.key===`ArrowLeft`||t.key===`ArrowUp`?-1:0;if(!r&&t.key!==`Home`&&t.key!==`End`)return;t.preventDefault();let i=t.key===`Home`?0:t.key===`End`?e.length-1:(c+r+e.length)%e.length;n(e[i].value),s.current[i]?.focus()},className:X(`ui-v2 relative inline-flex items-center gap-0.5 rounded-control bg-surface p-0.5 ring-1 ring-inset ring-line`,a),children:(0,Q.jsx)(Ac,{children:e.map((e,t)=>{let r=t===c;return(0,Q.jsxs)(`button`,{ref:e=>{s.current[t]=e},type:`button`,role:`radio`,"aria-checked":r,"aria-label":e.title,title:e.title,tabIndex:r?0:-1,onClick:()=>n(e.value),className:X(`relative inline-flex cursor-pointer items-center justify-center rounded-[calc(var(--radius-control)-2px)] font-medium`,`transition-colors duration-200 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,`[&_svg]:size-3.5`,i===`sm`?`h-[calc(var(--ocx-control-h-sm)-4px)] min-w-7 px-2 text-xs`:`h-[calc(var(--ocx-control-h)-4px)] min-w-8 px-3 text-[13px]`,r?`text-fg`:`text-fg-subtle hover:text-fg-muted`),children:[r&&(0,Q.jsx)(jc,{layoutId:o}),(0,Q.jsx)(`span`,{className:`relative inline-flex items-center gap-1.5`,children:e.label})]},e.value)})})})}var Nc={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`},Pc=(0,Z.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n,absoluteStrokeWidth:r=!1,className:i=``,altIcon:a,showAlt:o=!1,icon:s,primaryColor:c,secondaryColor:l,disableSecondaryOpacity:u=!1,...d},f)=>{let p=n===void 0?void 0:r?Number(n)*24/Number(t):n,m=p===void 0?{}:{strokeWidth:p,stroke:`currentColor`},h={ref:f,...Nc,width:t,height:t,color:c||e,className:i,...m,...d},g=[...o&&a?a:s].sort(([,e],[,t])=>{let n=e.opacity!==void 0;return t.opacity===void 0?n?-1:0:1}).map(([t,n])=>{let r=n.opacity!==void 0,i=r&&!u?n.opacity:void 0,a=l?{...n.stroke===void 0?{fill:r?l:c||e}:{stroke:r?l:c||e}}:{};return(0,Z.createElement)(t,{...n,...m,...a,opacity:i,key:n.key})});return(0,Z.createElement)(`svg`,h,g)});Pc.displayName=`HugeiconsIcon`;var Fc=[[`path`,{d:`M16 2V6M8 2V6`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M13 4H11C7.22876 4 5.34315 4 4.17157 5.17157C3 6.34315 3 8.22876 3 12V14C3 17.7712 3 19.6569 4.17157 20.8284C5.34315 22 7.22876 22 11 22H13C16.7712 22 18.6569 22 19.8284 20.8284C21 19.6569 21 17.7712 21 14V12C21 8.22876 21 6.34315 19.8284 5.17157C18.6569 4 16.7712 4 13 4Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M3 10H21`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`2`}],[`path`,{d:`M12.1258 14H12.0008M12.1258 18H12.0008M7.625 14H7.5M7.625 18H7.5M16.625 14H16.5M12.2508 14C12.2508 14.1381 12.1389 14.25 12.0008 14.25C11.8628 14.25 11.7508 14.1381 11.7508 14C11.7508 13.8619 11.8628 13.75 12.0008 13.75C12.1389 13.75 12.2508 13.8619 12.2508 14ZM12.2508 18C12.2508 18.1381 12.1389 18.25 12.0008 18.25C11.8628 18.25 11.7508 18.1381 11.7508 18C11.7508 17.8619 11.8628 17.75 12.0008 17.75C12.1389 17.75 12.2508 17.8619 12.2508 18ZM7.75 14C7.75 14.1381 7.63807 14.25 7.5 14.25C7.36193 14.25 7.25 14.1381 7.25 14C7.25 13.8619 7.36193 13.75 7.5 13.75C7.63807 13.75 7.75 13.8619 7.75 14ZM7.75 18C7.75 18.1381 7.63807 18.25 7.5 18.25C7.36193 18.25 7.25 18.1381 7.25 18C7.25 17.8619 7.36193 17.75 7.5 17.75C7.63807 17.75 7.75 17.8619 7.75 18ZM16.75 14C16.75 14.1381 16.6381 14.25 16.5 14.25C16.3619 14.25 16.25 14.1381 16.25 14C16.25 13.8619 16.3619 13.75 16.5 13.75C16.6381 13.75 16.75 13.8619 16.75 14Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`3`}]],Ic=[[`path`,{d:`M21 21H10C6.70017 21 5.05025 21 4.02513 19.9749C3 18.9497 3 17.2998 3 14V3`,stroke:`currentColor`,strokeLinecap:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M13 10L13 21`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M18 13L18 21`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`2`}],[`path`,{d:`M8 13L8 20`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`3`}],[`path`,{d:`M21 7.98693C19.16 7.98693 17.1922 8.24252 15.8771 6.49346C14.3798 4.50218 11.6202 4.50218 10.1229 6.49346C8.80782 8.24252 6.84003 7.98693 5 7.98693H3`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`4`}]],Lc=[[`path`,{d:`M14 4H10C6.22876 4 4.34315 4 3.17157 5.17157C2 6.34315 2 8.22876 2 12C2 15.7712 2 17.6569 3.17157 18.8284C4.34315 20 6.22876 20 10 20H14C17.7712 20 19.6569 20 20.8284 18.8284C22 17.6569 22 15.7712 22 12C22 8.22876 22 6.34315 20.8284 5.17157C19.6569 4 17.7712 4 14 4Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M7 9L8.83981 10.5858C9.61327 11.2525 10 11.5858 10 12C10 12.4142 9.61327 12.7475 8.83981 13.4142L7 15`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M13 16H17`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`2`}]],Rc=[[`path`,{d:`M14 21H16M14 21C13.1716 21 12.5 20.3284 12.5 19.5V17L12 17M14 21H10M10 21H8M10 21C10.8284 21 11.5 20.3284 11.5 19.5V17L12 17M12 17V21`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M16 3H8C5.17157 3 3.75736 3 2.87868 3.87868C2 4.75736 2 6.17157 2 9V11C2 13.8284 2 15.2426 2.87868 16.1213C3.75736 17 5.17157 17 8 17H16C18.8284 17 20.2426 17 21.1213 16.1213C22 15.2426 22 13.8284 22 11V9C22 6.17157 22 4.75736 21.1213 3.87868C20.2426 3 18.8284 3 16 3Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M12 12L12 13.5M12 12C12.737 12 13.3809 11.6013 13.7278 11.0079M12 12C11.263 12 10.6191 11.6013 10.2722 11.0079M12 8L12 6.5M12 8C12.737 8 13.3809 8.39866 13.7278 8.99209M12 8C11.263 8 10.6191 8.39865 10.2722 8.99209M15 8.25L13.7278 8.99209M9 11.75L10.2722 11.0079M15 11.75L13.7278 11.0079M9 8.25L10.2722 8.99209M13.7278 11.0079C13.9009 10.7119 14 10.3676 14 10C14 9.63244 13.9009 9.28805 13.7278 8.99209M10.2722 8.99209C10.0992 9.28804 10 9.63244 10 10C10 10.3676 10.0991 10.712 10.2722 11.0079`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`2`}]],zc=[[`path`,{d:`M7.5 14.5C7.5 11.2002 7.5 9.55025 8.52513 8.52513C9.55025 7.5 11.2002 7.5 14.5 7.5C17.7998 7.5 19.4497 7.5 20.4749 8.52513C21.5 9.55025 21.5 11.2002 21.5 14.5C21.5 17.7998 21.5 19.4497 20.4749 20.4749C19.4497 21.5 17.7998 21.5 14.5 21.5C11.2002 21.5 9.55025 21.5 8.52513 20.4749C7.5 19.4497 7.5 17.7998 7.5 14.5Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M7.5 16.5C6.10355 16.5 5.40533 16.5 4.84402 16.3036C3.83866 15.9518 3.0482 15.1613 2.69641 14.156C2.5 13.5947 2.5 12.8964 2.5 11.5V9.5C2.5 6.20017 2.5 4.55025 3.52513 3.52513C4.55025 2.5 6.20017 2.5 9.5 2.5H11.5C12.8964 2.5 13.5947 2.5 14.156 2.69641C15.1613 3.0482 15.9518 3.83866 16.3036 4.84402C16.5 5.40533 16.5 6.10355 16.5 7.5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}]],Bc=[[`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M9.5 9.5C9.5 8.11929 10.6193 7 12 7C13.3807 7 14.5 8.11929 14.5 9.5C14.5 10.3569 14.0689 11.1131 13.4117 11.5636C12.7283 12.0319 12 12.6716 12 13.5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M12.125 16.75H12M12.25 16.75C12.25 16.8881 12.1381 17 12 17C11.8619 17 11.75 16.8881 11.75 16.75C11.75 16.6119 11.8619 16.5 12 16.5C12.1381 16.5 12.25 16.6119 12.25 16.75Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`2`}]],Vc=[[`path`,{d:`M3 11.9896V14.5C3 17.7998 3 19.4497 4.02513 20.4749C5.05025 21.5 6.70017 21.5 10 21.5H14C17.2998 21.5 18.9497 21.5 19.9749 20.4749C21 19.4497 21 17.7998 21 14.5V11.9896C21 10.3083 21 9.46773 20.6441 8.74005C20.2882 8.01237 19.6247 7.49628 18.2976 6.46411L16.2976 4.90855C14.2331 3.30285 13.2009 2.5 12 2.5C10.7991 2.5 9.76689 3.30285 7.70242 4.90855L5.70241 6.46411C4.37533 7.49628 3.71179 8.01237 3.3559 8.74005C3 9.46773 3 10.3083 3 11.9896Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}]],Hc=[[`path`,{d:`M2.5 12C2.5 7.52166 2.5 5.28249 3.89124 3.89124C5.28249 2.5 7.52166 2.5 12 2.5C16.4783 2.5 18.7175 2.5 20.1088 3.89124C21.5 5.28249 21.5 7.52166 21.5 12C21.5 16.4783 21.5 18.7175 20.1088 20.1088C18.7175 21.5 16.4783 21.5 12 21.5C7.52166 21.5 5.28249 21.5 3.89124 20.1088C2.5 18.7175 2.5 16.4783 2.5 12Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M21.5 13.5H16.5743C15.7322 13.5 15.0706 14.2036 14.6995 14.9472C14.2963 15.7551 13.4889 16.5 12 16.5C10.5111 16.5 9.70373 15.7551 9.30054 14.9472C8.92942 14.2036 8.26777 13.5 7.42566 13.5H2.5`,stroke:`currentColor`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}]],Uc=[[`path`,{d:`M20.4999 16.5V8.5C20.4999 6.14298 20.4999 4.96447 19.7676 4.23223C19.0354 3.5 17.8569 3.5 15.4999 3.5H8.49988C6.14286 3.5 4.96434 3.5 4.23211 4.23223C3.49988 4.96447 3.49988 6.14298 3.49988 8.5V16.5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M21.9841 20.5H2.01567C1.63273 20.5 1.38367 20.1088 1.55493 19.7764L3.49988 16.5H20.4999L22.4448 19.7764C22.6161 20.1088 22.367 20.5 21.9841 20.5Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}]],Wc=[[`path`,{d:`M20.1088 3.89124C21.5 5.28249 21.5 7.52166 21.5 12C21.5 16.4783 21.5 18.7175 20.1088 20.1088C18.7175 21.5 16.4783 21.5 12 21.5C7.52166 21.5 5.28249 21.5 3.89124 20.1088C2.5 18.7175 2.5 16.4783 2.5 12C2.5 7.52166 2.5 5.28249 3.89124 3.89124C5.28249 2.5 7.52166 2.5 12 2.5C16.4783 2.5 18.7175 2.5 20.1088 3.89124Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M8.5 2.5V21.5`,stroke:`currentColor`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M15.5 2.5V21.5`,stroke:`currentColor`,strokeWidth:`1.5`,key:`2`}]],Gc=[[`path`,{d:`M18.7088 3.49534C16.8165 2.55382 14.5009 2 12 2C9.4991 2 7.1835 2.55382 5.29116 3.49534C4.36318 3.95706 3.89919 4.18792 3.4496 4.91378C3 5.63965 3 6.34248 3 7.74814V11.2371C3 16.9205 7.54236 20.0804 10.173 21.4338C10.9067 21.8113 11.2735 22 12 22C12.7265 22 13.0933 21.8113 13.8269 21.4338C16.4576 20.0804 21 16.9205 21 11.2371L21 7.74814C21 6.34249 21 5.63966 20.5504 4.91378C20.1008 4.18791 19.6368 3.95706 18.7088 3.49534Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M9 11.5C9 11.5 10.4079 11.7519 11 13.5C11 13.5 12.5 10.5 15 9.5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}]],Kc=[[`path`,{d:`M19 4H5C4.06812 4 3.60218 4 3.23463 4.15224C2.74458 4.35523 2.35523 4.74458 2.15224 5.23463C2 5.60218 2 6.06812 2 7C2 7.93188 2 8.39782 2.15224 8.76537C2.35523 9.25542 2.74458 9.64477 3.23463 9.84776C3.60218 10 4.06812 10 5 10H19C19.9319 10 20.3978 10 20.7654 9.84776C21.2554 9.64477 21.6448 9.25542 21.8478 8.76537C22 8.39782 22 7.93188 22 7C22 6.06812 22 5.60218 21.8478 5.23463C21.6448 4.74458 21.2554 4.35523 20.7654 4.15224C20.3978 4 19.9319 4 19 4Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}],[`path`,{d:`M19 14H5C4.06812 14 3.60218 14 3.23463 14.1522C2.74458 14.3552 2.35523 14.7446 2.15224 15.2346C2 15.6022 2 16.0681 2 17C2 17.9319 2 18.3978 2.15224 18.7654C2.35523 19.2554 2.74458 19.6448 3.23463 19.8478C3.60218 20 4.06812 20 5 20H19C19.9319 20 20.3978 20 20.7654 19.8478C21.2554 19.6448 21.6448 19.2554 21.8478 18.7654C22 18.3978 22 17.9319 22 17C22 16.0681 22 15.6022 21.8478 15.2346C21.6448 14.7446 21.2554 14.3552 20.7654 14.1522C20.3978 14 19.9319 14 19 14Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`1`}],[`path`,{d:`M6.125 7H6M6.25 7C6.25 7.13807 6.13807 7.25 6 7.25C5.86193 7.25 5.75 7.13807 5.75 7C5.75 6.86193 5.86193 6.75 6 6.75C6.13807 6.75 6.25 6.86193 6.25 7Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`2`}],[`path`,{d:`M10.125 7H10M10.25 7C10.25 7.13807 10.1381 7.25 10 7.25C9.86193 7.25 9.75 7.13807 9.75 7C9.75 6.86193 9.86193 6.75 10 6.75C10.1381 6.75 10.25 6.86193 10.25 7Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`3`}],[`path`,{d:`M6.125 17H6M6.25 17C6.25 17.1381 6.13807 17.25 6 17.25C5.86193 17.25 5.75 17.1381 5.75 17C5.75 16.8619 5.86193 16.75 6 16.75C6.13807 16.75 6.25 16.8619 6.25 17Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`4`}],[`path`,{d:`M10.125 17H10M10.25 17C10.25 17.1381 10.1381 17.25 10 17.25C9.86193 17.25 9.75 17.1381 9.75 17C9.75 16.8619 9.86193 16.75 10 16.75C10.1381 16.75 10.25 16.8619 10.25 17Z`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`5`}]],qc=[[`path`,{d:`M5 14L8.5 17.5L19 6.5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}]];function Jc({id:e,title:t,lede:n,children:r,className:i}){let a=(0,Z.useId)();return(0,Q.jsxs)(`section`,{id:e,"aria-labelledby":a,className:X(`pv2-section min-w-0 scroll-mt-6 rounded-card bg-surface p-1`,i),children:[(0,Q.jsxs)(`header`,{className:`flex flex-col gap-0.5 px-4 pt-3 pb-3`,children:[(0,Q.jsx)(`h3`,{id:a,className:`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em] text-fg`,children:t}),n&&(0,Q.jsx)(`p`,{className:`m-0 max-w-[70ch] text-[13px] leading-[18px] text-fg-muted`,children:n})]}),(0,Q.jsx)(`div`,{className:`pv2-section-body flex min-w-0 flex-col divide-y divide-line rounded-[12px] bg-raised ring-1 ring-line`,children:r})]})}function Yc({label:e,expanded:t,controls:n,onClick:r,buttonRef:i,popup:a}){return(0,Q.jsx)(`button`,{ref:i,type:`button`,onClick:r,"aria-label":e,title:e,"aria-expanded":t,"aria-controls":n,"aria-haspopup":a,className:X(`pv2-help inline-grid size-[22px] shrink-0 cursor-pointer place-items-center rounded-full border-0 bg-transparent p-0 text-fg-subtle`,`transition-colors duration-150 hover:bg-surface-2 hover:text-fg`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,t&&`bg-surface-2 text-fg`),children:(0,Q.jsx)(Pc,{icon:Bc,size:15,strokeWidth:1.8,"aria-hidden":`true`})})}function Xc({label:e,labelFor:t,labelId:n,hint:r,details:i,help:a,badge:o,control:s,children:c,stacked:l,inline:u,className:d,busy:f}){let p=b(),m=(0,Z.useId)(),[h,g]=(0,Z.useState)(!1),_=typeof e==`string`?e:void 0,v=`m-0 text-[14px] leading-5 font-medium text-fg`;return(0,Q.jsxs)(`div`,{className:X(`pv2-row flex min-w-0 flex-col gap-3 px-4 py-3.5`,d),"aria-busy":f||void 0,children:[(0,Q.jsxs)(`div`,{className:X(`flex min-w-0 flex-col gap-3`,!l&&`sm:flex-row sm:items-center sm:justify-between sm:gap-6`,u&&`flex-row items-center justify-between gap-4`),children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-h-[22px] flex-wrap items-center gap-x-1.5 gap-y-1`,children:[t?(0,Q.jsx)(`label`,{htmlFor:t,id:n,className:v,children:e}):(0,Q.jsx)(`span`,{id:n,className:v,children:e}),i&&(0,Q.jsx)(Yc,{label:_?p(`proxyV2.detailsFor`,{name:_}):p(`proxyV2.details`),expanded:h,controls:m,onClick:()=>g(e=>!e)}),a,o]}),r&&(0,Q.jsx)(`p`,{className:`m-0 max-w-[62ch] text-[13px] leading-[18px] text-fg-muted`,children:r}),i&&(0,Q.jsx)(`div`,{id:m,hidden:!h,className:`pv2-details mt-1.5 max-w-[68ch] text-[13px] leading-[19px] text-fg-muted`,children:i})]}),s&&(0,Q.jsx)(`div`,{className:X(`pv2-row-control flex min-w-0 flex-wrap items-center gap-2`,!l&&`sm:shrink-0 sm:justify-end`,u&&`shrink-0`),children:s})]}),c]})}function Zc({locale:e,health:t,providers:n,usage30d:r,usageLoading:i,healthLoading:a,startupHealth:o,projectConfigWarnings:s}){let c=b(),l=t?.status===`ok`,u=!!r&&r.summary.requests>0;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`dash-overview-head flex flex-col gap-2`,children:[(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 xl:grid-cols-5`,children:[(0,Q.jsx)(Qc,{label:c(`dash.status`),busy:a,children:(0,Q.jsxs)(`span`,{className:X(`flex items-center gap-2`,l?`text-success`:`text-danger`),children:[(0,Q.jsx)(`span`,{className:X(`size-2 shrink-0 rounded-full`,l?`bg-success`:`bg-danger`),"aria-hidden":`true`}),c(l?`dash.online`:`dash.offline`)]})}),(0,Q.jsx)(Qc,{label:c(`dash.version`),busy:a,title:t?.version,children:(0,Q.jsx)(`span`,{className:`dash-stat-version block truncate`,children:t?.version??`—`})}),(0,Q.jsx)(Qc,{label:c(`dash.uptime`),busy:a,children:t?Xr(t.uptime,e):`—`}),(0,Q.jsx)(Qc,{label:c(`dash.providers`),busy:a,children:n.length}),(0,Q.jsx)(Qc,{label:c(`dash.tokens30d`),busy:i,sub:u?c(`dash.coverage`).replace(`{pct}`,`${Math.round(r.summary.coverageRatio*100)}%`):void 0,children:u?$e(r.summary.totalTokens,e):`—`})]}),(0,Q.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>En(`startup`),className:X(`group flex h-[var(--ocx-control-h)] w-full cursor-pointer items-center gap-2.5 rounded-control border-0 bg-surface px-3.5 text-left text-[13px] text-fg-muted`,`transition-colors duration-150 hover:bg-surface-2 hover:text-fg`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`),children:[(0,Q.jsx)(`span`,{className:X(`size-2 shrink-0 rounded-full`,o===`error`?`bg-danger`:o===`at-risk`?`bg-warning`:o===`unverified`?`bg-fg-subtle`:`bg-success`),"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:c(o===`error`?`startup.error`:o===`unverified`?`startup.unverified`:o===`at-risk`?`startup.summary.atRisk`:o===`protected`?`startup.summary.protected`:`startup.summary.native`)}),(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`,className:`shrink-0 text-fg-subtle transition-transform duration-150 group-hover:translate-x-0.5`})]}):(0,Q.jsx)(`div`,{className:`h-[var(--ocx-control-h)] rounded-control bg-surface`,"aria-hidden":`true`})})]}),(0,Q.jsx)(ni,{data:r}),s.length>0&&(0,Q.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,Q.jsx)(St,{}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:c(`dash.projectConfigTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:c(`dash.projectConfigHint`)}),(0,Q.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,Q.jsxs)(`li`,{style:{marginBottom:8},children:[(0,Q.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,Q.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}function Qc({label:e,children:t,sub:n,busy:r,title:i}){return(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1 rounded-card bg-surface px-4 py-3`,"aria-busy":r||void 0,title:i,children:[(0,Q.jsx)(`span`,{className:`text-xs font-medium text-fg-subtle`,children:e}),(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-[17px] leading-6 font-semibold tracking-[-0.01em] tabular-nums text-fg`,children:t}),n&&(0,Q.jsx)(`span`,{className:`dash-stat-coverage truncate text-xs text-fg-subtle`,children:n})]})}function $c({maMode:e,maSupportsPlaintextV2:t,maBusy:n,switchMaMode:r}){let i=b();return(0,Q.jsx)(`fieldset`,{disabled:n,className:`dash-ma-switch m-0 min-w-0 border-0 p-0 disabled:opacity-60`,children:(0,Q.jsx)(Mc,{"aria-label":i(`dash.multiAgent`),value:e,onChange:t=>{t!==e&&r(t)},items:Wr(t||e===`v2-plaintext`).map(e=>({value:e,label:i(`models.v2Mode_${e}`)}))})})}function el({maHelpTriggerRef:e,maHelpOpen:t,setMaHelpOpen:n}){let r=b();return(0,Q.jsx)(Yc,{buttonRef:e,label:r(`dash.multiAgent`),expanded:t,controls:`multi-agent-help-dialog`,popup:`dialog`,onClick:()=>n(!0)})}var tl=`gpt-daybreak-blue-latest`,nl=`gpt-6-astra`,rl=`gpt-6-sol`,il=`gpt-6-luna`,al=`gpt-6.1-sol`,ol=`gpt-6.1-terra`,sl=`gpt-6.2-sol`,cl=`gpt-6.2-astra`,ll=`gpt-6-astra-minor`,ul=Object.freeze({contextWindow:272e3,maxContextWindow:872e3,maxInputTokens:872e3});Object.freeze({...ul,contextWindow:5e5}),Object.freeze({...ul,contextWindow:5e5});var dl=new Set([tl,ll]),fl=Object.freeze({[tl]:`gpt-5.6-sol`,[ll]:nl});Object.freeze(Object.keys(fl)),Object.freeze({[tl]:{displayName:`Daybreak Blue`,description:`Frontier general-purpose model with safeguards for defensive cybersecurity work.`},[ll]:{displayName:`GPT-6-Astra-Minor`,description:`Unreleased GPT-6 Astra variant; shown only when your account's Codex roster lists it.`}});var pl=[...Object.freeze([`gpt-5.5`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`,tl,nl,rl,il,al,ol,sl,cl,ll])],ml=new Set(pl);[...dl];var hl=18e5,gl=[`account_unavailable`,`access_denied`,`rate_limited`,`upstream_error`,`redirect_blocked`,`destination_blocked`,`dns_failed`,`timeout`,`transport_error`,`response_unusable`];function _l(e){return gl.find(t=>t===e)}var vl=6e4,yl=864e5;function bl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=Object.keys(e);if(t.length!==1||t[0]!==`ttlMs`)return;let n=e.ttlMs;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=6e4&&n<=864e5?{ttlMs:n}:void 0}var xl=1e3,Sl=12e4,Cl=4e3;function wl(e){try{let t=e.trim();if(/[\u0000-\u001f\u007f]/.test(t))return!1;let n=t.replace(/^[a-z][a-z\d+.-]*:[/\\]*/i,``).split(/[/\\]/,1)[0]??``;if(/[?#]/.test(t)||n.includes(`@`))return!1;let r=new URL(t);if(r.username||r.password||r.search||r.hash)return!1;let i=r.hostname,a=i===`localhost`||i===`[::1]`||/^(?:(?:127|10)\.\d+|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+$/.test(i)||/^\[f[cd][\da-f]{2}:/.test(i)||/^\[::ffff:7f[\da-f]{2}:/.test(i);return r.protocol===`https:`||r.protocol===`http:`&&a&&r.pathname.replace(/\/+$/,``).endsWith(`/systemone`)}catch{return!1}}function Tl(e){return e?e.adapter===`jev-decision`?e.disabled===!0?`disabled`:wl(e.baseUrl??``)?!e.defaultModel?.trim()&&!e.models?.[0]?.trim()?`model`:null:`endpoint`:`notDecision`:`missing`}function El(e){return e.name===`jev`?e.adapter===`jev-decision`&&e.disabled!==!0&&e.hasApiKey===!0:Tl(e)===null}var Dl={typesafe:`cws.jev.backend.typesafe`,systemone:`cws.jev.backend.systemone`,model:`cws.jev.backend.model`,unknown:`cws.jev.backend.unknown`};function Ol(e){return e.decisionModel==null?e.decisionProvider!=null&&e.decisionProvider.trim()!==`jev`?`systemone`:`typesafe`:`model`}function kl(e,t,n){let r=e.trim(),i=e=>r===`combo/${e.id.trim()}`||!!e.alias?.trim()&&r===e.alias.trim()||!!e.model?.trim()&&r===e.model.trim();return!!n&&i(n)||t.some(e=>e.strategy===`jev`&&i(e))}function Al(e,t,n,r){let i=new Set(t.filter(e=>!e.disabled&&e.adapter!==`jev-decision`).map(e=>e.name)),a=e.filter(e=>!e.disabled&&e.provider!==`combo`&&i.has(e.provider)).map(e=>e.namespaced?.trim()||`${e.provider}/${e.id}`);return a.push(...n.filter(e=>e.strategy!==`jev`).map(e=>e.model)),[...new Set(a)].filter(e=>!kl(e,n,r)).sort((e,t)=>e.localeCompare(t))}var jl=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],Ml=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`,`jev`],Nl={failover:`cws.strategy.failover`,"round-robin":`cws.strategy.roundRobin`,random:`cws.strategy.random`,"least-used":`cws.strategy.leastUsed`,"reset-window":`cws.strategy.resetWindow`,jev:`cws.strategy.jev`},Pl={failover:`cws.strategy.failoverHint`,"round-robin":`cws.strategy.roundRobinHint`,random:`cws.strategy.randomHint`,"least-used":`cws.strategy.leastUsedHint`,"reset-window":`cws.strategy.resetWindowHint`,jev:`cws.strategy.jevHint`},Fl={failover:`cws.targets.failoverHint`,"round-robin":`cws.targets.roundRobinHint`,random:`cws.targets.randomHint`,"least-used":`cws.targets.leastUsedHint`,"reset-window":`cws.targets.resetWindowHint`,jev:`cws.targets.jevHint`},Il=new Set(Ml),Ll={missing:`cws.jev.decisionIssue.missing`,notDecision:`cws.jev.decisionIssue.notDecision`,disabled:`cws.jev.decisionIssue.disabled`,endpoint:`cws.jev.decisionIssue.endpoint`,model:`cws.jev.decisionIssue.model`};function Rl(e,t,n=`strict`){let r=e.filter(e=>e.provider.trim()&&e.model.trim());if(r.length===0)return[...jl];let i=new Set(jl),a=null;for(let e of r){let r=`${e.provider.trim()}/${e.model.trim()}`,o=t.get(r);if(o===void 0||n===`adaptive`&&o.length===0)continue;let s=o.filter(e=>i.has(e));if(a===null)a=s;else{let e=new Set(s);a=a.filter(t=>e.has(t))}}if(a===null)return[...jl];let o=new Set(a);return jl.filter(e=>o.has(e))}var zl=hl,Bl=0;function Vl(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},...e.reasoningEfforts===void 0?{}:{reasoningEfforts:[...e.reasoningEfforts]},...e.modelProfile===void 0?{}:{modelProfile:e.modelProfile},clientKey:e.clientKey??`ct-${++Bl}`}}function Hl(e){return e===`disabled`?`disabled`:`auto`}function Ul(e){return e===`adaptive`?`adaptive`:`strict`}var Wl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Gl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,Kl=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function ql(e){return Wl.test(e.trim())}function Jl(e){return`combo/${e.trim()}`}function Yl(e,t){return(typeof t==`string`?t.trim():``)||Jl(e)}function Xl(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!Kl.test(n));return{...e,alias:n?t:null,model:Yl(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function Zl(e){let t=typeof e==`string`?e.trim():``;return t&&t!==`jev`?t:null}function Ql(e){return typeof e==`number`&&Number.isInteger(e)?e:null}function $l(e){return typeof e==`string`&&e.trim()?e.trim():null}function eu(e){return typeof e==`string`&&Il.has(e)?e:`failover`}function tu(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function nu(e){return typeof e==`string`&&jl.includes(e)?e:null}function ru(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function iu(e){if(!Array.isArray(e)||e.length===0)return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`||!jl.includes(r))return;let e=r;if(n.has(e))return;n.add(e),t.push(e)}return t}function au(e){if(!e||typeof e!=`object`)return[];let t=e.combos;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`?t.id.trim():``;if(!r)continue;let i=Array.isArray(t.targets)?t.targets:[],a=[];for(let e of i){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.provider==`string`?t.provider.trim():``,r=typeof t.model==`string`?t.model.trim():``;if(!n||!r)continue;let i=ru(t.weight),o=iu(t.reasoningEfforts);a.push(Vl({provider:n,model:r,...i===void 0?{}:{weight:i},...o===void 0?{}:{reasoningEfforts:o},...typeof t.modelProfile==`string`?{modelProfile:t.modelProfile}:{}}))}let o=Zl(t.decisionProvider),s=$l(t.decisionModel),c=Ql(t.decisionTimeoutMs),l=t.sessionPin===null?null:bl(t.sessionPin);n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():Yl(r,$l(t.alias)),alias:$l(t.alias),nativeAlias:t.nativeAlias===!0,displayName:$l(t.displayName),strategy:eu(t.strategy),stickyLimit:tu(t.stickyLimit),defaultEffort:nu(t.defaultEffort),imageInput:Hl(t.imageInput),reasoningEffortMode:Ul(t.reasoningEffortMode),...o===null?{}:{decisionProvider:o},...s===null?{}:{decisionModel:s},...c===null?{}:{decisionTimeoutMs:c},...l===void 0?{}:{sessionPin:l},targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function ou(e){let t=[],n=[],r=[];for(let i of e)i.strategy===`failover`?t.push(i):i.strategy===`round-robin`?n.push(i):r.push(i);return{failover:t,roundRobin:n,other:r}}function su(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.id.toLowerCase().includes(n)||e.model.toLowerCase().includes(n)?!0:e.targets.some(e=>e.provider.toLowerCase().includes(n)||e.model.toLowerCase().includes(n))):e}function cu(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function lu(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function uu(e,t){let n=cu(e.routingQuota);if(!n||n.state!==`available`&&n.state!==`exhausted`)return null;let r=lu(n.updatedAt),i=lu(n.validUntil);return r===null||r<0||r>t||t-r>=zl||i===null||i<=t||i>r+zl?null:{state:n.state,validUntil:i}}function du(e,t){return uu(e,t)?.state??`unknown`}function fu(e,t=Date.now()){if(!Array.isArray(e))return;let n;for(let r of e){let e=cu(r);if(!e||typeof e.provider!=`string`||!e.provider.trim())continue;let i=uu(e,t);i&&(n===void 0||i.validUntil<n)&&(n=i.validUntil)}return n}function pu(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=cu(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=du(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function mu(e,t,n){let r=e.flatMap(e=>{let t=e.provider.trim();return!t||!e.model.trim()||!Object.hasOwn(n,t)||n[t]?.disabled===!0?[]:[t]});if(r.length===0)return`unknown`;let i=!1;for(let e of r){let n=t[e]??`unknown`;if(n===`available`)return`available`;n===`unknown`&&(i=!0)}return i?`unknown`:`exhausted`}function hu(e,t={}){let n=[],r=t.cataloguedComboIds;for(let i of e)i.targets.length===0?n.push({id:i.id,model:i.model,reason:`empty-targets`}):i.targets.length<2&&n.push({id:i.id,model:i.model,reason:`few-targets`}),r&&i.targets.length>0&&!r.has(i.id)&&n.push({id:i.id,model:i.model,reason:`catalog-omitted`}),t.providerQuotaStates&&t.providers&&mu(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function gu(e,t){return e.reasoningEfforts===void 0||t.reasoningEfforts===void 0?e.reasoningEfforts===t.reasoningEfforts:e.reasoningEfforts.length===t.reasoningEfforts.length&&e.reasoningEfforts.every((e,n)=>e===t.reasoningEfforts[n])}function _u(e,t){return e.id!==t.id||e.alias!==t.alias||e.nativeAlias!==t.nativeAlias||e.displayName!==t.displayName||e.strategy!==t.strategy||e.stickyLimit!==t.stickyLimit||e.defaultEffort!==t.defaultEffort||(e.imageInput??`auto`)!==(t.imageInput??`auto`)||(e.reasoningEffortMode??`strict`)!==(t.reasoningEffortMode??`strict`)||e.strategy===`jev`&&((e.decisionProvider??null)!==(t.decisionProvider??null)||(e.decisionModel??null)!==(t.decisionModel??null)||(e.decisionTimeoutMs??null)!==(t.decisionTimeoutMs??null)||e.sessionPin===void 0!=(t.sessionPin===void 0)||(e.sessionPin?.ttlMs??null)!==(t.sessionPin?.ttlMs??null))||e.targets.length!==t.targets.length?!1:e.targets.every((e,n)=>{let r=t.targets[n];return e.provider===r.provider&&e.model===r.model&&(e.weight??1)===(r.weight??1)&&gu(e,r)&&(e.modelProfile??``)===(r.modelProfile??``)})}function vu(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},...t.visionSidecarTargets?.length?{visionSidecarTargets:t.visionSidecarTargets}:{},combo:{targets:e.targets.map(e=>({provider:e.provider.trim(),model:e.model.trim(),...n?{weight:e.weight??1}:{},...e.reasoningEfforts===void 0?{}:{reasoningEfforts:[...e.reasoningEfforts]},...e.modelProfile?.trim()?{modelProfile:e.modelProfile.trim()}:{}})),strategy:e.strategy,defaultEffort:e.defaultEffort,imageInput:e.imageInput===`disabled`?`disabled`:`auto`,reasoningEffortMode:e.reasoningEffortMode===`adaptive`?`adaptive`:`strict`,...e.strategy===`round-robin`?{stickyLimit:e.stickyLimit}:{},...e.alias&&e.alias.trim()?{alias:e.alias.trim()}:{},...e.nativeAlias?{nativeAlias:!0}:{},...e.displayName&&e.displayName.trim()?{displayName:e.displayName.trim()}:{},...e.strategy===`jev`?{decisionProvider:e.decisionModel?.trim()?null:Zl(e.decisionProvider),decisionModel:e.decisionModel?.trim()||null,decisionTimeoutMs:e.decisionTimeoutMs??null,...e.sessionPin===void 0?{}:{sessionPin:e.sessionPin}}:{}}}}function yu(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!ql(n))return`invalidId`;if(t.existingIds.includes(n))return`duplicateId`;if(Object.hasOwn(t.providers,`combo`))return`reservedNamespace`;if(Object.hasOwn(t.providers,n))return`providerCollision`;let r=e.alias?.trim()??``,i=e.displayName?.trim()??``;if(r){if(!Gl.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&Kl.test(r)&&!e.nativeAlias)return`aliasNativeFamily`;if((t.existingAliases??[]).includes(r))return`duplicateAlias`}let a=[...e.displayName??``].some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127});if(e.displayName!==null&&(i.length>128||a))return`invalidDisplayName`;if(e.nativeAlias&&!ml.has(r))return`unsupportedNativeAlias`;if(e.nativeAlias&&!i)return`missingNativeAliasDisplayName`;if(e.targets.length<1)return`noTargets`;for(let n of e.targets){if(!n.provider.trim()||!n.model.trim())return`incompleteTarget`;if(!Object.hasOwn(t.providers,n.provider.trim()))return`unknownProvider`;if(n.reasoningEfforts!==void 0&&(n.reasoningEfforts.length===0||n.reasoningEfforts.some(e=>!jl.includes(e))||new Set(n.reasoningEfforts).size!==n.reasoningEfforts.length))return`invalidReasoningEfforts`;if(n.modelProfile!==void 0&&(n.modelProfile.length>512||[...n.modelProfile].some(e=>{let t=e.charCodeAt(0);return t<32&&t!==9&&t!==10&&t!==13||t===127})))return`invalidModelProfile`}let o=new Set;for(let t of e.targets){let e=`${t.provider.trim()}/${t.model.trim()}`;if(o.has(e))return`duplicateTarget`;o.add(e)}if(e.strategy===`round-robin`&&(!Number.isInteger(e.stickyLimit)||e.stickyLimit<1||e.stickyLimit>100))return`invalidStickyLimit`;if(e.strategy===`round-robin`||e.strategy===`random`)for(let t of e.targets){let e=t.weight??1;if(!Number.isInteger(e)||e<1||e>1e4)return`invalidWeight`}if(e.strategy===`jev`&&e.sessionPin!=null&&!bl(e.sessionPin))return`invalidSessionPin`;if(e.strategy===`jev`&&e.decisionTimeoutMs!=null&&(!Number.isInteger(e.decisionTimeoutMs)||e.decisionTimeoutMs<1e3||e.decisionTimeoutMs>12e4))return`invalidDecisionTimeout`;if(e.strategy===`jev`&&Ol(e)===`model`){let n=e.decisionModel?.trim()??``;if(!n||n.length>512||e.decisionProvider!=null||kl(n,t.combos??[],e)||t.decisionModels&&!t.decisionModels.includes(n))return`invalidDecisionModel`}return e.strategy===`jev`&&Ol(e)===`systemone`&&(!e.decisionProvider?.trim()||Cu(e.decisionProvider,t.providers)!==null)?`invalidDecisionProvider`:e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function bu(e=``){return{id:e,model:e?Jl(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`strict`,targets:[Vl()]}}var xu=[`gpt-6-astra`,`gpt-5.6-sol`,`gpt-5.6-luna`];function Su(e,t,n){let r=xu.flatMap(n=>{let r=e.find(e=>e.id===n&&(t===void 0||t.has(e.provider)));return r?[Vl({provider:r.provider,model:r.id})]:[]});return{id:`jev-auto`,model:`jev-auto`,alias:`jev-auto`,nativeAlias:!1,displayName:null,strategy:`jev`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`adaptive`,decisionProvider:Zl(n),targets:r.length>0?r:[Vl()]}}function Cu(e,t){let n=Zl(e);return n===null?null:Tl(Object.hasOwn(t,n)?t[n]:void 0)}function wu(e,t){let n=e.filter(e=>e.adapter===`jev-decision`&&e.name!==`jev`).toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>{let t=Tl(e);return{id:e.name,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t?{issue:t}:{}}}),r=Zl(t),i=r!==null&&!n.some(e=>e.id===r)?[{id:r,issue:e.some(e=>e.name===r)?`notDecision`:`missing`}]:[];return[{id:null},...n,...i]}function Tu(e,t){if(e.strategy!==`jev`)return null;let n=Zl(e.decisionProvider),r=n===null?void 0:t.find(e=>e.name===n);return{provider:n,model:e.decisionModel?.trim()||null,baseUrl:r?.baseUrl?.trim()||null,timeoutMs:e.decisionTimeoutMs??null}}var Eu=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],Du=[`manual`,`auto`],Ou=300,ku=[`manual`,`manual+auto`,`auto`],Au={manual:`compactionRouting.triggersManual`,"manual+auto":`compactionRouting.triggersBoth`,auto:`compactionRouting.triggersAuto`},ju=[`all`,`selected`],Mu={all:`compactionRouting.sourcesAll`,selected:`compactionRouting.sourcesSelected`};function Nu(e){if(!e)return`manual`;let t=e.includes(`auto`);return e.includes(`manual`)?t?`manual+auto`:`manual`:t?`auto`:`manual`}function Pu(e){if(e===`auto`)return[`auto`];if(e===`manual+auto`)return[`manual`,`auto`]}function Fu(e){let t=new Map;for(let n of au(e))t.set(n.model,[...new Set(n.targets.flatMap(e=>e.provider?[e.provider]:[]))]);return t}function Iu(e){let t=e.compactionRouting;if(t==null)return null;if(!t||typeof t!=`object`||!(`model`in t)||typeof t.model!=`string`||!t.model.trim())throw Error(`invalid settings`);let n=`reasoningEffort`in t?t.reasoningEffort:void 0;if(n!==void 0&&(typeof n!=`string`||!Eu.includes(n)))throw Error(`invalid effort`);let r=`triggers`in t?t.triggers:void 0,i=`sourceModels`in t?t.sourceModels:void 0;if(i!==void 0&&(!Array.isArray(i)||!i.length||!i.every(e=>typeof e==`string`&&e.trim())))throw Error(`invalid sourceModels`);if(r!==void 0&&(!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`&&Du.includes(e))||new Set(r).size!==r.length))throw Error(`invalid triggers`);return{model:t.model,...n?{reasoningEffort:n}:{},...r?{triggers:r}:{},...i?{sourceModels:i}:{}}}function Lu(e){if(!e)return``;try{return new URL(e).hostname||e}catch{return e}}function Ru(e,t){let n=t.get(e);return n?`${e} (${n})`:e}function zu(e){return(0,Q.jsx)(Bu,{...e},e.apiBase)}function Bu({apiBase:e,models:t,providers:n=[]}){let r=b(),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(``),[u,f]=(0,Z.useState)(`manual`),[p,m]=(0,Z.useState)(`all`),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)(``),[y,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(()=>new Map),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(null),A=(0,Z.useCallback)(e=>{a(e),s(e?.model??``),l(e?.reasoningEffort??``),f(Nu(e?.triggers)),m(e?.sourceModels?`selected`:`all`),g(e?.sourceModels??[])},[]),j=e=>{g(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),T(null)},M=(0,Z.useCallback)(async()=>{if(k.current)return;let t=d(15e3);k.current=t,C(!1);try{let n=Iu(await cr(await fetch(`${e}/api/settings`,{signal:t.signal})));O.current&&k.current===t&&A(n);let r=await fetch(`${e}/api/combos`,{signal:t.signal}).then(cr).then(Fu).catch(()=>new Map);O.current&&k.current===t&&D(r)}catch{O.current&&k.current===t&&C(!0)}finally{t.clear(),k.current===t&&(k.current=null)}},[e,A]);(0,Z.useEffect)(()=>{O.current=!0;let e=window.setTimeout(()=>{M()},0);return()=>{window.clearTimeout(e),O.current=!1,k.current?.controller.abort(),k.current?.clear(),k.current=null}},[M]);let N=async()=>{if(k.current||i===void 0)return;let t=d(15e3);k.current=t,x(!0),T(null);try{let n=Iu(await cr(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({compactionRouting:o?{model:o,...c?{reasoningEffort:c}:{},...Pu(u)?{triggers:Pu(u)}:{},...p===`selected`&&h.length>0?{sourceModels:h}:{}}:null}),signal:t.signal})));O.current&&k.current===t&&(A(n),T(`saved`))}catch{O.current&&k.current===t&&T(`failed`)}finally{t.clear(),O.current&&k.current===t&&x(!1),k.current===t&&(k.current=null)}},P=[{value:``,label:r(`compactionRouting.currentModel`)},...[...new Set([...t.map(e=>e.namespaced),...o?[o]:[]])].map(e=>({value:e,label:Fe(e,r)}))],F=[...new Set([...n.map(e=>e.name),...t.flatMap(e=>e.provider?[e.provider]:[])])].map(e=>`${e}/*`),I=new Set([...F,...t.map(e=>e.namespaced)]),L=(i?.sourceModels??[]).filter(e=>!I.has(e)),R=y||i===void 0||S,z=i?.sourceModels?`selected`:`all`,B=new Set(i?.sourceModels),V=o!==(i?.model??``)||c!==(i?.reasoningEffort??``)||u!==Nu(i?.triggers)||p!==z||p===`selected`&&(h.length!==(i?.sourceModels?.length??0)||h.some(e=>!B.has(e))),H=p===`selected`&&h.length===0,U=new Set(h),W=[...new Set(t.map(e=>e.namespaced))].filter(e=>e.toLowerCase().includes(_.trim().toLowerCase())),ee=e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:U.has(e),disabled:R,onChange:()=>{j(e)}}),(0,Q.jsx)(`span`,{children:e})]},e),G=E.get(o),te=G!==void 0||o.startsWith(Jl(``)),ne=o.slice(0,Math.max(o.indexOf(`/`),0)),K=new Map(n.map(e=>[e.name,Lu(e.baseUrl)]).filter(([,e])=>e)),q=te?``:Ru(ne||o,K),J=G?.map(e=>Ru(e,K)).join(`, `)||r(`compactionRouting.comboProvidersUnknown`),re=u!==`manual`,Y=h.join(`, `),ie=!o||H?null:te?p===`selected`?r(`compactionRouting.comboWarningScoped`,{combo:o,providers:J,sources:Y}):r(`compactionRouting.comboWarning`,{combo:o,providers:J}):p===`selected`?r(`compactionRouting.providerWarningScoped`,{provider:q,sources:Y}):r(`compactionRouting.providerWarning`,{provider:q});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`compaction-routing-title`,"aria-busy":y||i===void 0&&!S,children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`flex-start`,flexWrap:`wrap`},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 20rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`compaction-routing-title`,children:r(`compactionRouting.title`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.description`)}),(0,Q.jsxs)(`details`,{className:`pv2-more`,children:[(0,Q.jsx)(`summary`,{children:r(`proxyV2.details`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.dataNotice`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.effortHint`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.sourcesHint`)})]})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls compaction-routing-controls`,style:{flex:`0 1 auto`},children:[(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-model`,children:r(`compactionRouting.model`)}),(0,Q.jsx)(Vn,{id:`compaction-routing-model`,value:o,options:P,disabled:R,label:r(`compactionRouting.model`),onChange:e=>{s(e),e||(l(``),f(`manual`),m(`all`),g([])),T(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-triggers`,children:r(`compactionRouting.triggers`)}),(0,Q.jsx)(Vn,{id:`compaction-routing-triggers`,value:u,disabled:R||!o,align:`right`,label:r(`compactionRouting.triggers`),options:ku.map(e=>({value:e,label:r(Au[e])})),onChange:e=>{f(e),T(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-sources`,children:r(`compactionRouting.sources`)}),(0,Q.jsx)(Vn,{id:`compaction-routing-sources`,value:p,disabled:R||!o,align:`right`,label:r(`compactionRouting.sources`),options:ju.map(e=>({value:e,label:r(Mu[e])})),onChange:e=>{m(e),T(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-effort`,children:r(`compactionRouting.effort`)}),(0,Q.jsx)(Vn,{id:`compaction-routing-effort`,value:c,disabled:R||!o,align:`right`,label:r(`compactionRouting.effort`),options:[{value:``,label:r(`compactionRouting.currentEffort`)},...Eu.map(e=>({value:e,label:r(`models.reasoningEffort.${e}`)}))],onChange:e=>{l(e),T(null)}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:R||!V||H,onClick:()=>{N()},children:r(y?`common.saving`:`common.save`)})]})]}),o&&p===`selected`&&(0,Q.jsxs)(`div`,{className:`compaction-sources-block`,children:[(0,Q.jsx)(`div`,{className:`field-label compaction-sources-title`,children:r(`compactionRouting.sourcesGridTitle`)}),(0,Q.jsxs)(`div`,{className:`source-scope-groups`,children:[F.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:r(`compactionRouting.sourcesProviders`)}),F.map(ee)]}),t.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:r(`compactionRouting.sourcesModels`)}),(0,Q.jsx)(`input`,{type:`search`,className:`input`,value:_,disabled:R,"aria-label":r(`pws.modelSearchPlaceholder`),placeholder:r(`pws.modelSearchPlaceholder`),onChange:e=>v(e.target.value)}),W.slice(0,Ou).map(ee),W.length>Ou&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:r(`pws.modelsTruncated`,{shown:Ou,total:W.length})})]}),L.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:r(`compactionRouting.sourcesSaved`)}),L.map(ee)]}),H&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.sourcesNone`)})]})]}),ie&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(St,{width:14}),` `,ie]}),o&&re&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(St,{width:14}),` `,r(`compactionRouting.autoNotice`)]}),S&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[r(`compactionRouting.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{M()},children:r(`common.retry`)})]}),w===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:r(`compactionRouting.saveFailed`)}),w===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:r(`compactionRouting.saved`)})]})}function Vu(e){if(!(`reasoningRetention`in e))throw Error(`Missing reasoningRetention settings`);return e.reasoningRetention??null}function Hu({apiBase:e}){let t=b();return(0,Q.jsxs)(`details`,{className:`panel`,children:[(0,Q.jsx)(`summary`,{className:`font-semibold`,children:t(`reasoningRetention.advanced`)}),(0,Q.jsx)(Uu,{apiBase:e},e)]})}function Uu({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(`20`),[c,l]=(0,Z.useState)(`100000`),[u,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(!1),v=(0,Z.useRef)(null),y=(0,Z.useCallback)(e=>{r(e),a(e?.enabled===!0),s(String(e?.maxContextPercent??20)),l(String(e?.maxTokens??1e5))},[]),x=(0,Z.useCallback)(async()=>{if(v.current)return;let t=d(15e3);v.current=t,m(!1);try{let n=Vu(await cr(await fetch(`${e}/api/settings`,{signal:t.signal})));_.current&&v.current===t&&y(n)}catch{_.current&&v.current===t&&m(!0)}finally{t.clear(),v.current===t&&(v.current=null)}},[e,y]);(0,Z.useEffect)(()=>{_.current=!0;let e=window.setTimeout(()=>{x()},0);return()=>{window.clearTimeout(e),_.current=!1,v.current?.controller.abort(),v.current?.clear(),v.current=null}},[x]);let S=o.trim()!==``&&Number.isFinite(Number(o))&&Number(o)>0&&Number(o)<=100,C=c.trim()!==``&&Number.isSafeInteger(Number(c))&&Number(c)>0,w=!i||S&&C,T=i!==(n?.enabled===!0)||i&&(Number(o)!==(n?.maxContextPercent??20)||Number(c)!==(n?.maxTokens??1e5)),E=async(t=!1)=>{if(v.current||n===void 0||!t&&!w)return;let r=d(15e3);v.current=r,f(!0),g(null);try{let n=Vu(await cr(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:r.signal,body:JSON.stringify({reasoningRetention:t?null:i?{enabled:!0,maxContextPercent:Number(o),maxTokens:Number(c)}:{enabled:!1}})})));_.current&&v.current===r&&(y(n),g(`saved`))}catch{_.current&&v.current===r&&g(`failed`)}finally{r.clear(),_.current&&v.current===r&&f(!1),v.current===r&&(v.current=null)}},D=u||n===void 0||p;return(0,Q.jsxs)(`section`,{"aria-labelledby":`reasoning-retention-title`,"aria-busy":u||n===void 0&&!p,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`reasoning-retention-title`,children:t(`reasoningRetention.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`reasoningRetention.description`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`reasoningRetention.storageHint`)}),(0,Q.jsx)(Rn,{on:i,disabled:D,label:t(`reasoningRetention.enable`),showLabel:!0,onClick:()=>{a(e=>!e),g(null)}}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`,alignItems:`flex-end`},children:[i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-percent`,children:[t(`reasoningRetention.percent`),(0,Q.jsx)(`input`,{id:`reasoning-retention-percent`,className:`input`,type:`number`,min:`0`,max:`100`,step:`any`,value:o,disabled:D,"aria-invalid":!S||void 0,"aria-describedby":S?void 0:`reasoning-retention-error`,onInput:e=>{s(e.currentTarget.value),g(null)}})]}),(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-tokens`,children:[t(`reasoningRetention.tokens`),(0,Q.jsx)(`input`,{id:`reasoning-retention-tokens`,className:`input`,type:`number`,min:`1`,step:`1`,value:c,disabled:D,"aria-invalid":!C||void 0,"aria-describedby":C?void 0:`reasoning-retention-error`,onInput:e=>{l(e.currentTarget.value),g(null)}})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:D||!w||!T,onClick:()=>{E()},children:t(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:D||n===null&&!T,onClick:()=>{E(!0)},children:t(`reasoningRetention.reset`)})]}),!w&&(0,Q.jsx)(`div`,{id:`reasoning-retention-error`,className:`notice notice-err`,role:`alert`,children:t(`reasoningRetention.invalid`)}),p&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[t(`reasoningRetention.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{x()},children:t(`common.retry`)})]}),h===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`reasoningRetention.saveFailed`)}),h===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`reasoningRetention.saved`)})]})}var Wu=0;function Gu(e){let t=e.split(/\n{2,}/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}function Ku(e,t,n,r,i){let a=S[e],o=`opencodex-action-dialog-${++Wu}`,s=document.activeElement,c=typeof s?.focus==`function`?s:null,l=!1,u=document.createElement(`dialog`);u.id=o,u.className=`modal-overlay`,u.setAttribute(`aria-labelledby`,`${o}-body`);let d=document.createElement(`button`);d.type=`button`,d.className=`modal-backdrop-dismiss`,d.tabIndex=-1,d.setAttribute(`aria-label`,a[`common.close`]);let f=document.createElement(`form`);f.className=`modal-card`;let p=e=>{if(l)return;l=!0,window.removeEventListener(`hashchange`,m),window.removeEventListener(`popstate`,m),document.removeEventListener(`keydown`,h),r?.removeEventListener(`abort`,m);let t=u.contains(document.activeElement);try{if(u.open&&typeof u.close==`function`&&u.close(),u.remove(),c?.isConnected)c.focus();else if(t){let e=i?.(c);e?.isConnected&&e.focus()}}finally{n(e)}};function m(){p(t)}function h(e){e.key===`Escape`&&p(t)}return d.addEventListener(`click`,()=>p(t)),u.addEventListener(`cancel`,e=>{e.preventDefault(),p(t)}),window.addEventListener(`hashchange`,m),window.addEventListener(`popstate`,m),r?.addEventListener(`abort`,m),u.append(d,f),document.body.append(u),typeof u.showModal==`function`?u.showModal():(u.setAttribute(`open`,``),document.addEventListener(`keydown`,h)),{form:f,bodyId:`${o}-body`,finish:p}}function qu(e,t,n,r=`div`){let i=document.createElement(r);i.id=t;for(let e of Gu(n)){let t=document.createElement(`p`);t.className=`modal-desc`,t.textContent=e,i.append(t)}return e.append(i),i}function Ju(e){let t=e.locale??x(),n=S[t],r=e.tone===`danger`;return new Promise(i=>{if(e.signal?.aborted){i(!1);return}let{form:a,bodyId:o,finish:s}=Ku(t,!1,i,e.signal,e.restoreFocusFallback);qu(a,o,e.message);let c=document.createElement(`div`);c.className=`modal-actions`;let l=document.createElement(`button`);l.type=`button`,l.className=`btn btn-ghost`,l.textContent=n[`common.cancel`],l.addEventListener(`click`,()=>s(!1));let u=document.createElement(`button`);u.type=`submit`,u.className=r?`btn btn-danger`:`btn btn-primary`,u.textContent=e.confirmLabel??n[`common.ok`],a.addEventListener(`submit`,e=>{e.preventDefault(),s(!0)}),c.append(l,u),a.append(c),queueMicrotask(()=>(r?l:u).focus())})}function Yu(e){let t=e.locale??x(),n=S[t];return new Promise(r=>{if(e.signal?.aborted){r(null);return}let{form:i,bodyId:a,finish:o}=Ku(t,null,r,e.signal),s=document.createElement(`input`),c=`${a}-input`,l=qu(i,a,e.message,`label`);l.className=`field-label`,l.setAttribute(`for`,c),s.id=c,s.className=`input`,s.type=`text`,s.value=e.initialValue??``,s.spellcheck=!1,s.autocapitalize=`none`,e.maxLength!==void 0&&(s.maxLength=e.maxLength);let u=document.createElement(`div`),d=`${a}-error`;u.id=d,u.className=`notice notice-err`,u.setAttribute(`role`,`alert`),u.hidden=!0;let f=e=>{u.textContent=e??``,u.hidden=e===null,e===null?(s.removeAttribute(`aria-invalid`),s.removeAttribute(`aria-describedby`)):(s.setAttribute(`aria-invalid`,`true`),s.setAttribute(`aria-describedby`,d))},p=document.createElement(`div`);p.className=`modal-actions`;let m=document.createElement(`button`);m.type=`button`,m.className=`btn btn-ghost`,m.textContent=n[`common.cancel`],m.addEventListener(`click`,()=>o(null));let h=document.createElement(`button`);h.type=`submit`,h.className=`btn btn-primary`,h.textContent=e.confirmLabel??n[`common.save`],i.addEventListener(`submit`,t=>{t.preventDefault();let n=s.value,r=e.validate?.(n)??null;f(r),r===null?o(n):(h.disabled=!0,s.focus())}),s.addEventListener(`input`,()=>{h.disabled&&=!1,u.hidden||f(null)}),p.append(m,h),i.append(s,u,p),queueMicrotask(()=>s.focus())})}function Xu(){return Ht()}function Zu(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function Qu(e){typeof window<`u`&&typeof window.clearInterval==`function`?window.clearInterval(e):clearInterval(e)}function $u(e,t,n){let r=n?.pauseWhenHidden!==!1,i=null,a=!1,o=()=>{try{e()}catch(e){console.error(`[visibility-poll]`,e)}},s=()=>{i!==null||a||(i=Zu(o,t))},c=()=>{i!==null&&(Qu(i),i=null)},l=()=>{r&&(Xu()?c():(o(),s()))};r&&Xu()||s();let u=r?Ut(l):null;return n?.immediate&&o(),()=>{a=!0,c(),u?.()}}var ed=new Map;function td(e,t){let n=`${e}:${t}`,r=ed.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),ed.set(n,r)),r}var nd=new Map;function rd(e){let t=nd.get(e);return t||(t=new Intl.NumberFormat(e),nd.set(e,t)),t}function id(e,t){if(!Number.isFinite(e)||e<=0)return`0 B`;let n=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],r=Math.min(Math.floor(Math.log(e)/Math.log(1024)),n.length-1),i=e/1024**r;return`${td(t,r===0?0:1).format(i)} ${n[r]}`}function ad(e,t){return!Number.isFinite(e)||e<0?`—`:Xr(e/1e3,t)}function od(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function sd(e){if(e.observedMetric)return e.observedMetric;if(e.watchdog?.observedMetric)return e.watchdog.observedMetric;let t=[{metric:`rss`,bytes:e.rss},{metric:`external`,bytes:e.external??0},{metric:`arrayBuffers`,bytes:e.arrayBuffers??0}];return t.reduce((e,t)=>t.bytes>e.bytes?t:e,t[0]).metric}function cd(e){if(e.length<2)return null;let t=e[0],n=e[e.length-1],r=n.at-t.at;return r<=0?null:(od(n)-od(t))/r*36e5}function ld({label:e,value:t,sub:n,tone:r}){return(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`label`,children:e}),(0,Q.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,Q.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function ud({observedBytes:e,thresholdBytes:t,metric:n,locale:r,t:i}){let a=e!==null&&t!==null&&t>0?e/t:null,o=a===null?`unknown`:a>=1?`over`:a>=.75?`warn`:`ok`,s=a===null?null:Math.round(a*100);return(0,Q.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,Q.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,Q.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,Q.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,Q.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:id(e,r),t!==null&&(0,Q.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,id(t,r)]})]})]}),(0,Q.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,Q.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,Q.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var dd=60,fd=1500,pd=12e4;function md({apiBase:e}){let{locale:t,t:n}=s(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(`idle`),[u,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await fetch(`${e}/api/startup-health`);if(!n.ok||t)return;let r=await n.json();t||m(r.protection===`none`)}catch{}})(),()=>{t=!0}},[e]),(0,Z.useEffect)(()=>{let t=!1,n=!1,r=null,a=async()=>{if(n)return;n=!0;let a=d(1e4);r=a;try{let n=await fetch(`${e}/api/system/memory`,{signal:a.signal});if(!n.ok)throw Error(`memory unavailable`);let r=await n.json();if(t)return;i(r),o(!1),g(typeof r.activeTurnCount==`number`),r.isDraining&&c===`idle`&&l(`draining`),(c===`draining`||c===`reconnecting`)&&_!=null&&typeof r.pid==`number`&&r.pid!==_&&!r.isDraining&&(l(`idle`),v(null),f(null))}catch{if(t)return;c===`draining`||c===`reconnecting`?l(`reconnecting`):o(!0)}finally{a.clear(),r===a&&(r=null),n=!1}};a();let s=$u(()=>void a(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),s()}},[e,c,_]),(0,Z.useEffect)(()=>{if(c!==`reconnecting`)return;let t=!1,r=!1,i=null,a=Date.now(),o=()=>{if(r||t)return;r=!0;let o=d(5e3);i=o,fetch(`${e}/api/system/health`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=pd&&(l(`error`),f(n(`dash.mem.restartFailed`)));return}let r=_==null;if(_!=null)try{let t=await e.json();r=typeof t.pid==`number`&&t.pid!==_}catch{r=!0}t||(r?(l(`idle`),v(null),f(null)):Date.now()-a>=pd&&(l(`error`),f(n(`dash.mem.restartFailed`))))}).catch(()=>{t||Date.now()-a>=pd&&(l(`error`),f(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let s=setInterval(o,fd);return()=>{t=!0,i?.controller.abort(),i?.clear(),clearInterval(s)}},[e,c,_,n]);let y=async()=>{let t=r?.activeTurnCount??0,i=[n(`dash.mem.restartConfirm`,{count:t,seconds:dd})];if(p&&i.push(n(`dash.mem.restartNoSupervisor`)),await Ju({message:i.join(`
3
-
4
- `),tone:`danger`})){f(null),v(typeof r?.pid==`number`?r.pid:null),l(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{l(`error`),v(null),f(n(`dash.mem.restartFailed`))}}};if(a&&!r&&c===`idle`)return(0,Q.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(rt,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let b=r?.watchdog?cd(r.watchdog.samples):null,x=r?r.observedBytes??r.watchdog?.observedBytes??od(r):null,S=r?sd(r):null,C=(()=>{let e=r?.watchdog?.warnThresholdBytes;if(b===null||b<=0||x===null||!e)return;let t=e-x;if(t<=0)return`danger`;let n=t/b;if(n<=1)return`danger`;if(n<=8)return`warn`})(),w=r?.responseState,T=r?.activeTurnCount,E=c===`draining`||c===`reconnecting`;return(0,Q.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Q.jsxs)(`div`,{className:`mem-head`,children:[(0,Q.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,Q.jsx)(rt,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),h&&(0,Q.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,Q.jsxs)(`span`,{className:`mem-inflight`,children:[(0,Q.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,Q.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof T==`number`?rd(t).format(T):`—`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:E,onClick:()=>{y()},children:n(`dash.mem.restart`)})]})]}),(0,Q.jsx)(ud,{observedBytes:x,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:S,locale:t,t:n}),(0,Q.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,Q.jsx)(ld,{label:n(`dash.mem.rss`),value:r?id(r.rss,t):`—`}),(0,Q.jsx)(ld,{label:n(`dash.mem.jsHeap`),value:r?id(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:id(r.heapTotal,t)}):void 0}),(0,Q.jsx)(ld,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?id(r.jscHeap.heapSize,t):`—`}),(0,Q.jsx)(ld,{label:n(`dash.mem.growth`),value:b===null?`—`:`${b>=0?`+`:`−`}${id(Math.abs(b),t)}${n(`dash.mem.perHour`)}`,tone:C})]}),(0,Q.jsxs)(`details`,{style:{marginTop:10},children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsx)(ld,{label:n(`dash.mem.observed`),value:x===null?`—`:`${id(x,t)} (${S})`}),(0,Q.jsx)(ld,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:id(r.external,t)}),(0,Q.jsx)(ld,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:id(r.arrayBuffers,t)})]}),(0,Q.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsx)(ld,{label:n(`dash.mem.storeEntries`),value:w?rd(t).format(w.count):`—`}),(0,Q.jsx)(ld,{label:n(`dash.mem.storeTotal`),value:w?id(w.totalBytes,t):`—`}),(0,Q.jsx)(ld,{label:n(`dash.mem.storeLargest`),value:w?id(w.largestBytes,t):`—`}),(0,Q.jsx)(ld,{label:n(`dash.mem.storeOldest`),value:w?w.count===0?`—`:ad(w.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,Q.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,Q.jsx)(ld,{label:n(`dash.mem.threshold`),value:id(r.watchdog.warnThresholdBytes,t)}),(0,Q.jsx)(ld,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),h&&(0,Q.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[c===`draining`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof T==`number`?T:0})}),c===`reconnecting`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),c===`error`&&u&&(0,Q.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:u}),p&&c===`idle`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}var hd=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function gd(e){let t=e.memoryModels;if(t==null)return{};if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`invalid settings`);let n={};for(let e of[`extract`,`consolidation`]){let r=t[e];if(r===void 0)continue;if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`invalid phase`);let i=`model`in r&&typeof r.model==`string`?r.model.trim():``;if(!i)throw Error(`invalid model`);let a=`reasoningEffort`in r?r.reasoningEffort:void 0;if(a!==void 0&&(typeof a!=`string`||!hd.includes(a)))throw Error(`invalid effort`);n[e]={model:i,...a?{reasoningEffort:a}:{}}}return n}function _d(e,t){return e?{model:e,...t?{reasoningEffort:t}:{}}:void 0}function vd(e){return(0,Q.jsx)(yd,{...e},e.apiBase)}function yd({apiBase:e,models:t}){let n=b(),[r,i]=(0,Z.useState)(void 0),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(null),C=(0,Z.useRef)(!1),w=(0,Z.useRef)(null),T=(0,Z.useRef)(null),E=Br(a,T),D=(0,Z.useCallback)(e=>{i(e),c(e.extract?.model??``),u(e.extract?.reasoningEffort??``),p(e.consolidation?.model??``),h(e.consolidation?.reasoningEffort??``)},[]),O=(0,Z.useCallback)(async()=>{if(w.current)return;let t=d(15e3);w.current=t,y(!1);try{let n=gd(await cr(await fetch(`${e}/api/settings`,{signal:t.signal})));C.current&&w.current===t&&D(n)}catch{C.current&&w.current===t&&y(!0)}finally{t.clear(),w.current===t&&(w.current=null)}},[e,D]);(0,Z.useEffect)(()=>{C.current=!0;let e=window.setTimeout(()=>{O()},0);return()=>{window.clearTimeout(e),C.current=!1,w.current?.controller.abort(),w.current?.clear(),w.current=null}},[O]);let k=async()=>{if(w.current||r===void 0)return;let t=d(15e3);w.current=t,_(!0),S(null);let n=_d(s,l),i=_d(f,m);try{let r=gd(await cr(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({memoryModels:n||i?{...n?{extract:n}:{},...i?{consolidation:i}:{}}:null}),signal:t.signal})));C.current&&w.current===t&&(D(r),S(`saved`))}catch{C.current&&w.current===t&&S(`failed`)}finally{t.clear(),C.current&&w.current===t&&_(!1),w.current===t&&(w.current=null)}},A=[{value:``,label:n(`memoryModels.off`)},...[...new Set([...t.map(e=>e.namespaced),...[s,f].filter(Boolean)])].map(e=>({value:e,label:Fe(e,n)}))],j=[{value:``,label:n(`memoryModels.defaultEffort`)},...hd.map(e=>({value:e,label:n(`models.reasoningEffort.${e}`)}))],M=g||r===void 0||v,N=s!==(r?.extract?.model??``)||l!==(r?.extract?.reasoningEffort??``)||f!==(r?.consolidation?.model??``)||m!==(r?.consolidation?.reasoningEffort??``),P=!!s!=!!f,F=n(`memoryModels.info`),I=(e,t,r,i,a)=>(0,Q.jsxs)(`div`,{className:`spread memory-models-row`,style:{flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 18rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:n(`memoryModels.${e}`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:n(`memoryModels.${e}Hint`)})]}),(0,Q.jsxs)(`div`,{className:`memory-models-controls`,children:[(0,Q.jsx)(Vn,{id:`memory-models-${e}`,value:t,options:A,disabled:M,label:n(`memoryModels.model`),onChange:e=>{i(e),e||a(``),S(null)}}),(0,Q.jsx)(Vn,{id:`memory-models-${e}-effort`,value:r,options:j,disabled:M||!t,align:`right`,label:n(`memoryModels.effort`),onChange:e=>{a(e),S(null)}})]})]});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`memory-models-title`,"aria-busy":g||r===void 0&&!v,children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,id:`memory-models-title`,style:{display:`flex`,alignItems:`center`,gap:6},children:[n(`memoryModels.title`),(0,Q.jsx)(`button`,{ref:T,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>o(e=>!e),"aria-label":n(`memoryModels.infoLabel`),"aria-expanded":a,"aria-haspopup":`dialog`,"aria-controls":`memory-models-help-dialog`,children:(0,Q.jsx)(He,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:n(`memoryModels.description`)}),I(`extract`,s,l,c,u),I(`consolidation`,f,m,p,h),(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`,flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Q.jsx)(`div`,{className:`muted setting-hint`,style:{flex:`1 1 18rem`,minWidth:0},children:n(`memoryModels.dataNotice`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:M||!N,onClick:()=>{k()},children:n(g?`common.saving`:`common.save`)})]}),P&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(St,{width:14}),` `,n(`memoryModels.accountNotice`)]}),v&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[n(`memoryModels.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{O()},children:n(`common.retry`)})]}),x===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:n(`memoryModels.saveFailed`)}),x===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:n(`memoryModels.saved`)}),(0,Q.jsxs)(`dialog`,{ref:E,id:`memory-models-help-dialog`,className:`modal-overlay`,style:{display:a?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`memory-models-help-title`,onCancel:e=>{e.preventDefault(),o(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:()=>o(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`memory-models-help-title`,children:n(`memoryModels.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>o(!1),"aria-label":n(`common.close`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:F}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!1),children:n(`common.ok`)})})]})]})]})}function bd(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid reasoning settings`);let t=e;if(typeof t.modelSwitch!=`boolean`||typeof t.accountSwitch!=`boolean`)throw Error(`Missing reasoning settings`);return{modelSwitch:t.modelSwitch,accountSwitch:t.accountSwitch}}function xd({apiBase:e}){return(0,Q.jsx)(Sd,{apiBase:e},e)}function Sd({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(null),_=(0,Z.useCallback)(e=>{r(e),a(e.modelSwitch),s(e.accountSwitch)},[]),v=(0,Z.useCallback)(async()=>{if(g.current)return;let t=d(15e3);g.current=t,f(!1);try{let n=bd(await cr(await fetch(`${e}/api/native-reasoning-retention`,{signal:t.signal})));h.current&&g.current===t&&_(n)}catch{h.current&&g.current===t&&f(!0)}finally{t.clear(),g.current===t&&(g.current=null)}},[e,_]);(0,Z.useEffect)(()=>{h.current=!0;let e=window.setTimeout(()=>{v()},0);return()=>{window.clearTimeout(e),h.current=!1,g.current?.controller.abort(),g.current?.clear(),g.current=null}},[v]);let y=async(t=!1)=>{if(g.current||n===void 0)return;let r=d(15e3);g.current=r,l(!0),m(null);try{let n=bd(await cr(await fetch(`${e}/api/native-reasoning-retention`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:r.signal,body:JSON.stringify(t?null:{modelSwitch:i,accountSwitch:o})})));h.current&&g.current===r&&(_(n),m(`saved`))}catch{h.current&&g.current===r&&m(`failed`)}finally{r.clear(),h.current&&g.current===r&&l(!1),g.current===r&&(g.current=null)}},x=c||n===void 0||u,S=i!==n?.modelSwitch||o!==n?.accountSwitch;return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`native-reasoning-retention-title`,"aria-busy":c||n===void 0&&!u,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`native-reasoning-retention-title`,children:t(`nativeReasoningRetention.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`nativeReasoningRetention.description`)}),(0,Q.jsxs)(`div`,{className:`stack`,style:{gap:`var(--space-3)`},children:[(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsx)(`span`,{children:t(`nativeReasoningRetention.modelSwitch`)}),(0,Q.jsx)(Rn,{on:i,disabled:x,label:t(`nativeReasoningRetention.modelSwitch`),onClick:()=>{a(e=>!e),m(null)}})]}),(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsx)(`span`,{children:t(`nativeReasoningRetention.accountSwitch`)}),(0,Q.jsx)(Rn,{on:o,disabled:x,label:t(`nativeReasoningRetention.accountSwitch`),onClick:()=>{s(e=>!e),m(null)}})]}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`nativeReasoningRetention.accountHint`)}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:x||!S,onClick:()=>{y()},children:t(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:x||!S&&!n?.modelSwitch&&!n?.accountSwitch,onClick:()=>{y(!0)},children:t(`nativeReasoningRetention.reset`)})]})]}),u&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[t(`nativeReasoningRetention.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{v()},children:t(`common.retry`)})]}),p===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`nativeReasoningRetention.saveFailed`)}),p===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`nativeReasoningRetention.saved`)})]})}function Cd(e){if(!e||typeof e!=`object`)return null;let t=e;return t.schema!==`ocx.fallback/1`||!t.global||!Array.isArray(t.devices)?null:{schema:t.schema,global:{model:t.global.model!==!1,provider:t.global.provider!==!1},providers:t.providers&&typeof t.providers==`object`?t.providers:{},routes:t.routes&&typeof t.routes==`object`?t.routes:{},devices:t.devices.filter(e=>!!e&&typeof e.id==`string`),last:t.last&&typeof t.last==`object`?t.last:null}}function wd({apiBase:e,section:t,readOnly:n=!1,embedded:r=!1}){let i=b(),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(m.current)return;let t=++h.current,n=d(15e3);try{let r=await fetch(e+`/api/fallback`,{signal:n.signal}),i=r.ok?Cd(await r.json()):null;if(!i)throw Error(`shape`);!m.current&&t===h.current&&(o(i),c(!1))}catch{!m.current&&t===h.current&&c(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=$u(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async t=>{if(m.current||n)return;m.current=!0,h.current+=1,p(!0),u(!1);let r=d(15e3);try{let n=await fetch(e+`/api/fallback`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({writes:t}),signal:r.signal}),i=n.ok?Cd(await n.json()):null;if(!i)throw Error(`save`);h.current+=1,o(i)}catch{u(!0)}finally{r.clear(),m.current=!1,p(!1)}},[e,n]),v=e=>i(e===!1?`fallback.state.off`:e===!0?`fallback.state.on`:`fallback.state.inherit`),y=f||n;if(!a)return t===`devices`?null:(0,Q.jsxs)(`section`,{className:`panel fallback-panel`,"aria-busy":!s||void 0,children:[!r&&(0,Q.jsx)(`h3`,{children:i(t===`routing`?`fallback.title`:`fallback.devices.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,role:`status`,children:i(s?`fallback.loadFailed`:`common.loading`)}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},children:i(`common.retry`)})]});if(t===`devices`)return(0,Q.jsxs)(`section`,{className:`panel fallback-panel`,children:[(0,Q.jsx)(`h3`,{children:i(`fallback.devices.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(n?`fallback.devices.childNote`:`fallback.devices.desc`)}),a.devices.length===0?(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`fallback.devices.empty`)}):(0,Q.jsxs)(`table`,{className:`fallback-devices`,"aria-label":i(`fallback.devices.title`),children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`fallback-device-head`,children:[(0,Q.jsx)(`th`,{scope:`col`,children:i(`fallback.devices.device`)}),(0,Q.jsx)(`th`,{scope:`col`,children:i(`fallback.devices.local`)}),(0,Q.jsx)(`th`,{scope:`col`,children:i(`fallback.devices.chains`)})]})}),(0,Q.jsx)(`tbody`,{children:a.devices.map(e=>{let t=e.model!==!1&&e.provider!==!1,n=e.alias??e.id;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`strong`,{children:n}),e.alias&&(0,Q.jsx)(`code`,{className:`fallback-device-id`,children:e.id})]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Td,{label:i(`fallback.devices.localFor`,{name:n}),on:e.localFallback,disabled:y,onToggle:()=>{_([{scope:`device`,key:e.id,setting:`localFallback`,value:!e.localFallback||null}])}})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Td,{label:i(`fallback.devices.chainsFor`,{name:n}),on:t,disabled:y,onToggle:()=>{let n=!t&&null;_([{scope:`device`,key:e.id,setting:`model`,value:n},{scope:`device`,key:e.id,setting:`provider`,value:n}])}})})]},e.id)})})]}),l&&(0,Q.jsx)($,{tone:`err`,children:i(`fallback.saveFailed`)})]});let x=[...Object.entries(a.providers).map(([e,t])=>({scope:`provider`,key:e,value:t})),...Object.entries(a.routes).map(([e,t])=>({scope:`route`,key:e,value:t}))],S=a.last;return(0,Q.jsxs)(`section`,{className:`panel fallback-panel`,"aria-label":r?i(`fallback.title`):void 0,children:[!r&&(0,Q.jsx)(`h3`,{children:i(`fallback.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(n?`fallback.devices.childNote`:`fallback.desc`)}),[`model`,`provider`].map(e=>(0,Q.jsxs)(`div`,{className:`fallback-switch-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(e===`model`?`fallback.model`:`fallback.provider`)}),(0,Q.jsx)(`div`,{className:`card-sub`,children:i(e===`model`?`fallback.modelHint`:`fallback.providerHint`)})]}),(0,Q.jsx)(Td,{label:i(e===`model`?`fallback.model`:`fallback.provider`),on:a.global[e],disabled:y,onToggle:()=>{_([{scope:`global`,setting:e,value:!a.global[e]&&null}])}})]},e)),(0,Q.jsx)(`p`,{className:`card-sub faint`,children:i(`fallback.rotationNote`)}),x.length>0&&(0,Q.jsxs)(`div`,{className:`fallback-overrides`,children:[(0,Q.jsx)(`strong`,{children:i(`fallback.overrides`)}),(0,Q.jsx)(`ul`,{children:x.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:i(e.scope===`provider`?`fallback.scope.provider`:`fallback.scope.route`,{name:e.key})}),(0,Q.jsxs)(`span`,{className:`card-sub`,children:[i(`fallback.model`),`: `,v(e.value.model),` · `,i(`fallback.provider`),`: `,v(e.value.provider)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:y,onClick:()=>{_([`model`,`provider`].filter(t=>e.value[t]!==void 0).map(t=>({scope:e.scope,key:e.key,setting:t,value:null})))},children:i(`fallback.clear`)})]},e.scope+`:`+e.key))})]}),(0,Q.jsxs)(`div`,{className:`fallback-last`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:i(`fallback.last`)}),S?(0,Q.jsxs)(`p`,{className:`card-sub`,children:[(0,Q.jsx)(`time`,{dateTime:S.at,children:new Date(S.at).toLocaleString()}),` · `,(0,Q.jsx)(`code`,{children:S.route}),`: `,(0,Q.jsx)(`code`,{children:S.from}),` → `,(0,Q.jsx)(`code`,{children:S.to}),` (`,(0,Q.jsx)(`code`,{children:S.trigger}),`) · `,i(S.outcome===`refused`?`fallback.last.refused`:`fallback.last.taken`)]}):(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`fallback.last.none`)})]}),l&&(0,Q.jsx)($,{tone:`err`,children:i(`fallback.saveFailed`)})]})}function Td({label:e,on:t,disabled:n,onToggle:r}){return(0,Q.jsx)(`button`,{type:`button`,className:`toggle `+(t?`on`:``),"aria-pressed":t,"aria-label":e,title:e,onClick:r,disabled:n,children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})}var Ed=15e3,Dd=`ocx:telemetry-status-changed`,Od=new Set([`env-ocx-telemetry`,`env-do-not-track`,`declined`,`accepted`,`default-on`,`awaiting-notice`]);function kd(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(typeof t.effective!=`boolean`)return null;let n=t.decision===`accepted`||t.decision===`declined`?t.decision:null,r=typeof t.reason==`string`&&Od.has(t.reason)?t.reason:n===`accepted`?`accepted`:n===`declined`?`declined`:t.effective?`default-on`:`awaiting-notice`,i=t.envOverride===`OCX_TELEMETRY`||t.envOverride===`DO_NOT_TRACK`?t.envOverride:r===`env-ocx-telemetry`?`OCX_TELEMETRY`:r===`env-do-not-track`?`DO_NOT_TRACK`:null,a=t.preview&&typeof t.preview==`object`&&!Array.isArray(t.preview)?t.preview:{},o=typeof t.previewEligible==`boolean`?t.previewEligible:void 0;return{effective:t.effective,reason:r,decision:n,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:null,noticeShownAt:typeof t.noticeShownAt==`string`?t.noticeShownAt:null,envOverride:i,installChannel:typeof t.installChannel==`string`?t.installChannel:`unknown`,lastSentDay:typeof t.lastSentDay==`string`?t.lastSentDay:null,lastSentAt:typeof t.lastSentAt==`string`?t.lastSentAt:null,preview:a,...o===void 0?{}:{previewEligible:o}}}function Ad(e){return e.decision!==null||e.envOverride!==null?!1:e.reason===`awaiting-notice`||e.reason===`default-on`}function jd(e){return JSON.stringify(e?.preview??{},null,2)}function Md(e){if(typeof window<`u`&&typeof window.dispatchEvent==`function`)try{let t=window.CustomEvent??CustomEvent;window.dispatchEvent(new t(Dd,{detail:e}))}catch{}}function Nd(e){if(typeof document>`u`)return!1;let t=document.querySelectorAll(`dialog`);for(let n of t)if(!(e&&n.matches(e))&&(n.open||n.hasAttribute(`open`)||n.classList.contains(`modal-overlay`)&&n.style.display!==`none`))return!0;return!1}function Pd(e){if(typeof document>`u`)return()=>{};let t=document.body??document.documentElement,n=(typeof window<`u`?window.MutationObserver:void 0)??(typeof MutationObserver<`u`?MutationObserver:void 0),r=n&&t?new n(()=>{e()}):null;return r?.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`open`,`style`,`class`]}),document.addEventListener(`close`,e,!0),document.addEventListener(`cancel`,e,!0),()=>{r?.disconnect(),document.removeEventListener(`close`,e,!0),document.removeEventListener(`cancel`,e,!0)}}async function Fd(e,t){let n=d(Ed),r=()=>n.controller.abort(t?.reason);if(t?.aborted)throw n.clear(),t.reason??new DOMException(`Aborted`,`AbortError`);t?.addEventListener(`abort`,r,{once:!0});try{let t=await fetch(e+`/api/telemetry`,{signal:n.signal});if(!t.ok)throw Error(`HTTP `+String(t.status));let r=kd(await t.json());if(!r)throw Error(`invalid telemetry status payload`);return r}finally{t?.removeEventListener(`abort`,r),n.clear()}}async function Id(e,t,n){let r=d(Ed);try{let n=await fetch(e+`/api/telemetry`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({decision:t}),signal:r.signal});if(!n.ok){let e=await n.json().catch(()=>null),t=e&&typeof e==`object`&&typeof e.code==`string`?e.code:null;throw new Ld(n.status,t)}let i=kd(await n.json().catch(()=>null))??await Fd(e).catch(()=>null);return i&&Md(i),i}finally{r.clear()}}var Ld=class extends Error{status;code;constructor(e,t){super(t?`HTTP ${String(e)} ${t}`:`HTTP ${String(e)}`),this.name=`TelemetrySaveError`,this.status=e,this.code=t}};function Rd(e){return e instanceof Ld&&e.code===`agent_consent_required`}var zd=`https://opencodex.me/reference/code-signing/#privacy`,Bd=`dialog.telemetry-preview-overlay`;function Vd({apiBase:e,readOnly:t=!1}){let n=b(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[,h]=(0,Z.useState)(0),g=(0,Z.useRef)(!1),_=(0,Z.useRef)(0),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useId)(),w=(0,Z.useId)(),T=(0,Z.useCallback)(async()=>{if(g.current)return;let t=++_.current;try{let n=await Fd(e);!g.current&&t===_.current&&(i(n),o(!1),u(!1))}catch{!g.current&&t===_.current&&o(!0)}},[e]);(0,Z.useEffect)(()=>{if(t)return;let e=window.setTimeout(()=>{T()},0),n=$u(()=>{T()},3e4),r=e=>{let t=e.detail;t&&!g.current&&(_.current+=1,i(t),o(!1),u(!1))};return window.addEventListener(Dd,r),()=>{window.clearTimeout(e),n(),window.removeEventListener(Dd,r)}},[T,t]),(0,Z.useEffect)(()=>{if(!p)return;let e=Nd(Bd),t=()=>{let t=Nd(Bd);t!==e&&(e=t,h(e=>e+1))};return t(),Pd(t)},[p]);let E=p&&Nd(Bd),D=!!(p&&r&&!E);(0,Z.useEffect)(()=>{if(!D)return;let e=x.current;return e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``)),S.current?.focus(),()=>{e?.open&&e.close?.()}},[D]),(0,Z.useEffect)(()=>{if(p)return;let e=y.current;e&&(y.current=null,e.isConnected&&e.focus())},[p]);let O=(0,Z.useCallback)(()=>{x.current?.open&&x.current.close?.(),m(!1)},[]),k=r?.effective??!1,A=r?.envOverride??null,j=!r||d||t||l||A!==null,M=(0,Z.useCallback)(async()=>{if(g.current||!r||t||l||r.envOverride!==null)return;let n=r.effective?`declined`:`accepted`;g.current=!0,_.current+=1,f(!0),c(null);let a=!1;try{let t=await Id(e,n,r);_.current+=1,t?(i(t),o(!1)):(u(!0),a=!0)}catch(e){e instanceof Ld?c(Rd(e)?`session`:`failed`):(u(!0),a=!0)}finally{g.current=!1,f(!1)}a&&T()},[e,T,t,l,r]),N=A===`DO_NOT_TRACK`?`DO_NOT_TRACK=1`:A===`OCX_TELEMETRY`?`OCX_TELEMETRY=0`:null;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(Xc,{className:`telemetry-settings-row`,label:n(`proxyV2.telemetryToggleLabel`),hint:n(t?`proxyV2.telemetryReadOnlyHint`:`proxyV2.telemetryToggleHint`),details:n(`proxyV2.telemetryDetails`),busy:!t&&!r&&!a,control:t?void 0:(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a&&(!r||l)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d,onClick:()=>{T()},children:n(`common.retry`)}),(0,Q.jsx)(`button`,{ref:v,type:`button`,className:`btn btn-ghost btn-sm telemetry-preview-trigger`,disabled:!r,"aria-haspopup":`dialog`,"aria-expanded":D,onClick:()=>{y.current=v.current,m(!0)},children:n(`proxyV2.telemetryWhatIsSent`)}),(0,Q.jsx)(Rn,{on:k,label:n(`proxyV2.telemetryToggleLabel`),disabled:j,onClick:()=>{M()}})]}),children:[N&&(0,Q.jsx)($,{tone:`warn`,children:n(`proxyV2.telemetryEnvOverride`,{envVar:N})}),a&&!r&&(0,Q.jsx)($,{tone:`err`,children:n(`proxyV2.telemetryLoadFailed`)}),l&&(0,Q.jsx)($,{tone:`warn`,children:n(`proxyV2.telemetrySaveUnconfirmed`)}),s&&(0,Q.jsx)($,{tone:`err`,children:n(s===`session`?`proxyV2.telemetrySaveNeedsHumanSession`:`proxyV2.telemetrySaveFailed`)})]}),D&&r&&(0,Q.jsxs)(`dialog`,{ref:x,"aria-labelledby":C,"aria-describedby":w,className:`modal-overlay telemetry-preview-overlay`,onCancel:e=>{e.preventDefault(),O()},onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),O())},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:O}),(0,Q.jsxs)(`div`,{className:`modal-card telemetry-preview-dialog flex flex-col gap-3`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:C,className:`m-0`,children:n(`proxyV2.telemetryWhatIsSent`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:O,"aria-label":n(`common.close`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-control bg-raised p-3 text-[13px] leading-[19px]`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`strong`,{className:`text-fg`,children:[n(`proxyV2.telemetrySentTitle`),`: `]}),(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:n(`proxyV2.telemetrySentItems`)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`strong`,{className:`text-fg`,children:[n(`proxyV2.telemetryNeverTitle`),`: `]}),(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:n(`proxyV2.telemetryNeverItems`)})]})]}),(0,Q.jsx)(`p`,{id:w,className:`modal-desc m-0`,children:n(`proxyV2.telemetryPreviewHint`)}),r.previewEligible===!1&&(0,Q.jsx)(`p`,{className:`telemetry-preview-ineligible m-0 text-[12px] text-fg-muted`,children:n(`proxyV2.telemetryPreviewIneligible`)}),(0,Q.jsx)(`pre`,{className:`log-detail-json telemetry-preview-json`,children:jd(r)}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{ref:S,type:`button`,className:`btn btn-primary`,onClick:O,autoFocus:!0,children:n(`common.close`)})})]})]})]})}function Hd({t:e,open:t,triggerRef:n,onClose:r,maxValue:i,maxInvalid:a,timeoutValue:o,timeoutInvalid:s,disabled:c,setMaxDraft:l,setMaxInvalid:u,setTimeoutDraft:d,setTimeoutInvalid:f,commitMaxDescriptions:p,commitTimeout:m}){let h=(0,Z.useRef)(null),g=(0,Z.useRef)(null),[_,v]=(0,Z.useState)(),y=(0,Z.useCallback)(()=>{n.current&&v(Ln(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,Z.useLayoutEffect)(()=>{if(!t)return;y();let e=()=>y();return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[t,y,a,s]),(0,Z.useEffect)(()=>{if(!t)return;let e=e=>{let t=e.target;if(h.current?.contains(t)||n.current?.contains(t))return;let i=document.activeElement;i&&h.current?.contains(i)&&i.blur(),r()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t,r,n]),(0,Z.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),r(),n.current?.focus())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,r,n]),(0,Z.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,Q.jsxs)(`div`,{ref:h,id:`dash-vision-advanced-popover`,className:`dash-vision-advanced-popover`,role:`dialog`,"aria-modal":`false`,"aria-label":e(`dash.visionAdvancedPopover`),style:{..._,zIndex:60},children:[(0,Q.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,Q.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Q.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,Q.jsx)(`input`,{ref:g,className:`input mono codex-auto-switch-input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:i,disabled:c,"aria-invalid":a||void 0,"aria-label":e(`dash.visionMaxDescriptions`),"aria-describedby":a?`dash-vision-max-error dash-vision-max-label`:`dash-vision-max-label`,onChange:e=>{u(!1),l(e.target.value)},onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),p(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),l(null),u(!1)))}})}),a&&(0,Q.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,Q.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Q.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:Cr,max:Sr,step:1e3,inputMode:`numeric`,value:o,disabled:c,"aria-invalid":s||void 0,"aria-label":e(`dash.visionTimeout`),"aria-describedby":s?`dash-vision-timeout-error dash-vision-timeout-label`:`dash-vision-timeout-label`,onChange:e=>{f(!1),d(e.target.value)},onBlur:e=>m(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),m(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),d(null),f(!1)))}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,Q.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:Cr,max:Sr})})]})]}):null}function Ud(e,t){switch(t){case`helper`:return e(`shadowCall.sourceHelper`);case`memory`:return e(`shadowCall.sourceMemory`);case`legacy`:return e(`shadowCall.sourceLegacy`);case`custom`:return e(`shadowCall.sourceCustom`)}}function Wd({options:e,sourceModels:t,disabled:n=!1,saving:r=!1,onChange:i,className:a}){let o=b(),s=(0,Z.useId)();return!e||e.length===0?null:(0,Q.jsxs)(`div`,{className:[`shadow-source-toggles`,a].filter(Boolean).join(` `),role:`group`,"aria-label":o(`shadowCall.sources`),"aria-describedby":s,children:[(0,Q.jsx)(`div`,{className:`shadow-source-toggle-list`,children:e.map(e=>{let a=tr(e.id,t),s=nr(e,t),c=`blocked`in s&&s.blocked===`covered`?s.prefix:void 0,l=`blocked`in s&&s.blocked===`last`,u=c?o(`shadowCall.sourceCovered`,{prefix:c}):l?o(`shadowCall.sourceLastRequired`):void 0,d=c?o(`shadowCall.sourceCoveredShort`,{prefix:c}):l?o(`shadowCall.sourceRequired`):void 0;return(0,Q.jsxs)(`span`,{className:`shadow-source-toggle${a?` on`:``}`,children:[(0,Q.jsx)(Rn,{on:a,onClick:()=>{`sourceModels`in s&&i(s.sourceModels)},disabled:n||r||c!==void 0||l,label:`${e.id} (${Ud(o,e.role)})`,title:u}),(0,Q.jsx)(`code`,{className:`shadow-source-id`,children:er([e.id])}),(0,Q.jsx)(`span`,{className:`muted text-caption shadow-source-role`,children:Ud(o,e.role)}),d?(0,Q.jsx)(`span`,{className:`muted text-caption shadow-source-reason`,children:d}):null]},e.id)})}),(0,Q.jsx)(`span`,{id:s,className:`muted text-caption shadow-source-hint`,children:o(`shadowCall.sourceHint`)})]})}var Gd=`w-[15rem] max-w-full`,Kd=`w-[9.5rem] max-w-full`;function qd({d:e}){let{t,maMode:n,maError:r}=e;return(0,Q.jsxs)(Jc,{id:`proxy-subagents`,title:t(`proxyV2.secSubagents`),lede:t(`proxyV2.secSubagentsLede`),children:[(0,Q.jsx)(Xc,{label:t(`dash.multiAgent`),hint:t(`proxyV2.maModeHint`),help:(0,Q.jsx)(el,{...e}),control:(0,Q.jsx)($c,{maMode:n,maSupportsPlaintextV2:e.maSupportsPlaintextV2,maBusy:e.maBusy,switchMaMode:e.switchMaMode}),children:r&&(0,Q.jsx)(`div`,{role:`alert`,className:`text-[13px] break-words text-danger`,children:r})}),(0,Q.jsx)(Jd,{apiBase:e.apiBase,d:e}),(0,Q.jsx)(Yd,{apiBase:e.apiBase,d:e})]})}function Jd({apiBase:e,d:t}){let{t:n,maMode:r,maModeResolved:i,effortCapHelpTriggerRef:a,effortCapHelpOpen:o,setEffortCapHelpOpen:s,effortCap:c,subagentEffortCap:l,effortCapSaving:u,setEffortCap:d,setSubagentEffortCap:f,setEffortCapSaving:p}=t;if(!i||r===`v1`)return null;let m=[{value:``,label:n(`dash.effortCapNone`)},...lr.map(e=>({value:e,label:e}))],h=async t=>{if(!u){p(!0);try{let n=await cr(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Xc,{className:`dash-effort-panel`,label:n(`dash.effortCapLabel`),hint:n(`proxyV2.effortCapHint`),help:(0,Q.jsx)(Yc,{buttonRef:a,label:n(`dash.effortCapLabel`),expanded:o,controls:`effort-cap-help-dialog`,popup:`dialog`,onClick:()=>s(e=>!e)}),control:(0,Q.jsx)(Vn,{value:c,options:m,fullWidth:!0,className:Kd,onChange:e=>{h({effortCap:e||null})},disabled:u,label:n(`dash.effortCapLabel`),align:`right`})}),(0,Q.jsx)(Xc,{label:n(`dash.subagentEffortCapLabel`),hint:n(`proxyV2.subagentEffortCapHint`),control:(0,Q.jsx)(Vn,{value:l,options:m,fullWidth:!0,className:Kd,onChange:e=>{h({subagentEffortCap:e||null})},disabled:u,label:n(`dash.subagentEffortCapLabel`),align:`right`})})]})}function Yd({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,Q.jsx)(Xc,{className:`dash-delegation-row`,label:t(`dash.injectionLabel`),hint:t(`proxyV2.injectionHint`),control:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Vn,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:Fe(`${e.provider}/${e.model}`,t)}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`),align:`right`,fullWidth:!0,className:Gd}),n&&i.length>0&&(0,Q.jsx)(Vn,{value:r,options:[{value:``,label:t(`dash.injectionEffortNone`)},...i.map(e=>({value:e,label:e}))],onChange:e=>{s({model:n||null,effort:e||null})},disabled:o,label:t(`dash.injectionEffortLabel`),align:`right`,fullWidth:!0,className:Kd}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>En(`#subagents`),children:t(`dash.injectionManage`)})]})})}function Xd({d:e}){let{t,settings:n,settingsSaving:r,syncing:i,toggleCodexAutoStart:a,toggleCodexDesktopAuthless:o,toggleCodexClientCompaction:s}=e,c=!n||r||i,l=n?.catalogRefreshPending?(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}):null,u=(0,Q.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[13px] leading-[19px] text-fg-muted`,children:t(`dash.codexRemoteHistoryHint`)});return(0,Q.jsxs)(Jc,{id:`proxy-codex`,title:t(`proxyV2.secCodex`),lede:t(`proxyV2.secCodexLede`),children:[(0,Q.jsx)(Xc,{label:t(`dash.codexAutoStart`),hint:t(`proxyV2.autoStartShort`),details:t(`dash.codexAutoStartHint`),inline:!0,control:(0,Q.jsx)(Zd,{on:n?.codexAutoStart??!0,label:t(`dash.codexAutoStart`),disabled:c,onClick:a})}),(0,Q.jsx)(Xc,{label:t(`dash.codexDesktopAuthless`),hint:t(`proxyV2.authlessShort`),details:t(`dash.codexDesktopAuthlessHint`),inline:!0,control:(0,Q.jsx)(Zd,{on:n?.codexDesktopAuthless??!1,label:t(`dash.codexDesktopAuthless`),disabled:c,onClick:o}),children:(n?.codexDesktopAuthless||n?.catalogRefreshPending)&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[n?.codexDesktopAuthless&&u,l]})}),(0,Q.jsx)(Xc,{label:t(`dash.codexClientCompaction`),hint:t(`proxyV2.clientCompactionShort`),details:t(`dash.codexClientCompactionHint`),inline:!0,control:(0,Q.jsx)(Zd,{on:n?.codexClientCompaction??!1,label:t(`dash.codexClientCompaction`),disabled:c,onClick:s}),children:(!n?.codexDesktopAuthless&&n?.codexClientCompaction||n?.catalogRefreshPending)&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[!n?.codexDesktopAuthless&&n?.codexClientCompaction&&u,l]})}),(0,Q.jsx)(Qd,{d:e})]})}function Zd({on:e,label:t,disabled:n,onClick:r}){return(0,Q.jsx)(`button`,{type:`button`,className:`switch ${e?`on`:``}`,onClick:r,disabled:n,"aria-label":t,"aria-pressed":e,children:(0,Q.jsx)(`span`,{className:`knob`})})}function Qd({d:e}){let{t,runSync:n,syncing:r,settingsSaving:i,updateTriggerRef:a,openUpdateDialog:o,updateLoading:s,updateOpen:c,syncResult:l,syncError:u,updateJob:d,reconnecting:f,clearSyncFeedback:p}=e,m=!!l&&(!!l.warning||!!l.nativeSubagentDefaultsWarning||!!l.staleAppServerHint),[h,g]=(0,Z.useState)(!1),_=(0,Z.useRef)(null);(0,Z.useEffect)(()=>(_.current&&=(clearTimeout(_.current),null),(l||u)&&!m&&(_.current=setTimeout(()=>{_.current=null,g(!0),p()},u?8e3:6e3)),()=>{_.current&&clearTimeout(_.current)}),[l,u,m,p]);let v=()=>{g(!1),n()},y=()=>{g(!0),p()};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Xc,{className:`maintenance-panel dash-sync-summary`,label:t(`dash.syncModels`),hint:t(`dash.syncModelsHint`),control:(0,Q.jsxs)(`div`,{className:`maintenance-actions flex items-center gap-2`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm`,onClick:v,disabled:r||i,children:[(0,Q.jsx)(Ke,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,Q.jsx)(`button`,{ref:a,type:`button`,className:`maintenance-update-anchor`,onClick:o,disabled:s,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":c,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]}),children:d&&(0,Q.jsxs)(`div`,{className:`notice ${d.status===`failed`?`notice-err`:`notice-ok`} dash-update-job`,role:`status`,children:[d.status===`failed`?(0,Q.jsx)(St,{}):(0,Q.jsx)(Ke,{}),(0,Q.jsxs)(`span`,{children:[fr(d.status,t),d.latestVersion?` ${t(`dash.updateVersionTransition`,{currentVersion:d.currentVersion,latestVersion:d.latestVersion})}`:``,f?` ${t(`dash.updateReconnecting`)}`:``,d.error?` ${d.error}`:``]})]})}),!h&&l&&(0,Q.jsxs)(`div`,{className:`action-toast notice ${m?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[m?(0,Q.jsx)(St,{}):(0,Q.jsx)(st,{}),(0,Q.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:l.added}),l.warning?` ${l.warning}`:``,l.nativeSubagentDefaultsWarning?` ${l.nativeSubagentDefaultsWarning}`:``,l.staleAppServerHint?(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(z,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Q.jsx)(Ie,{width:13,height:13,"aria-hidden":`true`})})]}),!h&&u&&(0,Q.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{children:t(`dash.syncFailed`,{error:u})}),(0,Q.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Q.jsx)(Ie,{width:13,height:13,"aria-hidden":`true`})})]})]})}function $d({d:e}){let{t,sidecar:n,sidecarSaving:r,sidecarModels:i,visionModels:a,models:o,saveSidecar:s,sidecarCodexApply:c,shadowCall:l,shadowCallSaving:u,shadowCallError:d,shadowCallHelpTriggerRef:f,shadowCallHelpOpen:p,setShadowCallHelpOpen:m,saveShadowCall:h}=e,g=t(`shadowCall.memoryLabel`),_=n?.vision?.enabled!==!1,v=_?n?.vision?.model??`gpt-5.6-luna`:``,y=n?.vision.backend??a.find(e=>e.value===n?.vision.model)?.backend,b=n?.webSearch.backend??i.find(e=>e.value===n?.webSearch.model)?.backend,x=n?.webSearch?.enabled!==!1,S=x?n?.webSearch?.model??`gpt-5.6-luna`:``,C=n?.vision?.reasoning??`low`,w=Dr(o,v),T=kr(w,C),E=String(n?.vision?.maxDescriptionsPerTurn??8),D=String(n?.vision?.timeoutMs??xr),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(!1),R=(0,Z.useRef)(null),z=O??E,B=A??D,V=(e=z)=>{let t=wr(e);t===void 0?(k(e),N(!0)):(N(!1),k(null),t!==(n?.vision?.maxDescriptionsPerTurn??8)&&s(yr(t)))},H=(e=B)=>{let t=Tr(e);t===void 0?(j(e),F(!0)):(F(!1),j(null),t!==(n?.vision?.timeoutMs??xr)&&s(br(t)))};return(0,Q.jsxs)(Jc,{id:`proxy-sidecars`,title:t(`proxyV2.secSidecars`),lede:t(`proxyV2.secSidecarsLede`),children:[(0,Q.jsxs)(`div`,{className:`pv2-row dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!n||void 0,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Q.jsx)(`div`,{className:`pv2-row-label`,children:t(`dash.webSearchSidecar`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)}),_r(c)&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{children:t(`dash.webSearchCodexSync`)})]})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsx)(`div`,{className:`dash-sidecar-select-row`,children:(0,Q.jsx)(Vn,{value:S,options:[{value:``,label:t(`dash.webSearchOff`)},...i],onChange:e=>{if(e===``){s(gr(!1));return}let t={webSearch:Ir(o,i,e)};x||(t.webSearch={...t.webSearch,enabled:!0}),s(t)},disabled:!n||r,label:t(`dash.sidecarModel`),align:`right`})}),n&&b===`anthropic`&&(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Q.jsx)(Vn,{value:n.webSearch.anthropicInstance??``,label:t(`sidecar.pool`),options:[{value:``,label:t(`sidecar.poolCurrent`)},{value:`anthropic`,label:t(`sidecar.poolA`)},{value:`anthropic2`,label:t(`sidecar.poolB`)}],disabled:r,align:`right`,onChange:e=>{s({webSearch:{anthropicInstance:e===`anthropic`||e===`anthropic2`?e:null}})}}),n.webSearch.anthropicPool?.mixed&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,title:t(`dash.webSearchStreamHint`),children:[(0,Q.jsx)(`span`,{className:`muted setting-hint dash-sidecar-toggle-label`,children:t(`dash.webSearchStream`)}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${n?.webSearch?.streamRoutedModelOutput?`on`:``}`,onClick:()=>{s({webSearch:{streamRoutedModelOutput:!n?.webSearch?.streamRoutedModelOutput}})},disabled:!x||!n||r,"aria-label":t(`dash.webSearchStream`),"aria-pressed":n?.webSearch?.streamRoutedModelOutput===!0,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]})]}),(0,Q.jsxs)(`div`,{className:`pv2-row dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!n||void 0,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Q.jsx)(`div`,{className:`pv2-row-label`,children:t(`dash.visionSidecar`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-select-row`,children:[(0,Q.jsx)(Vn,{value:v,options:[{value:``,label:t(`dash.visionOff`)},...a],onChange:e=>{if(e===``){s(hr(!1));return}let t=kr(Dr(o,e),T),n={vision:{model:e,backend:Lr(o,a,e),reasoning:t}};_||(n.vision={...n.vision,enabled:!0}),s(n)},disabled:!n||r,label:t(`dash.sidecarModel`)}),(0,Q.jsx)(Vn,{value:T,options:Or(w,T).map(e=>({value:e,label:e})),onChange:e=>{s(mr(e))},disabled:!_||!n||r,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),n&&y===`anthropic`&&(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Q.jsx)(Vn,{value:n.vision.anthropicInstance??``,label:t(`sidecar.pool`),options:[{value:``,label:t(`sidecar.poolCurrent`)},{value:`anthropic`,label:t(`sidecar.poolA`)},{value:`anthropic2`,label:t(`sidecar.poolB`)}],disabled:r,align:`right`,onChange:e=>{s({vision:{anthropicInstance:e===`anthropic`||e===`anthropic2`?e:null}})}}),n.vision.anthropicPool?.mixed&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Q.jsx)(`div`,{className:`dash-sidecar-trailing-row`,children:(0,Q.jsxs)(`button`,{type:`button`,ref:R,className:`dash-vision-advanced-trigger`,onClick:()=>L(e=>!e),disabled:!_||!n||r,"aria-expanded":I,"aria-haspopup":`dialog`,"aria-controls":`dash-vision-advanced-popover`,children:[(0,Q.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`,style:{transform:I?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,Dn.createPortal)((0,Q.jsx)(Hd,{t,open:I,triggerRef:R,onClose:()=>L(!1),maxValue:z,maxInvalid:M,timeoutValue:B,timeoutInvalid:P,disabled:!_||!n||r,setMaxDraft:k,setMaxInvalid:N,setTimeoutDraft:j,setTimeoutInvalid:F,commitMaxDescriptions:V,commitTimeout:H}),document.body)]}),(0,Q.jsxs)(Xc,{className:`dash-shadow-row`,busy:!l,label:t(`dash.shadowCallIntercept`),hint:t(`proxyV2.shadowShort`),help:(0,Q.jsx)(Yc,{buttonRef:f,label:t(`dash.shadowCallIntercept`),expanded:p,controls:`shadow-call-help-dialog`,popup:`dialog`,onClick:()=>m(e=>!e)}),badge:(0,Q.jsx)(`code`,{className:`dash-shadow-badge rounded-[6px] bg-surface-2 px-1.5 py-0.5 font-mono text-[11px] text-fg-muted`,children:`⚠ ${rr(l?.sourceModels,g)}`}),control:(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(Vn,{value:l?.model??``,options:Nr(o,l?.model,l?.sourceModels).map(e=>e.value===``?e:{...e,label:Fe(e.value,t)}),onChange:e=>{h({model:e})},disabled:!l||u||!l?.enabled,label:t(`dash.shadowCallModel`),align:`right`,fullWidth:!0,className:Gd}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${l?.enabled?`on`:``}`,onClick:()=>h({enabled:!l?.enabled}),disabled:!l||u,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":l?.enabled??!1,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),children:[(0,Q.jsx)(Wd,{className:`dash-shadow-sources`,options:l?.sourceModelOptions,sourceModels:l?.sourceModels,disabled:!l?.enabled,saving:u,onChange:e=>void h({sourceModels:e})}),d&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{children:d})]})]})]})}function ef({readOnly:e=!1,...t}){let{t:n}=t;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(qd,{d:t}),(0,Q.jsx)(Xd,{d:t}),(0,Q.jsx)($d,{d:t}),(0,Q.jsxs)(Jc,{id:`proxy-compaction`,title:n(`proxyV2.secCompaction`),lede:n(`proxyV2.secCompactionLede`),children:[(0,Q.jsx)(zu,{apiBase:t.apiBase,models:t.models,providers:t.providers}),(0,Q.jsx)(xd,{apiBase:t.apiBase}),(0,Q.jsx)(Hu,{apiBase:t.apiBase})]}),(0,Q.jsxs)(Jc,{id:`proxy-memory`,title:n(`proxyV2.secMemory`),lede:n(`proxyV2.secMemoryLede`),children:[(0,Q.jsx)(vd,{apiBase:t.apiBase,models:t.models}),(0,Q.jsx)(md,{apiBase:t.apiBase})]}),(0,Q.jsx)(Jc,{id:`proxy-fallback`,title:n(`proxyV2.secFallback`),lede:n(`proxyV2.secFallbackLede`),children:(0,Q.jsx)(wd,{apiBase:t.apiBase,section:`routing`,readOnly:e,embedded:!0})}),(0,Q.jsx)(Jc,{id:`proxy-telemetry`,title:n(`proxyV2.secTelemetry`),lede:n(`proxyV2.secTelemetryLede`),children:(0,Q.jsx)(Vd,{apiBase:t.apiBase,readOnly:e})})]})}var tf=[[`proxy-subagents`,`proxyV2.secSubagents`],[`proxy-codex`,`proxyV2.secCodex`],[`proxy-sidecars`,`proxyV2.secSidecars`],[`proxy-compaction`,`proxyV2.secCompaction`],[`proxy-memory`,`proxyV2.secMemory`],[`proxy-fallback`,`proxyV2.secFallback`],[`proxy-telemetry`,`proxyV2.secTelemetry`]];function nf({items:e,label:t,className:n}){let r=Tc(),[i,a]=(0,Z.useState)(e[0]?.id??``),o=e.map(e=>e.id).join(`|`);(0,Z.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let e=new Map,t=new IntersectionObserver(t=>{for(let n of t)n.isIntersecting?e.set(n.target.id,n.boundingClientRect.top):e.delete(n.target.id);let n=o.split(`|`).find(t=>e.has(t));n&&a(n)},{rootMargin:`0px 0px -55% 0px`,threshold:0});for(let e of o.split(`|`)){let n=document.getElementById(e);n&&t.observe(n)}return()=>t.disconnect()},[o]);let s=e=>{let t=document.getElementById(e);if(!t)return;a(e),t.scrollIntoView({behavior:r?`auto`:`smooth`,block:`start`});let n=t.querySelector(`h3, h2`);n&&(n.tabIndex=-1,n.focus({preventScroll:!0}))};return(0,Q.jsxs)(`nav`,{"aria-label":t,className:X(`pv2-index min-w-0`,n),children:[(0,Q.jsx)(`p`,{className:`m-0 mb-1.5 hidden px-2.5 text-xs font-medium text-fg-subtle lg:block`,children:t}),(0,Q.jsx)(`ul`,{className:`m-0 flex list-none gap-1 overflow-x-auto p-0 pb-1 lg:flex-col lg:gap-0.5 lg:overflow-visible lg:pb-0`,children:e.map(e=>{let t=e.id===i;return(0,Q.jsx)(`li`,{className:`shrink-0`,children:(0,Q.jsx)(`button`,{type:`button`,"aria-current":t?`location`:void 0,onClick:()=>s(e.id),className:X(`flex h-[var(--ocx-control-h-sm)] w-full cursor-pointer items-center rounded-[8px] border-0 bg-transparent px-2.5 text-left text-[13px] font-medium whitespace-nowrap text-fg-muted`,`transition-colors duration-150 hover:bg-surface hover:text-fg`,`focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-highlight`,t&&`bg-surface text-fg shadow-[inset_0_0_0_1px_var(--ocx-line)]`),children:e.label})},e.id)})})]})}function rf({readOnly:e=!1,...t}){let n=tf.map(([e,n])=>({id:e,label:t.t(n)}));return(0,Q.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,Q.jsx)(Zc,{...t}),(0,Q.jsxs)(`div`,{className:`pv2-overview-grid grid min-w-0 gap-5 lg:grid-cols-[11rem_minmax(0,1fr)] lg:gap-8`,children:[(0,Q.jsx)(nf,{items:n,label:t.t(`proxyV2.indexLabel`),className:`lg:sticky lg:top-4 lg:self-start`}),(0,Q.jsx)(`div`,{className:`flex min-w-0 flex-col gap-5`,children:(0,Q.jsx)(ef,{...t,readOnly:e})})]})]})}function af({t:e,providers:t}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,Q.jsx)(Un,{title:(0,Q.jsx)(z,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:e(`dash.col.name`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,Q.jsx)(`tbody`,{children:t.map(t=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`font-semibold`,children:re(t.name,e)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,Q.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,Q.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var of=`__ocxCachedAt`;function sf(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return cf(n)?n.data:n}catch{return null}}function cf(e){return typeof e==`object`&&!!e&&typeof e[of]==`number`&&`data`in e}function lf(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return cf(n)?{data:n.data,cachedAt:n[of]}:{data:n,cachedAt:null}}catch{return null}}function uf(e,t){try{sessionStorage.setItem(e,JSON.stringify({[of]:Date.now(),data:t}))}catch{}}function df(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function ff(e){try{sessionStorage.removeItem(e)}catch{}}function pf(e,t,n){if(!n)return{kind:`disabled`,data:void 0,error:void 0,showSkeleton:!1,refreshing:!1,showError:!1};let r=e.data!==void 0,i=!e.lastAttemptOk&&e.error!==void 0;return e.refreshing?r?{kind:`loading-with-stale-data`,data:e.data,error:e.error,showSkeleton:!1,refreshing:!0,showError:i}:{kind:i?`retrying-cold`:`cold`,data:void 0,error:i?e.error:void 0,showSkeleton:!0,refreshing:!0,showError:!1}:i?r?{kind:`failed-with-stale`,data:e.data,error:e.error,showSkeleton:!1,refreshing:!1,showError:!0}:{kind:`failed-cold`,data:void 0,error:e.error,showSkeleton:!1,refreshing:!1,showError:!0}:r?{kind:t(e.data)?`ready-empty`:`ready-populated`,data:e.data,error:void 0,showSkeleton:!1,refreshing:!1,showError:!1}:{kind:`cold`,data:void 0,error:void 0,showSkeleton:!0,refreshing:!1,showError:!1}}function mf(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,Z.useMemo)(()=>a?lf(a):null,[a]),c=bn(e,t,(0,Z.useCallback)(async e=>{let t=await n(e);return a&&uf(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:pf(c,i,r.enabled!==!1)}}function hf(){return typeof navigator>`u`?``:navigator.userAgent}function gf(e=hf()){return e.match(/OpenCodexDesktop\/(\S+)/)?.[1]??null}function _f(e=hf()){return gf(e)!==null}var vf=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function yf(e=typeof location>`u`?``:location.search){let t=new URLSearchParams(e).get(`desktop_session`);return t&&vf.test(t)?t:null}function bf(e,t,n){let r=e+`/api/update/badge`;if(!_f(t))return r;let i=yf(n);return r+`?surface=desktop`+(i?`&session=`+encodeURIComponent(i):``)}function xf(e=hf()){return/Windows/i.test(e)?`windows`:/Mac OS X|Macintosh/i.test(e)?`macos`:/Linux|X11/i.test(e)&&!/Android/i.test(e)?`linux`:`unknown`}function Sf(e=hf()){if(!_f(e))return null;let t=xf(e);return t===`windows`?`http://tauri.localhost/update.html`:t===`macos`||t===`linux`?`tauri://localhost/update.html`:null}function Cf(e=hf()){let t=Sf(e);return t?(window.location.assign(t),!0):!1}function wf(e=hf()){if(!_f(e))return null;let t=xf(e);return t===`windows`?`http://tauri.localhost/cli.html`:t===`macos`||t===`linux`?`tauri://localhost/cli.html`:null}function Tf(e=hf()){let t=wf(e);return t?(window.location.assign(t),!0):!1}function Ef(e,t=typeof location>`u`?``:location.origin){if(!/^https?:\/\//i.test(e))return!1;try{return new URL(e).origin!==t}catch{return!1}}function Df(e){return e.desktop!==void 0&&(e.desktop.owned===!0||e.desktop.supervisor!==void 0)}function Of(e){return e.diagnosticStale!==!0&&If(e)&&e.desktop?.running===!1&&e.desktop.viable===!1&&e.desktop.supervisionUnknown!==!0}function kf(e,t=!1){return!t&&e.diagnosticStale!==!0&&(e.status===`native`||e.status===`protected`)?e.status:e.diagnosticStale===!0&&e.routingKind===`opencodex-local`?`unverified`:!t&&Of(e)?e.status:If(e)&&(t||e.diagnosticStale===!0||e.desktop?.supervisionUnknown===!0&&e.desktop.loginState!==`disabled`||e.desktop?.loginState!==`disabled`&&e.desktop?.loginState!==`enabled`)?`unverified`:t?`error`:e.status}function Af(e){if(!(e.status&&kf({...e,status:e.status})===`unverified`))return e.protection!==void 0&&e.protection!==`none`||!!(e.serviceInstalled||e.shimInstalled)}function jf(e){if(!e||!Df(e))return{desktop:!1,done:e?Af(e):void 0,titleKey:`shellV2.stepAutostart`,hintKey:`shellV2.stepAutostartHint`};let t=e.desktop;return{desktop:!0,done:e.diagnosticStale===!0?void 0:t.viable===!0?!0:t.loginState===`disabled`||e.platform===`darwin`&&t.running===!1&&t.viable===!1&&t.supervisionUnknown!==!0?!1:void 0,titleKey:`shellV2.stepAutostartDesktop`,hintKey:`shellV2.stepAutostartDesktopHint`,subPath:`desktop`}}function Mf(e,t){return t?`startup.unhealthy`:e.viable?`startup.viable`:e.running&&e.loginState===`disabled`&&(e.owned||e.supervisor!==void 0)?`startup.loginDisabled`:e.running&&!e.loginEnabled&&(e.owned||e.supervisor!==void 0)?`startup.desktopLoginUnverified`:`startup.unhealthy`}function Nf(e){if(e.routingKind===`custom-local`)return`startup.riskDetailCustomLocal`;if(e.routingKind===`opencodex-local`){if(e.diagnosticStale&&e.desktop)return`startup.desktopReopenRecovery`;if(e.desktop?.owned)return`startup.desktopRecovery`;if(e.desktop?.supervisor)return`startup.desktopSupervisedRecovery`}return e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function Pf(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Ff(e,t){return{request:++e.current,mutation:t.current}}function If(e){let t=e.desktop?.supervisor,n=typeof t==`object`&&t&&!Array.isArray(t)?t:null,r=n!==null&&typeof n.supervisorPid==`number`&&Number.isSafeInteger(n.supervisorPid)&&n.supervisorPid>0&&typeof n.runtimePid==`number`&&Number.isSafeInteger(n.runtimePid)&&n.runtimePid>0&&typeof n.app==`string`&&n.app.length>0;return e.routingKind===`opencodex-local`&&(e.desktop?.owned===!0||r)}function Lf(e,t){return e.status===`error`?{status:t?`unverified`:`error`,desktopManaged:t}:{status:e.status,desktopManaged:e.desktopManaged===!0||e.stale&&e.status===`unverified`&&t}}var Rf=2e3;function zf(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:kf({...e,status:t})}function Bf(e){return e?e.stale&&e.status!==`error`:!1}function Vf(e,t,n=e!==null&&e!==`error`){return!t||n?e:t.diagnosticStale?t.routingKind===`opencodex-local`?`unverified`:e:kf(t)}var Hf=3e4;function Uf(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function Wf(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function Gf(e,t){try{let n=await fetch(`${e}/api/startup-health`,{signal:t});if(!n.ok)throw Error(`startup health unavailable`);let r=await n.json(),i=zf(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0,...If(r)?{desktopManaged:!0}:{}}}catch(e){if(Wf(e,t))throw e;return{status:`error`,stale:!1}}}async function Kf(e,t){try{return(await Xn(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function qf(e,t){return cr(await fetch(`${e}/api/models`,{signal:t}))}async function Jf(e,t){return ei(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Yf(e,t,n){let{request:r,mutation:i}=Ff(n.shadowCallRequestEpochRef,n.shadowCallMutationEpochRef),[a,o]=await Promise.all([fetch(`${e}/api/sidecar-settings`,{signal:t}),fetch(`${e}/api/shadow-call-settings`,{signal:t})]),s=await cr(a),c;try{if(o.ok){let e=await o.json();Pf({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else Pf({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{Pf({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}return{sidecar:s,shadowCall:c}}async function Xf(e,t,n){let{request:r,mutation:i}=Ff(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await cr(await fetch(`${e}/api/settings`,{signal:t})),o,s;return Pf({request:r,mutation:i},{request:n.settingsRequestEpochRef.current,mutation:n.settingsMutationEpochRef.current,mutationInFlight:n.settingsMutationInFlightRef.current})&&(o=a,s=a.startupHealth),{settings:o,startupHealthSeed:s}}async function Zf(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`,supportsPlaintextV2:!1};let r=await n.json(),i=Hr(r.multiAgentSurfaceAdvisory),a=r.supportsPlaintextV2Mode===!0;return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`||r.multiAgentMode===`v2-plaintext`?{maMode:r.multiAgentMode,advisory:i,supportsPlaintextV2:a}:{maMode:`default`,advisory:i,supportsPlaintextV2:a}}catch(e){if(Wf(e,t))throw e;return{maMode:`default`,supportsPlaintextV2:!1}}}async function Qf(e,t){let n=e=>({health:null,providers:[],error:!0,failure:e}),r=new AbortController,i=AbortSignal.any([t,r.signal]),a,o,s=new Promise(e=>{o=()=>e(`access`)}),c=e=>((e.status===401||e.status===403)&&((e.status===403||a===void 0)&&(a=e.status===403?`denied`:`auth`),o()),e);try{let r=[`/api/system/health`,`/api/providers`].map(t=>Promise.resolve().then(()=>fetch(`${e}${t}`,{signal:i})).then(c)),o=await Promise.race([Promise.allSettled(r),s]);if(t.throwIfAborted(),o===`access`)return n(a??`auth`);let[l,u]=o;if(l.status===`rejected`||u.status===`rejected`)return n(`unavailable`);let d=l.value,f=u.value;if(!d.ok||!f.ok)return n(`request`);try{let e=await cr(d),t=await cr(f);return!e||typeof e.status!=`string`||typeof e.version!=`string`||!Number.isFinite(e.uptime)||e.uptime<0||!Array.isArray(t)||t.some(e=>!e||typeof e.name!=`string`||typeof e.adapter!=`string`||typeof e.baseUrl!=`string`||typeof e.hasApiKey!=`boolean`||e.defaultModel!==void 0&&typeof e.defaultModel!=`string`)?n(`invalid`):{health:e,providers:t,error:!1}}catch(e){if(Wf(e,t))throw e;return n(`invalid`)}}finally{r.abort()}}async function $f(e,t){let[n,r]=await Promise.all([fetch(`${e}/api/injection-model`,{signal:t}).catch(()=>null),fetch(`${e}/api/effort-caps`,{signal:t}).catch(()=>null)]),i;try{if(n?.ok){let e=await n.json();i={...Uf(e),injectionEfforts:e.efforts??[],injectionAvailable:e.available??[]}}}catch{}let a;try{if(r?.ok){let e=await r.json();a={effortCap:e.effortCap??``,subagentEffortCap:e.subagentEffortCap??``}}}catch{}return{injection:i,effortCaps:a}}function ep(e){if(tp(e)&&Array.isArray(e.clientIntegrations))return e.clientIntegrations.filter(e=>tp(e)&&e.ok===!1).map(e=>({client:typeof e.client==`string`?e.client:``,...Number.isSafeInteger(e.profileId)&&e.profileId>=0?{profileId:e.profileId}:{},...typeof e.reason==`string`?{reason:e.reason}:{},...typeof e.refusalReason==`string`?{refusalReason:e.refusalReason}:{},...typeof e.snapshotPath==`string`?{snapshotPath:e.snapshotPath}:{},...e.residual===!0?{residual:!0}:{}}))}function tp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function np(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function rp(e){if(!tp(e))throw Error(`invalid selected models response`);let t=e.selected;if(!tp(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,np(t)]))}async function ip(e,t=fetch,n){let r=await t(`${e}/api/selected-models`,n?{signal:n}:void 0);if(!r.ok)throw Error(`selected models HTTP ${r.status}`);return rp(await r.json())}function ap(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function op(e,t,n,r,i){return ap(e,t,n,r)&&!i}async function sp(e,t,n,r,i,a=fetch,o){return a(`${e}/api/model-visibility`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope:t,provider:n,targets:r,enabled:i}),...o?{signal:o}:{}})}function cp(e,t){return e===t}function lp(e,t){switch(t.reason){case`http`:return e(`models.discoveryFailedHttp`,{status:t.httpStatus});case`blocked`:return e(`models.discoveryFailedBlocked`);case`invalid_response`:return e(`models.discoveryFailedInvalidResponse`);case`network`:return e(`models.discoveryFailedNetwork`);case`provider`:return e(`models.discoveryFailedProvider`);default:return e(`models.discoveryFailedGeneric`)}}function up(e){return e.some(e=>e.pricingStatus!==void 0)}function dp(e,t){return t?e.filter(e=>e.pricingStatus===`free`):[...e]}function fp(e,t){return e&&up(t)}function pp(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t>=127&&t<=159||t===8232||t===8233})}function mp(e){let t=e.trim();return t?t.length>128?`models.displayNameTooLong`:t.includes(`/`)?`models.displayNameNoSlash`:pp(t)?`models.displayNameNoControl`:null:`models.displayNameRequired`}var hp=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function gp(e){return{enabled:e.enabled,agentsMaxThreadsConflict:e.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof e.maxConcurrentThreadsPerSession==`number`?e.maxConcurrentThreadsPerSession:null,multiAgentMode:e.multiAgentMode===`v1`||e.multiAgentMode===`v2`||e.multiAgentMode===`v2-plaintext`?e.multiAgentMode:`default`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0,multiAgentSurfaceAdvisory:e.multiAgentSurfaceAdvisory,supportsPlaintextV2Mode:e.supportsPlaintextV2Mode===!0,plaintextAgentMessagesEnabled:e.plaintextAgentMessagesEnabled===!0}}function _p(e){return e===`shadow_call_target_invalid`?`models.shadowCallTargetInvalid`:e===`shadow_call_source_invalid`?`models.shadowCallSourceInvalid`:`models.shadowCallSaveFailed`}var vp=Array.from({length:18},(e,t)=>1e5+t*5e4),yp=new Set(vp),bp=[272e3,372e3,922e3],xp=new Set(bp),Sp=`custom`,Cp=[4,8,16,32,64,128,256,500,1e3],wp=new Set(Cp);function Tp(e,t){return t?Math.max(0,e-1):e}function Ep(e,t){return t?e+1:e}var Dp=`ocx-models-collapsed:v2`;function Op(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?e>=1e6?Number((e/1e6).toFixed(2))+`M`:`${e/1e3}k`:e.toLocaleString()}function kp(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ap(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);op(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?Fe(a.namespaced,r):a.namespaced})}return i}function jp(e,t,n){let r=new Set(t.filter(e=>e.native===!0).map(e=>e.namespaced)),i=e.filter(e=>!r.has(e.value));return n&&!i.some(e=>e.value===n)&&i.push({value:n,label:e.find(e=>e.value===n)?.label??n}),i}function Mp(e=localStorage){try{let t=e.getItem(Dp);if(t===null)return null;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(e=>typeof e==`string`)):null}catch{return null}}function Np(e,t=localStorage){try{t.setItem(Dp,JSON.stringify([...e]))}catch{}}function Pp(e){let t=e.replace(/[_,\s]/g,``);if(!t)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}var Fp=`ocx.dash.controls.v1:`,Ip=`ocx.dash.overview.v1:`,Lp=`ocx.dash.usage30d.v1:`,Rp=`ocx.dash.startup.v3:`,zp=`ocx.dash.maMode.v1:`;function Bp(e,t){switch(t.type){case`polled`:return e.beforeSave?e:{...e,settings:{...t.settings,catalogRefreshPending:e.settings?.catalogRefreshPending===!0||t.settings.catalogRefreshPending}};case`save-started`:return!e.settings||e.beforeSave?e:{beforeSave:e.settings,settings:{...e.settings,[t.key]:t.value}};case`save-succeeded`:return!e.settings||!e.beforeSave?e:{...e,settings:{...e.settings,[t.key]:t.settings[t.key],catalogRefreshPending:t.key===`codexDesktopAuthless`||t.key===`codexClientCompaction`||e.settings.catalogRefreshPending,startupHealth:t.settings.startupHealth??e.settings.startupHealth}};case`save-failed`:return e.beforeSave?{...e,settings:e.beforeSave}:e;case`save-finished`:return{...e,beforeSave:null};case`applied`:return e.settings?{...e,settings:{...e.settings,catalogRefreshPending:!1}}:e}}function Vp(e){let t=new Map;for(let n of e){let e=t.get(n.provider);e?e.push(n):t.set(n.provider,[n])}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t))}function Hp(e){return`${Fp}${e}`}function Up(e,t=0,n){let{locale:r,t:i}=s(),[a,o]=(0,Z.useState)(ar),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(new Set),f=(0,Z.useMemo)(()=>sf(Hp(e)),[e]),p=(0,Z.useMemo)(()=>sf(`${Ip}${e}`),[e]),m=(0,Z.useMemo)(()=>sf(`${Lp}${e}`),[e]),h=(0,Z.useMemo)(()=>{let t=sf(`${Rp}${e}`);return t&&[`native`,`protected`,`unverified`].includes(t.status)&&typeof t.desktopManaged==`boolean`?t:null},[e]),g=(0,Z.useMemo)(()=>sf(`${zp}${e}`),[e]),[_,v]=(0,Z.useState)(()=>p?.health??null),[y,b]=(0,Z.useState)(()=>h?.status??null),[x,S]=(0,Z.useState)(()=>p?.providers??[]),[C,w]=(0,Z.useState)([]),[T,E]=(0,Z.useReducer)(Bp,{settings:f?.settings??null,beforeSave:null}),{settings:D}=T,O=T.beforeSave!==null,[k,A]=(0,Z.useState)(()=>f?.sidecar??null),[j,M]=(0,Z.useState)(()=>f?.shadowCall??null),[N,P]=(0,Z.useState)(()=>m),[F,I]=(0,Z.useState)(!1),[L,R]=(0,Z.useState)(),[z,B]=(0,Z.useState)(!1),[V,H]=(0,Z.useState)(null),[U,W]=(0,Z.useState)(!1),[ee,G]=(0,Z.useState)(!1),[te,ne]=(0,Z.useState)(()=>g??`default`),[K,q]=(0,Z.useState)(!1),[J,re]=(0,Z.useState)(null),[Y,ie]=(0,Z.useState)(null),[ae,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(null),le=Y?.apiBase===e?Y.advisory:null,ue=ae===e,de=se?.apiBase===e?se.mode:null,[fe,pe]=(0,Z.useState)(null),[me,he]=(0,Z.useState)(!1),[ge,_e]=(0,Z.useState)(!1),[ve,ye]=(0,Z.useState)(!1),[be,xe]=(0,Z.useState)(``),[Se,Ce]=(0,Z.useState)(``),[we,Te]=(0,Z.useState)([]),[Ee,De]=(0,Z.useState)([]),[Oe,ke]=(0,Z.useState)(!1),[Ae,je]=(0,Z.useState)(!0),[Me,Ne]=(0,Z.useState)(!1),[Pe,Fe]=(0,Z.useState)(``),[Ie,Le]=(0,Z.useState)(``),[Re,ze]=(0,Z.useState)(!1),[Be,Ve]=(0,Z.useState)(null),[He,Ue]=(0,Z.useState)(null),[We,Ge]=(0,Z.useState)([]),[Ke,qe]=(0,Z.useState)(!1),[Je,Ye]=(0,Z.useState)(`latest`),[Xe,Ze]=(0,Z.useState)(!0),[Qe,$e]=(0,Z.useState)(!1),et=(0,Z.useRef)(0),tt=(0,Z.useRef)(null),nt=(0,Z.useRef)(0),rt=(0,Z.useRef)(0),it=(0,Z.useRef)(0),at=(0,Z.useRef)(!1),ot=(0,Z.useRef)(0),st=(0,Z.useRef)(0),ct=(0,Z.useRef)(!1),[lt,ut]=(0,Z.useState)(null),[dt,ft]=(0,Z.useState)(null),[pt,X]=(0,Z.useState)(null),[mt,ht]=(0,Z.useState)(!1),[gt,_t]=(0,Z.useState)(!1),vt=(0,Z.useRef)(null),yt=(0,Z.useRef)(null),bt=(0,Z.useRef)(null),xt=(0,Z.useRef)(null),St=Br(ge,vt),Ct=Br(Ke,yt),wt=Br(me,bt),Tt=Br(ve,xt);(0,Z.useEffect)(()=>{let e=()=>o(ar());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>()=>{nt.current+=1,tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null)},[]);let Et=(0,Z.useRef)(h?.status??null),Dt=(0,Z.useRef)(!1),Ot=(0,Z.useRef)(h?.desktopManaged===!0),kt=(0,Z.useRef)(e),At=(0,Z.useRef)(0),jt=(0,Z.useRef)({settingsRequestEpochRef:rt,settingsMutationEpochRef:it,settingsMutationInFlightRef:at,shadowCallRequestEpochRef:ot,shadowCallMutationEpochRef:st,shadowCallMutationInFlightRef:ct}).current,Mt=bn(`dashboard-startup-health:${e}`,[e,t],t=>Gf(e,t),{pollMs:3e4});(0,Z.useEffect)(()=>{kt.current!==e&&(kt.current=e,At.current+=1,Et.current=h?.status??null,Dt.current=!1,Ot.current=h?.desktopManaged===!0,b(Et.current))},[e,h]);let Nt=Bf(Mt.data),Pt=Mt.refresh;(0,Z.useEffect)(()=>{if(!Nt)return;let e=window.setTimeout(()=>{Pt()},Rf);return()=>window.clearTimeout(e)},[Nt,Pt]);let Ft=bn(`dashboard-overview:${e}`,[e,t],t=>Qf(e,t),{pollMs:5e3}),It=pf(Ft,e=>e.health===null,!0),Lt=_!==null||Ft.data!==void 0,Rt=bn(`dashboard-ma-mode:${e}`,[e,t],t=>Zf(e,t),{pollMs:5e3}),zt=bn(`dashboard-sidecars:${e}`,[e,t],async t=>{let n=At.current;return{...await Yf(e,t,jt),startupHealthGeneration:n}},{pollMs:5e3}),Bt=bn(`dashboard-settings:${e}`,[e,t],async t=>{let n=At.current;return{...await Xf(e,t,jt),startupHealthGeneration:n}},{pollMs:5e3}),Vt=bn(`dashboard-multi-agent:${e}`,[e,t],t=>$f(e,t),{pollMs:5e3,enabled:Lt}),Ht=bn(ti(e,`all`,n),[e,t,n],t=>Jf(e,t),{enabled:Lt,pollMs:6e4,deadlineMs:6e4}),Ut=bn(`dashboard-diagnostics:${e}`,[e,t],t=>Kf(e,t),{pollMs:Hf,enabled:Lt}),Wt=bn(`dashboard-models:${e}`,[e,gt,t],t=>qf(e,t),{enabled:Lt&&!gt});(0,Z.useEffect)(()=>{if(Mt.data!==void 0){let t=Mt.data;At.current+=1;let n=Lf(t,Ot.current);b(n.status),Et.current=n.status,Dt.current=t.status!==`error`,Ot.current=n.desktopManaged,t.status!==`error`&&t.status!==`at-risk`&&!t.stale?df(`${Rp}${e}`,n):ff(`${Rp}${e}`)}},[Mt.data,e]),(0,Z.useEffect)(()=>{let t=Ft.data;t&&(t.health&&(v(t.health),S(t.providers),df(`${Ip}${e}`,{health:t.health,providers:t.providers})),_t(t.error))},[Ft.data,e]),(0,Z.useEffect)(()=>{Rt.data!==void 0&&(ne(Rt.data.maMode),ie({advisory:Rt.data.advisory??null,apiBase:e}),pe({supports:Rt.data.supportsPlaintextV2,apiBase:e}),df(`${zp}${e}`,Rt.data.maMode))},[Rt.data,e]);let Gt=fe?.apiBase===e&&fe.supports===!0,Kt=Rt.data!==void 0||g!==null;(0,Z.useEffect)(()=>{let e=Vt.data;e&&(e.injection&&(je(e.injection.multiAgentGuidanceEnabled),Ne(e.injection.syncCodexSubagentDefaults),xe(e.injection.injectionModel),Ce(e.injection.injectionEffort),Te(e.injection.injectionEfforts),De(e.injection.injectionAvailable)),e.effortCaps&&(Fe(e.effortCaps.effortCap),Le(e.effortCaps.subagentEffortCap)))},[Vt.data]),(0,Z.useEffect)(()=>{let t=zt.data;if(!t)return;A(t.sidecar),t.shadowCall!==void 0&&M(t.shadowCall);let n=sf(Hp(e))??{};df(Hp(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[zt.data,e]),(0,Z.useEffect)(()=>{let t=Bt.data;if(t&&(t.settings!==void 0&&E({type:`polled`,settings:t.settings}),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===At.current)){let n=Et.current,r=Vf(n,t.startupHealthSeed,Dt.current);b(r),Et.current=r,t.startupHealthSeed&&!Dt.current&&(!t.startupHealthSeed.diagnosticStale||t.startupHealthSeed.routingKind===`opencodex-local`)&&(Ot.current=If(t.startupHealthSeed)),r&&r!==`at-risk`&&r!==`error`&&!t.startupHealthSeed?.diagnosticStale?df(`${Rp}${e}`,{status:r,desktopManaged:Ot.current}):(r===`at-risk`||r===`error`)&&ff(`${Rp}${e}`)}},[Bt.data,e]),(0,Z.useEffect)(()=>{if(!D)return;let t=sf(Hp(e))??{};df(Hp(e),{...t,settings:D})},[D,e]),(0,Z.useEffect)(()=>{Ht.data!==void 0&&(P(Ht.data),df(`${Lp}${e}`,Ht.data))},[Ht.data,e]),(0,Z.useEffect)(()=>{Ut.data&&Ge(Ut.data)},[Ut.data]),(0,Z.useEffect)(()=>{Wt.data&&w(Wt.data),W(Wt.loading)},[Wt.data,Wt.loading]),(0,Z.useEffect)(()=>()=>{rt.current+=1,ot.current+=1},[]);let qt=bn(pt?.id&&pt.restart?`update-job:${e}:${pt.id}`:`update-job:idle:${e}`,[e,pt?.id,pt?.restart,pt?.latestVersion],async t=>{if(!pt?.id||!pt.restart)return{reconnecting:!1};let n=pt.latestVersion;try{let r=await cr(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(pt.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await cr(await fetch(`${e}/api/system/health`,{cache:`no-store`,signal:t}))).version===n)return{job:r.job,reconnecting:!1,reload:!0}}catch{return{job:r.job,reconnecting:!0}}return{job:r.job,reconnecting:!1}}}catch{return{reconnecting:!0}}return{reconnecting:!1}},{pollMs:1500,enabled:!!(pt?.id&&pt.restart),pauseWhenHidden:!1});(0,Z.useEffect)(()=>{let e=qt.data;e&&(`job`in e&&e.job&&X(e.job),ht(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[qt.data]);let Jt=(0,Z.useMemo)(()=>Vp(C),[C]),Yt=(0,Z.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return Jt;let t=[];for(let[n,r]of Jt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Jt,c]),Xt=(0,Z.useMemo)(()=>{let e=k?.webSearch?.backend;return jr(k?.webSearchModels,C,k?.webSearch?.model,e===`routed`?void 0:e)},[C,k?.webSearchModels,k?.webSearch]),Zt=(0,Z.useMemo)(()=>Mr(k?.visionModels,C,k?.vision?.model,k?.vision?.backend),[k?.visionModels,C,k?.vision]),Qt=async t=>{if(!k||F)return;t=Fr(k,t);let n=k,r={webSearch:pr(k.webSearch,t.webSearch),vision:pr(k.vision,t.vision),...k.visionModels?{visionModels:k.visionModels}:{},...k.webSearchModels?{webSearchModels:k.webSearchModels}:{}};I(!0),A(r);try{let n=await cr(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);R(e=>vr(e,n.codexWebSearch)),A({webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=sf(Hp(e))??{};df(Hp(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}}})}catch{A(n)}finally{I(!1)}};async function $t(t){if(!j||z)return;let n=j,r={...j,...t};B(!0),H(null),ct.current=!0,M(r);try{let r=await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!r.ok){M(n);let e=await r.json().catch(()=>null);H(i(_p(e?.code)));return}st.current+=1}catch{M(n),H(i(`models.networkError`))}finally{ct.current=!1,B(!1)}}let en=async(t,n=!1,r=!1)=>{q(!0),re(null);try{let a={multiAgentMode:t};n&&(a.multiAgentSurfaceAdvisoryAcknowledged=!0),r&&(a.plaintextAgentMessagesAcknowledged=!0);let o=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(o.ok){if(t===`v2-plaintext`){let t=!1;try{t=Gr(await o.json())}catch{}if(!t){re(i(`models.saveFailed`));return}pe({supports:!0,apiBase:e})}ne(t),n&&oe(e),df(`${zp}${e}`,t)}else{let e=i(`dash.maSwitchFailed`,{status:String(o.status)});try{let t=await o.json();e=typeof t.error==`string`&&t.error||typeof t.message==`string`&&t.message||e}catch{}re(e)}}catch(e){re(e instanceof Error?e.message:i(`dash.maNetworkError`))}finally{q(!1)}},tn=async t=>{K||te===t||(t===`v1`?await en(`v1`):ce({mode:t,apiBase:e}))},nn=async()=>{oe(e);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentSurfaceAdvisoryAcknowledged:!0})});t.ok||re(i(`dash.maSwitchFailed`,{status:String(t.status)}))}catch(e){re(e instanceof Error?e.message:i(`dash.maNetworkError`))}},rn=async()=>{let e=de;ce(null),e===`v2-plaintext`?await en(e,!1,!0):e?await en(e,!0):await nn()},an=async()=>{ce(null),te===`v1`?await nn():await en(`v1`,!0)},on=()=>{de?ce(null):oe(e)},sn=!de&&!ue&&le?.required===!0,cn=async t=>{if(!Oe){ke(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await cr(await fetch(`${e}/api/injection-model`)),r=Uf(n);je(r.multiAgentGuidanceEnabled),Ne(r.syncCodexSubagentDefaults),xe(r.injectionModel),Ce(r.injectionEffort),Array.isArray(n.efforts)&&Te(n.efforts),Array.isArray(n.available)&&De(n.available)}catch{}finally{ke(!1)}}},ln=async t=>{if(!D||O||ee)return;let n=!(D[t]??t===`codexAutoStart`);at.current=!0,E({type:`save-started`,key:t,value:n});try{let r=await cr(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({[t]:n})}),`save failed`);it.current+=1,E({type:`save-succeeded`,key:t,settings:r}),(t===`codexDesktopAuthless`||t===`codexClientCompaction`)&&await mn()}catch{E({type:`save-failed`}),_t(!0)}finally{at.current=!1,E({type:`save-finished`})}},un=()=>ln(`codexAutoStart`),dn=()=>ln(`codexDesktopAuthless`),fn=()=>ln(`codexClientCompaction`),pn=(0,Z.useCallback)(()=>{Ve(null),Ue(null)},[]),mn=async()=>{if(!ee){G(!0),Ve(null),Ue(null);try{let t=await cr(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Ve(t),t.ok&&t.status===`applied`&&(E({type:`applied`}),R(void 0)),t.projectConfigGrouped&&Ge(t.projectConfigGrouped)}catch(e){Ue(e instanceof Error?e.message:String(e))}finally{G(!1)}}},hn=async(t,n=!1)=>{n&&(et.current=0),tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null);let r=++nt.current;$e(!0),ft(null),ut(null);try{let n=await cr(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==nt.current)return;if(ut(n),n.reason===`latest_unavailable`&&et.current<2){let e=++et.current;tt.current=window.setTimeout(()=>{r===nt.current&&(tt.current=null,hn(t))},800*e);return}n.reason!==`latest_unavailable`&&(et.current=0),$e(!1)}catch(e){if(r!==nt.current)return;ft(e instanceof Error?e.message:String(e)),$e(!1)}},gn=()=>{nt.current+=1,tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null),$e(!1),qe(!1)},_n=()=>{if(Cf())return;let e=ur(_?.version);Ye(e),Ze(!0),qe(!0),hn(e,!0)},vn=e=>{Ye(e),hn(e,!0)},yn=(0,Z.useRef)(_n);return(0,Z.useEffect)(()=>{yn.current=_n}),(0,Z.useEffect)(()=>{let e=()=>{or()&&(Tn(`dashboard`),yn.current())},t=or()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:r,t:i,selectedSection:a,setSelectedSection:o,modelQuery:c,setModelQuery:l,expandedProviders:u,setExpandedProviders:d,health:_,startupHealth:y,providers:x,models:C,settings:D,sidecar:k,shadowCall:j,usage30d:N,usageLoading:Ht.loading&&!N,healthLoading:Ft.loading&&!_,sidecarSaving:F,shadowCallSaving:z,shadowCallError:V,modelsLoading:U,settingsSaving:O,syncing:ee,maMode:te,maModeResolved:Kt,maBusy:K,setMaHelpOpen:he,maHelpOpen:me,maError:J,maSupportsPlaintextV2:Gt,maAdvisory:le,maAdvisoryOpen:sn,pendingMaMode:de,keepMaMode:rn,chooseMaV1:an,dismissMaSurfaceDialog:on,effortCapHelpOpen:ge,setEffortCapHelpOpen:_e,shadowCallHelpOpen:ve,setShadowCallHelpOpen:ye,injectionModel:be,injectionEffort:Se,injectionEfforts:we,injectionAvailable:Ee,injectionSaving:Oe,multiAgentGuidanceEnabled:Ae,syncCodexSubagentDefaults:Me,saveInjection:cn,effortCap:Pe,subagentEffortCap:Ie,effortCapSaving:Re,setEffortCap:Fe,setSubagentEffortCap:Le,setEffortCapSaving:ze,syncResult:Be,syncError:He,projectConfigWarnings:We,updateOpen:Ke,updateChannel:Je,setUpdateRestart:Ze,updateRestart:Xe,updateLoading:Qe,updateCheck:lt,updateError:dt,updateJob:pt,reconnecting:mt,error:gt||It.showError,connectionFailure:Ft.data?.failure??(It.showError?`unavailable`:void 0),refreshDashboard:Ft.refresh,effortCapHelpTriggerRef:vt,updateTriggerRef:yt,maHelpTriggerRef:bt,shadowCallHelpTriggerRef:xt,effortCapHelpDialogRef:St,updateDialogRef:Ct,maHelpDialogRef:wt,shadowCallHelpDialogRef:Tt,filteredGroups:Yt,sidecarModels:Xt,visionModels:Zt,sidecarCodexApply:L,saveSidecar:Qt,saveShadowCall:$t,switchMaMode:tn,toggleCodexAutoStart:un,toggleCodexDesktopAuthless:dn,toggleCodexClientCompaction:fn,runSync:mn,clearSyncFeedback:pn,fetchUpdateCheck:hn,closeUpdateDialog:gn,openUpdateDialog:_n,changeUpdateChannel:vn,runUpdate:async()=>{if(lt?.canUpdate){ft(null);try{let t=await cr(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Je,restart:Xe})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);X(t.job),ht(!1),gn()}catch(e){ft(e instanceof Error?e.message:String(e))}}}}}function Wp(e){En(sr(e))}function Gp({apiBase:e,targetKey:t,readOnly:n=!1,connected:r=!1,authenticationPending:i=!1,refreshEpoch:a=0}){let o=Up(e,a,t),{t:s,error:c,selectedSection:l,providers:u,models:d,modelsLoading:f,modelQuery:p,setModelQuery:m,filteredGroups:h,expandedProviders:g,setExpandedProviders:_}=o;if(i)return null;let v=o.connectionFailure===`auth`||o.connectionFailure===`denied`;if(c&&(v||!o.health))return(0,Q.jsxs)(Un,{style:{marginTop:40},icon:(0,Q.jsx)(St,{}),title:(0,Q.jsx)(`span`,{style:{color:`var(--red)`},children:s(o.connectionFailure===`denied`?`dash.permissionDenied`:o.connectionFailure===`auth`?`dash.authRequired`:`dash.dataUnavailable`)}),children:[!r&&o.connectionFailure===`unavailable`&&(0,Q.jsx)(z,{k:`dash.runStart`,cmd:`ocx start`}),(0,Q.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>o.refreshDashboard(),children:s(`common.retry`)})]});let y=(0,Q.jsx)(rf,{...o,readOnly:n}),b=(0,Q.jsx)(af,{t:s,providers:u}),x=(0,Q.jsx)(Yr,{t:s,models:d,modelsLoading:f,modelQuery:p,setModelQuery:m,filteredGroups:h,expandedProviders:g,setExpandedProviders:_}),S=(0,Q.jsx)(Jr,{...o}),C=[{id:`overview`,label:s(`dash.workspace.overview`),body:y},{id:`providers`,label:s(`dash.activeProviders`),body:b},{id:`models`,label:s(`dash.availableModels`),body:x}],w=C.find(e=>e.id===l)??C[0],T=Wp,E=e=>{let t=C.findIndex(e=>e.id===l),n=-1;if(e.key===`ArrowRight`?n=(t+1)%C.length:e.key===`ArrowLeft`?n=(t-1+C.length)%C.length:e.key===`Home`?n=0:e.key===`End`&&(n=C.length-1),n<0)return;e.preventDefault();let r=C[n];T(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,Q.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[c&&(0,Q.jsxs)($,{tone:`warn`,children:[s(`dash.staleData`),` `,(0,Q.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>o.refreshDashboard(),children:s(`common.retry`)})]}),(0,Q.jsxs)(`header`,{className:`mb-5 flex flex-col gap-1.5`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:s(`shellV2.pageProxyDetails`)}),(0,Q.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[14px] leading-[1.55] text-fg-muted`,children:s(l===`overview`?`proxyV2.pageLede`:`dash.subtitle`)})]}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":s(`dash.workspace.sections`),children:C.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":l===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:l===e.id?0:-1,className:`page-tab${l===e.id?` page-tab--active`:``}`,onClick:()=>T(e.id),onKeyDown:E,children:e.label},e.id))}),(0,Q.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${w.id}`,"aria-labelledby":`dashboard-tab-${w.id}`,tabIndex:0,children:w.body}),S]})}var Kp={primary:`bg-accent text-on-accent shadow-sm hover:bg-accent/88`,outline:`bg-raised text-fg ring-1 ring-inset ring-line-strong hover:bg-surface`,ghost:`bg-transparent text-fg-muted hover:bg-surface hover:text-fg`,danger:`bg-danger-soft text-danger ring-1 ring-inset ring-danger/20 hover:bg-danger hover:text-on-accent`},qp={sm:`h-[var(--ocx-row-control-h,var(--ocx-control-h-sm))] gap-1.5 px-3 text-[13px]`,md:`h-[var(--ocx-control-h)] gap-2 px-4 text-[13px]`,icon:`size-[var(--ocx-control-h)] p-0`},Jp=(0,Z.forwardRef)(function({variant:e=`outline`,size:t=`md`,className:n,type:r=`button`,...i},a){return(0,Q.jsx)(`button`,{ref:a,type:r,className:X(`ui-v2 inline-flex shrink-0 cursor-pointer items-center justify-center rounded-control font-medium whitespace-nowrap select-none`,`transition-[background-color,color,box-shadow,scale] duration-200 ease-soft active:scale-[0.97]`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-50`,`[&_svg]:size-4 [&_svg]:shrink-0`,Kp[e],qp[t],n),...i})}),Yp=Object.freeze([`completed`,`failed`,`incomplete`,`aborted`]);Object.freeze(Yp.filter(e=>e!==`aborted`)),Object.freeze([`terminal`,`client_cancel`,`non_stream`,`body_stall`,`body_overflow`]);function Xp(e){return e.closeReason===`client_cancel`||e.status===499?`aborted`:e.terminalStatus===`failed`?`failed`:e.terminalStatus===`incomplete`||e.closeReason===`body_stall`||e.closeReason===`body_overflow`?`incomplete`:e.terminalStatus===`completed`||e.terminalStatus===void 0&&(e.status===101||e.status>=200&&e.status<400)?`completed`:`failed`}function Zp(e,t){return e.filter(e=>e.timestamp>=t&&Xp(e)===`failed`)}function Qp(e){let t=`home-startup:${e}`,n=async t=>{let n=await fetch(`${e}/api/startup-health`,{signal:t});return n.ok?await n.json():null},r=bn(t,[e],n);return vn(t,n,{enabled:r.lastAttemptOk&&r.data?.diagnosticStale===!0,pollMs:Rf}),r}var $p=[`slate`,`red`,`orange`,`amber`,`lime`,`green`,`teal`,`cyan`,`blue`,`indigo`,`violet`,`pink`],em=/^[a-z0-9][a-z0-9-]{1,22}[a-z0-9]$/,tm=`https://opencodex.me/dashboard/`,nm=`https://opencodex.me/guides/telemetry/#public-profile-and-rank-opt-in`,rm=15e3;function im(e){return em.test(e)&&!e.includes(`--`)&&!/^[0-9-]+$/.test(e)}var am=class extends Error{status;code;constructor(e,t){super(t?`HTTP ${String(e)} ${t}`:`HTTP ${String(e)}`),this.name=`ProfileRequestError`,this.status=e,this.code=t}};function om(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sm(e){return typeof e==`string`&&$p.includes(e)}function cm(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function lm(e){if(!om(e)||typeof e.connected!=`boolean`)return null;let t=om(e.profile)?e.profile:null,n=t&&typeof t.handle==`string`&&typeof t.displayName==`string`&&sm(t.avatar)?{handle:t.handle,displayName:t.displayName,avatar:t.avatar,connectedAt:typeof t.connectedAt==`string`?t.connectedAt:``,lastSentDay:typeof t.lastSentDay==`string`?t.lastSentDay:null,pendingDelete:t.pendingDelete===!0,revoked:t.revoked===!0}:null;return{connected:e.connected&&n!==null,unreadable:e.unreadable===!0,profile:n,telemetryEffective:e.telemetryEffective===!0,nextDay:typeof e.nextDay==`string`?e.nextDay:null}}function um(e){if(!om(e)||!om(e.periods))return null;let t={};for(let n of[`day`,`week`,`month`]){let r=e.periods[n];if(!om(r))return null;t[n]={rank:typeof r.rank==`number`&&r.rank>0?Math.floor(r.rank):null,of:cm(r.of),tokens:cm(r.tokens),requests:cm(r.requests)}}return{periods:t,families:Array.isArray(e.families)?e.families.filter(om).filter(e=>typeof e.family==`string`).map(e=>({family:String(e.family),requests:cm(e.requests),tokens:cm(e.tokens)})):[]}}async function dm(e,t,n={},r){let i=d(rm),a=()=>i.controller.abort(r?.reason);r?.addEventListener(`abort`,a,{once:!0});try{let r=await fetch(e+t,{...n,signal:i.signal});if(!r.ok){let e=await r.json().catch(()=>null),t=om(e)&&typeof e.code==`string`?e.code:null;throw new am(r.status,t)}return await r.json().catch(()=>null)}finally{r?.removeEventListener(`abort`,a),i.clear()}}async function fm(e,t){let n=lm(await dm(e,`/api/telemetry/profile`,{},t));if(!n)throw Error(`invalid profile status payload`);return n}async function pm(e,t){let n=await dm(e,`/api/telemetry/profile/rank`,{},t),r=um(om(n)?n.rank:null);if(!r)throw Error(`invalid profile rank payload`);return r}async function mm(e,t){await dm(e,`/api/telemetry/profile`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...t,acknowledgePublic:!0})})}async function hm(e){let t=await dm(e,`/api/telemetry/profile`,{method:`DELETE`}),n=om(t)?t.status:null;return n===`deleted`||n===`deletion_pending`||n===`not_connected`||n===`local_removed`?n:`deleted`}function gm(e){if(!em.test(e))return null;let t=new URL(tm);return t.search=new URLSearchParams({profile:e}).toString(),t.hash=`leaderboard`,t.toString()}var _m={slate:`#64748b`,red:`#ef4444`,orange:`#f97316`,amber:`#f59e0b`,lime:`#84cc16`,green:`#22c55e`,teal:`#14b8a6`,cyan:`#06b6d4`,blue:`#3b82f6`,indigo:`#6366f1`,violet:`#8b5cf6`,pink:`#ec4899`},vm=[`day`,`week`,`month`];function ym(e){return[...e.trim()][0]?.toUpperCase()??`?`}function bm(e){let t=e instanceof am?e.code:null;return t===`handle_taken`?`telemetryProfile.errTaken`:t===`invalid`?`telemetryProfile.errInvalid`:t===`rate_limited`?`telemetryProfile.errRateLimited`:t===`telemetry_off`?`telemetryProfile.errTelemetryOff`:t===`agent_consent_required`?`telemetryProfile.errSession`:`telemetryProfile.errUnavailable`}function xm({apiBase:e}){let t=b(),n=new Intl.NumberFormat(x(),{notation:`compact`,maximumFractionDigits:1}),r=new Intl.NumberFormat(x()),i=bn(`telemetry-profile:${e}`,[e],t=>fm(e,t),{pollMs:6e4}),a=i.data?.profile??null,o=a&&!a.pendingDelete&&!a.revoked?a.handle:``,s=bn(`telemetry-profile-rank:${e}:${o}`,[e,o],t=>o?pm(e,t):Promise.resolve(null),{pollMs:3e5}),c=i.refresh;(0,Z.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>c();return window.addEventListener(Dd,e),()=>window.removeEventListener(Dd,e)},[c]);let[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(!1);if(p()||!i.data)return null;let A=i.data;if(!a&&!A.unreadable&&!A.telemetryEffective)return null;let j=d.trim().toLowerCase(),M=im(j)&&m.trim().length>0&&[...m.trim()].length<=32&&g!==null&&v&&!S,N=async()=>{if(M&&g){C(!0),T(null);try{await mm(e,{handle:j,displayName:m.trim(),avatar:g}),u(!1),i.refresh()}catch(e){T(bm(e))}finally{C(!1)}}},P=async()=>{C(!0),T(null);try{let t=await hm(e);k(t===`deletion_pending`),D(!1)}catch(e){T(bm(e))}finally{C(!1),i.refresh()}},F=a?gm(a.handle):null;return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4 rounded-card bg-surface p-5`,"aria-labelledby":`telemetry-profile-title`,"data-testid":`telemetry-profile-card`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-3`,children:[(0,Q.jsx)(`h2`,{id:`telemetry-profile-title`,className:`m-0 text-[15px] font-semibold`,children:t(`telemetryProfile.title`)}),(0,Q.jsx)(`a`,{href:nm,target:`_blank`,rel:`noreferrer`,className:`text-[13px] font-medium text-highlight hover:underline`,children:t(`telemetryProfile.learnMore`)})]}),A.unreadable&&!a&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:t(`telemetryProfile.unreadable`)}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(Jp,{variant:`outline`,disabled:S,onClick:()=>{P()},children:t(`telemetryProfile.disconnect`)})})]}),!a&&!A.unreadable&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:t(`telemetryProfile.lede`)}),(0,Q.jsxs)(`ul`,{className:`m-0 flex list-none flex-col gap-1 p-0 text-[13px] text-fg-muted`,children:[(0,Q.jsx)(`li`,{children:t(`telemetryProfile.publicWhat`)}),(0,Q.jsx)(`li`,{children:t(`telemetryProfile.neverWhat`)})]}),l?(0,Q.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),N()},children:[(0,Q.jsxs)(`label`,{className:`flex flex-col gap-1 text-[13px]`,children:[(0,Q.jsx)(`span`,{className:`font-medium`,children:t(`telemetryProfile.handleLabel`)}),(0,Q.jsx)(`input`,{name:`handle`,value:d,onChange:e=>f(e.target.value),autoComplete:`off`,spellCheck:!1,maxLength:24,className:`rounded-control border border-line bg-raised px-2.5 py-1.5 font-mono text-[14px]`}),(0,Q.jsx)(`span`,{className:`text-xs text-fg-subtle`,children:t(`telemetryProfile.handleHint`)})]}),(0,Q.jsxs)(`label`,{className:`flex flex-col gap-1 text-[13px]`,children:[(0,Q.jsx)(`span`,{className:`font-medium`,children:t(`telemetryProfile.nameLabel`)}),(0,Q.jsx)(`input`,{name:`displayName`,value:m,onChange:e=>h(e.target.value),autoComplete:`off`,maxLength:32,className:`rounded-control border border-line bg-raised px-2.5 py-1.5 text-[14px]`})]}),(0,Q.jsxs)(`fieldset`,{className:`m-0 flex flex-col gap-1 border-0 p-0 text-[13px]`,children:[(0,Q.jsx)(`legend`,{className:`mb-1 font-medium`,children:t(`telemetryProfile.colourLabel`)}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:$p.map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-label":e,"aria-pressed":g===e,onClick:()=>_(e),className:X(`size-6 cursor-pointer rounded-full border-2`,g===e?`border-fg`:`border-transparent`),style:{backgroundColor:_m[e]}},e))})]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2 text-[13px]`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,name:`acknowledgePublic`,checked:v,onChange:e=>y(e.target.checked)}),(0,Q.jsx)(`span`,{children:t(`telemetryProfile.acknowledge`)})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsxs)(Jp,{variant:`primary`,type:`submit`,disabled:!M,"aria-busy":S,children:[S&&(0,Q.jsx)(we,{"aria-hidden":!0,className:`animate-spin motion-reduce:animate-none`}),t(S?`telemetryProfile.connecting`:`telemetryProfile.connect`)]}),(0,Q.jsx)(Jp,{variant:`outline`,onClick:()=>{u(!1),T(null)},children:t(`telemetryProfile.cancel`)})]})]}):(0,Q.jsx)(`div`,{children:(0,Q.jsx)(Jp,{variant:`primary`,onClick:()=>u(!0),children:t(`telemetryProfile.connect`)})})]}),a&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`grid size-9 shrink-0 place-items-center rounded-full text-[15px] font-semibold text-white`,style:{backgroundColor:_m[a.avatar]},children:ym(a.displayName)}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-col`,children:[(0,Q.jsx)(`span`,{className:`truncate text-[14px] font-semibold`,children:a.displayName}),(0,Q.jsxs)(`span`,{className:`truncate font-mono text-xs text-fg-subtle`,children:[`@`,a.handle]})]})]}),a.pendingDelete||O?(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-warning`,children:t(`telemetryProfile.deletionPending`)}):a.revoked?(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-warning`,children:t(`telemetryProfile.revoked`)}):(0,Q.jsxs)(Q.Fragment,{children:[!A.telemetryEffective&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:t(`telemetryProfile.paused`)}),s.error?(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:t(`telemetryProfile.rankUnavailable`)}):s.data?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`grid grid-cols-3 gap-2`,children:vm.map(e=>{let i=s.data.periods[e];return(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5 rounded-control bg-surface-2 px-3 py-2`,children:[(0,Q.jsx)(`span`,{className:`text-xs font-medium text-fg-subtle`,children:t(`telemetryProfile.${e}`)}),(0,Q.jsx)(`span`,{className:`truncate text-[15px] font-semibold tabular-nums`,children:i.rank===null?t(`telemetryProfile.notRanked`):t(`telemetryProfile.rankOf`,{rank:r.format(i.rank),of:r.format(i.of)})}),(0,Q.jsx)(`span`,{className:`truncate text-xs text-fg-muted tabular-nums`,children:t(`telemetryProfile.totals`,{tokens:n.format(i.tokens),requests:r.format(i.requests)})})]},e)})}),vm.every(e=>s.data.periods[e].rank===null)&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:t(`telemetryProfile.firstRank`)}),s.data.families.length>0&&(0,Q.jsxs)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:[t(`telemetryProfile.topModels`),`: `,s.data.families.slice(0,3).map(e=>e.family).join(`, `)]})]}):null]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[F&&!a.pendingDelete&&(0,Q.jsx)(`a`,{href:F,target:`_blank`,rel:`noreferrer`,className:`text-[13px] font-medium text-highlight hover:underline`,children:t(`telemetryProfile.viewLeaderboard`)}),a.pendingDelete||O?(0,Q.jsxs)(Jp,{variant:`outline`,disabled:S,"aria-busy":S,onClick:()=>{P()},children:[S&&(0,Q.jsx)(we,{"aria-hidden":!0,className:`animate-spin motion-reduce:animate-none`}),t(`telemetryProfile.retry`)]}):E?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`text-[13px]`,children:t(`telemetryProfile.disconnectConfirm`)}),(0,Q.jsxs)(Jp,{variant:`outline`,disabled:S,"aria-busy":S,onClick:()=>{P()},children:[S&&(0,Q.jsx)(we,{"aria-hidden":!0,className:`animate-spin motion-reduce:animate-none`}),t(`telemetryProfile.disconnectYes`)]}),(0,Q.jsx)(Jp,{variant:`outline`,onClick:()=>D(!1),children:t(`telemetryProfile.cancel`)})]}):(0,Q.jsx)(Jp,{variant:`outline`,onClick:()=>D(!0),children:t(`telemetryProfile.disconnect`)})]})]}),w&&(0,Q.jsx)(`p`,{role:`alert`,className:`m-0 text-[13px] text-danger`,children:t(w)})]})}function Sm(e,t){return t==null&&e!==null}function Cm(e){return e?`/healthz`:`/api/system/health`}function wm(e){let t=e&&typeof e==`object`?e.version:void 0;return typeof t==`string`&&t.length>0?t:null}function Tm(e){let t=e&&typeof e==`object`?e.uptime:void 0;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}async function Em(e,t,n,r=fetch){let i=await r(`${e}${t}`,{signal:n});if(i.status===401||i.status===403)return{version:null,uptime:null};if(!i.ok)return null;let a=await i.json();return{version:wm(a),uptime:Tm(a)}}var Dm=864e5;async function Om(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function km({apiBase:e,navigate:t,onReloadCodex:n,reloadingCodex:r}){let i=b(),a=x(),o=new Intl.NumberFormat(a),s=new Intl.NumberFormat(a,{notation:`compact`,maximumFractionDigits:1}),c=bn(`home-health:${e}`,[e],t=>Em(e,`/api/system/health`,t),{pollMs:3e4}),l=bn(`home-usage:${e}`,[e],t=>Om(`${e}/api/usage?range=7d`,t),{pollMs:6e4}),u=bn(`home-config:${e}`,[e],t=>Om(`${e}/api/config`,t)),d=Qp(e),f=bn(`home-failures:${e}`,[e],async t=>{let n=await fetch(`${e}/api/logs?limit=500`,{signal:t});if(!n.ok)throw Error(`logs unavailable`);let r=await n.json();if(!r||typeof r!=`object`||!(`logs`in r)||!Array.isArray(r.logs))throw Error(`logs unavailable`);return Zp(r.logs,Date.now()-Dm)},{pollMs:3e4}),p=f.error==null&&f.data!==void 0,m=p?f.data??[]:[],h=c.data!=null,g=Object.keys(u.data?.providers??{}).length,_=l.data?.summary?.requests??0,v=l.data?.summary?.totalTokens??0,y=c.data?.uptime??null,S=jf(d.data),C=[{key:`provider`,done:g>0,title:i(`shellV2.stepProvider`),hint:i(`shellV2.stepProviderHint`),showHint:!1,go:()=>t(`providers`)},{key:`request`,done:_>0,title:i(`shellV2.stepFirstRequest`),hint:i(`shellV2.stepFirstRequestHint`),showHint:!1,go:()=>t(`integrations`)},{key:`autostart`,done:S.done,title:i(S.titleKey),hint:i(S.hintKey),showHint:!!d.data&&S.desktop&&S.done===void 0,go:()=>S.subPath?t(`startup`,S.subPath):t(`startup`)}],w=C.filter(e=>e.done).length,T=w===C.length,E=h?p?m.length>0?i(`shellV2.homeErrorsToday`,{count:o.format(m.length)}):i(`shellV2.homeOk`):i(`shellV2.homeErrorsUnavailable`):i(`shellV2.homeDown`);return(0,Q.jsxs)(`div`,{className:`ui-v2 flex flex-col gap-6 font-sans text-fg`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-4`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,Q.jsx)(`span`,{className:`relative inline-flex size-3 shrink-0`,"aria-hidden":!0,children:(0,Q.jsx)(`span`,{className:X(`relative size-3 rounded-full`,h?!p||m.length?`bg-warning`:`bg-success`:`bg-danger`)})}),(0,Q.jsx)(`h1`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-balance`,children:E})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsxs)(Jp,{variant:`outline`,onClick:n,disabled:r,children:[(0,Q.jsx)(`span`,{className:X(`inline-flex`,r&&`animate-spin`),children:(0,Q.jsx)(Ke,{})}),i(r?`dash.codexRestarting`:`dash.codexRestart`)]}),(0,Q.jsx)(Jp,{variant:`primary`,onClick:()=>t(`logs`),children:i(`shellV2.openLogs`)})]})]}),(0,Q.jsxs)(`section`,{className:`grid grid-cols-2 gap-3 md:grid-cols-4`,children:[(0,Q.jsx)(Am,{label:i(`shellV2.tileVersion`),value:c.data?.version?`v${c.data.version}`:`—`}),(0,Q.jsx)(Am,{label:i(`shellV2.tileUptime`),value:h&&y!==null?i(`shellV2.uptimeValue`,{h:String(Math.floor(y/3600)),m:String(Math.floor(y%3600/60))}):`—`}),(0,Q.jsx)(Am,{label:i(`shellV2.tileRequests`),value:o.format(_)}),(0,Q.jsx)(Am,{label:i(`shellV2.tileTokens`),value:s.format(v)})]}),(0,Q.jsx)(xm,{apiBase:e}),(0,Q.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]`,children:[(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4 rounded-card bg-surface p-5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-[15px] font-semibold`,children:i(`shellV2.checklistTitle`)}),(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:i(`shellV2.checklistProgress`,{done:String(w),total:String(C.length)})})]}),(0,Q.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-surface-2`,"aria-hidden":!0,children:(0,Q.jsx)(`div`,{className:`h-full origin-left rounded-full bg-accent transition-transform duration-[600ms] ease-soft`,style:{transform:`scaleX(${w/C.length})`}})}),T?(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:i(`shellV2.checklistAllDone`)}):(0,Q.jsx)(`ol`,{className:`m-0 flex list-none flex-col gap-1 p-0`,children:C.map((e,t)=>{let n=e.done===!1&&C.findIndex(e=>e.done===!1)===t;return(0,Q.jsx)(`li`,{"data-step":e.key,children:(0,Q.jsxs)(`button`,{type:`button`,onClick:e.go,className:X(`group flex w-full cursor-pointer items-center gap-3 rounded-control p-2.5 text-left transition-colors hover:bg-raised`,n&&`bg-raised shadow-sm ring-1 ring-line`),children:[(0,Q.jsx)(`span`,{className:X(`grid size-6 shrink-0 place-items-center rounded-full text-xs font-semibold`,e.done?`bg-success text-on-accent`:n?`bg-accent text-on-accent`:`bg-surface-2 text-fg-muted`),"aria-hidden":!0,children:e.done?`✓`:t+1}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,Q.jsx)(`span`,{className:X(`text-[14px] font-medium`,e.done&&`text-fg-subtle line-through`),children:e.title}),(e.done===!1||e.showHint)&&(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted`,children:e.hint})]}),e.done===!1&&(0,Q.jsxs)(`span`,{className:`text-[13px] font-medium text-highlight opacity-0 transition-opacity group-hover:opacity-100`,children:[i(`shellV2.stepOpen`),` →`]})]})},e.key)})})]}),(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3 rounded-card bg-surface p-5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-[15px] font-semibold`,children:i(`shellV2.recentErrors`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(`logs`),className:`cursor-pointer text-[13px] font-medium text-highlight hover:underline`,children:i(`shellV2.viewAll`)})]}),p?m.length===0?(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:i(`shellV2.noErrors`)}):(0,Q.jsx)(`ul`,{className:`m-0 flex list-none flex-col gap-1 p-0`,children:m.slice(0,4).map(e=>(0,Q.jsxs)(`li`,{className:`flex items-baseline gap-2.5 rounded-control px-1 py-1.5 text-[13px]`,children:[(0,Q.jsx)(`span`,{className:`font-mono text-xs text-fg-subtle tabular-nums`,children:new Date(e.timestamp).toLocaleTimeString(a,{hour:`2-digit`,minute:`2-digit`})}),(0,Q.jsx)(`span`,{className:`rounded-full bg-warning-soft px-1.5 text-[11px] font-semibold text-warning tabular-nums`,children:e.status}),(0,Q.jsxs)(`span`,{className:`min-w-0 flex-1 truncate`,children:[e.provider,` · `,e.model]})]},`${e.timestamp}:${e.model}`))}):(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:i(`shellV2.homeErrorsUnavailable`)}),(0,Q.jsxs)(`div`,{className:`mt-auto flex items-center justify-between gap-3 border-t border-line pt-3 text-[13px] text-fg-muted`,children:[(0,Q.jsxs)(`span`,{children:[i(`shellV2.tileProviders`),` `,(0,Q.jsx)(`b`,{className:`font-semibold text-fg tabular-nums`,children:o.format(g)})]}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(`dashboard`,`update`),className:`cursor-pointer font-medium text-highlight hover:underline`,children:i(`shellV2.checkUpdate`)})]})]})]})]})}function Am({label:e,value:t}){return(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1 rounded-card bg-surface px-4 py-3.5`,children:[(0,Q.jsx)(`span`,{className:`text-xs font-medium text-fg-subtle`,children:e}),(0,Q.jsx)(`span`,{className:`truncate text-stat font-semibold tracking-[-0.02em] tabular-nums`,children:t})]})}var jm={done:`bg-success-soft text-success`,todo:`bg-highlight-soft text-highlight`,optional:`bg-surface-2 text-fg-muted`};function Mm({title:e,term:t,body:n,badge:r,icon:i,onOpen:a,openLabel:o}){return(0,Q.jsxs)(`button`,{type:`button`,onClick:a,"aria-label":`${e} — ${o}`,className:X(`ui-v2 group flex h-full w-full cursor-pointer flex-col gap-3 rounded-card bg-surface p-5 text-left`,`transition-[translate,box-shadow,background-color] duration-300 ease-soft hover:-translate-y-0.5 hover:bg-raised hover:shadow-md hover:ring-1 hover:ring-line`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`),children:[(0,Q.jsxs)(`span`,{className:`flex items-start justify-between gap-3`,children:[i&&(0,Q.jsx)(`span`,{className:`grid size-9 shrink-0 place-items-center rounded-control bg-raised text-fg shadow-sm ring-1 ring-line transition-colors group-hover:bg-fg group-hover:text-bg [&_svg]:size-[18px]`,children:i}),r&&(0,Q.jsx)(`span`,{className:X(`ml-auto rounded-full px-2 py-0.5 text-[11px] font-semibold`,jm[r.tone]),children:r.label})]}),(0,Q.jsxs)(`span`,{className:`flex flex-col gap-1`,children:[(0,Q.jsx)(`span`,{className:`text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:e}),t&&(0,Q.jsx)(`span`,{className:`font-mono text-[11px] text-fg-subtle`,children:t})]}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:n}),(0,Q.jsxs)(`span`,{className:`mt-auto inline-flex items-center gap-1 pt-1 text-[13px] font-medium text-highlight`,children:[o,(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`transition-transform duration-300 ease-soft group-hover:translate-x-0.5`,children:`→`})]})]})}var Nm=X(`ui-v2 inline-flex size-[var(--ocx-control-h-sm)] shrink-0 cursor-pointer items-center justify-center rounded-[8px] text-fg-subtle`,`transition-colors duration-150 hover:bg-surface-2 hover:text-fg`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-35 [&_svg]:size-4`),Pm=`flex min-w-0 flex-col overflow-hidden rounded-[12px] bg-raised ring-1 ring-inset ring-line`,Fm=`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`;async function Im(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Lm({apiBase:e,navigate:t}){let n=b(),r=bn(`home-config:${e}`,[e],t=>Im(`${e}/api/config`,t)),i=bn(`setup-usage:${e}`,[e],t=>Im(`${e}/api/usage?range=all`,t)),a=Qp(e),o={label:n(`shellV2.badgeOptional`),tone:`optional`},s=r.data?Object.keys(r.data.providers??{}).length>0:void 0,c=i.data?(i.data.summary?.requests??0)>0:void 0,l=jf(a.data),u=[{key:`provider`,title:n(`shellV2.stepProvider`),hint:n(`shellV2.stepProviderHint`),done:s,open:()=>t(`providers`)},{key:`apps`,title:n(`shellV2.setupApps`),hint:n(`shellV2.setupAppsHint`),done:c,open:()=>t(`integrations`)},{key:`request`,title:n(`shellV2.stepFirstRequest`),hint:n(`shellV2.stepFirstRequestHint`),done:c,open:()=>t(`providers`)},{key:`autostart`,title:n(l.titleKey),hint:n(l.hintKey),done:l.done,open:()=>l.subPath?t(`startup`,l.subPath):t(`startup`)}],d=u.filter(e=>e.done===!0).length,f=d===u.length,p=u.findIndex(e=>e.done===!1),m=n(`shellV2.stepOpen`);return(0,Q.jsxs)(`div`,{className:`ui-v2 flex flex-col gap-8 font-sans text-fg`,children:[(0,Q.jsxs)(`header`,{className:`flex max-w-[640px] flex-col gap-2`,children:[(0,Q.jsx)(`h1`,{className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:n(`shellV2.setupTitle`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[15px] text-fg-muted`,children:n(`shellV2.setupIntro`)})]}),(0,Q.jsxs)(`section`,{"aria-labelledby":`setup-essentials`,className:`flex max-w-[760px] flex-col gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,Q.jsx)(`h2`,{id:`setup-essentials`,className:Fm,children:n(`connectV2.setupEssentials`)}),(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:n(`shellV2.checklistProgress`,{done:String(d),total:String(u.length)})})]}),(0,Q.jsx)(`div`,{className:`h-1 overflow-hidden rounded-full bg-surface-2`,role:`progressbar`,"aria-labelledby":`setup-essentials`,"aria-valuemin":0,"aria-valuemax":u.length,"aria-valuenow":d,children:(0,Q.jsx)(`div`,{className:`h-full origin-left rounded-full bg-accent transition-transform duration-[600ms] ease-soft`,style:{transform:`scaleX(${d/u.length})`}})}),f&&(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:n(`shellV2.checklistAllDone`)}),(0,Q.jsx)(`ol`,{className:X(Pm,`m-0 mt-1 list-none divide-y divide-line p-0`),children:u.map((e,t)=>(0,Q.jsx)(Rm,{step:e,index:t,current:t===p,openLabel:m,doneLabel:n(`shellV2.badgeDone`),todoLabel:n(`shellV2.badgeTodo`)},e.key))})]}),(0,Q.jsxs)(`section`,{"aria-labelledby":`setup-optional`,className:`flex flex-col gap-3`,children:[(0,Q.jsx)(`h2`,{id:`setup-optional`,className:Fm,children:n(`connectV2.setupOptional`)}),(0,Q.jsxs)(`div`,{className:`grid max-w-[760px] gap-3 sm:grid-cols-2`,children:[(0,Q.jsx)(Mm,{icon:(0,Q.jsx)(fe,{}),title:n(`shellV2.setupApiKeys`),body:n(`shellV2.setupApiKeysHint`),badge:o,onOpen:()=>t(`integrations`,`keys`),openLabel:m}),(0,Q.jsx)(Mm,{icon:(0,Q.jsx)(Oe,{}),title:n(`shellV2.setupRemote`),body:n(`shellV2.setupRemoteHint`),badge:o,onOpen:()=>t(`remote`),openLabel:m})]})]})]})}function Rm({step:e,index:t,current:n,openLabel:r,doneLabel:i,todoLabel:a}){let o=e.done===!0;return(0,Q.jsxs)(`li`,{"data-step":e.key,className:X(`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3.5`,n&&`bg-surface`),children:[(0,Q.jsx)(`span`,{className:X(`grid size-7 shrink-0 place-items-center rounded-full text-[12px] font-semibold tabular-nums [&_svg]:size-3.5`,o?`bg-success-soft text-success`:n?`bg-accent text-on-accent`:`bg-surface-2 text-fg-muted`),"aria-hidden":!0,children:o?(0,Q.jsx)(st,{strokeWidth:2.5}):t+1}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 basis-[16rem] flex-col gap-0.5`,children:[(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:X(`text-[14px] leading-5 font-medium`,o&&`text-fg-muted`),children:e.title}),e.done!==void 0&&(0,Q.jsx)(`span`,{className:X(`rounded-full px-1.5 text-[11px] leading-[18px] font-medium`,o?`bg-success-soft text-success`:`bg-surface-2 text-fg-muted`),children:o?i:a})]}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:e.hint})]}),(0,Q.jsx)(Jp,{size:`sm`,variant:n?`primary`:`outline`,onClick:e.open,"aria-label":`${e.title} — ${r}`,className:`max-sm:ml-11`,children:r})]})}var zm=[{id:`subagents`,title:`shellV2.advSubagents`,when:`shellV2.advSubagentsWhen`,term:{name:`Subagents`},Icon:vt,page:`subagents`,finds:[`dash.injectionLabel`,`dash.multiAgent`],words:[`delegation`,`agents`]},{id:`advisor`,title:`shellV2.advAdvisor`,when:`shellV2.advAdvisorWhen`,term:{name:`Advisor`},Icon:Tt,page:`advisor`,finds:[`nav.advisor`,`advisor.policy`,`proxyV2.consentTitle`],words:[`consult`,`preflight`]},{id:`proxy`,title:`shellV2.advProxy`,when:`shellV2.advProxyWhen`,term:{key:`proxyV2.advTermProxy`},Icon:rt,page:`dashboard`,finds:[`dash.webSearchSidecar`,`dash.visionSidecar`,`dash.shadowCallIntercept`,`compactionRouting.title`,`memoryModels.title`,`fallback.title`,`dash.syncModels`,`dash.codexAutoStart`,`dash.codexDesktopAuthless`,`dash.effortCapLabel`,`nativeReasoningRetention.title`,`reasoningRetention.title`,`dash.checkUpdate`,`proxyV2.secTelemetry`,`proxyV2.telemetryToggleLabel`],words:[`web search`,`vision`,`shadow`,`fallback`,`reasoning`,`update`,`sync`,`telemetry`,`privacy`]},{id:`routing`,title:`shellV2.advRouting`,when:`shellV2.advRoutingWhen`,term:{key:`proxyV2.advTermRouting`},Icon:ge,page:`models`,subPath:`routing`},{id:`prompt`,title:`shellV2.advPrompt`,when:`shellV2.advPromptWhen`,term:{key:`proxyV2.advTermPrompt`},Icon:Qe,page:`codex-set`,subPath:`prompt`},{id:`claude`,title:`shellV2.advClaude`,when:`shellV2.advClaudeWhen`,term:{name:`Claude Code`},Icon:Ct,page:`claude`,subPath:`code`},{id:`providers`,title:`shellV2.advProviders`,when:`shellV2.advProvidersWhen`,term:{key:`proxyV2.advTermProviders`},Icon:Je,page:`providers`},{id:`storage`,title:`shellV2.advStorage`,when:`shellV2.advStorageWhen`,term:{key:`proxyV2.advTermStorage`},Icon:ce,page:`storage`},{id:`diagnostics`,title:`shellV2.advDiagnostics`,when:`shellV2.advDiagnosticsWhen`,term:{key:`logs.tabDebug`},Icon:Me,page:`logs`,subPath:`debug`},{id:`desktop`,title:`shellV2.advDesktopCompat`,when:`shellV2.advDesktopCompatWhen`,term:{key:`proxyV2.advTermDesktop`},Icon:yt,page:`codex-set`,subPath:`desktop`}];function Bm(e){return`name`in e.term?e.term.name:l[e.term.key]}function Vm({navigate:e}){let t=b(),[n,r]=(0,Z.useState)(``),i=e=>`name`in e.term?e.term.name:t(e.term.key),a=(0,Z.useDeferredValue)(n.trim().toLowerCase()),o=zm.filter(e=>!a||[t(e.title),t(e.when),i(e),Bm(e),...(e.finds??[]).map(e=>t(e)),...e.words??[]].some(e=>e.toLowerCase().includes(a)));return(0,Q.jsxs)(`div`,{className:`ui-v2 flex flex-col gap-6 font-sans text-fg`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-wrap items-end justify-between gap-4`,children:[(0,Q.jsxs)(`div`,{className:`flex max-w-[640px] flex-col gap-2`,children:[(0,Q.jsx)(`h1`,{className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:t(`shellV2.pageAllSettings`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[15px] text-fg-muted`,children:t(`shellV2.advancedIntro`)})]}),(0,Q.jsxs)(`label`,{className:`relative flex w-full items-center sm:w-72`,children:[(0,Q.jsx)(`span`,{className:`pointer-events-none absolute left-3 text-fg-subtle [&_svg]:size-4`,children:(0,Q.jsx)(We,{"aria-hidden":!0})}),(0,Q.jsx)(`input`,{type:`search`,value:n,onChange:e=>r(e.target.value),placeholder:t(`shellV2.advancedSearch`),"aria-label":t(`shellV2.advancedSearch`),className:`h-[var(--ocx-control-h)] w-full rounded-control bg-surface pr-3 pl-9 text-sm text-fg ring-1 ring-line outline-none ring-inset placeholder:text-fg-subtle focus:ring-2 focus:ring-highlight`})]})]}),a&&(0,Q.jsx)(`p`,{className:`m-0 -mt-3 text-[13px] text-fg-muted`,role:`status`,children:t(`proxyV2.hubCount`,{count:o.length})}),o.length===0?(0,Q.jsx)(`p`,{className:`m-0 rounded-card bg-surface p-6 text-center text-[14px] text-fg-muted`,children:t(`shellV2.advancedEmpty`)}):(0,Q.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 xl:grid-cols-3`,children:o.map(n=>(0,Q.jsx)(Mm,{icon:(0,Q.jsx)(n.Icon,{"aria-hidden":!0}),title:t(n.title),term:i(n),body:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`b`,{className:`font-medium text-fg`,children:t(`shellV2.advancedWhen`)}),` · `,t(n.when)]}),onOpen:()=>e(n.page,n.subPath),openLabel:t(`shellV2.stepOpen`)},n.id))})]})}function Hm(e,t=e){let n=(0,Z.useMemo)(()=>({apiBase:e,targetKey:t}),[e,t]),[r,i]=(0,Z.useState)(()=>({target:n,providers:[],status:{}})),a=r.target===n?r:{target:n,providers:[],status:{}};r!==a&&i(a);let o=(0,Z.useCallback)(e=>{i(t=>t.target===n?{...t,providers:typeof e==`function`?e(t.providers):e}:t)},[n]),s=(0,Z.useCallback)(e=>{i(t=>t.target===n?{...t,status:typeof e==`function`?e(t.status):e}:t)},[n]);return{oauthProviders:a.providers,oauthStatus:a.status,setOauthProviders:o,setOauthStatus:s}}function Um(e){let t=Object.create(null);for(let n of e)t[n.provider]={requests:n.requests,totalTokens:n.totalTokens};return t}function Wm(e,t){let n=Object.create(null);for(let r of e){let e=t[r.provider]?.totalTokens??0,{provider:i,...a}=r;(n[i]??=[]).push({...a,shareRatio:e>0?Math.min(1,Math.max(0,r.totalTokens/e)):0})}return n}function Gm(e){return Object.entries(e).filter(e=>typeof e[1].requests==`number`&&e[1].requests>0).map(([e,t])=>({name:e,...t,requests:t.requests})).sort((e,t)=>t.requests-e.requests||e.name.localeCompare(t.name))}var Km={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function qm(e,t,n){let r=typeof t==`object`&&t?t:Km,i=typeof t==`number`?t:n??Date.now();if(e===void 0||!Number.isFinite(e))return r.notChecked;let a=Math.max(0,i-e),o=Math.floor(a/6e4);if(o<1)return r.justNow;if(o<60)return r.minutesAgo(o);let s=Math.floor(o/60);return s<24?r.hoursAgo(s):r.daysAgo(Math.floor(s/24))}function Jm(e){return{justNow:e(`time.justNow`),notChecked:e(`time.notChecked`),minutesAgo:t=>e(`time.minutesAgo`,{n:t}),hoursAgo:t=>e(`time.hoursAgo`,{n:t}),daysAgo:t=>e(`time.daysAgo`,{n:t})}}function Ym(e,t){let n=[];for(let r of e.ready)r.activeNeedsReauth&&n.push({name:r.name,reason:t[r.name]??`Active account needs re-authentication`});for(let r of e.needsSetup){let e=r.activeNeedsReauth?t[r.name]??`Active account needs re-authentication`:t[r.name]??`Missing credentials`;n.push({name:r.name,reason:e})}for(let r of e.disabled){let e=t[r.name];e&&n.push({name:r.name,reason:e})}return n}function Xm(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function Zm(e,t=`en`){if(e===void 0)return`—`;if(t.toLowerCase().slice(0,2)===`de`){let t=e=>e.replace(/\.0+$/,``).replace(`.`,`,`);return e>=1e9?`${t((e/1e9).toFixed(2))} Mrd.`:e>=1e6?`${t((e/1e6).toFixed(1))} Mio.`:e>=1e3?`${t((e/1e3).toFixed(1))} Tsd.`:String(e)}return e>=1e9?`${(e/1e9).toFixed(2).replace(/\.?0+$/,``)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Qm(e,t=`en`){return Zm(e,t)}function $m(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function eh(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:e===`Total subscription credits`?4.5:5}var th=`Total subscription credits`;function nh(e){return e.trim().toLowerCase()===th.toLowerCase()?th:e}function rh(e,t){if(e===void 0||!t)return!1;let n=nh(e);for(let e of t)if(nh(e)===n)return!0;return!1}function ih(e,t){switch(e){case`First-party models`:return t(`quota.cursorFirstParty`);case`API usage`:return t(`quota.cursorApiUsage`);case`Total subscription credits`:return t(`quota.totalSubscriptionCredits`);default:return e}}function ah(e,t,n){let r=Pt(e,t);if(!r)return[];let i=[];typeof r.fiveHourPercent==`number`&&i.push({rank:0,row:{windowKey:`fiveHour`,label:n(`codexAuth.fiveHour`),limitLabel:n(`quota.fiveHourLimit`),percent:r.fiveHourPercent,resetAt:r.fiveHourResetAt}}),typeof r.weeklyPercent==`number`&&i.push({rank:1,row:{windowKey:`weekly`,label:n(`codexAuth.weekly`),limitLabel:n(`quota.weeklyLimit`),percent:r.weeklyPercent,resetAt:r.weeklyResetAt}}),typeof r.monthlyPercent==`number`&&i.push({rank:4,row:{windowKey:`monthly`,label:n(`codexAuth.monthly`),limitLabel:n(`quota.monthlyLimit`),percent:r.monthlyPercent,resetAt:r.monthlyResetAt}});for(let e of r.customWindows??[]){let t=nh(e.label),r=ih(t,n);i.push({rank:eh(t),row:{id:JSON.stringify([e.modelId??null,e.label,e.resetAt??null]),customLabel:t,label:r,...typeof e.displayLabel==`string`&&e.displayLabel.trim()?{displayLabel:e.displayLabel}:{},limitLabel:r,percent:e.percent,resetAt:e.resetAt,...e.weeklyAllowancePercent===void 0?{}:{weeklyAllowancePercent:e.weeklyAllowancePercent}}})}for(let e of r.displayWindows??[])i.push({rank:eh(e.label),row:{id:JSON.stringify([`display`,e.label,e.resetAt??null]),customLabel:e.label,label:e.label,limitLabel:e.label,percent:e.percent,resetAt:e.resetAt,...e.weeklyAllowancePercent===void 0?{}:{weeklyAllowancePercent:e.weeklyAllowancePercent},notInEffect:!0}});if(r.creditsUsd&&typeof r.creditsUsd.percent==`number`&&!r.customWindows?.some(e=>e.modelId===void 0&&nh(e.label)===th)){let e=ih(th,n);i.push({rank:eh(th),row:{customLabel:th,label:e,limitLabel:e,percent:r.creditsUsd.percent,resetAt:r.creditsUsd.expiresAt}})}let a=new Map;return i.sort((e,t)=>e.rank-t.rank).map(({row:e})=>{let t=e.id??e.windowKey??e.customLabel,n=a.get(t)??0;return a.set(t,n+1),{...e,id:JSON.stringify([t,n])}})}function oh(e){if(!e)return-1;let t=[e.fiveHourPercent,e.weeklyPercent,e.monthlyPercent].filter(e=>typeof e==`number`);for(let n of e.customWindows??[])n.modelId===void 0&&typeof n.percent==`number`&&t.push(n.percent);return!e.customWindows?.some(e=>e.modelId===void 0&&nh(e.label)===th)&&typeof e.creditsUsd?.percent==`number`&&t.push(e.creditsUsd.percent),t.length?Math.max(...t):-1}function sh(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;case`vi`:return`vi-VN`;case`pt`:return`pt-BR`;default:return e}}function ch(e){return e>=99.5}function lh(e,t){return t>0&&e>=t}function uh(e,t){return lh(e,t)||ch(e)?`bar-warn`:`bar-green`}function dh(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function fh(e){return{"--bar-scale":String(dh(e)/100)}}function ph(e,t,n=Date.now()){let r=n-e;return!Number.isFinite(r)||r<6e4?null:r<36e5?t(`quota.ageMinutes`).replace(`{n}`,String(Math.floor(r/6e4))):r<864e5?t(`quota.ageHours`).replace(`{n}`,String(Math.floor(r/36e5))):t(`quota.ageDays`).replace(`{n}`,String(Math.floor(r/864e5)))}function mh({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1,incompleteWindowKeys:c,incompleteCustomWindowLabels:l,observedAt:u,afterWeekly:d}){let{locale:f}=s(),p=ah(e,t,r),m=e?.unknownBudgetWindows??[],h=m.map((e,t)=>(0,Q.jsxs)(`div`,{className:`quota-stacked-row`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsx)(`span`,{className:`quota-stacked-limit`,children:e.label}),(0,Q.jsx)(`span`,{className:`quota-stacked-reset muted`,children:xh(e.resetAt,r,f)})]}),(0,Q.jsx)(`span`,{className:`muted`,children:r(`cws.quota.unknown`)})]},`unknown-${e.label}-${t}`)),g=u===void 0?null:ph(u,r),_=g===null?null:(0,Q.jsx)(`p`,{className:`quota-observed muted`,title:r(`quota.observedHint`),children:r(`quota.observedAgo`).replace(`{age}`,g)});return p.length===0&&m.length===0?o?a===`stacked`?(0,Q.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,Q.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,Q.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,Q.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,Q.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,Q.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):a===`compact`&&d?(0,Q.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:d}):null:a===`stacked`?(0,Q.jsxs)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:[_,p.map(e=>(0,Q.jsx)(vh,{row:e,threshold:n,t:r,locale:f,incomplete:e.windowKey?c?.has(e.windowKey)===!0:rh(e.customLabel,l)},e.id)),h]}):(0,Q.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:[_,p.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsx)(_h,{credits:e.customLabel===th,hint:hh(e,r).join(` · `),label:e.displayLabel??e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:f}),e.windowKey===`weekly`&&d]},e.id)),h,!p.some(e=>e.windowKey===`weekly`)&&d]})}function hh(e,t){return[...e.weeklyAllowancePercent===void 0?[]:[gh(e.weeklyAllowancePercent,t)],...e.notInEffect?[t(`quota.notInEffect`)]:[]]}function gh(e,t){return t(`quota.weeklyShare`,{pct:Math.round(e)})}function _h({credits:e,hint:t,label:n,percent:r,resetAt:i,threshold:a,t:o,locale:s}){let c=ch(r),l=lh(r,a),u=uh(r,a),d=bh(i,o,s),f=d.day||d.time?`${o(`codexAuth.resets`)} ${d.day} ${d.time}`.replace(/\s+/g,` `).trim():void 0,p=d.day!==``||d.time!==``;return(0,Q.jsxs)(`div`,{className:`quota-row${e?` quota-row--credits`:``}${l?` quota-row--warn`:``}${c?` quota-row--exhausted`:``}`,children:[(0,Q.jsx)(`span`,{className:`quota-label`,title:[t,f].filter(Boolean).join(` · `)||void 0,children:n}),(0,Q.jsx)(`span`,{className:`quota-reset-label`,children:p?o(`codexAuth.resets`):``}),(0,Q.jsx)(`span`,{className:`quota-reset-day`,children:d.day}),(0,Q.jsx)(`span`,{className:`quota-reset-time`,children:d.time}),(0,Q.jsx)(`div`,{className:`bar`,title:f,children:(0,Q.jsx)(`div`,{className:`bar-fill ${u}`,style:fh(r)})}),(0,Q.jsxs)(`span`,{className:`quota-val${l?` quota-val--warn`:``}`,title:c?o(`quota.limitReached`):f,"aria-label":f,children:[l&&(0,Q.jsx)(St,{width:12,height:12,"aria-hidden":`true`}),Math.round(r),`%`,c?` · ${o(`quota.limitReached`)}`:``]})]})}function vh({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=ch(e.percent),o=lh(e.percent,t),s=uh(e.percent,t),c=xh(e.resetAt,n,r);return(0,Q.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,Q.jsx)(`span`,{className:`quota-stacked-limit`,children:e.displayLabel??e.limitLabel}),i&&(0,Q.jsx)(`span`,{className:`quota-window-partial`,role:`note`,"aria-label":n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),title:n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),children:n(`pws.capacity.windowPartial`)}),e.notInEffect&&(0,Q.jsx)(`span`,{className:`quota-window-inactive muted`,role:`note`,title:n(`quota.notInEffectHint`),children:n(`quota.notInEffect`)})]}),(0,Q.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),e.weeklyAllowancePercent!==void 0&&(0,Q.jsx)(`span`,{className:`quota-window-share muted`,children:gh(e.weeklyAllowancePercent,n)}),(0,Q.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Q.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,Q.jsx)(`div`,{className:`bar-fill ${s}`,style:fh(e.percent)})}),(0,Q.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,Q.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,Q.jsx)(St,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function yh(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=e<1e10?e*1e3:e,n=new Date(t);return Number.isFinite(n.getTime())?{date:n,ms:t}:null}function bh(e,t,n){let r=yh(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=sh(n),s=new Intl.DateTimeFormat(o,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(i);return i.getFullYear()===a.getFullYear()&&i.getMonth()===a.getMonth()&&i.getDate()===a.getDate()?{day:t(`codexAuth.today`),time:s}:{day:new Intl.DateTimeFormat(o,{day:`numeric`,month:`short`}).format(i),time:s}}function xh(e,t,n=`en`,r=Date.now()){let i=yh(e);if(!i)return``;let{date:a,ms:o}=i,s=sh(n),c=new Intl.DateTimeFormat(s,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(a),l=new Date(r),u=new Date(l.getFullYear(),l.getMonth(),l.getDate()).getTime(),d=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),f=Math.round((d-u)/864e5);if(f===1)return t(`quota.resetsTomorrow`,{time:c});let p=a.getFullYear()!==l.getFullYear(),m=new Intl.DateTimeFormat(s,{day:`numeric`,month:`short`,...p?{year:`numeric`}:{}}).format(a);if(o<=r)return t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`});let h=Math.round((o-r)/6e4);if(h<60)return t(`quota.resetsRelativeMinutes`,{n:Math.max(1,h)});let g=Math.round(h/60);return g<12&&f===0?t(`quota.resetsRelativeHours`,{n:Math.max(1,g)}):f===0?t(`quota.resetsToday`,{time:c}):t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`})}function Sh({credits:e,updatedAt:t}){let{t:n,locale:r}=s(),i=e=>new Intl.NumberFormat(r,{maximumFractionDigits:2}).format(e),a=e=>n(`quota.workbuddy.amount`,{amount:i(e)}),o=e.total>0?Math.min(100,e.used/e.total*100):0;return(0,Q.jsxs)(`div`,{"data-workbuddy-credits":!0,children:[(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,Q.jsx)(`strong`,{children:a(e.remaining)})]}),(0,Q.jsx)(mh,{quota:{updatedAt:t,customWindows:[{label:n(`quota.totalSubscriptionCredits`),percent:o}]},threshold:80,t:n,layout:`stacked`}),(0,Q.jsxs)(`div`,{className:`pws-capacity-details`,children:[(0,Q.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Q.jsx)(`span`,{children:n(`quota.workbuddy.usage`,{used:i(e.used),total:i(e.total)})})}),e.groups.filter(e=>e.total>0||e.remaining>0).map(e=>(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.workbuddy.${e.kind}`)}),(0,Q.jsxs)(`strong`,{children:[a(e.remaining),` / `,i(e.total)]})]},e.kind)),e.frozen>0&&(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.workbuddy.frozen`)}),(0,Q.jsx)(`strong`,{children:a(e.frozen)})]}),e.expiring&&(0,Q.jsx)(`p`,{className:`muted`,children:n(`quota.workbuddy.expiring`,{amount:i(e.expiring.amount),date:new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(e.expiring.at)})})]})]})}function Ch(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;case`vi`:return`vi-VN`;case`pt`:return`pt-BR`;default:return e}}function wh(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function Th({report:e,pending:t}){let n=b(),{locale:r}=s(),i=Y(e),a=gt(e),o=pe(e),c=a?.creditsUsd,l=i?.presentation===`aggregate`,u=new Set,d=new Set;if(l&&i){i.fiveHour?.incomplete&&u.add(`fiveHour`),i.weekly?.incomplete&&u.add(`weekly`),i.monthly?.incomplete&&u.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&d.add(e.label)}let f=l&&i?[...i.fiveHour?[{key:0,label:n(`codexAuth.fiveHour`),window:i.fiveHour}]:[],...i.weekly?[{key:1,label:n(`codexAuth.weekly`),window:i.weekly}]:[],...i.monthly?[{key:2,label:n(`codexAuth.monthly`),window:i.monthly}]:[],...(i.customWindows??[]).map((e,t)=>({key:t+3,label:e.label,window:e}))]:[],p=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),m=e=>{let t=wh(e);return t===null?null:new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(t)},h=Ch(r),g=e=>new Intl.NumberFormat(h,{style:`currency`,currency:`USD`}).format(e),_=c?.expiresAt===void 0?null:(e=>{let t=wh(e);return t===null?null:new Intl.DateTimeFormat(h,{dateStyle:`medium`}).format(t)})(c.expiresAt);return(0,Q.jsxs)(Q.Fragment,{children:[a?.workbuddyCredits&&(0,Q.jsx)(Sh,{credits:a.workbuddyCredits,updatedAt:a.updatedAt}),l&&(0,Q.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(a||t)&&(0,Q.jsx)(mh,{quota:a,threshold:80,t:n,layout:`stacked`,pending:t,...o===void 0?{}:{observedAt:o},incompleteWindowKeys:l?u:void 0,incompleteCustomWindowLabels:l?d:void 0}),(c||i)&&(0,Q.jsxs)(`div`,{className:`pws-capacity-details`,children:[c&&(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,Q.jsx)(`strong`,{children:g(c.remaining)})]}),_!==null&&(0,Q.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Q.jsx)(`span`,{children:n(`quota.creditsPeriodEnds`,{date:_})})}),f.flatMap(({key:e,label:t,window:r})=>{let i=r.nextRecoveryAt===void 0?null:m(r.nextRecoveryAt);return i!==null&&r.nextRecoveryPercent!==void 0?[(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,i]}),(0,Q.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:p(r.nextRecoveryPercent)})})]},e)]:[]}),l&&i&&i.currentAccount?.quota&&(0,Q.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,Q.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,Q.jsx)(mh,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i&&i.incomplete&&i.excludedAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts})}),i&&i.unknownPlanAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.uncalibratedPlan`,{count:i.unknownPlanAccounts})}),i&&i.partialWindowAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function Eh({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o,onRefreshAllQuotas:c}){let l=b(),{locale:u}=s(),d=Jm(l),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),g=async()=>{if(c&&!f){p(!0),h(null);try{let e=await c();h({ok:e,text:l(e?`pws.quotaRefreshDone`:`codexAuth.quotaRefreshFailed`)})}catch{h({ok:!1,text:l(`codexAuth.quotaRefreshFailed`)})}finally{p(!1)}}},_=(0,Z.useMemo)(()=>[...e.ready,...e.needsSetup,...e.unverified,...e.disabled],[e]),v=(0,Z.useMemo)(()=>new Set(_.map(e=>e.name)),[_]),y=(0,Z.useMemo)(()=>Ym(e,{}),[e]),x=y.length,S=(0,Z.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),C=e.ready.length-S,w=e.needsSetup.length+S,T=(0,Z.useMemo)(()=>{let e=[];for(let n of _){let r=t[n.name],i=r?gt(r):null,a=r?Y(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?oh(i):-1})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[_,t]),E=(0,Z.useMemo)(()=>{let e={};for(let[t,r]of Object.entries(n))v.has(t)&&(e[t]=r);return Gm(e).slice(0,4)},[n,v]),D=e=>{let t=Xm(e);return t===`reauth`?l(`pws.attention.reauth`):t===`missing`?l(`pws.attention.missingCredentials`):e};return(0,Q.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,Q.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,Q.jsx)(`div`,{className:`pws-dashboard-header-text`,children:(0,Q.jsx)(`h2`,{className:`pws-dashboard-title`,children:l(`pws.dashboard.title`)})}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-header-actions`,children:[m&&(0,Q.jsx)(`span`,{role:`status`,className:m.ok?`pws-status-ok`:`pws-status-warn`,children:m.text}),c&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:f,onClick:()=>{g()},children:[(0,Q.jsx)(Ke,{width:14,height:14,"aria-hidden":`true`}),` `,l(f?`codexAuth.refreshingQuota`:`pws.refreshAllQuotas`)]}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:l(`prov.editJson`)})]})]}),(0,Q.jsxs)(`dl`,{className:`pws-dashboard-summary${e.unverified.length?` pws-dashboard-summary--unverified`:``}`,children:[(0,Q.jsx)(Dh,{count:C,label:l(`pws.status.ready`),tone:`ok`}),(0,Q.jsx)(Dh,{count:w,label:l(S>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),e.unverified.length>0&&(0,Q.jsx)(Dh,{count:e.unverified.length,label:l(`pws.vertexUnverified`),tone:`warn`}),(0,Q.jsx)(Dh,{count:e.disabled.length,label:l(`prov.disabledBadge`),tone:`muted`})]}),x>0&&(0,Q.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":l(`pws.attentionTitle`),children:[(0,Q.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:l(`pws.attentionTitle`)}),(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-banners`,children:y.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-banner-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(St,{width:16,height:16})}),(0,Q.jsx)(de,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:re(e.name,l)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:D(e.reason)})]}),(0,Q.jsx)(lt,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,Q.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":l(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,Q.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:l(`pws.dashboard.rateLimits`)}),T.length>0?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:T.map(({item:e,report:t})=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,Q.jsx)(de,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:re(e.name,l)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:l(`pws.dashboard.checkedAgo`,{time:qm(t.updatedAt,d)})})]}),(0,Q.jsx)(lt,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Q.jsx)(Th,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Q.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,Q.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Q.jsx)(mh,{quota:null,threshold:80,t:l,layout:`stacked`,pending:!0})})]},t))}):(0,Q.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:l(`pws.dashboard.noRateLimits`)})]}),(0,Q.jsx)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":l(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:(0,Q.jsxs)(`details`,{className:`pws-dashboard-recent-details`,children:[(0,Q.jsx)(`summary`,{className:`pws-dashboard-section-title`,children:l(`pws.dashboard.recentlyUsed`)}),E.length>0?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:E.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,Q.jsx)(de,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:re(e.name,l)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:l(`pws.dashboard.requests`,{count:Zm(e.requests,u)})}),(0,Q.jsx)(lt,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Q.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,Q.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:l(`pws.dashboard.noUsage`)})]})})]})]})}function Dh({count:e,label:t,tone:n}){return(0,Q.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}${e>0?` has-count`:``}`,children:[(0,Q.jsxs)(`dt`,{className:`pws-dashboard-card-label`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-card-dot`,"aria-hidden":`true`}),t]}),(0,Q.jsx)(`dd`,{className:`pws-dashboard-card-count`,children:e})]})}function Oh({editor:e,providerName:t,saving:n,onSave:r,message:i,targetLabel:a}){let o=b(),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{e.open&&s.current?.focus()},[e.open]),e.open?(0,Q.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,Q.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,Q.jsx)(`span`,{className:`pwi-json-panel-title`,children:o(`pws.jsonEditorTitle`,{name:t})}),(0,Q.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:o(`pws.jsonRestore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:o(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty||e.conflict===!0,children:o(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,Q.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:o(`pws.jsonEditorDesc`)}),a&&(0,Q.jsx)(`p`,{className:`pwi-json-panel-target muted`,children:o(`pws.draftTarget`,{target:a})}),e.conflict&&(0,Q.jsxs)(`div`,{className:`pwi-settings-conflict`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:o(`pws.draftConflict`)}),e.conflicts&&e.conflicts.length>0&&(0,Q.jsxs)(`div`,{className:`pwi-settings-conflict-fields`,children:[(0,Q.jsx)(`p`,{children:o(`pws.draftConflictFields`)}),(0,Q.jsx)(`ul`,{children:e.conflicts.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsx)(`code`,{children:e})},e))})]}),(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onUseSaved,disabled:n,children:o(`pws.draftConflictUseSaved`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e.onKeepDraft,disabled:n,children:o(`pws.draftConflictKeepDraft`)})]})]}),(0,Q.jsx)(`textarea`,{ref:s,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":o(`pws.jsonEditorDesc`)}),i&&(0,Q.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}function kh(e){if(e.adapter.trim()!==`openai-responses`||e.authMode&&e.authMode!==`key`&&e.authMode!==`local`)return!1;try{let t=new URL(e.baseUrl.trim());if(![`https:`,`http:`].includes(t.protocol)||t.username||t.password)return!1;let n=t.hostname.toLowerCase().replace(/\.$/,``);return n!==`api.openai.com`&&n!==`chatgpt.com`&&n!==`chat.openai.com`&&![`.openai.azure.com`,`.services.ai.azure.com`,`.cognitiveservices.azure.com`].some(e=>n.endsWith(e))}catch{return!1}}function Ah(){let e=new Map,t=(e,t)=>`${e}\u0000${t}`;return{read:(n,r)=>e.get(t(n,r)),write:(n,r,i)=>{e.set(t(n,r),i)},clear:(n,r)=>{e.delete(t(n,r))},claim:(n,r,i,a)=>{let o=e.get(t(n,r)),s=o?{...o,owner:i}:{...a,owner:i};return e.set(t(n,r),s),s},writeOwned:(n,r,i,a)=>{let o=e.get(t(n,r));return!o||o.owner!==i?!1:(e.set(t(n,r),{...a,owner:i}),!0)},clearOwned:(n,r,i)=>{let a=e.get(t(n,r));return!a||a.owner!==i?!1:(e.delete(t(n,r)),!0)}}}function jh(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function Mh(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function Nh(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function Ph(e){return e===void 0?``:String(e)}function Fh(e){let t=Mh(e.pacingRpm),n=Nh(e.pacingDelay),r=Nh(e.pacingConcurrency);return{enabled:e.pacingEnabled,...e.keyPacing,...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n},...r===void 0?{}:{maxConcurrentRequests:r},...Object.keys(e.pacingModels).length>0?{models:e.pacingModels}:{}}}function Ih(e){let t=Object.entries(e?.models??{}).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.requestsPerMinute??null,t.minIntervalMs??null,t.maxConcurrentRequests??null]);return JSON.stringify([e?.enabled===!0,e?.requestsPerMinute??null,e?.minIntervalMs??null,e?.maxConcurrentRequests??null,e?.keySelection??`active`,[e?.keys?.requestsPerMinute??null,e?.keys?.minIntervalMs??null,e?.keys?.maxConcurrentRequests??null],t])}function Lh(e){let t=he(e.name,e);return{adapter:e.adapter,baseUrl:e.baseUrl,project:e.project??``,location:e.location??``,defaultModel:e.defaultModel??``,authMode:String(e.authMode??(e.keyOptional?`local`:`key`)),apiKeyTransport:e.apiKeyTransport??`x-api-key`,note:e.note??``,allowPrivateNetwork:e.allowPrivateNetwork??!1,preserveReasoningReplay:e.preserveResponsesReasoningContent===!0,liveModels:t?e.liveModels!==!1:!1,cursorHttpVersion:jh(e.upstreamHttpVersion),pacingEnabled:e.requestPacing?.enabled===!0,keyPacing:{...e.requestPacing?.keySelection===void 0?{}:{keySelection:e.requestPacing.keySelection},...e.requestPacing?.keys===void 0?{}:{keys:{...e.requestPacing.keys}}},pacingRpm:Ph(e.requestPacing?.requestsPerMinute),pacingDelay:Ph(e.requestPacing?.minIntervalMs),pacingConcurrency:Ph(e.requestPacing?.maxConcurrentRequests),pacingModels:Object.fromEntries(Object.entries(e.requestPacing?.models??{}).map(([e,t])=>[e,{...t}]))}}function Rh(e){return Array.isArray(e)?e.map(Rh):e&&typeof e==`object`?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Rh(e[t])])):e}function zh(e){return JSON.stringify(Rh(e))}function Bh(e){return JSON.stringify(Rh(e))}function Vh(e,t,n){let r=Fh(e),i=Fh(t),a=structuredClone(n??{enabled:!1}),o=e=>{Bh(i[e])!==Bh(r[e])&&(i[e]===void 0?delete a[e]:a[e]=i[e])};for(let e of[`enabled`,`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`,`keySelection`])o(e);let s=(e,t,n)=>{if(!t&&!e)return n;if(!t)return;let r={...n??{}};for(let n of[`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`])t[n]!==e?.[n]&&(t[n]===void 0?delete r[n]:r[n]=t[n]);return Object.keys(r).length>0?r:void 0},c=s(r.keys,i.keys,a.keys);c?a.keys=c:delete a.keys;let l=new Set([...Object.keys(r.models??{}),...Object.keys(i.models??{}),...Object.keys(a.models??{})]),u=Object.create(null);for(let e of l){let t=r.models?.[e],n=i.models?.[e],o=a.models?.[e];if(!n&&!t){o&&(u[e]=o);continue}if(!n)continue;if(!t){u[e]=n;continue}let c=s(t,n,o);c&&(u[e]=c)}return Object.keys(u).length>0?a.models=u:delete a.models,a}function Hh(e,t,n){let r=Fh(e),i=Fh(t),a=n??{enabled:!1},o=[],s=(e,t)=>Bh(e)!==Bh(t);for(let e of[`enabled`,`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`,`keySelection`])s(i[e],r[e])&&s(a[e],r[e])&&s(i[e],a[e])&&o.push(`pacing.${e}`);for(let e of[`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`])s(i.keys?.[e],r.keys?.[e])&&s(a.keys?.[e],r.keys?.[e])&&s(i.keys?.[e],a.keys?.[e])&&o.push(`pacing.keys.${e}`);let c=new Set([...Object.keys(r.models??{}),...Object.keys(i.models??{}),...Object.keys(a.models??{})]);for(let e of c)for(let t of[`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`])s(i.models?.[e]?.[t],r.models?.[e]?.[t])&&s(a.models?.[e]?.[t],r.models?.[e]?.[t])&&s(i.models?.[e]?.[t],a.models?.[e]?.[t])&&o.push(`pacing.models.${e}.${t}`);return o}function Uh(e,t){let n=e.adapter.trim(),r=qe(t)&&(t.name===`google-vertex`||n===`google`),i=he(t.name,t)?t.liveModels!==!1:!1,a=jh(t.upstreamHttpVersion);return!ct(t.name)&&kh({adapter:n,baseUrl:e.baseUrl,authMode:e.authMode})&&e.preserveReasoningReplay!==(t.preserveResponsesReasoningContent===!0)||n!==t.adapter||e.baseUrl.trim()!==t.baseUrl||r&&(e.project.trim()!==(t.project??``)||e.location.trim()!==(t.location??``))||e.defaultModel.trim()!==(t.defaultModel??``)||e.authMode!==String(t.authMode??(t.keyOptional?`local`:`key`))||n===`anthropic`&&e.authMode===`key`&&e.apiKeyTransport!==(t.apiKeyTransport??`x-api-key`)||e.note.trim()!==(t.note??``)||e.allowPrivateNetwork!==(t.allowPrivateNetwork??!1)||e.liveModels!==i||n===`cursor`&&e.cursorHttpVersion!==a}function Wh(e,t){return Ih(Fh(e))!==Ih(t.requestPacing)}function Gh(e,t){return Uh(e,t)||Wh(e,t)}function Kh(e,t,n,r){let i={},a=e.adapter.trim(),o=t.adapter.trim(),s=qe(n)&&(n.name===`google-vertex`||a===`google`),c=he(n.name,n),l=!ct(n.name)&&kh({adapter:a,baseUrl:e.baseUrl,authMode:e.authMode});a!==o&&(i.adapter=a),r!==t.baseUrl.trim()&&(i.baseUrl=r),e.defaultModel.trim()!==t.defaultModel.trim()&&(i.defaultModel=e.defaultModel.trim()),e.authMode!==t.authMode&&(i.authMode=e.authMode),e.note.trim()!==t.note.trim()&&(i.note=e.note.trim()),e.allowPrivateNetwork!==t.allowPrivateNetwork&&(i.allowPrivateNetwork=e.allowPrivateNetwork),s&&(e.project.trim()!==t.project.trim()&&(i.project=e.project.trim()),e.location.trim()!==t.location.trim()&&(i.location=e.location.trim())),c&&e.liveModels!==t.liveModels&&(i.liveModels=e.liveModels),l&&e.preserveReasoningReplay!==t.preserveReasoningReplay&&(i.preserveResponsesReasoningContent=e.preserveReasoningReplay),a===`cursor`&&e.cursorHttpVersion!==t.cursorHttpVersion&&(i.upstreamHttpVersion=e.cursorHttpVersion===`http1.1`?`http1.1`:null);let u=o===`anthropic`&&t.authMode===`key`;a===`anthropic`&&e.authMode===`key`?e.apiKeyTransport!==t.apiKeyTransport&&(i.apiKeyTransport=e.apiKeyTransport):u&&n.apiKeyTransport!==void 0&&(i.apiKeyTransport=``);let d=Ih(Fh(e))!==Ih(Fh(t));return d&&(i.requestPacing=Fh(e)),{patch:i,fieldsDirty:Object.keys(i).some(e=>e!==`requestPacing`),pacingDirty:d}}function qh(e,t,n){let r=r=>Bh(t[r])===Bh(e[r])?n[r]:t[r],i={adapter:r(`adapter`),baseUrl:r(`baseUrl`),project:r(`project`),location:r(`location`),defaultModel:r(`defaultModel`),authMode:r(`authMode`),apiKeyTransport:r(`apiKeyTransport`),note:r(`note`),allowPrivateNetwork:r(`allowPrivateNetwork`),preserveReasoningReplay:r(`preserveReasoningReplay`),liveModels:r(`liveModels`),cursorHttpVersion:r(`cursorHttpVersion`),pacingEnabled:r(`pacingEnabled`),keyPacing:r(`keyPacing`),pacingRpm:r(`pacingRpm`),pacingDelay:r(`pacingDelay`),pacingConcurrency:r(`pacingConcurrency`),pacingModels:r(`pacingModels`)},a=Vh(e,t,Fh(n));return{...i,pacingEnabled:a.enabled===!0,keyPacing:{...a.keySelection===void 0?{}:{keySelection:a.keySelection},...a.keys===void 0?{}:{keys:{...a.keys}}},pacingRpm:Ph(a.requestsPerMinute),pacingDelay:Ph(a.minIntervalMs),pacingConcurrency:Ph(a.maxConcurrentRequests),pacingModels:Object.fromEntries(Object.entries(a.models??{}).map(([e,t])=>[e,{...t}]))}}function Jh(e){return e.split(`\0`,1)[0]||(typeof window>`u`?`same-origin`:window.location.origin)}function Yh(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid model response`);return e}function Xh(e){if(typeof e!=`string`||!e.trim())throw Error(`Invalid model identity`);return e}function Zh(e){if(!Array.isArray(e))throw Error(`Invalid model inventory`);let t=new Map,n=[];for(let r of e){let e=Yh(r),i=Xh(e.provider),a=Xh(e.id),o=Xh(e.namespaced);if(typeof e.disabled!=`boolean`)throw Error(`Invalid model visibility`);for(let t of[`native`,`custom`,`initialSelectionPending`,`contextCapped`])if(e[t]!==void 0&&typeof e[t]!=`boolean`)throw Error(`Invalid model flag`);if(e.custom===!0&&Xh(e.customId),e.customId!==void 0&&(e.custom!==!0||typeof e.customId!=`string`))throw Error(`Invalid custom ownership`);if(e.custom===!0&&e.native===!0)throw Error(`Conflicting model ownership`);if(e.displayName!==void 0&&typeof e.displayName!=`string`)throw Error(`Invalid model label`);for(let t of[`inputModalities`,`reasoningEfforts`])if(e[t]!==void 0&&(!Array.isArray(e[t])||e[t].some(e=>typeof e!=`string`)))throw Error(`Invalid model metadata`);for(let t of[`contextWindow`,`contextCap`])if(e[t]!==void 0&&(typeof e[t]!=`number`||!Number.isFinite(e[t])))throw Error(`Invalid model context`);let s={...e,provider:i,id:a,namespaced:o,disabled:e.disabled},c=t.get(i)??new Map,l=c.get(o);if(l&&(l.id!==a||l.disabled!==s.disabled||!!l.native!=!!s.native||!!l.custom!=!!s.custom||l.customId!==s.customId||!!l.initialSelectionPending!=!!s.initialSelectionPending))throw Error(`Conflicting model selector`);l||(c.set(o,s),n.push(s)),t.set(i,c)}return n}function Qh(e){let t=new Map;for(let n of e){let e=t.get(n.provider)??new Set;n.disabled||e.add(n.namespaced),t.set(n.provider,e)}return Object.fromEntries([...t].map(([e,t])=>[e,t.size]))}function $h(e){let t=Yh(e),n=Object.assign(Object.create(null),rp(t));for(let[e,t]of Object.entries(n))Xh(e),t.forEach(Xh);let r=Object.fromEntries(Object.entries(Yh(t.available)).map(([e,t])=>{if(Xh(e),!Array.isArray(t))throw Error(`Invalid available models`);return[e,t.map(Xh)]})),i=Object.hasOwn(t,`liveModelCounts`)?Yh(t.liveModelCounts):{},a=Object.fromEntries(Object.entries(i).map(([e,t])=>{if(Xh(e),typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`Invalid discovery count`);return[e,t]}));return{available:Object.assign(Object.create(null),r),selected:n,liveModelCounts:Object.assign(Object.create(null),a)}}function eg(e){let t=Yh(e);return{id:Xh(t.id),provider:Xh(t.provider),modelId:Xh(t.modelId)}}function tg(e){if(!Array.isArray(e))throw Error(`Invalid custom model inventory`);let t=new Map,n=new Set;for(let r of e){let e=eg(r),i=JSON.stringify([e.provider,e.modelId]);if(t.has(e.id)||n.has(i))throw Error(`Duplicate custom ownership`);t.set(e.id,e),n.add(i)}return[...t.values()]}function ng(e,t,n){let r=eg(e);if(r.provider!==t||r.modelId!==n)throw Error(`Unexpected created model`);return r}function rg(e){if(!e||typeof e!=`object`||Array.isArray(e))return!0;let t=e.catalogRefresh;if(!t||typeof t!=`object`||Array.isArray(t))return!0;let n=t;return n.status!==`committed`||typeof n.changed!=`boolean`||typeof n.degraded!=`boolean`}function ig(e){if(e===void 0)return;let t=Yh(e);if(t.status===`ok`)return{status:`ok`};if(t.status!==`failed`)throw Error(`Invalid provider discovery status`);if(t.reason===`http`){if(typeof t.httpStatus!=`number`||!Number.isInteger(t.httpStatus))throw Error(`Invalid provider discovery HTTP status`);return{status:`failed`,reason:`http`,httpStatus:t.httpStatus}}if(t.reason===`blocked`||t.reason===`invalid_response`||t.reason===`network`||t.reason===`provider`)return{status:`failed`,reason:t.reason};throw Error(`Invalid provider discovery reason`)}function ag(e){if(!Array.isArray(e))throw Error(`Invalid providers discovery response`);let t=Object.create(null);for(let n of e){let e=Yh(n),r=Xh(e.name),i=ig(e.discovery);i&&(t[r]=i)}return t}var og=[{id:`az`,labelKey:`pws.sort.az`},{id:`za`,labelKey:`pws.sort.za`},{id:`free-paid`,labelKey:`pws.sort.freePaid`},{id:`paid-free`,labelKey:`pws.sort.paidFree`},{id:`accounts-first`,labelKey:`pws.sort.accountsFirst`}];function sg(e){return ke(sf(e))}function cg({providers:e,apiBase:t,targetKey:n,targetLabel:r,defaultProvider:i,selectedName:a,onSelect:o,onRemoveProvider:s,onAddProvider:c,onEditConfig:l,jsonEditor:u,jsonSaving:f=!1,modelsRefreshToken:p=0,fetchDiscovery:m=!1,onModelsSettled:h,activeAccountNeedsReauth:g,quotaRefreshEpoch:_=0,quotaForceRefresh:v=!1,onQuotaRefreshSettled:y,onRefreshAllQuotas:x,detail:S}){let C=b(),[w,T]=(0,Z.useState)(``),[E,D]=(0,Z.useState)({ready:!0,needsSetup:!0,unverified:!0,disabled:!0}),[O,k]=(0,Z.useState)({free:!0,paid:!0}),[A,j]=(0,Z.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[M,N]=(0,Z.useState)(`az`),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(null),[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(!1),W=n??t,ee=`ocx.providers.quotas.v1:${W}`,G=`ocx.providers.usage.v2:${W}`,[te,ne]=(0,Z.useState)(()=>Zr(sf(G))),[K,q]=(0,Z.useState)(()=>sf(G)?.totals??{}),[J,Y]=(0,Z.useState)(()=>sf(G)?.models??{}),[ie,oe]=(0,Z.useState)(()=>sg(ee)??{}),[se,ce]=(0,Z.useState)(()=>!sf(G)),[ue,de]=(0,Z.useState)(()=>{let e=sg(ee);return!e||Object.keys(e).length===0}),[fe,pe]=(0,Z.useState)(0),me=JSON.stringify([t,W,p,fe]),he=R?.revision===me&&!B&&!H,ge=(0,Z.useMemo)(()=>Qh(R?.rows??[]),[R]),_e=(0,Z.useRef)(h);(0,Z.useEffect)(()=>{_e.current=h},[h]);let ve=(0,Z.useRef)(null),ye=bn(ti(t,`all`,n),[t,n],async e=>await ei(await fetch(t+`/api/usage?range=30d`,{signal:e})),{deadlineMs:6e4}),be=(0,Z.useMemo)(()=>{let t=ae(Ge(e));return Le(t,g??{})},[e,g]),xe=(0,Z.useCallback)(()=>{V(!0),U(!1),pe(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=!1,n=d(6e4),r=window.setTimeout(()=>{V(!0),(async()=>{let r=!1;try{let[i,a]=await Promise.all([fetch(`${t}/api/selected-models`,{signal:n.signal}).then(Yn).then($h),fetch(`${t}/api/models`,{signal:n.signal}).then(Yn).then(Zh)]),o=m?await fetch(`${t}/api/providers`,{signal:n.signal}).then(Yn).then(ag):void 0;if(e)return;z({revision:me,selection:i,rows:a,...o?{discovery:o}:{}}),U(!1),r=!0}catch{if(e)return;U(!0)}finally{n.controller.abort(),n.clear(),e||(V(!1),_e.current?.(r))}})()},0);return()=>{e=!0,window.clearTimeout(r),n.controller.abort(),n.clear()}},[t,m,me]),(0,Z.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=ye.data;if(e)return;if(!t){ye.loading&&ce(!sf(G));return}let n=Um(t.providers??[]);q(n);let r=Wm(t.models??[],n);Y(r);let i=Zr(t);ne(i),df(G,{totals:n,models:r,...i}),ce(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,G,ye.data,ye.loading]),(0,Z.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=sg(ee);(!n||Object.keys(n).length===0)&&de(!0);let i=d(2e4);r=()=>{i.controller.abort(),i.clear()},fetch(`${t}/api/provider-quotas${v?`?refresh=1`:``}`,{signal:i.signal}).then(e=>Xn(e)).then(t=>{if(e)return;if(!t){v&&y?.(!1,_);return}let n=Ne(t.reports);oe(n),df(ee,n),v&&y?.(!0,_)}).catch(()=>{e||(oe(e=>{let t=ke(e)??{};return df(ee,t),t}),v&&y?.(!1,_))}).finally(()=>{i.clear(),e||de(!1)})},0),r;return()=>{e=!0,window.clearTimeout(n),r?.()}},[t,_,v,ee,y]),(0,Z.useEffect)(()=>{if(!P)return;let e=e=>{ve.current&&!ve.current.contains(e.target)&&F(!1)},t=e=>{e.key===`Escape`&&F(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[P]);let Se=(0,Z.useMemo)(()=>[...be.ready,...be.needsSetup,...be.unverified,...be.disabled],[be]),Ce=(0,Z.useMemo)(()=>Se.filter(Ue).length,[Se]),we=Se.length-Ce,Ee=(0,Z.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of Se)e[Te(t)]+=1;return e},[Se]),De=(0,Z.useMemo)(()=>{let e=w.trim().toLowerCase(),t=t=>{let n=t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=Ue(t);return!(n&&!O.free||!n&&!O.paid||!A[Te(t)])});return wt(n,M)};return{ready:E.ready?t(be.ready):[],needsSetup:E.needsSetup?t(be.needsSetup):[],unverified:E.unverified?t(be.unverified):[],disabled:E.disabled?t(be.disabled):[]}},[be,w,E,O,A,M]),Oe=!E.ready||!E.needsSetup||!E.unverified||!E.disabled||!O.free||!O.paid||!A.cloud||!A.local||!A.selfHosted||!A.login||M!==`az`,Ae=()=>{D({ready:!0,needsSetup:!0,unverified:!0,disabled:!0}),k({free:!0,paid:!0}),j({cloud:!0,local:!0,selfHosted:!0,login:!0}),N(`az`)},je=(0,Z.useMemo)(()=>a?Se.find(e=>e.name===a)??null:null,[a,Se]),Me=(0,Z.useMemo)(()=>{let e=new Map;for(let t of Se){let n=re(t.name,C);e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e.entries())r>1&&t.add(n);return t},[Se,C]);if(Se.length===0)return(0,Q.jsx)(lg,{onAddProvider:c});let Pe=[{key:`ready`,label:C(`pws.status.ready`),count:be.ready.length},{key:`needsSetup`,label:C(`pws.status.needsSetup`),count:be.needsSetup.length},{key:`unverified`,label:C(`pws.vertexUnverified`),count:be.unverified.length},{key:`disabled`,label:C(`prov.disabledBadge`),count:be.disabled.length}],Fe=[{id:`ready`,label:C(`pws.status.ready`),count:De.ready.length,ariaLabel:C(`pws.groupReady`,{count:De.ready.length}),items:De.ready},{id:`needs-setup`,label:C(`pws.status.needsSetup`),count:De.needsSetup.length,ariaLabel:C(`pws.groupNeedsSetup`,{count:De.needsSetup.length}),items:De.needsSetup},{id:`unverified`,label:C(`pws.vertexUnverified`),count:De.unverified.length,ariaLabel:`${C(`pws.vertexUnverified`)} (${De.unverified.length})`,items:De.unverified},{id:`disabled`,label:C(`prov.disabledBadge`),count:De.disabled.length,ariaLabel:C(`pws.groupDisabled`,{count:De.disabled.length}),items:De.disabled}],Ie=Fe.flatMap(e=>e.items.map(e=>e.name)),Re=I&&Ie.includes(I)?I:a&&Ie.includes(a)?a:Ie[0]??null;return(0,Q.jsx)(`div`,{className:`pws-shell-container`,children:(0,Q.jsxs)(`div`,{className:`pws-root`,children:[(0,Q.jsxs)(`aside`,{className:`pws-rail`,"aria-label":C(`pws.providerList`),children:[(0,Q.jsxs)(`div`,{className:`pws-search-row`,children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(We,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:C(`pws.searchPlaceholder`),value:w,onChange:e=>T(e.target.value),"aria-label":C(`pws.searchPlaceholder`)})]}),(0,Q.jsxs)(`div`,{className:`pws-filter-wrap`,ref:ve,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${Oe||P?` pws-filter-btn--active`:``}`,onClick:()=>F(e=>!e),"aria-label":C(`pws.filterAria`),"aria-expanded":P,"aria-controls":`pws-provider-filters`,children:[(0,Q.jsx)(Nt,{width:18,height:18,"aria-hidden":`true`}),Oe&&(0,Q.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),P&&(0,Q.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":C(`pws.providerFiltersAria`),children:[(0,Q.jsx)(`div`,{className:`pws-filter-title`,children:C(`pws.filters`)}),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:C(`pws.filterStatus`)}),Pe.map(({key:e,label:t,count:n})=>(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:E[e],onChange:()=>D(t=>({...t,[e]:!t[e]}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:C(`pws.pricing`)}),(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:O.free,onChange:()=>k(e=>({...e,free:!e.free}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:C(`modal.badge.free`)}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:Ce})]}),(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:O.paid,onChange:()=>k(e=>({...e,paid:!e.paid}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:C(`pws.paid`)}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:we})]}),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:C(`pws.filterType`)}),[{key:`cloud`,label:C(`pws.type.cloud`),count:Ee.cloud},{key:`local`,label:C(`pws.type.local`),count:Ee.local},{key:`selfHosted`,label:C(`pws.type.selfHosted`),count:Ee.selfHosted},{key:`login`,label:C(`pws.type.login`),count:Ee.login}].map(({key:e,label:t,count:n})=>(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:A[e],onChange:()=>j(t=>({...t,[e]:!t[e]}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:C(`pws.sort`)}),(0,Q.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":C(`pws.sortProvidersAria`),children:og.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`pws-sort-btn${M===e.id?` pws-sort-btn--active`:``}`,onClick:()=>N(e.id),"aria-pressed":M===e.id,children:C(e.labelKey)},e.id))}),(0,Q.jsx)(`div`,{className:`pws-filter-footer`,children:(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:Ae,disabled:!Oe,children:C(`pws.resetAll`)})})]})]})]}),(0,Q.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":C(`pws.providersAria`),onKeyDown:e=>{let t=Array.from(e.currentTarget.querySelectorAll(`[role="option"]`));if(t.length===0)return;let n=document.activeElement,r=t.findIndex(e=>e===n||e.contains(n));if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let n=e.key===`ArrowDown`?1:-1;t[r<0?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus()}else e.key===`Home`?(e.preventDefault(),t[0]?.focus()):e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus())},children:[Object.values(De).every(e=>e.length===0)&&(0,Q.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:C(w?`pws.noSearchResults`:Oe?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Fe.map(({id:e,label:t,count:n,ariaLabel:r,items:c})=>c.length===0?null:(0,Q.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":r,children:[(0,Q.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-rail-group-count`,children:n})]}),c.map(e=>(0,Q.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,Q.jsx)(le,{item:e,selected:a===e.name,tabbable:Re===e.name,modelCount:R?Object.hasOwn(ge,e.name)?ge[e.name]:0:void 0,isDefault:i===e.name,showConfigId:Me.has(re(e.name,C)),onClick:()=>o(e.name),onFocus:()=>L(e.name)}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),s(e.name)},title:C(`pws.removeConfirmTitle`),children:(0,Q.jsx)(et,{width:14,height:14})})]},e.name))]},e))]})]}),(0,Q.jsxs)(`main`,{className:`pws-main`,"aria-label":C(`pws.workspaceMainAria`),children:[!u?.open&&(0,Q.jsx)(ni,{data:te}),u?.open?(0,Q.jsx)(Oh,{editor:u,providerName:C(`nav.providers`),targetLabel:r??Jh(t),saving:f,onSave:()=>{u.onSave()}}):je?S?.(he&&je.discovery===void 0&&R?.discovery?.[je.name]?{...je,discovery:R.discovery[je.name]}:je,{usageTotals:K[je.name],modelUsage:J[je.name],quotaReport:ie[je.name],availableModels:R?.selection.available[je.name]??[],hasLiveModels:(R?.selection.liveModelCounts[je.name]??0)>0,selectedModels:R?.selection.selected[je.name]??[],modelRows:R?.rows.filter(e=>e.provider===je.name)??null,modelRevision:me,modelRowsReady:he,modelsLoading:B||!he&&!H,modelsLoadFailed:H,onRetryModels:xe})??(0,Q.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,Q.jsx)(`h3`,{children:re(je.name,C)}),(0,Q.jsx)(`p`,{className:`muted`,children:C(`pws.detailComingSoon`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>o(null),children:C(`modal.back`)})]}):(0,Q.jsx)(Eh,{sections:be,quotaReports:ie,usageTotals:K,usageLoading:se,quotasLoading:ue,onSelectProvider:e=>o(e),onEditConfig:l,...x?{onRefreshAllQuotas:x}:{}})]})]})})}function lg({onAddProvider:e}){let t=b();return(0,Q.jsx)(`div`,{className:`pws-empty-root`,children:(0,Q.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,children:(0,Q.jsx)(jt,{style:{width:64,height:64}})}),(0,Q.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,Q.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(at,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(_t,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(fe,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function ug(e){if(_e(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||ye(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0,r=t===`key`||n||t===``,i=e.keyOptional===!0||Ye(e);return!r||i&&!n?null:`api-keys`}function dg(e,t,n){let r=t.alias?.trim();if(r)return r;let i=t.accountLabel?.trim()||t.maskedLabel?.trim();if(i)return i;let a=e.findIndex(e=>e.id===t.id);return n(`pws.accountOrdinal`,{count:String(a>=0?a+1:1)})}function fg(e){return e===`anthropic`||e===`anthropic2`}function pg(e,t){return e===`anthropic`?!0:e!==`anthropic2`||!t?!1:Object.hasOwn(t,`anthropicOAuthInstance`)&&t.anthropicOAuthInstance===`anthropic2`&&t.adapter===`anthropic`&&t.authMode===`oauth`}function mg({quota:e,quotaMode:t,quotaUnavailable:n,quotaPending:r,quotaFailure:i,quotaReadAt:a}){let o=b(),s=gt({quota:e});if(t===`unsupported`)return(0,Q.jsx)(`p`,{className:`muted`,"data-quota-state":`unsupported`,children:o(`pws.quotaUnsupported`)});let c=t===`probe`&&n?_l(i):void 0,l=t===`probe`&&r===!0;return(0,Q.jsxs)(`div`,{"data-quota-state":n?`unavailable`:l?`pending`:s?`ready`:t===`passive`?`unobserved`:`unknown`,children:[n&&(0,Q.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:o(c?`pws.quotaFailure.${c}`:`pws.accountQuotaUnavailable`)}),s||l?(0,Q.jsx)(Th,{report:{quota:s,updatedAt:s?.updatedAt,...t===`passive`?{observed:!0}:{}},pending:l&&!s}):!n&&(0,Q.jsx)(`p`,{className:`muted`,children:o(t===`passive`?`pws.quotaUnobserved`:`pws.quotaUnavailable`)}),n&&s&&(0,Q.jsxs)(`p`,{className:`muted`,children:[o(`pws.stats.quotaUpdated`),`: `,qm(s.updatedAt,Jm(o))]}),(n||!s)&&!l&&typeof a==`number`&&(0,Q.jsxs)(`p`,{className:`muted`,children:[o(`pws.quotaLastRead`),`: `,qm(a,Jm(o))]})]})}function hg({report:e,reading:t,onRefreshQuota:n}){let r=b(),i=mt(e),a=t!==void 0&&(t.quotaMode!==void 0||t.quota!==void 0||t.quotaUnavailable!==void 0||t.quotaPending!==void 0),o=a?t:{quota:gt(i),...i?.observed===!0?{quotaMode:`passive`}:{}},s=gt({quota:o.quota}),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),f=async()=>{if(n&&!c){l(!0),d(null);try{d(await n())}catch{d(!1)}finally{l(!1)}}};return(0,Q.jsxs)(`section`,{className:`pws-usage-block`,"aria-label":r(`pws.currentAccountUsage`),children:[(0,Q.jsxs)(`div`,{className:`pws-usage-block-head`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:r(`pws.currentAccountUsage`)}),t?.planLabel&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:t.planLabel}),n&&o.quotaMode!==`unsupported`&&(0,Q.jsxs)(`div`,{className:`pws-quota-refresh`,children:[u!==null&&(0,Q.jsx)(`span`,{role:`status`,className:u?`pws-status-ok`:`pws-status-warn`,children:r(u?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:c,onClick:()=>{f()},children:[(0,Q.jsx)(Ke,{width:14,height:14,"aria-hidden":`true`}),` `,r(c?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Q.jsx)(mg,{...o}),s&&!o.quotaUnavailable&&o.quotaMode!==`unsupported`&&(0,Q.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[!a&&i?.source?.trim()&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:r(`pws.stats.source`)}),(0,Q.jsx)(`dd`,{children:De(i.source)})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:r(`pws.stats.quotaUpdated`)}),(0,Q.jsx)(`dd`,{children:qm(s.updatedAt,Jm(r))})]})]})]})}function gg(e,t){let n=e=>{try{let t=new URL(e.trim());return t.username||t.password||t.search||t.hash?void 0:`${t.origin}${t.pathname.replace(/\/+$/,``)}`}catch{return}},r=n(e.baseUrl);if(r)return t.find(t=>t.id===e.name&&t.adapter===e.adapter&&n(t.baseUrl)===r)}function _g(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function vg(e){return Ce(e.id,_g(e))}function yg(e){return ye(_g(e))}function bg(e){let t={accounts:[],free:[],local:[],paid:[]};for(let n of e){let e=vg(n);t[e===`accounts`?`accounts`:yg(n)?`local`:e].push(n)}return t}function xg(e){return!!e?.trim()}var Sg=new Set([`local`,`localhost`,`ollama`,`vllm`,`lmstudio`,`lm studio`,`self-hosted`,`selfhosted`]);function Cg(e,t){let n=t.trim().toLowerCase();return!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||e.adapter.toLowerCase()===n?!0:Sg.has(n)&&yg(e)}function wg(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e=>{let t=e.label.toLowerCase(),r=e.id.toLowerCase();return r===n||t===n?0:t.startsWith(n)||r.startsWith(n)?1:2};return e.map((e,t)=>({preset:e,index:t})).sort((e,t)=>r(e.preset)-r(t.preset)||e.index-t.index).map(e=>e.preset)}function Tg(e,t,n){let r=t.trim().toLowerCase();return r?e.filter(e=>e.id===n||e.label.toLowerCase().includes(r)||e.id.toLowerCase().includes(r)):[...e]}function Eg(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.id));return e.filter(e=>!n.has(e.id))}var Dg={main:0,standard:1};function Og(e){let t=e.filter(e=>e.sponsor);return t.length===0?e:(t.sort((e,t)=>Dg[e.sponsor]-Dg[t.sponsor]||e.label.localeCompare(t.label,void 0,{sensitivity:`base`})||e.id.localeCompare(t.id)),[...t,...e.filter(e=>!e.sponsor)])}var kg={name:`OrcaRouter`,title:`pws.sponsor.orcaTitle`,description:`pws.sponsor.orcaDescription`},Ag={orcarouter:kg,"orcarouter-oauth":kg,tokenlab:{name:`TokenLab`,title:`pws.sponsor.tokenlabTitle`,description:`pws.sponsor.tokenlabDescription`}};function jg(e){if(e)try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password?e:void 0}catch{return}}function Mg({item:e,preset:t}){let n=b();if(!t?.sponsor||!gg(e,[t]))return null;let r=Object.hasOwn(Ag,t.id)?Ag[t.id]:void 0;if(!r)return null;let i=jg(t.sponsorUrl),a=jg(t.dashboardUrl);return(0,Q.jsxs)(`section`,{className:`pws-sponsor`,"aria-label":`${r.name} · ${n(`modal.badge.sponsor`)}`,children:[(0,Q.jsxs)(`div`,{className:`pws-sponsor-copy`,children:[(0,Q.jsxs)(`div`,{className:`pws-sponsor-byline`,children:[(0,Q.jsx)(`span`,{children:r.name}),(0,Q.jsx)(`span`,{className:`pws-sponsor-badge`,children:n(`modal.badge.sponsor`)})]}),(0,Q.jsx)(`h3`,{children:n(r.title)}),(0,Q.jsx)(`p`,{children:n(r.description)})]}),(i||a)&&(0,Q.jsxs)(`div`,{className:`pws-sponsor-actions`,children:[i&&(0,Q.jsxs)(`a`,{className:`btn btn-primary`,href:i,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.visit`,{provider:r.name}),(0,Q.jsx)(dt,{width:14,height:14,"aria-hidden":`true`})]}),a&&a!==i&&(0,Q.jsxs)(`a`,{className:`pws-sponsor-console`,href:a,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.console`),(0,Q.jsx)(dt,{width:13,height:13,"aria-hidden":`true`})]})]})]})}function Ng(e){return e.filter(e=>e.outcome===`failed`).map(e=>e.model)}function Pg({apiBase:e,provider:t,models:n,gate:r,blocked:i}){let a=b(),{locale:o}=s(),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)({kind:`idle`}),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{v.current&&(v.current.abort(),v.current=null,r.release()),y.current?.abort(),y.current=null},[r]);async function x(n,r){try{let i=await Yn(await fetch(`${e}/api/providers/test-completion?name=${encodeURIComponent(t)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:n,confirm:!0}),signal:r}),a(`pws.completion.failed`));if(!i)return{model:n,outcome:`skipped`,detail:a(`pws.completion.failed`)};if(!i.applicable){let e=`${a(`pws.completion.notApplicable`)}: ${a(`pws.completion.${i.reason}`)}`;return i.reason===`unsupported_adapter`?{model:n,outcome:`skipped`,detail:e}:{stop:e}}if(i.ok)return{model:n,outcome:`ok`,latencyMs:i.totalLatencyMs};if(i.termination===`aborted`||[`credential_missing`,`credential_changed`,`destination_refused`].includes(i.error?.code??``))return{model:n,outcome:`skipped`,detail:i.error?.code??`aborted`};let o=i.error?`${i.error.code}${i.error.status===void 0?``:` (${i.error.status})`}`:i.termination;return i.error?.code===`http_status`&&[401,403,429].includes(i.error.status??0)?{model:n,outcome:`skipped`,detail:o}:{model:n,outcome:`failed`,latencyMs:i.totalLatencyMs,detail:o}}catch(e){return{model:n,outcome:`skipped`,detail:e instanceof Error?e.message:a(`pws.completion.failed`)}}}async function S(){if(n.length===0||v.current||y.current||!r.claim())return;let e=new AbortController;v.current=e,d(!0),p(!1),l([]),h(null),_({kind:`idle`});try{if(!await Ju({message:a(`pws.completion.allConfirm`,{count:String(n.length),provider:t}),confirmLabel:a(`pws.completion.runAll`),signal:e.signal,locale:o})||e.signal.aborted)return;for(let t of n){if(e.signal.aborted)break;let n=await x(t,e.signal);if(e.signal.aborted)break;if(`stop`in n){h(n.stop);break}l(e=>[...e,n])}}finally{v.current===e&&(v.current=null,r.release(),d(!1))}}function C(){v.current?.abort(),v.current=null,r.release(),p(!0),d(!1)}async function w(){let n=Ng(c);if(n.length===0||v.current||y.current)return;let r=new AbortController;y.current=r,_({kind:`busy`});let i=!1;try{if(i=await Ju({message:a(`pws.completion.disableConfirm`,{count:String(n.length),provider:t}),confirmLabel:a(`pws.completion.disableFailed`,{count:String(n.length)}),tone:`danger`,locale:o,signal:r.signal}),!i||r.signal.aborted||y.current!==r)return;await Yn(await sp(e,`models`,t,n.map(e=>({id:e})),!1,fetch,r.signal),a(`pws.completion.disableError`)),!r.signal.aborted&&y.current===r&&_({kind:`done`,count:n.length})}catch(e){!r.signal.aborted&&y.current===r&&_({kind:`error`,message:e instanceof Error?e.message:a(`pws.completion.disableError`)})}finally{y.current===r&&(y.current=null,i||_({kind:`idle`}))}}let T={ok:0,failed:0,skipped:0};for(let e of c)T[e.outcome]++;let E=T.failed,D=T.skipped+(u?0:n.length-c.length);return(0,Q.jsxs)(`div`,{className:`pws-completion-bulk`,children:[(0,Q.jsxs)(`div`,{className:`row pws-completion-bulk-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n.length===0||u||g.kind===`busy`||i,onClick:()=>void S(),children:u?a(`pws.completion.progress`,{done:String(c.length),total:String(n.length)}):a(`pws.completion.runAll`)}),u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:C,children:a(`pws.completion.stop`)})]}),m&&(0,Q.jsx)(`p`,{role:`status`,className:`muted pws-completion-result`,children:m}),c.length>0&&(0,Q.jsxs)(`div`,{className:`pws-completion-result`,"data-completion-bulk-state":u?`running`:`done`,children:[!u&&(0,Q.jsxs)(`p`,{role:`status`,children:[f&&(0,Q.jsxs)(Q.Fragment,{children:[a(`pws.completion.stopped`,{done:String(c.length),total:String(n.length)}),` · `]}),a(`pws.completion.summary`,{passed:String(T.ok),failed:String(E),skipped:String(D)})]}),(0,Q.jsx)(`table`,{className:`pws-completion-table`,children:(0,Q.jsx)(`tbody`,{children:c.map(e=>(0,Q.jsxs)(`tr`,{"data-model-test-outcome":e.outcome,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.model})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`span`,{className:`badge ${e.outcome===`ok`?`badge-green`:e.outcome===`failed`?`badge-amber`:`badge-muted`}`,children:a(e.outcome===`ok`?`pws.completion.passed`:e.outcome===`failed`?`pws.completion.failedShort`:`pws.completion.notTested`)})}),(0,Q.jsx)(`td`,{className:`muted`,children:e.latencyMs===void 0?``:`${e.latencyMs} ms`}),(0,Q.jsx)(`td`,{className:`muted`,children:e.detail??``})]},e.model))})}),!u&&E>0&&g.kind!==`done`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g.kind===`busy`,onClick:()=>void w(),children:a(`pws.completion.disableFailed`,{count:String(E)})}),g.kind===`done`&&(0,Q.jsx)(`p`,{role:`status`,className:`pws-status-ok`,children:a(`pws.completion.disabledDone`,{count:String(g.count)})}),g.kind===`error`&&(0,Q.jsx)(`p`,{role:`alert`,className:`pws-inline-error`,children:g.message})]})]})}function Fg(e){let t=null,n=n=>({claim(){return t!==null&&t!==n?!1:(t=n,e(n),!0)},release(){t===n&&(t=null,e(null))}});return{single:n(`single`),bulk:n(`bulk`)}}function Ig({apiBase:e,provider:t,models:n,probeKey:r,selectedModel:i,onSelectedModelChange:a,initialResult:o=null,initialError:s=null,onStatusChange:c,onFixCredentials:l,onFixSettings:u,onFixModels:d}){let f=b(),[p,m]=(0,Z.useState)(``);i===void 0&&p!==``&&!n.includes(p)&&m(``);let h=i===void 0?p:i,g=n.includes(h)?h:``,[_,v]=(0,Z.useState)(null),[y]=(0,Z.useState)(()=>Fg(v));return(0,Q.jsxs)(`section`,{className:`pws-completion-test`,"aria-label":f(`pws.completion.title`),children:[(0,Q.jsx)(`h4`,{className:`pws-section-title`,children:f(`pws.completion.title`)}),(0,Q.jsx)(Vn,{label:f(`pws.completion.model`),value:g,options:[{value:``,label:f(`pws.completion.choose`)},...n.map(e=>({value:e,label:e}))],onChange:e=>{e!==g&&(i===void 0&&m(e),a?.(e),c?.({status:`untested`,model:e}))}}),(0,Q.jsx)(Lg,{apiBase:e,provider:t,model:g,initialResult:o,initialError:s,onStatusChange:c,onFixCredentials:l,onFixSettings:u,onFixModels:d,gate:y.single,blocked:_===`bulk`},JSON.stringify([e,r??``,t,g])),(0,Q.jsx)(Pg,{apiBase:e,provider:t,models:n,gate:y.bulk,blocked:_===`single`},JSON.stringify([e,r??``,t]))]})}function Lg({apiBase:e,provider:t,model:n,initialResult:r=null,initialError:i=null,onStatusChange:a,onFixCredentials:o,onFixSettings:c,onFixModels:l,gate:u,blocked:d}){let f=b(),{locale:p}=s(),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(r),[v,y]=(0,Z.useState)(i),x=(0,Z.useRef)(null),S=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(S.current=!0,()=>{S.current=!1,x.current&&(x.current.abort(),x.current=null,u.release())}),[u]);async function C(){if(!n||x.current||!u.claim())return;let r=new AbortController;x.current=r,h(!0);let i=()=>S.current&&!r.signal.aborted&&x.current===r;try{let o=await Ju({message:f(`pws.completion.confirm`,{model:n,provider:t}),confirmLabel:f(`pws.completion.run`),signal:r.signal,locale:p});if(!i()||!o)return;_(null),y(null),a?.({status:`testing`,model:n});let s=await Yn(await fetch(`${e}/api/providers/test-completion?name=${encodeURIComponent(t)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:n,confirm:!0}),signal:r.signal}),f(`pws.completion.failed`));if(!s)throw Error(f(`pws.completion.failed`));i()&&(_(s),a?.({status:s.applicable?s.ok?`ok`:`failed`:`not-applicable`,model:n,result:s,error:null}))}catch(e){if(i()){let t=e instanceof Error?e.message:f(`pws.completion.failed`);y(t),a?.({status:`failed`,model:n,result:null,error:t})}}finally{x.current===r&&(x.current=null,u.release(),S.current&&!r.signal.aborted&&h(!1))}}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!n||m||d,onClick:()=>void C(),children:f(m?`pws.testing`:`pws.completion.run`)}),v&&(0,Q.jsx)(`p`,{role:`alert`,className:`pws-inline-error pws-completion-result`,children:v}),v&&(0,Q.jsx)(`div`,{role:`status`,className:`pws-completion-recovery pws-completion-result muted`,"data-failure-recovery":`request`,children:(0,Q.jsx)(`span`,{children:f(`pws.completion.recovery.request`,{model:n})})}),g&&(0,Q.jsx)(zg,{result:g,onFixCredentials:o,onFixSettings:c,onFixModels:l})]})}function Rg(e){let t=e.error;return e.ok||!t?null:e.termination===`aborted`||t.code===`aborted`?`aborted`:t.code===`credential_changed`?`concurrency`:t.code===`credential_missing`||t.status===401||t.status===403?`auth`:t.status===429?`rate_limit`:e.termination===`timeout`||t.code===`timeout`||t.code===`network`||t.code===`destination_refused`||t.code===`redirect`?`connection`:t.status===400||t.status===404||t.status===422?`model`:`upstream`}function zg({result:e,onFixCredentials:t,onFixSettings:n,onFixModels:r}){let i=b();if(!e.applicable)return(0,Q.jsxs)(`div`,{role:`status`,className:`pws-completion-result muted`,children:[(0,Q.jsxs)(`p`,{children:[i(`pws.completion.notApplicable`),`: `,i(`pws.completion.${e.reason}`)]}),e.detail&&(0,Q.jsx)(`p`,{children:i(`pws.completion.${e.detail}`)}),e.adapter&&(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`code`,{children:e.adapter})})]});let a=Rg(e),o=t??n;return(0,Q.jsxs)(`div`,{role:`status`,className:`pws-completion-result`,"data-completion-test-state":e.ok?`ok`:`failed`,children:[(0,Q.jsx)(`p`,{className:e.ok?`pws-status-ok`:`pws-status-warn`,children:i(e.ok?`pws.completion.ok`:`pws.completion.failed`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:i(`pws.completion.ttft`)}),(0,Q.jsx)(`dd`,{children:e.ttftMs===null?`—`:`${e.ttftMs} ms`})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:i(`pws.completion.total`)}),(0,Q.jsxs)(`dd`,{children:[e.totalLatencyMs,` ms`]})]})]}),(0,Q.jsx)(`p`,{children:e.upstreamModel===null?i(`pws.completion.unreported`,{model:e.wireModel}):i(`pws.completion.reported`,{upstream:e.upstreamModel,model:e.wireModel})}),(0,Q.jsx)(`span`,{className:`badge ${e.modelComparison===`match`?`badge-green`:e.modelComparison===`mismatch`?`badge-amber`:`badge-muted`}`,children:i(`pws.completion.${e.modelComparison}`)}),e.comparisonNote&&(0,Q.jsx)(`p`,{className:`muted`,children:i(`pws.completion.${e.comparisonNote}`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(`pws.completion.identity`)}),e.error&&(0,Q.jsxs)(`p`,{role:`alert`,className:`pws-inline-error`,children:[(0,Q.jsx)(`code`,{children:e.error.code}),e.error.status!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[` (`,e.error.status,`)`]}),`: `,e.error.message]}),a&&(0,Q.jsxs)(`div`,{className:`pws-completion-recovery muted`,"data-failure-recovery":a,children:[(0,Q.jsx)(`span`,{children:a===`aborted`?i(`pws.completion.recovery.aborted`,{model:e.requestedModel}):a===`concurrency`?i(`pws.completion.recovery.credentialChanged`,{model:e.requestedModel}):a===`auth`?i(`pws.completion.recovery.auth`,{model:e.requestedModel}):a===`rate_limit`?i(`pws.completion.recovery.rateLimit`,{model:e.requestedModel}):a===`connection`?i(`pws.completion.recovery.connection`,{model:e.requestedModel}):a===`model`?i(`pws.completion.recovery.model`):i(`pws.completion.recovery.upstream`,{model:e.requestedModel})}),a===`auth`&&o&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-auth`,onClick:o,children:i(`pws.completion.recovery.fixAuth`)}),a===`rate_limit`&&o&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-rate-limit`,onClick:o,children:i(`pws.completion.recovery.fixAuth`)}),a===`connection`&&n&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-connection`,onClick:n,children:i(`pws.completion.recovery.fixSettings`)}),a===`model`&&r&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-model`,onClick:r,children:i(`pws.firstResponse.openProviderModels`)}),a===`upstream`&&n&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-settings`,onClick:n,children:i(`pws.completion.recovery.fixSettings`)})]})]})}function Bg(e,t,n,r=0){return JSON.stringify([e??null,t.name,t.adapter,t.baseUrl,t.authMode??null,t.apiKeyTransport??null,t.upstreamHttpVersion??null,t.requestPacing??null,t.liveModels??null,t.disabled===!0,t.hasApiKey===!0,t.hasHeaders===!0,t.allowPrivateNetwork===!0,t.keyOptional===!0,t.activeNeedsReauth===!0,t.vertexCredentialVerified===!0,n??null,r])}function Vg(e,t=[]){return[...new Set([...e.models??[],...t,...e.defaultModel?[e.defaultModel]:[]])]}function Hg(e,t,n,r=[],i=0){let a=Bg(t,e,n,i),o=Vg(e,r),[s,c]=(0,Z.useState)(e.name),[l,u]=(0,Z.useState)(a),[d,f]=(0,Z.useState)(0),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null);if(s!==e.name)c(e.name),u(a),f(e=>e+1),p!==``&&m(``),h!==null&&g(null),_!==null&&v(null);else{let e=p!==``&&!o.includes(p),t=h!==null&&h.model!==``&&!o.includes(h.model),n=_!==null&&!o.includes(_.model);(e||t||n)&&(f(e=>e+1),e&&m(``),h!==null&&g(null),_!==null&&v(null)),l===a?h!==null&&h.epoch!==d&&(f(e=>e+1),g(null)):(u(a),f(e=>e+1),h!==null&&g(null),_!==null&&!_.invalidated&&!n&&v({..._,invalidated:!0}))}let y=o.includes(p)?p:``;return{connectionProbeKey:a,completionModels:o,probeEpoch:d,selectedModel:y,completionProbe:h,reverifyModel:_?.invalidated===!0&&o.includes(_.model)&&(h===null||h.status===`untested`)?_.model:null,selectModel(e){e!==y&&(m(e),f(e=>e+1),g(null),v(null))},reportStatus(e){g({epoch:d,model:e.model,status:e.status,result:e.result??null,error:e.error??null}),e.status===`failed`?v({model:e.model,invalidated:!1}):(e.status===`ok`||e.status===`not-applicable`)&&v(null)},clearIfTesting(){h?.status===`testing`&&(f(e=>e+1),g(null))}}}function Ug({item:e,preset:t,usageTotals:n,quotaReport:r,currentQuotaReading:i,onRefreshQuota:a,oauthEmail:o,currentAccountLabel:c,oauth:l,apiBase:u,connectionIdentity:d,probeController:f,availableModels:p=[],selectedModels:m,modelRows:h,modelRowsReady:g=!1,modelsLoading:_=!1,modelsLoadFailed:v=!1,onRetryModels:y,onOpenAccounts:x,onOpenModelsTab:S,onOpenModels:C,onOpenConnect:w,onEditSettings:T,onViewUsage:E,onUpdateProvider:D,onCreateJevAuto:O,onReauthenticate:k,onCancelLogin:A,reauthBusy:j=!1}){let M=b(),{locale:N}=s(),P=Bt(e),F=!!e.activeNeedsReauth||l?.needsReauth===!0,I=e.authMode===`oauth`&&l?.loggedIn===!1,L=n?.requests,R=n?.totalTokens,z=Hg(e,u,d,p),B=f??z,{connectionProbeKey:V,completionModels:H,selectedModel:U,completionProbe:W,reverifyModel:ee}=B,[G,te]=(0,Z.useState)(null),ne=(0,Z.useRef)(null),K=G?.key===V&&G.testing,q=G?.key===V?G.result:null,J=xe(e)&&q?.ok!==!0,re=e.disabled===!0?`disabled`:J&&!F?`unverified`:F||I||P===`needs-setup`?`needs-setup`:`ready`,Y=M(re===`ready`?`pws.status.ready`:re===`unverified`?`pws.vertexUnverified`:re===`needs-setup`?F?`pws.status.needsAttention`:J?`pws.vertexUnverified`:`pws.status.needsSetup`:`prov.disabledBadge`),ie=[...new Set([...e.models??[],...e.defaultModel?[e.defaultModel]:[]])];(0,Z.useEffect)(()=>()=>{ne.current?.key===V&&(ne.current.controller.abort(),ne.current=null)},[V]);let ae=(0,Z.useCallback)(async()=>{if(u===void 0)return;ne.current?.controller.abort();let t=new AbortController;ne.current={key:V,controller:t},te({key:V,testing:!0,result:null});try{let n=await Yn(await fetch(`${u}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),M(`pws.connectionFailed`));if(!n)throw Error(M(`pws.connectionFailed`));t.signal.aborted||te({key:V,testing:!1,result:n})}catch(e){t.signal.aborted||te({key:V,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:M(`pws.connectionFailed`)}})}finally{ne.current?.controller===t&&(ne.current=null)}},[u,V,e.name,M]),oe=q?.applicable===!1?`not-applicable`:q?.ok===!0?`ok`:`failed`,se=q?.applicable===!1?M(`pws.connectionNotApplicable`):q?.ok===!0?q.message||M(`pws.connectionOk`):q?.error||M(`pws.connectionFailed`),ce=e.disabled===!0?`disabled`:F?`needs-attention`:I?`needs-login`:re===`needs-setup`||re===`unverified`?`needs-setup`:`saved`,le=M(ce===`disabled`?`pws.firstResponse.providerDisabled`:ce===`needs-attention`?`pws.firstResponse.providerNeedsAttention`:ce===`needs-login`?`pws.firstResponse.providerNeedsLogin`:ce===`needs-setup`?J?`pws.vertexSavedUnverified`:`pws.firstResponse.providerNeedsSetup`:`pws.firstResponse.providerSaved`),ue=(h??[]).filter(t=>t.provider===e.name),de=ue.filter(t=>op({[e.name]:m??[]},e.name,t.id,t.native===!0,t.disabled)),fe=h!=null&&g,pe=fe?ue.some(e=>e.initialSelectionPending===!0):e.initialModelSelection?.status===`pending`,me=e.liveModels!==!1&&e.discovery?.status===`failed`?e.discovery:void 0,he=_?`loading`:v||me&&(!fe||pe||de.length===0)?`failed`:pe?`pending`:fe?de.length>0?me?`ready-discovery-failed`:`ready`:ue.length>0||e.initialModelSelection?.status===`all-off`?`all-off`:ie.length>0?`configured`:`empty`:e.initialModelSelection?.status===`all-off`?`all-off`:ie.length>0||p.length>0?`configured`:`empty`,ge=he===`loading`?M(`pws.firstResponse.modelsLoading`):he===`failed`?me?lp(M,me):M(`pws.firstResponse.modelsFailed`):he===`pending`?M(`pws.firstResponse.modelsPending`):he===`ready-discovery-failed`?M(`pws.firstResponse.modelsReadyDiscoveryFailed`,{count:de.length}):he===`ready`?M(`pws.firstResponse.modelsReady`,{count:de.length}):he===`all-off`?M(`pws.firstResponse.modelsAllOff`):he===`configured`?M(`pws.firstResponse.modelsConfigured`,{count:ie.length||p.length}):M(`pws.firstResponse.modelsEmpty`),_e=W?.status??`untested`,ve=_e===`untested`&&ee!==null,ye=_e===`testing`?M(`pws.testing`):_e===`ok`?M(`pws.firstResponse.probeOk`,{model:W?.model??``}):_e===`failed`?M(`pws.firstResponse.probeFailed`,{model:W?.model??``}):_e===`not-applicable`?M(`pws.completion.notApplicable`):ve?M(`pws.firstResponse.probeReverify`,{model:ee}):M(`pws.firstResponse.probeUntested`),be=fg(e.name)&&pg(e.name,e)?void 0:o,Se=fg(e.name)&&pg(e.name,e)?c:void 0,Ce=S??C,we=x??T;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Mg,{item:e,preset:t}),(0,Q.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,Q.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":M(`pws.connection`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:M(`pws.connection`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:re===`ready`?`pws-status-ok`:`pws-status-warn`,children:[re===`ready`?(0,Q.jsx)(st,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Q.jsx)(St,{style:{width:13,height:13},"aria-hidden":`true`}),Y]})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`modal.baseUrl`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`pws.cell.auth`)}),(0,Q.jsx)(`dd`,{children:be?`${je(e,M)} · ${be}`:je(e,M)})]}),Se&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`pws.accountCurrent`)}),(0,Q.jsx)(`dd`,{children:Se})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`modal.defaultModel`)}),(0,Q.jsx)(`dd`,{children:e.defaultModel??(0,Q.jsx)(`span`,{className:`muted`,children:`—`})})]})]}),(0,Q.jsxs)(`div`,{className:`pws-first-response`,"aria-label":M(`pws.firstResponse.title`),children:[(0,Q.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`provider`,"data-step-state":ce,children:[(0,Q.jsx)(`span`,{className:`pws-first-response-label`,children:M(`pws.firstResponse.stepProvider`)}),(0,Q.jsx)(`span`,{className:ce===`saved`?`pws-status-ok`:`pws-status-warn`,children:le})]}),(0,Q.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`models`,"data-step-state":he,children:[(0,Q.jsx)(`span`,{className:`pws-first-response-label`,children:M(`pws.firstResponse.stepModels`)}),(0,Q.jsx)(`span`,{className:he===`ready`?`pws-status-ok`:he===`failed`||he===`all-off`||he===`empty`||he===`ready-discovery-failed`?`pws-status-warn`:`muted`,children:ge}),he===`failed`&&y&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:y,children:M(`common.retry`)}),Ce&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:Ce,children:M(`pws.firstResponse.openProviderModels`)})]}),(0,Q.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`clients`,"data-step-state":`info`,children:[(0,Q.jsx)(`span`,{className:`pws-first-response-label`,children:M(`pws.firstResponse.stepClients`)}),(0,Q.jsx)(`span`,{className:`muted`,children:M(`pws.firstResponse.clientStep`,{provider:e.name})}),w&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:w,children:M(`pws.firstResponse.openConnect`)})]}),(0,Q.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`probe`,"data-step-state":_e,...ve?{"data-reverify-pending":`true`}:{},children:[(0,Q.jsx)(`span`,{className:`pws-first-response-label`,children:M(`pws.firstResponse.stepProbe`)}),(0,Q.jsx)(`span`,{className:_e===`ok`?`pws-status-ok`:_e===`failed`||ve?`pws-status-warn`:`muted`,children:ye})]}),(0,Q.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`disconnect`,"data-step-state":`info`,children:[(0,Q.jsx)(`span`,{className:`pws-first-response-label`,children:M(`pws.firstResponse.stepDisconnect`)}),(0,Q.jsx)(`span`,{className:`muted`,children:M(`pws.firstResponse.disconnectNote`,{provider:e.name})}),w&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:w,children:M(`pws.firstResponse.openConnect`)})]})]}),u!==void 0&&(0,Q.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:K,onClick:()=>void ae(),children:M(K?`pws.testing`:`pws.testConnection`)}),q&&(0,Q.jsx)(`span`,{role:`status`,className:oe===`ok`?`pws-status-ok`:oe===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":oe,children:se}),q&&oe===`failed`&&we&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,"data-connection-recovery-action":`fix-connection`,onClick:we,children:M(x?`pws.completion.recovery.fixAuth`:`pws.completion.recovery.fixSettings`)})]}),u!==void 0&&(0,Q.jsx)(Ig,{apiBase:u,provider:e.name,probeKey:V,models:H,selectedModel:U,onSelectedModelChange:B.selectModel,initialResult:W?.result??null,initialError:W?.error??null,onStatusChange:B.reportStatus,onFixCredentials:we,onFixSettings:T,onFixModels:Ce},e.name),T&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:T,children:M(`pws.editSettings`)})]}),e.adapter===`jev-decision`&&O&&(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":M(`cws.jev.create`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:M(`cws.jev.create`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:M(`cws.jev.setupHint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:O,children:M(`cws.jev.create`)})]}),(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":M(`pws.authSummary`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:M(`pws.authSummary`)}),F?(0,Q.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,Q.jsx)(St,{style:{width:14,height:14},"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:M(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?M(`pws.attention.reauthForward`):M(`pws.attention.reauth`)]}),k&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:j,onClick:()=>k(),children:M(j?`prov.waitingBrowser`:`pws.reauthenticate`)}),j&&A&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),children:M(`common.cancel`)})]})]}):(0,Q.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,Q.jsx)(`span`,{className:`pws-auth-dot`}),(0,Q.jsx)(`span`,{children:e.authMode===`forward`?M(`pws.passthrough`):e.authMode===`oauth`?be?M(`pws.loggedInAs`,{email:be}):l?.loggedIn===!0?M(`pws.loggedInTitle`):l?.loggedIn===!1?M(`pws.notLoggedIn`):M(`startup.unverified`):e.hasApiKey?M(`pws.apiKeyConfigured`):je(e,M)})]})]}),(0,Q.jsx)(Wg,{item:e,onUpdateProvider:D})]}),(0,Q.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":M(`pws.statsAria`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:M(`pws.statsTitle`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[typeof L==`number`&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`pws.stats.totalRequests`)}),(0,Q.jsx)(`dd`,{className:`pws-kv-mono`,children:Zm(L,N)})]}),typeof R==`number`&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:M(`pws.stats.totalTokens`)}),(0,Q.jsx)(`dd`,{className:`pws-kv-mono`,children:Qm(R,N)})]}),typeof L!=`number`&&typeof R!=`number`&&(0,Q.jsx)(`div`,{className:`muted`,children:M(`pws.usageUnavailable`)})]}),E&&(0,Q.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:E,children:[M(`pws.viewUsage`),` →`]})]}),(0,Q.jsx)(hg,{report:r,reading:i,onRefreshQuota:a},`${e.name}:${d??``}`)]})]})]})}function Wg({item:e,onUpdateProvider:t}){let n=b(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``),d=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,Z.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``))i(!1),u(``);else{c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}}},[a,e.name,e.note,t,s,n]);return r?(0,Q.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Q.jsx)(`textarea`,{ref:d,className:`pws-notes-textarea`,value:a,onChange:e=>o(e.target.value),onBlur:()=>void f(),onKeyDown:t=>{t.key===`Escape`&&(o(e.note??``),u(``),i(!1))},placeholder:n(`pws.notePlaceholder`),rows:3,disabled:s}),l?(0,Q.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,Q.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Q.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,Q.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function Gg(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function Kg(e,t){let n=Gg(e);for(let r of t)if(r!==e&&Gg(r)===n)return!0;return!1}function qg({row:e,disambiguate:t,copied:n,isDefault:r,selected:i,action:a,disabled:o,onCopy:s,onRemove:c}){let l=b(),u=l(a===`delete`?`models.customDelete`:`models.hide`);return(0,Q.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:s,title:e.namespaced,"aria-label":l(n?`pws.modelCopied`:`pws.copyModelId`),children:(0,Q.jsx)(`span`,{className:`pws-model-id`,children:t?e.namespaced:e.id})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:l(`prov.defaultBadge`)}),i&&(0,Q.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:l(`pws.selected`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:e=>c(e.currentTarget),disabled:o,"aria-label":`${u}: ${e.namespaced}`,title:`${u}: ${e.namespaced}`,children:a===`delete`?(0,Q.jsx)(et,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Q.jsx)(nt,{style:{width:13,height:13},"aria-hidden":`true`})})]})}var Jg=300;function Yg(e){return(0,Q.jsx)(Xg,{...e},JSON.stringify([e.apiBase,e.item.name]))}function Xg({item:e,apiBase:t,availableModels:n,selectedModels:r,modelRows:i,modelRevision:a,modelRowsReady:o,modelsLoading:s=!1,modelsLoadFailed:c=!1,needsReauth:l=!1,onRetryModels:u,onOpenAccounts:f,onOpenModels:p}){let m=b(),[h,g]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(!1),[y,x]=(0,Z.useState)(``),[S,C]=(0,Z.useState)(0),w=JSON.stringify([t,e.name,a,S]),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(null),F=(0,Z.useRef)(null),I=(0,Z.useRef)(!1),L=(0,Z.useRef)(!0),R=(0,Z.useRef)(a),z=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useRef)(null),H=T?.key===w&&D!==w,U=i!==null&&o&&!s&&!c&&H,W=U&&(!j||a!==j.revision),ee=k||!!j&&!W,G=(i??[]).filter(t=>t.provider===e.name),te=G.some(e=>e.initialSelectionPending),ne=!U||ee||te,K=T?.rows.filter(t=>t.provider===e.name)??[],q=new Set(r),J=[...n,...e.models??[],...K.map(e=>e.modelId),...e.defaultModel?[e.defaultModel]:[]],re=y.trim(),Y=!!re&&(J.includes(re)||Kg(re,J)),ie=G.filter(e=>!e.disabled),ae=up(ie),oe=fp(_,ie),se=dp(ie,oe),ce=h.trim().toLowerCase(),le=se.filter(e=>[e.id,e.namespaced].some(e=>e.toLowerCase().includes(ce))),ue=new Map;for(let e of ie)ue.set(e.id,(ue.get(e.id)??0)+1);(0,Z.useEffect)(()=>{R.current=a},[a]),(0,Z.useEffect)(()=>{L.current=!0;let e=e=>{V.current&&e.target!==V.current.button&&e.target!==document.body&&(V.current.retained=!1)};return document.addEventListener(`focusin`,e),()=>{L.current=!1,document.removeEventListener(`focusin`,e),F.current!==null&&clearTimeout(F.current)}},[]),(0,Z.useEffect)(()=>{let e=!1,n=d(2e4);return fetch(`${t}/api/custom-models`,{signal:n.signal}).then(Yn).then(tg).then(t=>{e||(E({key:w,rows:t}),O(null))}).catch(()=>{e||O(w)}).finally(()=>n.clear()),()=>{e=!0,n.controller.abort(),n.clear()}},[t,w]),(0,Z.useEffect)(()=>{!k&&W&&(I.current=!1);let e=V.current;e&&!e.button.isConnected&&(e.retained&&document.activeElement===document.body&&(z.current??B.current)?.focus(),V.current=null)},[k,W,i]);let de=()=>{C(e=>e+1),u?.()},fe=async e=>{try{if(await navigator.clipboard.writeText((ue.get(e.id)??0)>1?e.namespaced:e.id),!L.current)return;P(e.namespaced),F.current!==null&&clearTimeout(F.current),F.current=setTimeout(()=>P(null),1200)}catch{}},pe=e=>e.custom===!0&&e.native!==!0&&K.some(t=>t.id===e.customId&&t.provider===e.provider&&t.modelId===e.id),me=e=>!U||e.initialSelectionPending?null:e.custom?pe(e)?`delete`:null:e.native!==!0&&K.some(t=>t.modelId===e.id)?null:`hide`,he=e=>{L.current?(M({...e,revision:R.current}),A(!1),de()):u?.()},ge=async()=>{if(ne||I.current||!re||Y)return;I.current=!0,A(!0),M(null);let n=d(6e4),r={outcome:`unconfirmed`,refreshPending:!1};try{let i=await fetch(`${t}/api/custom-models`,{method:`POST`,signal:n.signal,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,modelId:re})});if(i.status===201){let t=await Yn(i),n=ng(t,e.name,re);if(T?.rows.some(e=>e.id===n.id))throw Error(`Reused custom identity`);r={outcome:`saved`,created:n,refreshPending:rg(t)},L.current&&x(``)}else i.status>=400&&i.status<500&&(r={outcome:`rejected`,refreshPending:!1})}catch{}finally{n.clear(),he(r)}},_e=async(e,n)=>{let r=me(e);if(ne||I.current||!r)return;if(I.current=!0,!await Ju({message:m(r===`delete`?`models.customDeleteConfirm`:`models.hideConfirm`,{name:e.namespaced}),confirmLabel:m(r===`delete`?`common.delete`:`common.ok`),tone:`danger`})){I.current=!1;return}A(!0),M(null),V.current={button:n,retained:document.activeElement===n};let i=d(6e4),a={outcome:`unconfirmed`,refreshPending:!1};try{let n=r===`delete`?await fetch(`${t}/api/custom-models/${encodeURIComponent(e.customId)}`,{method:`DELETE`,signal:i.signal}):await sp(t,`models`,e.provider,[{id:e.id,native:e.native===!0}],!1,(e,t)=>fetch(e,{...t,signal:i.signal}));if(n.ok){let e=await Yn(n);e&&typeof e==`object`&&!Array.isArray(e)&&`ok`in e&&e.ok===!0&&(a={outcome:r===`delete`?`deleted`:`hidden`,refreshPending:rg(e)})}else n.status>=400&&n.status<500&&(a={outcome:`rejected`,refreshPending:!1})}catch{}finally{i.clear(),he(a)}},ve=j?.created&&W&&G.some(e=>e.customId===j.created?.id&&e.disabled),ye=j&&(j.refreshPending||c||D===w),be=j?j.outcome===`unconfirmed`?m(`pws.modelMutationUnconfirmed`):j.outcome===`rejected`?m(`models.customSaveFailed`):j.outcome===`saved`?m(ye?`pws.modelSavedRefreshPending`:ve?`pws.modelSavedHidden`:`pws.modelSaved`):m(ye?`pws.modelRemovedRefreshPending`:j.outcome===`deleted`?`pws.modelDefinitionDeleted`:`pws.modelHidden`):null;return(0,Q.jsxs)(`div`,{className:`pws-section`,children:[(0,Q.jsxs)(`div`,{className:`pws-section-head`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:m(`pws.tab.models`)}),i!==null&&(0,Q.jsx)(`span`,{className:`muted`,children:m(`pws.modelsAvailable`,{count:ie.length})})]}),(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsx)(`button`,{ref:B,type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:m(`pws.manageModelVisibility`)})}),l&&(0,Q.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,Q.jsx)(`span`,{children:m(`pws.modelsNeedsReauth`)}),f&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:m(`pws.tab.accounts`)})]}),o&&n.length===0&&ie.length>0&&(e.models?.length??0)>0&&!l&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:m(`pws.modelsConfiguredFallback`)}),te&&(0,Q.jsx)(`p`,{role:`status`,className:`muted`,children:m(`pws.modelSelectionPending`)}),(0,Q.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:m(`models.customAdd`)}),(0,Q.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,Q.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:y,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ge()},placeholder:m(`models.customFieldModelIdPlaceholder`),"aria-label":m(`models.customAdd`),disabled:k}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{ge()},disabled:ne||!re||Y,children:m(k?`models.customSaving`:`models.customAddBtn`)})]}),Y&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:m(`pws.modelKnown`)}),be&&(0,Q.jsx)(`p`,{className:j?.outcome===`unconfirmed`||j?.outcome===`rejected`?`pws-inline-error`:`muted text-label`,role:j?.outcome===`unconfirmed`||j?.outcome===`rejected`?`alert`:`status`,children:be}),ve&&ye&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:m(`pws.modelSavedHidden`)}),j?.refreshPending&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:m(`codexAuth.catalogRefreshPending`)}),c||D===w?(0,Q.jsxs)(`div`,{className:`pws-inline-error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:m(c?`pws.modelsLoadFailed`:`pws.modelOwnershipFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:de,disabled:k,children:m(`common.retry`)})]}):(!U||ee)&&(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:m(!o||s?`pws.modelsLoading`:`pws.modelOwnershipLoading`)}),j&&(j.outcome===`unconfirmed`||j.refreshPending)&&!c&&D!==w&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:de,disabled:k,children:m(`common.retry`)}),ae&&(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsx)(Rn,{on:_,onClick:()=>v(!_),label:m(`models.freeOnly`),showLabel:!0})}),(0,Q.jsx)(`input`,{ref:z,type:`search`,className:`input pws-model-search`,placeholder:m(`pws.modelSearchPlaceholder`),value:h,onChange:e=>g(e.target.value),"aria-label":m(`pws.modelSearchPlaceholder`)}),i!==null&&ie.length===0?(0,Q.jsx)(`p`,{className:`muted`,children:m(`pws.noModels`)}):le.length===0&&i!==null?(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:m(oe&&se.length===0?`models.noFreeMatch`:`pws.noModelMatch`)}):(0,Q.jsx)(`ul`,{className:`pws-model-list`,children:le.slice(0,Jg).map(t=>(0,Q.jsx)(qg,{row:t,disambiguate:(ue.get(t.id)??0)>1,copied:N===t.namespaced,isDefault:t.id===e.defaultModel,selected:t.native!==!0&&q.has(t.id),action:me(t),disabled:ne,onCopy:()=>{fe(t)},onRemove:e=>{_e(t,e)}},t.namespaced))}),le.length>Jg&&(0,Q.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:m(`pws.modelsTruncated`,{shown:String(Jg),total:String(le.length)})})]})}function Zg({item:e,usageTotals:t,quotaReport:n,currentQuotaReading:r,quotaIdentity:i,modelUsage:a,onRefreshQuota:o}){let c=b(),{locale:l}=s(),u=t?.requests!==void 0,[d,f]=(0,Z.useState)(null),p=(0,Z.useMemo)(()=>a?.length?a.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[a]),m=(0,Z.useMemo)(()=>{if(!p.length)return;let e=0,t=!1;for(let n of p)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[p]);return(0,Q.jsxs)(`div`,{className:`pws-section`,children:[(0,Q.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:c(`pws.usageLast30d`)}),u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":c(`pws.usageLast30d`),children:[(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:$m(m,l)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:c(`pws.estimatedCost`)})]}),(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value`,children:Zm(t?.requests,l)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:c(`pws.metricRequests`)})]}),(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value`,children:Qm(t?.totalTokens,l)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:c(`pws.metricTokens`)})]})]}),(0,Q.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:c(`pws.costDisclaimer`)})]}):(0,Q.jsx)(`p`,{className:`muted`,children:c(`pws.usageUnavailable`)})]}),p.length>0&&(0,Q.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:c(`pws.modelBreakdown`)}),(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`pws-model-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:c(`pws.col.model`)}),(0,Q.jsx)(`th`,{className:`num`,children:c(`pws.col.cost`)}),(0,Q.jsx)(`th`,{className:`num`,children:c(`pws.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:c(`pws.col.requests`)}),(0,Q.jsx)(`th`,{children:c(`pws.col.share`)})]})}),(0,Q.jsx)(`tbody`,{children:p.map(e=>{let t=e.model,n=d===t;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,Q.jsxs)(`td`,{className:`mono`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>f(n?null:t),children:e.model}),e.hasUnresolvedRequestedModel&&(0,Q.jsx)(`div`,{className:`muted pws-model-attribution`,children:c(`pws.unresolvedRequestedModel`)})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:$m(e.estimatedCostUsd,l)}),(0,Q.jsx)(`td`,{className:`num mono`,children:Qm(e.totalTokens,l)}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`pws-share-bar`,children:(0,Q.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,Q.jsx)(`tr`,{className:`pws-model-detail`,children:(0,Q.jsx)(`td`,{colSpan:5,children:(0,Q.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:c(`pws.tokenInput`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[` `,Qm(e.inputTokens,l)]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:c(`pws.tokenOutput`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[` `,Qm(e.outputTokens,l)]})]})]})})})]},t)})})]})})]}),(0,Q.jsx)(hg,{report:n,reading:r,onRefreshQuota:o},`${e.name}:${i??``}`)]})}function Qg(e){if(typeof e!=`string`)return;let t=e.trim();return t.length<=64&&/^[a-z0-9_.-]+$/.test(t)?t:void 0}var $g=[`pro`,`max_5x`,`max_20x`,`team`,`enterprise`,`ultra`];function e_(e){let t=Qg(e===`Ultra`?`ultra`:e);if(!t)return;let n=t.replace(/^(?:default_)?claude_/,``);return $g.some(e=>e===n)?n:t}function t_(e){let t=e_(e);switch(t){case`pro`:return`Pro`;case`max_5x`:return`Max 5x`;case`ultra`:case`max_20x`:return`Ultra`;case`team`:return`Team`;case`enterprise`:return`Enterprise`;default:return t}}var n_={oauth_organization_disabled:`accountPause.reason.organizationDisabled`,account_permission_denied:`accountPause.reason.permissionDenied`,subscription_inactive:`accountPause.reason.subscriptionInactive`,subscription_expired:`accountPause.reason.subscriptionExpired`,plan_downgraded:`accountPause.reason.planDowngraded`};function r_(e,t,n){let r=Object.hasOwn(n_,n.reason)?e(n_[n.reason]):e(`codexAuth.paused`),i=new Date(n.pausedAt);return Number.isNaN(i.getTime())?r:e(`accountPause.tooltip`,{reason:r,date:i.toLocaleString(t)})}var i_=Object.freeze({"kimi-responses":`kimi`});function a_(e){return Object.hasOwn(i_,e)?i_[e]:e}function o_(e,t){return e!==t&&Object.hasOwn(i_,e)&&i_[e]===t}function s_(e){return Object.keys(i_).filter(t=>i_[t]===e)}var c_={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,anthropic2:`Anthropic · Pool 2`,kimi:`Kimi (Moonshot)`,"meta-muse":`Meta Muse Code (CLI)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`,zed:`Zed Hosted AI`,devin:`Devin`,"dsh-account":`DeepSeek Account (DSH)`,"workbuddy-ai":`WorkBuddy AI`},l_=e=>c_[e]??e;function u_(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function d_(e){return u_(e)??`account-…`}function f_(e,t,n,r,i=1){let a=e.trim(),o=a===``?NaN:Number(a),s=Math.min(r,Math.max(n,(Number.isFinite(o)?o:n)+t));return String(i<1?Math.round(s*10)/10:Math.round(s))}function p_({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,Q.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,Q.jsx)(ot,{width:10,height:10,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Q.jsx)(Ot,{width:10,height:10,"aria-hidden":`true`})})]})}function m_({accountLabel:e,globalThreshold:t,override:n,disabled:r=!1,inputId:i,hintText:a,onChange:o}){let s=b(),c=(0,Z.useRef)(!1),l=(0,Z.useRef)(!1),[u,d]=(0,Z.useState)(!1),f=n!==null,[p,m]=(0,Z.useState)({override:n,draft:String(n??t)});p.override!==n&&m({override:n,draft:String(n??t)});let{draft:h}=p,g=e=>m(t=>({...t,draft:e})),_=()=>m(e=>({...e,draft:String(e.override??t)})),v=r||u,y=a??s(`accountPool.autoSwitchHint`),x=(0,Z.useId)(),S=async e=>{if(!(r||l.current)){l.current=!0,d(!0);try{await o(e)}finally{_(),l.current=!1,d(!1)}}},C=async()=>{if(!f||r||l.current)return;let e=h.trim(),t=e===``?NaN:Number(e);!Number.isInteger(t)||t<0||t>100?_():t!==n&&await S(t)},w=e=>{if(r||l.current)return;let t=f_(h,e,0,100);g(t);let i=Number(t);i!==n&&S(i)};return(0,Q.jsxs)(`div`,{className:`codex-account-auto-switch`,title:y,"aria-busy":u,"aria-disabled":v,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(c.current?c.current=!1:C())},children:[(0,Q.jsx)(`label`,{className:`codex-account-auto-switch-label`,htmlFor:f?i:void 0,children:s(`accountPool.autoSwitchThreshold`)}),f&&(0,Q.jsxs)(`span`,{className:`codex-account-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{id:i,className:`input mono codex-auto-switch-input codex-account-auto-switch-input`,type:`number`,min:0,max:100,step:1,inputMode:`numeric`,value:h,readOnly:v,"aria-disabled":v,"aria-label":s(`accountPool.autoSwitchThresholdAria`,{email:e}),"aria-describedby":x,onChange:e=>{v||g(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),C()):e.key===`Escape`&&(e.preventDefault(),_()))}}),(0,Q.jsx)(`span`,{className:`codex-account-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(p_,{disabled:r&&!u,incrementLabel:s(`codexAuth.autoSwitchThresholdInc`),decrementLabel:s(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>w(1),onDecrement:()=>w(-1)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle codex-account-auto-switch-toggle ${f?`on`:``}`,disabled:r&&!u,"aria-disabled":v,"aria-pressed":f,"aria-label":s(`accountPool.autoSwitchOverrideAria`,{email:e}),"aria-describedby":x,onPointerDownCapture:()=>{c.current=!0},onPointerUp:()=>{c.current=!1},onPointerCancel:()=>{c.current=!1},onClick:()=>{c.current=!1,S(f?null:t)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:x,className:`sr-only`,children:y})]})}function h_(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function g_(e){let t=h_(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function __(e){return e===`reauth_required`}function v_(e){return!!e?.needsReauth||__(e?.health?.status)}function y_(e){return e===`cooldown`}function b_(e){return e===`warning`||e===`reauth_required`}function x_(e){if(!e||e.status===`healthy`)return null;if(e.status===`cooldown`)return e.reason===`rate_limit`?`pws.healthLabel.rateLimited`:`pws.healthLabel.quotaLimited`;if(e.status===`reauth_required`)return e.reason===`refresh_failed`?`pws.healthLabel.refreshFailed`:`pws.healthLabel.reauthRequired`;switch(e.reason){case`validation_pending`:return`pws.healthLabel.validationPending`;case`refresh_conflict`:return`pws.healthLabel.credentialConflict`;case`metadata_mismatch`:return`pws.healthLabel.metadataMismatch`;case`stale_credentials`:return`pws.healthLabel.refreshFailed`;default:return`pws.healthLabel.reauthRequired`}}function S_(e,t){let n=x_(t);return n?e(n):null}function C_(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):d_(n);if(r.status===`cooldown`){let n=r.until?new Date(r.until).toLocaleString():``;return e(r.reason===`rate_limit`?`pws.healthSummary.rateLimited`:`pws.healthSummary.quotaLimited`,{provider:t,account:i,until:n})}return r.status===`reauth_required`?e(`pws.healthSummary.reauthRequired`,{provider:t,account:i}):r.reason===`validation_pending`?e(`pws.healthSummary.validationPending`,{provider:t,account:i}):r.reason===`refresh_conflict`?e(`pws.healthSummary.credentialConflict`,{provider:t,account:i}):r.reason===`metadata_mismatch`?e(`pws.healthSummary.metadataMismatch`,{provider:t,account:i}):e(`pws.healthSummary.staleCredentials`,{provider:t,account:i})}async function w_(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return T_(e)}function T_(e){if(typeof document>`u`||typeof document.execCommand!=`function`)return!1;let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.setAttribute(`aria-hidden`,`true`),t.style.position=`fixed`,t.style.top=`0`,t.style.opacity=`0`,document.body.appendChild(t);try{return t.select(),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}}function E_(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}function D_({title:e,meta:t,actions:n,children:r,className:i,bodyClassName:a,labelledBy:o,as:s=`section`}){let c=(0,Z.useId)(),l=o??c;return(0,Q.jsxs)(s,{className:X(`acc-panel flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,i),"aria-labelledby":e?l:void 0,children:[(e||n)&&(0,Q.jsxs)(`div`,{className:`flex min-h-11 flex-wrap items-center gap-x-3 gap-y-2 px-3 py-1.5`,children:[e&&(0,Q.jsxs)(`h3`,{id:l,className:`m-0 flex min-w-0 items-baseline gap-2 text-[14px] leading-5 font-semibold tracking-[-0.01em] text-fg`,children:[e,t!=null&&(0,Q.jsx)(`span`,{className:`text-[12px] font-normal text-fg-subtle tabular-nums`,children:t})]}),n&&(0,Q.jsx)(`div`,{className:`ml-auto flex flex-wrap items-center justify-end gap-1.5`,children:n})]}),(0,Q.jsx)(`div`,{className:X(`acc-panel__body flex min-w-0 flex-col rounded-[8px] bg-bg ring-1 ring-line`,a),children:r})]})}var O_={info:`text-fg-muted`,warn:`text-warning`,err:`text-danger`,ok:`text-success`};function k_({tone:e=`info`,children:t,action:n,role:r,className:i}){let a=e===`ok`?st:e===`info`?He:St;return(0,Q.jsxs)(`div`,{role:r,className:X(`acc-banner flex min-w-0 items-start gap-2.5 rounded-[10px] bg-raised px-3 py-2.5 text-[13px] leading-[18px] text-fg ring-1 ring-line`,e===`warn`&&`acc-banner--warn`,e===`err`&&`acc-banner--err`,i),children:[(0,Q.jsx)(`span`,{className:X(`mt-px shrink-0 [&_svg]:size-4`,O_[e]),"aria-hidden":`true`,children:(0,Q.jsx)(a,{})}),(0,Q.jsx)(`div`,{className:`min-w-0 flex-1 [overflow-wrap:anywhere]`,children:t}),n&&(0,Q.jsx)(`div`,{className:`-my-1 flex shrink-0 flex-wrap items-center gap-1.5`,children:n})]})}function A_({tone:e}){return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`inline-block size-2 shrink-0 rounded-full`,e===`ok`&&`bg-success`,e===`warn`&&`bg-warning`,e===`err`&&`bg-danger`,e===`idle`&&`bg-fg-subtle`,e===`active`&&`bg-fg`)})}function j_({open:e,controls:t,name:n,onToggle:r,className:i}){let a=b()(`accountsV2.about`,{name:n});return(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":e,"aria-controls":t,"aria-label":a,title:a,onClick:r,className:X(`acc-help-btn ui-v2 inline-grid size-6 shrink-0 cursor-pointer place-items-center rounded-full text-fg-subtle transition-colors`,`hover:bg-surface-2 hover:text-fg focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,e&&`bg-surface-2 text-fg`,`[&_svg]:size-[15px]`,i),children:(0,Q.jsx)(He,{"aria-hidden":`true`})})}function M_({id:e,open:t,children:n,className:r}){return(0,Q.jsx)(`div`,{id:e,hidden:!t,className:X(`acc-help rounded-[8px] bg-surface-2/60 px-3 py-2.5 text-[13px] leading-[19px] text-fg-muted`,r),children:n})}function N_(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t===127})}function P_(e,t){let n=e.trim();return n.length>80||N_(n)?t(`prov.aliasInvalid`):null}var F_=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,deviceCode:``,instructions:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function I_(e,t){switch(t.type){case`set-step`:return{...e,step:t.step};case`set-id`:return{...e,id:t.id};case`set-error`:return{...e,error:t.error};case`set-auth-url`:return{...e,authUrl:t.authUrl};case`set-login-hint`:return{...e,authUrl:t.authUrl,deviceCode:t.deviceCode??``,instructions:t.instructions??``,browserLaunch:t.browserLaunch};case`set-manual-code`:return{...e,manualCode:t.manualCode};case`set-manual-code-state`:return{...e,manualCodeState:t.manualCodeState};case`set-status-notice`:return{...e,statusNotice:t.statusNotice,statusTone:t.statusTone??e.statusTone};case`set-flow-id`:return{...e,flowId:t.flowId};case`clear-manual-code`:return{...e,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`};case`reset-oauth-start`:return{...e,error:``,statusNotice:``,statusTone:`ok`,flowId:null,browserLaunch:void 0};case`oauth-code-submitted`:return{...e,error:``,manualCode:``,manualCodeState:`waiting`,statusTone:`ok`,statusNotice:``};default:return e}}function L_({id:e,error:t,onIdChange:n,onStartOAuth:r,onStartDeviceOAuth:i,onClose:a}){let o=b();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{style:{marginBottom:4},children:o(`codexAuth.addTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o(`codexAuth.addPickDesc`)}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:o(`codexAuth.addIdLabel`)}),(0,Q.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:o(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,Q.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Q.jsx)(at,{width:20}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:o(`codexAuth.oauthLogin`)}),(0,Q.jsx)(`div`,{className:`sub`,children:o(`codexAuth.oauthDesc`)})]})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`list-row`,onClick:i,style:{marginBottom:8},children:(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Q.jsx)(ue,{width:20}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:o(`codexAuth.deviceLogin`)}),(0,Q.jsx)(`div`,{className:`sub`,children:o(`codexAuth.deviceDesc`)})]})]})}),t&&(0,Q.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,style:{width:`100%`},children:o(`codexAuth.cancel`)})]})}var R_=2500;function z_(){let[e,t]=(0,Z.useState)(null),n=(0,Z.useRef)(null),r=(0,Z.useRef)(0),i=(0,Z.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,Z.useEffect)(()=>i,[i]),{outcomeFor:(0,Z.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,Z.useCallback)((e,a)=>{let o=++r.current;w_(e).then(e=>{r.current===o&&(i(),t({scope:a,outcome:e?`copied`:`unavailable`}),n.current=setTimeout(()=>{n.current=null,r.current===o&&t(null)},R_))})},[i])}}function B_(e){try{let t=new URL(e).protocol;return t===`https:`||t===`http:`}catch{return!1}}function V_({url:e,openLabel:t}){let n=b(),{outcomeFor:r,copy:i}=z_();if(!e)return null;let a=r(e),o=n(a===`copied`?`prov.linkCopied`:a===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`),s=B_(e);return(0,Q.jsxs)(`div`,{className:`login-url-block`,children:[(0,Q.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,Q.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(e,e),children:[(0,Q.jsx)(ue,{style:{width:13,height:13},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{"aria-live":`polite`,children:o})]}),s&&(0,Q.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,Q.jsx)(dt,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t??n(`prov.didntOpen`)]})]})]})}function H_({hint:e,paste:t}){let n=b(),r=z_(),i=e.deviceCode??``,a=e.url??``;if(!i&&!a&&!e.instructions&&!t)return null;let o=r.outcomeFor(i),s=n(o===`copied`?`prov.codeCopied`:o===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),c=i||e.browserLaunch===`skipped`?n(`prov.openSignInPage`):void 0,l=i&&B_(a)?()=>{r.copy(i,i),window.open(a,`_blank`,`noopener,noreferrer`)}:null;return(0,Q.jsxs)(`div`,{className:`login-hint`,children:[e.browserLaunch===`failed`&&a&&(0,Q.jsx)(`div`,{className:`notice-warn login-hint-launch-failed`,role:`status`,children:n(`prov.browserLaunchFailed`)}),i&&(0,Q.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,Q.jsx)(`span`,{className:`text-label`,children:n(`prov.deviceCode`)}),(0,Q.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:i}),(0,Q.jsx)(`button`,{type:`button`,className:l?`btn btn-ghost btn-sm`:`btn btn-primary btn-sm`,onClick:()=>r.copy(i,i),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:s})}),l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm login-hint-copy-open`,onClick:l,children:n(`prov.copyCodeAndOpen`)})]}),(0,Q.jsx)(V_,{url:a,openLabel:c}),e.instructions&&(0,Q.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&!i&&(0,Q.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:n(`prov.pasteRedirectHint`)}),(0,Q.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,Q.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:t.value,onChange:e=>t.onChange(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),t.onSubmit())},placeholder:n(`prov.pasteRedirect`),"aria-label":n(`prov.pasteRedirect`),disabled:t.busy,className:`input text-label login-hint-paste-input`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:t.busy||t.disabled===!0||!t.value.trim(),onClick:t.onSubmit,children:t.busy?t.submittingLabel??n(`prov.pasteSubmitting`):n(`prov.pasteSubmit`)})]}),t.message&&(0,Q.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function U_({reauthAccountId:e,authUrl:t,deviceCode:n,instructions:r,browserLaunch:i,manualCode:a,manualCodeBusy:o,manualCodeWaiting:s,statusNotice:c,statusTone:l,flowId:u,error:d,onSwitchToDevice:f,onManualCodeChange:p,onSubmitManualCode:m,onClose:h}){let g=b();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{style:{marginBottom:4},children:g(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:g(`codexAuth.oauthWaiting`)}),(0,Q.jsx)(H_,{hint:{url:t,deviceCode:n,instructions:r,browserLaunch:i},paste:{value:a,busy:o,disabled:o||s||!a.trim()||!u,submittingLabel:g(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:p,onSubmit:m}}),c&&(0,Q.jsx)(`div`,{className:l===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:c}),d&&(0,Q.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:d}),f&&!n&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,style:{width:`100%`,marginTop:8},children:g(`codexAuth.deviceLogin`)}),(0,Q.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,Q.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:h,style:{width:`100%`},children:g(`codexAuth.cancel`)})]})}var W_=`ocx.oauth.openBrowser`;function G_(){try{let e=window.localStorage.getItem(W_);return e===`0`?!1:e===`1`||void 0}catch{return}}function K_(){let e=G_();return e===void 0?{}:{openBrowser:e}}function q_(e){try{window.localStorage.setItem(W_,e?`1`:`0`)}catch{}}function J_(e){return e===`started`||e===`failed`||e===`skipped`?e:void 0}function Y_(e,t){let n=t||e,r=`${n}\u0000${e}`,i=()=>typeof window>`u`?{apiBase:e,targetKey:n,origin:``,requestGeneration:0,transport:`same-origin`}:V(`shared`,e),[a,o]=(0,Z.useState)(()=>({identity:r,capture:i()}));return a.identity!==r&&o({identity:r,capture:i()}),a.capture}function X_(e){if(typeof e!=`object`||!e||Array.isArray(e))return{catalogRefreshPending:!1};let t=Object.getOwnPropertyDescriptor(e,`catalogRefreshPending`),n=Object.getOwnPropertyDescriptor(e,`validationPending`);return{...n&&`value`in n&&n.value===!0?{validationPending:!0}:{},catalogRefreshPending:t!==void 0&&`value`in t&&t.value===!0}}var Z_=3e5,Q_=96e4;function $_({apiBase:e,targetKey:t,reauthAccountId:n,ui:r,dispatch:a,t:o}){let s=Y_(e,t),c=(0,Z.useRef)(!0),l=(0,Z.useRef)(0),u=(0,Z.useRef)(!1),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(0),_=(0,Z.useRef)(r.manualCodeState),y=(0,Z.useRef)(null),b=(0,Z.useRef)(null),x=(0,Z.useRef)(()=>{}),S=(0,Z.useRef)(()=>{}),C=r.manualCodeState===`submitting`,w=r.manualCodeState===`waiting`;(0,Z.useEffect)(()=>{_.current=r.manualCodeState},[r.manualCodeState]),(0,Z.useEffect)(()=>{m.current=r.flowId},[r.flowId]);let T=(0,Z.useCallback)(()=>{d.current&&=(d.current(),null),f.current&&=(clearTimeout(f.current),null),p.current?.abort(),p.current=null,u.current=!1},[]),E=(0,Z.useCallback)(()=>{a({type:`clear-manual-code`}),l.current=0},[a]),D=(0,Z.useCallback)(async()=>{g.current+=1,E();let e=m.current,t=h.current;m.current=null,h.current=null,a({type:`set-flow-id`,flowId:null}),a({type:`set-login-hint`,authUrl:``}),T(),y.current?.abort(),y.current=null,e&&t&&await i(t,`${t.apiBase}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:e})}).catch(()=>{})},[E,a,T]);(0,Z.useEffect)(()=>(c.current=!0,()=>{E(),c.current=!1,b.current=null,y.current?.abort(),y.current=null,g.current+=1;let e=m.current,t=h.current;m.current=null,h.current=null,a({type:`set-flow-id`,flowId:null}),T(),e&&t&&i(t,`${t.apiBase}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:e})}).catch(()=>{})}),[E,a,T]);let O=(0,Z.useCallback)((e,t)=>{x.current=e,S.current=t},[]),k=(0,Z.useCallback)(()=>{r.step===`oauth-waiting`&&D(),S.current()},[r.step,D]),A=(0,Z.useCallback)(async(e,t)=>{E(),m.current=null,h.current=null,a({type:`set-flow-id`,flowId:null});let r={...s},b=++g.current,C=new AbortController;y.current?.abort(),y.current=C,a({type:`reset-oauth-start`}),l.current=0;let w=()=>c.current&&g.current===b&&v(r);try{let s=n??e?.trim()??``,v=t?.device===!0,y=()=>i(r,`${r.apiBase}/api/codex-auth/login`,{signal:C.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...K_(),...v?{device:!0}:{},...n?{id:n,reauth:!0}:s?{id:s}:{}})}),b=await y();if(!w())return;if(b.status===409){if(await i(r,`${r.apiBase}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),!w()||C.signal.aborted)return;if(b=await y(),b.status===409){a({type:`set-error`,error:o(`codexAuth.oauthAlreadyInProgress`)});return}}let O=await Yn(b,o(`modal.networkError`));if(!w()||!O)return;if(O.url){m.current=O.flowId??null,h.current=r,a({type:`set-flow-id`,flowId:O.flowId??null}),a({type:`set-login-hint`,authUrl:O.url,deviceCode:O.deviceCode,instructions:O.instructions,browserLaunch:J_(O.browserLaunch)}),a({type:`set-step`,step:`oauth-waiting`}),T();let e=O.flowId??``,t=n?`&reauth=1`:``,y=e?`${r.apiBase}/api/codex-auth/login-status?flowId=${encodeURIComponent(e)}${s?`&accountId=${encodeURIComponent(s)}`:``}${t}`:`${r.apiBase}/api/codex-auth/login-status`,b=new AbortController;p.current=b,d.current=$u(async()=>{if(u.current||b.signal.aborted||p.current!==b)return;if(!w()){T();return}u.current=!0;let e=AbortSignal.any([b.signal,AbortSignal.timeout(1e4)]);try{let t=await Xn(await i(r,y,{signal:e}));if(p.current!==b||b.signal.aborted)return;if(!w()){T();return}if(!t){l.current+=1,l.current>=3&&a({type:`set-status-notice`,statusNotice:o(`codexAuth.oauthStatusRetrying`),statusTone:`warn`});return}l.current=0,_.current===`waiting`?a({type:`set-status-notice`,statusNotice:o(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}):a({type:`set-status-notice`,statusNotice:``,statusTone:`ok`}),t.status===`done`?(T(),E(),m.current=null,h.current=null,a({type:`set-flow-id`,flowId:null}),x.current(X_(t)),S.current(),g.current+=1):(t.status===`error`||t.status===`expired`)&&(T(),E(),m.current=null,h.current=null,g.current+=1,a({type:`set-flow-id`,flowId:null}),n||a({type:`set-step`,step:`pick`}),a({type:`set-error`,error:t.error??o(`codexAuth.loginFailed`)}))}catch(e){if(!c.current||b.signal.aborted||e instanceof Error&&e.name===`AbortError`)return;l.current+=1,l.current>=3&&a({type:`set-status-notice`,statusNotice:o(`codexAuth.oauthStatusRetrying`),statusTone:`warn`})}finally{u.current=!1}},2e3),f.current=setTimeout(()=>{d.current&&(E(),D(),c.current&&(n||a({type:`set-step`,step:`pick`}),a({type:`set-error`,error:o(`modal.loginTimeout`)})))},v?Q_:Z_)}O.error&&!O.url&&a({type:`set-error`,error:O.error})}catch(e){w()&&!(e instanceof Error&&e.name===`AbortError`)&&a({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[D,E,a,n,s,T,o]);return(0,Z.useEffect)(()=>{n?b.current!==n&&(b.current=n,A()):b.current=null},[n,A]),{manualCodeBusy:C,manualCodeWaiting:w,bindCallbacks:O,closeModal:k,startOAuth:A,submitManualCode:(0,Z.useCallback)(async()=>{let e=m.current,t=h.current,n=r.manualCode.trim();if(e&&t&&n&&!C&&!w){if(!v(t))a({type:`set-error`,error:o(`prov.targetChanged`)});else{a({type:`set-manual-code-state`,manualCodeState:`submitting`}),a({type:`set-status-notice`,statusNotice:``,statusTone:`ok`});try{let r=await i(t,`${t.apiBase}/api/codex-auth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:e,input:n})});if(!c.current)return;if(!v(t)){a({type:`set-error`,error:o(`prov.targetChanged`)}),a({type:`set-manual-code-state`,manualCodeState:`idle`});return}if(!r.ok){a({type:`set-error`,error:o(`prov.pasteFail`,{error:(await r.json().catch(()=>({}))).error??r.statusText})}),a({type:`set-manual-code-state`,manualCodeState:`idle`});return}a({type:`oauth-code-submitted`}),a({type:`set-status-notice`,statusNotice:o(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}),l.current=0}catch{c.current&&(a({type:`set-error`,error:o(`modal.networkError`)}),a({type:`set-manual-code-state`,manualCodeState:`idle`}))}}}},[a,C,w,o,r.manualCode])}}function ev({apiBase:e,targetKey:t,onClose:n,onAdded:r,reauthAccountId:i}){let a=b(),[o,s]=(0,Z.useReducer)(I_,i,F_),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),{manualCodeBusy:u,manualCodeWaiting:d,bindCallbacks:f,closeModal:p,startOAuth:m,submitManualCode:h}=$_({apiBase:e,targetKey:t,reauthAccountId:i,ui:o,dispatch:s,t:a});(0,Z.useEffect)(()=>{f(r,n)},[f,r,n]),(0,Z.useEffect)(()=>{c.current=document.activeElement;let e=l.current;e&&!e.open&&e.showModal();let t=e?.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);return t&&t.focus(),()=>{c.current?.focus()}},[]);let g=(0,Z.useCallback)(e=>{e.preventDefault(),p()},[p]),_=a(i?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,Q.jsx)(`dialog`,{ref:l,"aria-label":_,className:`modal-overlay`,onCancel:g,children:(0,Q.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[o.step===`pick`&&(0,Q.jsx)(L_,{id:o.id,error:o.error,onIdChange:e=>s({type:`set-id`,id:e}),onStartOAuth:()=>{m(o.id)},onStartDeviceOAuth:()=>{m(o.id,{device:!0})},onClose:p}),o.step===`oauth-waiting`&&(0,Q.jsx)(U_,{reauthAccountId:i,authUrl:o.authUrl,deviceCode:o.deviceCode,instructions:o.instructions,browserLaunch:o.browserLaunch,manualCode:o.manualCode,manualCodeBusy:u,manualCodeWaiting:d,statusNotice:o.statusNotice,statusTone:o.statusTone,flowId:o.flowId,error:o.error,onSwitchToDevice:()=>{m(o.id,{device:!0})},onManualCodeChange:e=>s({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{h()},onClose:p})]})})}var tv=[2,1,0,-1,-2],nv=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function rv(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function iv(e){let t=rv(e);return t>0?`+${t}`:String(t)}function av(e){return nv.has(e)}function ov(e){return nv.get(e)??null}function sv(e,t){let n=rv(t);return e(`accountPool.priorityOption`,{name:e(ov(n)??`accountPool.priorityCustom`),value:iv(n)})}var cv=[`quota`,`round-robin`,`fill-first`,`reset-first`],lv=[`five-hour`,`weekly`,`max-utilization`],uv=`quota`,dv=`five-hour`,fv=new Set(cv),pv=new Set(lv);function mv(e){return typeof e==`string`&&fv.has(e)?e:uv}function hv(e){return typeof e==`string`&&pv.has(e)?e:dv}function gv(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function _v(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}var vv=`openai`;function yv(e,t,n){let r=e??{},i=r.autoSwitchThreshold??n?.threshold;return{provider:t,kind:r.kind===`codex`||r.kind===`anthropic`?r.kind:`generic`,supported:Array.isArray(r.supported)?r.supported.filter(e=>typeof e==`string`):[],enabled:typeof r.enabled==`boolean`?r.enabled:null,enabledEffective:r.enabledEffective===!0,strategy:mv(r.strategy??n?.strategy),stickyLimit:gv(r.stickyLimit??n?.stickyLimit),autoSwitchThreshold:typeof i==`number`?i:null,quotaWindow:(r.quotaWindow??n?.quotaWindow)===void 0||r.quotaWindow===null?null:hv(r.quotaWindow??n?.quotaWindow),nativeMessages:fg(t)?Object.hasOwn(r,`nativeMessages`)?r.nativeMessages===!0:n?.nativeMessages??!0:null,...r.warning===`config_bookkeeping_failed`?{warning:r.warning}:{}}}function bv(e,t){return{provider:e,...t.enabled===void 0?{}:{enabled:t.enabled},...t.strategy===void 0?{}:{strategy:t.strategy},...t.stickyLimit===void 0?{}:{stickyLimit:t.stickyLimit},...t.threshold===void 0?{}:{autoSwitchThreshold:t.threshold},...t.quotaWindow===void 0?{}:{quotaWindow:t.quotaWindow},...fg(e)&&t.nativeMessages!==void 0?{nativeMessages:t.nativeMessages}:{}}}async function xv(e,t,n=(e,t)=>fetch(e,t),r){try{let i=await n(`${e}/api/pool/settings?provider=${encodeURIComponent(t)}`,r);return i.ok?yv(await i.json(),t):null}catch{return null}}var Sv=class extends Error{code=`config_save_state_unknown`;constructor(){super(`config_save_state_unknown`),this.name=`PoolSettingsSaveStateUnknownError`}};async function Cv(e,t,n,r=(e,t)=>fetch(e,t),i){try{let a=await r(`${e}/api/pool/settings`,{...i,method:`PUT`,headers:{"Content-Type":`application/json`,...i?.headers??{}},body:JSON.stringify(bv(t,n))});if(!a.ok){if(fg(t)&&a.status===409&&(await a.json().catch(()=>null))?.code===`config_save_state_unknown`)throw new Sv;return null}return yv(await a.json().catch(()=>({})),t,n)}catch(e){if(e instanceof Sv)throw e;return null}}async function wv(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};let r=await Cv(e,vv,{strategy:t.strategy,stickyLimit:t.stickyLimit},n);return r?{ok:!0,strategy:r.strategy,stickyLimit:r.stickyLimit}:{ok:!1}}var Tv=1e4;function Ev(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Dv(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Ov(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function kv(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Av(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function jv(e,t,n){if(e<=0){let t=Ov(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Dv(t)??Ov(0,n)}}async function Mv(e,t,n=(e,t)=>fetch(e,t),r=Tv){return!Number.isInteger(t)||t<0||t>100?!1:await Cv(e,vv,{threshold:t},(e,t)=>n(e,t),{signal:AbortSignal.timeout(r)})!==null}var Nv={short:90,long:98};function Pv(e){let t=e&&typeof e==`object`?e:void 0,n=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=100;return t&&n(t.short)&&n(t.long)?{short:t.short,long:t.long}:{...Nv}}function Fv(e,t){return e!==null&&e.epoch===t}var Iv=3e4,Lv=new Map;function Rv(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:null}function zv(e,t=!0,n){let r=n??e,a=Y_(e,n),o=Lv.get(r),[s,c]=(0,Z.useState)(()=>o?.accounts??[]),l=bn(ti(e,`codex`,r),[e,r],async t=>ei(await fetch(`${e}/api/usage?range=30d&surface=codex`,{signal:t}),`account usage load failed`),{enabled:t}),[u,f]=(0,Z.useState)(()=>o?.activeId??null),[p,m]=(0,Z.useState)(()=>o==null?`loading`:`ready`),[h,g]=(0,Z.useState)(!1),[_,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(!1),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(0),[P,F]=(0,Z.useState)(()=>o!=null),[I,L]=(0,Z.useState)(0),R=(0,Z.useRef)(null);R.current===null&&(R.current=new Set);let z=(0,Z.useRef)(null),B=(0,Z.useRef)(0),V=(0,Z.useRef)(null),H=(0,Z.useRef)(null);H.current===null&&(H.current=new Set);let U=(0,Z.useRef)(null),W=(0,Z.useRef)(null),ee=(0,Z.useRef)(!!o?.accounts.length),G=(0,Z.useRef)(o!=null),te=(0,Z.useRef)(r),[ne,K]=(0,Z.useState)(r),[q,J]=(0,Z.useState)(0);ne!==r&&(K(r),J(q+1),c([]),f(null),m(`loading`),g(!1),j(null),F(!1),N(0),y(null),x(null),C(null),T(null),D(null),k(!1));let re=(0,Z.useRef)(r),Y=(0,Z.useRef)(q);(0,Z.useLayoutEffect)(()=>{re.current=r,Y.current=q,V.current=null,U.current=null},[r,q]),(0,Z.useEffect)(()=>{te.current!==r&&(te.current=r,B.current+=1,ee.current=!1,G.current=!1,z.current=null)},[r]);let ie=(0,Z.useRef)(null),ae=(0,Z.useRef)(null),oe=(0,Z.useRef)(null),se=(0,Z.useRef)(null),ce=(0,Z.useRef)(e);(0,Z.useLayoutEffect)(()=>{ce.current=e},[e]);let le=(0,Z.useCallback)(e=>v(e)&&e.apiBase===ce.current,[]),ue=(0,Z.useCallback)(e=>(H.current.add(e),()=>{H.current.delete(e)}),[]),de=(0,Z.useCallback)(()=>U.current?.key===r?Av(U.current.value):void 0,[r]),fe=(0,Z.useCallback)(()=>U.current?.key===r?U.current.value:void 0,[r]),pe=(0,Z.useCallback)(async(t=!1,n={})=>{let o=a,s=r,l=q;if(!le(o)||re.current!==s)return!1;let u=++B.current,p=n.validatePending===!0,h=()=>B.current===u&&le(o)&&re.current===s,_=Lv.get(r)?.accounts.length??0,v=d(p?3e4+12e4*Math.max(1,_):2e4),y=p?{}:null;y&&(R.current.add(y),L(R.current.size)),N(e=>e+1);try{let n=[...H.current],a=new Map;for(let e of n)a.set(e,e.beginActiveRead());!t&&!G.current&&m(`loading`);let l=null,u,d=(async()=>{try{let n=await i(o,`${e}/api/codex-auth/accounts${p?`/refresh`:t?`?refresh=1`:``}`,{method:p?`POST`:`GET`,signal:v.signal});if(!n.ok)throw Error(`account load failed`);let r=await n.json();return h()&&(l=(r.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel,n=Ve(e.quota);return{...e,...t?{logLabel:t}:{},priority:rv(e.priority),autoSwitchThresholdOverride:Rv(e.autoSwitchThresholdOverride),quotaAutoRefresh:e.quotaAutoRefresh??{...n,fiveHourEnabled:!1,weeklyEnabled:!1}}}),c(l),ee.current=l.length>0,G.current=!0,m(`ready`),g(!1)),!0}catch{return!1}})(),_=(async()=>{try{let t=await i(o,`${e}/api/codex-auth/active`,{signal:v.signal});if(!t.ok)throw Error(`active account load failed`);let r=await t.json();if(h()){let e=r.activeCodexAccountId??null,t=V.current;t&&t.staleReadsRemaining>0&&e!==t.id?--t.staleReadsRemaining:(V.current=null,u=e,f(e)),U.current={key:s,value:r},j(typeof r.pinnedAccountId==`string`?r.pinnedAccountId:null);for(let e of n)e.acceptActiveRead(r,a.get(e))}return!0}catch{if(h())for(let e of n)e.rejectActiveRead();return!1}})(),[y,b]=await Promise.all([d,_]);if(!h())return!1;if(y){m(`ready`),G.current=!0;let e=Lv.get(r);return Lv.set(r,{accounts:l??e?.accounts??[],activeId:u===void 0?e?.activeId??null:u}),b}return G.current||m(`error`),g(!0),!1}finally{v.clear(),y&&(R.current.delete(y),L(R.current.size)),Y.current===l&&N(e=>Math.max(0,e-1)),h()&&F(!0)}},[e,r,q,a,le]);(0,Z.useEffect)(()=>{t&&z.current!==r&&(z.current=r,Promise.resolve().then(()=>{pe()}))},[e,r,t,pe]);let me=s.some(e=>e.hasCredential&&!e.quota);(0,Z.useEffect)(()=>{if(!t||!me||I>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{R.current.size===0&&pe(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,me,I,pe]),(0,Z.useEffect)(()=>{if(!(!t||I>0))return $u(()=>{R.current.size===0&&pe()},Iv)},[t,pe,I]);let he=(0,Z.useCallback)(()=>{let e={};return R.current.add(e),L(R.current.size),e},[]),ge=(0,Z.useCallback)(e=>{R.current.delete(e)&&L(R.current.size)},[]),_e=(0,Z.useCallback)(async(t,n)=>{let r=a,o=Y.current;if(o!==q||!le(r))return{ok:!1,reason:`stale`};if(n?.expectedPinnedAccountId&&!s.some(e=>e.id===n.expectedPinnedAccountId||n.expectedPinnedAccountId===`__main__`&&e.isMain))return{ok:!1,reason:`pin_changed`};if(Fv(W.current,o)||Fv(ae.current,o))return{ok:!1,reason:`busy`};let c={epoch:o};W.current=c,y(t??`__main__`);let l=`request`;try{let a=await i(r,`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t,...n?{expectedPinnedAccountId:n.expectedPinnedAccountId}:{}})});if(!a.ok)throw(await a.json().catch(()=>({}))).code===`account_pin_changed`&&(l=`pin_changed`),Error(`account switch failed`);if(!le(r))return{ok:!1,reason:`stale`};let o=(await a.json().catch(()=>({}))).activeCodexAccountId??t;return V.current={id:o??null,staleReadsRemaining:1},f(o??null),j(o??null),pe(),{ok:!0,activeId:o??null}}catch{return t===null&&le(r)&&(V.current=null,await pe()),{ok:!1,reason:l}}finally{W.current===c&&(W.current=null,y(null))}},[s,e,le,pe,a,q]),ve=(0,Z.useCallback)(async(t,n)=>{let r=a;try{return(await i(r,`${e}/api/codex-auth/accounts/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,alias:n.trim()})})).ok?le(r)?(await pe(),{ok:!0}):{ok:!1,reason:`stale`}:{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,le,pe,a]),ye=(0,Z.useCallback)(async(t,n)=>{let r=a,o=Y.current;if(o!==q||!le(r))return{ok:!1,reason:`stale`};if(Fv(ie.current,o))return{ok:!1,reason:`busy`};let s={epoch:o};ie.current=s,x(t);try{let a=await i(r,`${e}/api/codex-auth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,paused:n})});if(!a.ok)return{ok:!1,reason:`request`};if(!le(r))return{ok:!1,reason:`stale`};let o=await a.json().catch(()=>({})),s=o&&typeof o==`object`?o:{};if(c(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,paused:n}:e)),Object.prototype.hasOwnProperty.call(s,`activeCodexAccountId`)){let e=s.activeCodexAccountId??null;V.current={id:e,staleReadsRemaining:1},f(e)}return n&&j(e=>e===t?null:e),pe(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{ie.current===s&&(ie.current=null,x(null))}},[e,le,pe,a,q]),be=(0,Z.useCallback)(async(t,n)=>{let r=a,o=Y.current;if(o!==q||!le(r))return{ok:!1,reason:`stale`};if(Fv(ae.current,o)||Fv(W.current,o))return{ok:!1,reason:`busy`};let s={epoch:o};ae.current=s,C(t);try{let a=await i(r,`${e}/api/codex-auth/accounts/priority`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,priority:n})});if(!a.ok)return{ok:!1,reason:`request`};if(!le(r))return{ok:!1,reason:`stale`};let o=await a.json().catch(()=>({})),s=rv((o&&typeof o==`object`?o:{}).priority??n);return c(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,priority:s}:e)),j(null),V.current=null,pe(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{ae.current===s&&(ae.current=null,C(null))}},[e,le,pe,a,q]),xe=(0,Z.useCallback)(async(t,n)=>{let r=a,o=Y.current;if(o!==q||!le(r))return{ok:!1,reason:`stale`};if(Fv(oe.current,o))return{ok:!1,reason:`busy`};let s={epoch:o};oe.current=s,T(t);try{let a=await i(r,`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,threshold:n})});if(!a.ok)return{ok:!1,reason:`request`};if(!le(r))return{ok:!1,reason:`stale`};let o=await a.json().catch(()=>({})),s=o&&typeof o==`object`?o:{},l=Object.prototype.hasOwnProperty.call(s,`autoSwitchThresholdOverride`)?Rv(s.autoSwitchThresholdOverride):n;return c(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,autoSwitchThresholdOverride:l}:e)),pe(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{oe.current===s&&(oe.current=null,T(null))}},[e,le,pe,a,q]),Se=(0,Z.useCallback)(async(t,n,r)=>{let o=a,s=Y.current;if(s!==q||!le(o))return{ok:!1,reason:`stale`};if(Fv(se.current,s))return{ok:!1,reason:`busy`};let l={epoch:s};se.current=l,D(t);try{return(await i(o,`${e}/api/codex-auth/accounts/credits`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).ok?le(o)?(c(e=>e.map(r)),pe(),{ok:!0}):{ok:!1,reason:`stale`}:{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}finally{se.current===l&&(se.current=null,D(null))}},[e,le,pe,a,q]),Ce=(0,Z.useCallback)((e,t)=>Se(e,{id:e,creditsAfterLimit:t},n=>n.id===e||e===`__main__`&&n.isMain?{...n,creditsAfterLimit:t}:n),[Se]),we=(0,Z.useCallback)(e=>Se(`*`,{all:e},t=>({...t,creditsAfterLimit:e})),[Se]),Te=(0,Z.useCallback)(async()=>{let t=a,n=Y.current;if(n!==q||!le(t))return{ok:!1,reason:`stale`};if(Fv(ie.current,n))return{ok:!1,reason:`busy`};let r={epoch:n};ie.current=r,k(!0);try{let n=await i(t,`${e}/api/codex-auth/accounts/pause-exhausted`,{method:`PUT`});if(!n.ok)return{ok:!1,reason:`request`};if(!le(t))return{ok:!1,reason:`stale`};let r=await n.json().catch(()=>({})),a=r&&typeof r==`object`?r:{},o=new Set(a.pausedAccountIds??[]);if(c(e=>e.map(e=>o.has(e.id)||o.has(`__main__`)&&e.isMain?{...e,paused:!0}:e)),Object.prototype.hasOwnProperty.call(a,`activeCodexAccountId`)){let e=a.activeCodexAccountId??null;V.current={id:e,staleReadsRemaining:1},f(e)}return j(e=>e!==null&&o.has(e)?null:e),pe(),{ok:!0,pausedCount:a.pausedCount??o.size}}catch{return{ok:!1,reason:`request`}}finally{ie.current===r&&(ie.current=null,k(!1))}},[e,le,pe,a,q]),Ee=(0,Z.useCallback)(async t=>{let n=a;try{let r=await i(n,`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`});if(!r.ok)return{ok:!1,reason:`request`};if(!le(n))return{ok:!1,reason:`stale`};let a=X_(await r.json().catch(()=>({})));return await pe(),{ok:!0,...a}}catch{return{ok:!1,reason:`request`}}},[e,le,pe,a]),De=(0,Z.useCallback)(async()=>await pe()?{ok:!0}:{ok:!1,reason:`reload`},[pe]),Oe=u&&u!==`__main__`?s.find(e=>e.id===u):null,ke=s.find(e=>e.isMain),Ae=Oe??ke,je=!Ae?.paused&&v_(Ae);return{accounts:(0,Z.useMemo)(()=>{let e=new Map((l.data?.accounts??[]).map(e=>[e.accountLogLabel,e]));return s.map(t=>{let n=t.isMain?`main`:t.logLabel,r=n?e.get(n):void 0;return r?{...t,usage30d:r}:t})},[s,l.data]),activeId:u,loadState:p,refreshing:M>0,refreshFailed:h,initialLoading:!P,switchingId:_,pauseUpdatingId:b,priorityUpdatingId:S,autoSwitchUpdatingId:w,creditsAfterLimitUpdatingId:E,pausingExhausted:O,activeNeedsReauth:je,activePinnedId:A,load:pe,switchAccount:_e,setAccountPaused:ye,setAccountPriority:be,setAccountAutoSwitchThreshold:xe,setAccountCreditsAfterLimit:Ce,setAllCreditsAfterLimit:we,pauseExhaustedAccounts:Te,saveAlias:ve,removeAccount:Ee,syncAfterAccountAdded:De,pauseRefresh:he,resumeRefresh:ge,subscribeLoadObserver:ue,readLastThreshold:de,readLastActive:fe}}function Bv(e,t,n,r,i){let[a,o]=(0,Z.useState)({apiBase:e,busy:!1}),s=(0,Z.useRef)(null),c=(0,Z.useRef)(0),l=(0,Z.useEffectEvent)((e,t)=>{i?.onRead(e,t)}),u=i?.revision??0,f=(0,Z.useRef)(null);a.apiBase!==e&&o({apiBase:e,busy:!1});let p=a.apiBase===e?a.visible:void 0,m=a.apiBase===e&&a.busy;return(0,Z.useEffect)(()=>{let e=new AbortController;return s.current=e,()=>{e.abort(),f.current?.abort(),f.current=null}},[e]),(0,Z.useEffect)(()=>{let t=new AbortController,n=d(15e3),r=c.current,i=fetch(`${e}/api/settings`,{signal:n.signal}).then(e=>{if(!e.ok)throw Error(`read`);return e.json()});return l(i,t.signal),i.then(n=>{t.signal.aborted||f.current||c.current!==r||n&&typeof n==`object`&&`showCodexCredits`in n&&typeof n.showCodexCredits==`boolean`&&o({apiBase:e,visible:n.showCodexCredits,busy:!1})}).catch(()=>{}).finally(()=>n.clear()),()=>{t.abort(),n.controller.abort(),n.clear()}},[e,u]),{visible:p,busy:m,toggle:async()=>{let i=s.current;if(p===void 0||m||f.current||!i||i.signal.aborted)return;let a=new AbortController;f.current=a;let l=d(15e3),u=()=>l.controller.abort();a.signal.addEventListener(`abort`,u,{once:!0});let h=()=>s.current===i&&!i.signal.aborted,g=!p;c.current+=1,o({apiBase:e,visible:g,busy:!0});try{let i;try{let t=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:l.signal,body:JSON.stringify({showCodexCredits:g})});if(!t.ok)throw Error(`save`);let n=await t.json();if(typeof n?.showCodexCredits!=`boolean`)throw Error(`shape`);i=n.showCodexCredits}catch{h()&&(o({apiBase:e,visible:p,busy:!1}),n(r(`codexAuth.creditsToggleFailed`),`err`));return}if(!h())return;o({apiBase:e,visible:i,busy:!0}),n(r(i?`codexAuth.creditsShown`:`codexAuth.creditsHidden`),`ok`);try{let e=await t(!0);h()&&!e&&n(r(`codexAuth.quotaRefreshFailed`),`err`)}catch{h()&&n(r(`codexAuth.quotaRefreshFailed`),`err`)}}finally{l.clear(),a.signal.removeEventListener(`abort`,u),h()&&(f.current=null,o(e=>({...e,busy:!1})))}}}}var Vv=`https://auth.openai.com/codex/device`,Hv=2e3,Uv=1e4,Wv=new Set([`identity_mismatch`,`credential_changed`,`native_main_unavailable`,`device_authorization_failed`,`publication_failed`,`reconciliation_failed`,`flow_in_progress`]);function Gv(e){return typeof e==`string`&&Wv.has(e)?e:`request_failed`}function Kv(e){return typeof e==`string`&&e.startsWith(Vv)?e:``}function qv(e){return typeof e==`string`&&/^[A-Z0-9-]{1,16}$/i.test(e)?e:``}function Jv(e,t,n){let r=Y_(e,n),a=n??e,[o,s]=(0,Z.useState)({phase:`idle`}),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(a),[h,g]=(0,Z.useState)(a);h!==a&&(g(a),s({phase:`idle`}));let _=(0,Z.useCallback)(()=>{f.current?.abort(),f.current=null},[]);(0,Z.useEffect)(()=>{if(m.current===a)return;m.current=a;let e=c.current,t=l.current;c.current=null,l.current=null,u.current=null,d.current=null,_(),e&&t&&i(t,`${t.apiBase}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(e)}`,{method:`DELETE`}).catch(()=>{})},[a,_]);let y=(0,Z.useCallback)(async()=>{let e=c.current,n=l.current;if(!e||!n)_(),c.current=null,l.current=null,s({phase:`idle`});else{u.current=e;try{let r=await i(n,`${n.apiBase}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(e)}`,{method:`DELETE`}),a=await r.json().catch(()=>({}));if(p.current||c.current!==e)return;if(!v(n)||r.status===409&&a.error===`target_changed`||r.status===404&&a.code===`unknown_flow`){_(),c.current=null,l.current=null,s({phase:`failed`,code:`request_failed`});return}if(!r.ok||a.status!==`cancelled`&&a.status!==`succeeded`&&a.status!==`failed`)throw Error();_(),c.current=null,l.current=null,s(a.status===`failed`?{phase:`failed`,code:Gv(a.code)}:{phase:a.status}),a.status===`succeeded`&&t()}catch{if(p.current||c.current!==e)return;s(t=>{if(p.current||c.current!==e)return t;let n=t.phase===`pending`||t.phase===`committing`?t:d.current;return n?.flowId===e?{...n,cancelFailed:!0}:t})}}},[t,_]),b=(0,Z.useCallback)(async()=>{_(),c.current=null,l.current=null,u.current=null,d.current=null;let e={...r},n=new AbortController;f.current=n;let a=()=>!n.signal.aborted&&!p.current&&f.current===n&&v(e);s({phase:`starting`});let o;try{let t=await i(e,`${e.apiBase}/api/codex-auth/main/reauth-device`,{method:`POST`,signal:n.signal}),r=await t.json().catch(()=>({}));if(!t.ok){if(!v(e)){f.current===n&&!p.current&&s({phase:`failed`,code:`request_failed`});return}if(!a())return;s({phase:`failed`,code:Gv(r.code)});return}if(!a())return;if(typeof r.flowId!=`string`||!r.flowId){s({phase:`failed`,code:`request_failed`});return}o=r.flowId}catch{f.current===n&&!p.current&&s({phase:`failed`,code:`request_failed`});return}let m=o;c.current=m,l.current=e;let h=``,g=``;for(;a();){if(c.current!==m)return;try{let r=await i(e,`${e.apiBase}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(m)}`,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(Uv)])}),o=await r.json().catch(()=>({}));if(!a()||c.current!==m)return;if(!r.ok){if(r.status===409&&o.error===`target_changed`||r.status===404&&o.code===`unknown_flow`){_(),c.current=null,l.current=null,s({phase:`failed`,code:`request_failed`});return}let e=u.current===m;if(s(t=>!a()||c.current!==m||(t.phase===`pending`||t.phase===`committing`)&&t.flowId===m&&(e||t.cancelFailed)?t:{phase:`failed`,code:Gv(o.code)}),!e)return}else if(h=Kv(o.verificationUrl)||h,g=qv(o.deviceCode)||g,o.status===`pending`||o.status===`committing`){let e={phase:o.status,flowId:m,verificationUrl:h,deviceCode:g};d.current=e,s(t=>(t.phase===`pending`||t.phase===`committing`)&&t.flowId===m&&t.cancelFailed?{...e,cancelFailed:!0}:e)}else if(o.status===`succeeded`){c.current=null,l.current=null,s({phase:`succeeded`}),t();return}else if(o.status===`cancelled`){c.current=null,l.current=null,s({phase:`cancelled`});return}else if(o.status===`failed`){c.current=null,l.current=null,s({phase:`failed`,code:Gv(o.code)});return}}catch{if(!a()||c.current!==m)return}await new Promise(e=>setTimeout(e,Hv))}!p.current&&c.current===m&&!v(e)&&(_(),c.current=null,l.current=null,s({phase:`failed`,code:`request_failed`}))},[t,r,_]);return(0,Z.useEffect)(()=>(p.current=!1,()=>{p.current=!0,_();let e=c.current,t=l.current;c.current=null,l.current=null,e&&t&&i(t,`${t.apiBase}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(e)}`,{method:`DELETE`}).catch(()=>{})}),[_]),{state:o,start:b,cancel:y}}var Yv={en:{"nativeMain.title":`Native main login`,"nativeMain.manage":`Manage main login`,"nativeMain.close":`Close main login manager`,"nativeMain.separate":`These controls change the native Codex login, not the account selected for the next Pool request.`,"nativeMain.home":`Effective CODEX_HOME`,"nativeMain.current":`Registered active profile`,"nativeMain.unregistered":`Not registered`,"nativeMain.physicalHint":`This home belongs to the OpenCodex server, which may be a different computer. The backend verifies the physical login before any switch.`,"nativeMain.busyOther":`Another native login operation is running. Finish or cancel it first.`,"nativeMain.working":`Working…`,"nativeMain.changed":`The home, active profile or recovery state changed. Review the refreshed state and confirm again.`,"nativeMain.error":`The result could not be confirmed. A missing response does not mean the original login was restored.`,"nativeMain.doctorHint":`Run {cmd} on the server for details.`,"nativeMain.saved":`Current login saved as a profile. The physical login was not changed.`,"nativeMain.lastResult":`Last confirmed result`,"nativeMain.restart":`Login change completed. The server requires a native Codex restart.`,"nativeMain.done":`Operation completed. The server did not request a native Codex restart.`,"nativeMain.refreshFailed":`Could not refresh all account information. A completed change has not been undone. Refresh before another operation.`,"nativeMain.refresh":`Refresh status`,"nativeMain.unsupported":`This credential store is not supported. Native profile management requires the file credential store.`,"nativeMain.recoveryHint":`An interrupted transaction needs recovery. Recover finishes reconciliation; restore rolls back the pending transaction. Neither action runs until you confirm.`,"nativeMain.recover":`Recover interrupted change`,"nativeMain.rollback":`Restore pending transaction`,"nativeMain.empty":`No native profiles are registered yet. Save the current login first.`,"nativeMain.active":`Active`,"nativeMain.switchTo":`Switch native login to {label}`,"nativeMain.switch":`Switch`,"nativeMain.restore":`Return to previously displayed: {label}`,"nativeMain.restoreHint":`This shortcut selects the profile shown before your last switch, not a server-verified transaction history. It is kept only on this page.`,"nativeMain.label":`Profile label`,"nativeMain.save":`Save current as profile`,"nativeMain.saveHint":`For an already registered active login, saving updates its label. It does not add a new login.`,"nativeMain.confirmHint":`This changes only the native login in the home below. Close native Codex on that computer first. Pool strategy, membership, provider keys and task/history data are not edited by this panel.`,"nativeMain.stepClose":`Close native Codex on the server computer for the displayed CODEX_HOME. Keep it closed until you have checked the result.`,"nativeMain.stepConfirm":`Select the checkbox below to confirm Codex is closed, then confirm the change.`,"nativeMain.stepResult":`Wait for the result and the updated active profile, then follow the instructions to reopen Codex.`,"nativeMain.reopenHint":`Check the updated active profile, then reopen native Codex on the server computer with the displayed CODEX_HOME. Follow any restart requirement shown here.`,"nativeMain.retryHint":`Refresh the status and review the active profile. To retry a login change, select the action again and confirm that Codex is closed. Nothing is retried automatically.`,"nativeMain.errorCodexBusy":`Native Codex is still running on the server computer. Close it for the displayed CODEX_HOME before retrying.`,"nativeMain.errorProcessCheck":`The server could not verify whether native Codex is running. Check that Codex is closed on that computer and inspect the server diagnostics before retrying.`,"nativeMain.errorRequests":`Main-account requests are still running or draining. Wait for them to finish before retrying.`,"nativeMain.errorBusy":`Another native-login operation is running. Wait for it to finish before trying again.`,"nativeMain.errorAuth":`The current native login could not be read or verified against its saved profile. Inspect the server diagnostics before another change.`,"nativeMain.errorKeyStore":`The saved profile or operating-system key store could not be opened. Inspect the key-store and profile diagnostics on the server before another change.`,"nativeMain.errorStorage":`The server cannot safely access the login folder or profile storage. Check the server diagnostics before another change.`,"nativeMain.errorProfile":`The saved profile state cannot be used for this action. Refresh and review the profile list; inspect the diagnostics if the problem persists.`,"nativeMain.errorRecovery":`Profile storage or an interrupted transaction needs attention. Refresh status and inspect the server diagnostics. Use recovery controls only when the panel offers them.`,"nativeMain.errorRolledBack":`The server reports that the switch failed and the original login was restored. Review the refreshed active profile before another attempt.`,"nativeMain.stopped":`I have stopped native Codex using this CODEX_HOME and understand that a restart may be required.`,"nativeMain.cancel":`Cancel`,"nativeMain.confirm":`Confirm native-login change`,"nativeMain.unavailable":`Profile changes are unavailable. Check the diagnostic code before continuing.`},ko:{"nativeMain.title":`실제 Codex 메인 로그인`,"nativeMain.manage":`메인 로그인 관리`,"nativeMain.close":`메인 로그인 관리 닫기`,"nativeMain.separate":`이 기능은 실제 Codex 로그인을 변경합니다. 다음 요청에 사용할 Pool 계정 선택과는 다릅니다.`,"nativeMain.home":`실제 적용되는 CODEX_HOME`,"nativeMain.current":`등록된 활성 프로필`,"nativeMain.unregistered":`등록되지 않음`,"nativeMain.physicalHint":`이 경로는 OpenCodex 서버의 경로이며, 현재 컴퓨터와 다를 수 있습니다. 서버는 전환 전에 실제 로그인을 검증합니다.`,"nativeMain.busyOther":`다른 메인 로그인 작업이 진행 중입니다. 먼저 완료하거나 취소해 주세요.`,"nativeMain.working":`처리 중…`,"nativeMain.changed":`적용 경로, 활성 프로필 또는 복구 상태가 바뀌었습니다. 갱신된 정보를 검토하고 다시 확인해 주세요.`,"nativeMain.error":`결과를 확인하지 못했습니다. 응답이 없다고 해서 원래 로그인이 복원되었다는 뜻은 아닙니다.`,"nativeMain.doctorHint":`자세한 내용은 서버에서 {cmd} 명령을 실행해 확인하세요.`,"nativeMain.saved":`현재 로그인을 프로필로 저장했습니다. 실제 로그인은 변경하지 않았습니다.`,"nativeMain.lastResult":`마지막으로 확인된 결과`,"nativeMain.restart":`로그인 변경을 완료했습니다. 서버는 Codex 재시작이 필요하다고 응답했습니다.`,"nativeMain.done":`작업을 완료했습니다. 서버는 Codex 재시작이 필요하지 않다고 응답했습니다.`,"nativeMain.refreshFailed":`일부 계정 정보를 갱신하지 못했습니다. 완료된 변경이 취소된 것은 아닙니다. 다음 작업 전에 새로고침해 주세요.`,"nativeMain.refresh":`상태 새로고침`,"nativeMain.unsupported":`이 자격 증명 저장 방식은 지원하지 않습니다. 파일 저장 방식이 필요합니다.`,"nativeMain.recoveryHint":`중단된 전환에 복구가 필요합니다. 복구는 상태 정리를 진행하고, 되돌리기는 미완료 전환을 원복합니다. 확인 전에는 실행되지 않습니다.`,"nativeMain.recover":`중단된 전환 복구`,"nativeMain.rollback":`미완료 전환 되돌리기`,"nativeMain.empty":`등록된 메인 프로필이 없습니다. 현재 로그인을 먼저 저장해 주세요.`,"nativeMain.active":`활성`,"nativeMain.switchTo":`실제 로그인을 {label}(으)로 전환`,"nativeMain.switch":`전환`,"nativeMain.restore":`이전에 표시된 프로필로 돌아가기: {label}`,"nativeMain.restoreHint":`마지막 전환 전에 표시된 프로필을 선택하는 바로가기입니다. 서버가 검증한 거래 이력은 아니며 이 페이지에만 보관됩니다.`,"nativeMain.label":`프로필 이름`,"nativeMain.save":`현재 로그인을 프로필로 저장`,"nativeMain.saveHint":`현재 로그인이 이미 등록되어 있으면 이름을 변경합니다. 새 로그인은 추가하지 않습니다.`,"nativeMain.confirmHint":`아래 경로의 실제 로그인만 변경합니다. 해당 컴퓨터의 Codex를 먼저 종료해 주세요. 이 패널은 Pool 전략·구성, 공급자 키, 작업·기록 데이터를 수정하지 않습니다.`,"nativeMain.stepClose":`서버 컴퓨터에서 표시된 CODEX_HOME을 사용하는 실제 Codex를 종료합니다. 결과를 확인할 때까지 종료 상태를 유지합니다.`,"nativeMain.stepConfirm":`아래 체크박스를 선택해 Codex가 종료되었음을 확인한 다음 변경을 확인합니다.`,"nativeMain.stepResult":`작업 결과와 갱신된 활성 프로필을 기다린 다음 안내에 따라 Codex를 다시 엽니다.`,"nativeMain.reopenHint":`갱신된 활성 프로필을 확인한 다음 서버 컴퓨터에서 표시된 CODEX_HOME을 사용하는 실제 Codex를 다시 엽니다. 여기에 재시작이 필요하다고 표시되면 해당 안내를 따릅니다.`,"nativeMain.retryHint":`상태를 새로고침하고 활성 프로필을 확인합니다. 로그인 변경을 다시 시도하려면 작업을 다시 선택하고 Codex가 종료되었음을 확인해야 합니다. 자동으로 다시 시도하지 않습니다.`,"nativeMain.errorCodexBusy":`서버 컴퓨터에서 Codex가 아직 실행 중입니다. 다시 시도하기 전에 표시된 CODEX_HOME을 사용하는 Codex를 종료하세요.`,"nativeMain.errorProcessCheck":`서버가 Codex 실행 여부를 확인하지 못했습니다. 해당 컴퓨터에서 Codex가 종료됐는지 확인하고 서버 진단을 살펴본 뒤 다시 시도하세요.`,"nativeMain.errorRequests":`메인 계정 요청이 실행 중이거나 종료를 기다리고 있습니다. 요청이 끝난 뒤 다시 시도하세요.`,"nativeMain.errorBusy":`다른 실제 로그인 작업이 진행 중입니다. 해당 작업이 끝날 때까지 기다린 다음 다시 시도해야 합니다.`,"nativeMain.errorAuth":`현재 실제 로그인을 읽거나 저장된 프로필과 일치하는지 확인하지 못했습니다. 다음 변경 전에 서버 진단을 확인하세요.`,"nativeMain.errorKeyStore":`저장된 프로필 또는 운영체제 키 저장소를 열지 못했습니다. 다음 변경 전에 서버에서 키 저장소와 프로필 진단을 확인하세요.`,"nativeMain.errorStorage":`서버가 로그인 폴더 또는 프로필 저장소에 안전하게 접근할 수 없습니다. 다음 변경 전에 서버 진단을 확인해야 합니다.`,"nativeMain.errorProfile":`저장된 프로필 상태로 이 작업을 수행할 수 없습니다. 프로필 목록을 새로고침하고 확인하세요. 문제가 계속되면 진단을 확인하세요.`,"nativeMain.errorRecovery":`프로필 저장소 또는 중단된 전환을 확인해야 합니다. 상태를 새로고침하고 서버 진단을 확인하세요. 패널에 복구 기능이 표시될 때만 사용하세요.`,"nativeMain.errorRolledBack":`서버는 전환이 실패하여 원래 로그인을 복원했다고 응답했습니다. 다시 시도하기 전에 갱신된 활성 프로필을 확인하세요.`,"nativeMain.stopped":`이 CODEX_HOME을 사용하는 Codex를 종료했으며, 변경 후 재시작이 필요할 수 있음을 확인했습니다.`,"nativeMain.cancel":`취소`,"nativeMain.confirm":`메인 로그인 변경 확인`,"nativeMain.unavailable":`프로필을 변경할 수 없습니다. 계속하기 전에 진단 코드를 확인하세요.`},de:{"nativeMain.title":`Native Codex-Hauptanmeldung`,"nativeMain.manage":`Hauptanmeldung verwalten`,"nativeMain.close":`Anmeldungsverwaltung schließen`,"nativeMain.separate":`Diese Aktionen ändern die native Codex-Anmeldung, nicht das Konto für die nächste Pool-Anfrage.`,"nativeMain.home":`Wirksames CODEX_HOME`,"nativeMain.current":`Registriertes aktives Profil`,"nativeMain.unregistered":`Nicht registriert`,"nativeMain.physicalHint":`Dieser Pfad gehört zum OpenCodex-Server, möglicherweise auf einem anderen Computer. Das Backend prüft die tatsächliche Anmeldung vor jedem Wechsel.`,"nativeMain.busyOther":`Eine andere native Anmeldung läuft. Beenden oder abbrechen Sie sie zuerst.`,"nativeMain.working":`Wird verarbeitet…`,"nativeMain.changed":`Pfad, aktives Profil oder Wiederherstellungsstatus haben sich geändert. Prüfen und bestätigen Sie den neuen Stand.`,"nativeMain.error":`Das Ergebnis konnte nicht bestätigt werden. Eine fehlende Antwort bedeutet nicht, dass die ursprüngliche Anmeldung wiederhergestellt wurde.`,"nativeMain.doctorHint":`Führen Sie {cmd} auf dem Server aus, um Details zu sehen.`,"nativeMain.saved":`Aktuelle Anmeldung als Profil gespeichert. Die tatsächliche Anmeldung wurde nicht geändert.`,"nativeMain.lastResult":`Zuletzt bestätigtes Ergebnis`,"nativeMain.restart":`Anmeldung geändert. Der Server verlangt einen Neustart von nativem Codex.`,"nativeMain.done":`Vorgang abgeschlossen. Der Server verlangt keinen Codex-Neustart.`,"nativeMain.refreshFailed":`Nicht alle Kontodaten konnten aktualisiert werden. Eine abgeschlossene Änderung wurde nicht zurückgenommen. Aktualisieren Sie vor weiteren Aktionen.`,"nativeMain.refresh":`Status aktualisieren`,"nativeMain.unsupported":`Dieser Anmeldespeicher wird nicht unterstützt. Native Profile benötigen den dateibasierten Speicher.`,"nativeMain.recoveryHint":`Eine unterbrochene Transaktion muss wiederhergestellt werden. Wiederherstellen gleicht den Zustand ab; Zurücksetzen nimmt die ausstehende Transaktion zurück. Beide benötigen Ihre Bestätigung.`,"nativeMain.recover":`Unterbrochenen Wechsel wiederherstellen`,"nativeMain.rollback":`Ausstehende Transaktion zurücksetzen`,"nativeMain.empty":`Noch keine nativen Profile. Speichern Sie zuerst die aktuelle Anmeldung.`,"nativeMain.active":`Aktiv`,"nativeMain.switchTo":`Native Anmeldung zu {label} wechseln`,"nativeMain.switch":`Wechseln`,"nativeMain.restore":`Zum zuvor angezeigten Profil: {label}`,"nativeMain.restoreHint":`Diese Verknüpfung wählt das vor Ihrem letzten Wechsel angezeigte Profil, keinen servergeprüften Transaktionsverlauf. Sie bleibt nur auf dieser Seite erhalten.`,"nativeMain.label":`Profilname`,"nativeMain.save":`Aktuelle Anmeldung als Profil speichern`,"nativeMain.saveHint":`Ist die aktive Anmeldung bereits registriert, wird ihr Name geändert. Es wird keine neue Anmeldung hinzugefügt.`,"nativeMain.confirmHint":`Nur die native Anmeldung im folgenden Pfad wird geändert. Schließen Sie dort zuerst Codex. Pool-Strategie, Mitgliedschaft, Anbieterschlüssel sowie Aufgaben und Verlauf werden nicht bearbeitet.`,"nativeMain.stepClose":`Schließen Sie natives Codex auf dem Servercomputer für das angezeigte CODEX_HOME. Lassen Sie es geschlossen, bis Sie das Ergebnis geprüft haben.`,"nativeMain.stepConfirm":`Aktivieren Sie das Kontrollkästchen unten, um zu bestätigen, dass Codex geschlossen ist, und bestätigen Sie dann die Änderung.`,"nativeMain.stepResult":`Warten Sie auf das Ergebnis und das aktualisierte aktive Profil und folgen Sie dann den Anweisungen zum erneuten Öffnen von Codex.`,"nativeMain.reopenHint":`Prüfen Sie das aktualisierte aktive Profil und öffnen Sie dann natives Codex auf dem Servercomputer mit dem angezeigten CODEX_HOME. Beachten Sie alle hier angezeigten Neustartanforderungen.`,"nativeMain.retryHint":`Aktualisieren Sie den Status und prüfen Sie das aktive Profil. Um einen Anmeldewechsel erneut zu versuchen, wählen Sie die Aktion erneut und bestätigen Sie, dass Codex geschlossen ist. Nichts wird automatisch erneut versucht.`,"nativeMain.errorCodexBusy":`Natives Codex läuft noch auf dem Servercomputer. Schließen Sie es für das angezeigte CODEX_HOME vor einem erneuten Versuch.`,"nativeMain.errorProcessCheck":`Der Server konnte nicht prüfen, ob natives Codex läuft. Prüfen Sie auf diesem Computer, dass Codex beendet ist, und lesen Sie vor einem erneuten Versuch die Serverdiagnose.`,"nativeMain.errorRequests":`Anfragen des Hauptkontos laufen noch oder werden abgearbeitet. Warten Sie vor einem erneuten Versuch auf deren Abschluss.`,"nativeMain.errorBusy":`Ein anderer Vorgang für die native Anmeldung läuft. Warten Sie, bis er abgeschlossen ist, bevor Sie es erneut versuchen.`,"nativeMain.errorAuth":`Die aktuelle native Anmeldung konnte nicht gelesen oder mit dem gespeicherten Profil abgeglichen werden. Prüfen Sie vor einer weiteren Änderung die Serverdiagnose.`,"nativeMain.errorKeyStore":`Das gespeicherte Profil oder der Schlüsselspeicher des Betriebssystems konnte nicht geöffnet werden. Prüfen Sie vor einer weiteren Änderung die Schlüssel- und Profildiagnose auf dem Server.`,"nativeMain.errorStorage":`Der Server kann nicht sicher auf den Anmeldeordner oder den Profilspeicher zugreifen. Prüfen Sie vor einer weiteren Änderung die Serverdiagnose.`,"nativeMain.errorProfile":`Der gespeicherte Profilzustand erlaubt diese Aktion nicht. Aktualisieren und prüfen Sie die Profilliste; lesen Sie bei anhaltenden Problemen die Diagnose.`,"nativeMain.errorRecovery":`Der Profilspeicher oder eine unterbrochene Transaktion benötigt Aufmerksamkeit. Aktualisieren Sie den Status und prüfen Sie die Serverdiagnose. Nutzen Sie Wiederherstellungsaktionen nur, wenn das Panel sie anbietet.`,"nativeMain.errorRolledBack":`Der Server meldet, dass der Wechsel fehlgeschlagen ist und die ursprüngliche Anmeldung wiederhergestellt wurde. Prüfen Sie vor einem erneuten Versuch das aktualisierte aktive Profil.`,"nativeMain.stopped":`Ich habe natives Codex für dieses CODEX_HOME beendet und weiß, dass ein Neustart nötig sein kann.`,"nativeMain.cancel":`Abbrechen`,"nativeMain.confirm":`Änderung der Hauptanmeldung bestätigen`,"nativeMain.unavailable":`Profiländerungen sind nicht verfügbar. Prüfen Sie zuerst den Diagnosecode.`},fr:{"nativeMain.title":`Connexion principale native Codex`,"nativeMain.manage":`Gérer la connexion principale`,"nativeMain.close":`Fermer la gestion de connexion`,"nativeMain.separate":`Ces commandes modifient la connexion native Codex, pas le compte choisi pour la prochaine requête du Pool.`,"nativeMain.home":`CODEX_HOME effectif`,"nativeMain.current":`Profil actif enregistré`,"nativeMain.unregistered":`Non enregistré`,"nativeMain.physicalHint":`Ce chemin appartient au serveur OpenCodex, qui peut être un autre ordinateur. Le serveur vérifie la connexion réelle avant tout changement.`,"nativeMain.busyOther":`Une autre opération de connexion est en cours. Terminez-la ou annulez-la.`,"nativeMain.working":`Traitement…`,"nativeMain.changed":`Le chemin, le profil actif ou la récupération a changé. Vérifiez les informations actualisées et confirmez à nouveau.`,"nativeMain.error":`Le résultat n’a pas pu être confirmé. L’absence de réponse ne signifie pas que la connexion d’origine a été restaurée.`,"nativeMain.doctorHint":`Exécutez {cmd} sur le serveur pour obtenir des détails.`,"nativeMain.saved":`Connexion actuelle enregistrée comme profil. La connexion réelle reste inchangée.`,"nativeMain.lastResult":`Dernier résultat confirmé`,"nativeMain.restart":`Connexion modifiée. Le serveur demande un redémarrage de Codex natif.`,"nativeMain.done":`Opération terminée. Le serveur ne demande pas de redémarrage de Codex.`,"nativeMain.refreshFailed":`Certaines informations n’ont pas pu être actualisées. Une modification terminée n’a pas été annulée. Actualisez avant une autre opération.`,"nativeMain.refresh":`Actualiser l’état`,"nativeMain.unsupported":`Ce stockage d’identifiants n’est pas pris en charge. Les profils natifs exigent le stockage dans un fichier.`,"nativeMain.recoveryHint":`Une transaction interrompue nécessite une récupération. Récupérer réconcilie l’état ; restaurer annule la transaction en attente. Les deux actions exigent une confirmation.`,"nativeMain.recover":`Récupérer le changement interrompu`,"nativeMain.rollback":`Restaurer la transaction en attente`,"nativeMain.empty":`Aucun profil natif enregistré. Enregistrez d’abord la connexion actuelle.`,"nativeMain.active":`Actif`,"nativeMain.switchTo":`Utiliser {label} comme connexion native`,"nativeMain.switch":`Changer`,"nativeMain.restore":`Revenir au profil affiché précédemment : {label}`,"nativeMain.restoreHint":`Ce raccourci sélectionne le profil affiché avant votre dernier changement, et non un historique de transactions vérifié par le serveur. Il reste uniquement sur cette page.`,"nativeMain.label":`Nom du profil`,"nativeMain.save":`Enregistrer la connexion actuelle`,"nativeMain.saveHint":`Si la connexion active est déjà enregistrée, son nom est mis à jour. Aucune nouvelle connexion n’est ajoutée.`,"nativeMain.confirmHint":`Seule la connexion native du chemin ci-dessous change. Fermez d’abord Codex sur cet ordinateur. Ce panneau ne modifie ni la stratégie ni les membres du Pool, les clés fournisseur, les tâches ou l’historique.`,"nativeMain.stepClose":`Fermez Codex natif sur l’ordinateur du serveur pour le CODEX_HOME affiché. Gardez-le fermé jusqu’à ce que vous ayez vérifié le résultat.`,"nativeMain.stepConfirm":`Cochez la case ci-dessous pour confirmer que Codex est fermé, puis confirmez la modification.`,"nativeMain.stepResult":`Attendez le résultat et le profil actif actualisé, puis suivez les instructions pour rouvrir Codex.`,"nativeMain.reopenHint":`Vérifiez le profil actif actualisé, puis rouvrez Codex natif sur l’ordinateur du serveur avec le CODEX_HOME affiché. Respectez toute exigence de redémarrage indiquée ici.`,"nativeMain.retryHint":`Actualisez l’état et vérifiez le profil actif. Pour réessayer un changement de connexion, sélectionnez à nouveau l’action et confirmez que Codex est fermé. Aucune action n’est réessayée automatiquement.`,"nativeMain.errorCodexBusy":`Codex natif fonctionne encore sur l’ordinateur du serveur. Fermez-le pour le CODEX_HOME affiché avant de réessayer.`,"nativeMain.errorProcessCheck":`Le serveur n’a pas pu vérifier si Codex natif fonctionne. Vérifiez son arrêt sur cet ordinateur et consultez le diagnostic du serveur avant de réessayer.`,"nativeMain.errorRequests":`Des requêtes du compte principal sont encore en cours ou en cours de terminaison. Attendez leur fin avant de réessayer.`,"nativeMain.errorBusy":`Une autre opération de connexion native est en cours. Attendez qu’elle se termine avant de réessayer.`,"nativeMain.errorAuth":`La connexion native actuelle n’a pas pu être lue ou vérifiée avec le profil enregistré. Consultez le diagnostic du serveur avant toute autre modification.`,"nativeMain.errorKeyStore":`Le profil enregistré ou le trousseau du système n’a pas pu être ouvert. Consultez leurs diagnostics sur le serveur avant toute autre modification.`,"nativeMain.errorStorage":`Le serveur ne peut pas accéder en toute sécurité au dossier de connexion ou au stockage des profils. Consultez le diagnostic du serveur avant toute autre modification.`,"nativeMain.errorProfile":`L’état du profil enregistré ne permet pas cette action. Actualisez et vérifiez la liste ; consultez le diagnostic si le problème persiste.`,"nativeMain.errorRecovery":`Le stockage des profils ou une transaction interrompue nécessite une intervention. Actualisez l’état et consultez le diagnostic du serveur. Utilisez la récupération uniquement si le panneau la propose.`,"nativeMain.errorRolledBack":`Le serveur indique que le changement a échoué et que la connexion initiale a été restaurée. Vérifiez le profil actif actualisé avant un nouvel essai.`,"nativeMain.stopped":`J’ai arrêté Codex natif utilisant ce CODEX_HOME et comprends qu’un redémarrage peut être nécessaire.`,"nativeMain.cancel":`Annuler`,"nativeMain.confirm":`Confirmer le changement de connexion`,"nativeMain.unavailable":`La modification des profils est indisponible. Vérifiez le code de diagnostic avant de continuer.`},zh:{"nativeMain.title":`原生 Codex 主登录`,"nativeMain.manage":`管理主登录`,"nativeMain.close":`关闭主登录管理`,"nativeMain.separate":`这些操作更改原生 Codex 登录,不会选择下一次 Pool 请求使用的账号。`,"nativeMain.home":`实际使用的 CODEX_HOME`,"nativeMain.current":`已注册的活动配置`,"nativeMain.unregistered":`尚未注册`,"nativeMain.physicalHint":`此路径属于 OpenCodex 服务器,可能位于另一台计算机。后端会在切换前验证实际登录。`,"nativeMain.busyOther":`另一项原生登录操作正在进行。请先完成或取消。`,"nativeMain.working":`处理中…`,"nativeMain.changed":`路径、活动配置或恢复状态已变化。请查看刷新后的状态并重新确认。`,"nativeMain.error":`无法确认结果。未收到响应并不意味着原来的登录已恢复。`,"nativeMain.doctorHint":`在服务器上运行 {cmd} 可查看详细信息。`,"nativeMain.saved":`已将当前登录保存为配置。实际登录未改变。`,"nativeMain.lastResult":`最近确认的结果`,"nativeMain.restart":`登录已更改。服务器要求重启原生 Codex。`,"nativeMain.done":`操作已完成。服务器未要求重新启动 Codex。`,"nativeMain.refreshFailed":`部分账号信息刷新失败。已完成的更改并未撤销。请在继续操作前刷新。`,"nativeMain.refresh":`刷新状态`,"nativeMain.unsupported":`不支持此凭据存储方式。原生配置管理需要文件凭据存储。`,"nativeMain.recoveryHint":`中断的事务需要恢复。恢复会完成状态协调;还原会回滚待处理事务。两项操作均需确认后才执行。`,"nativeMain.recover":`恢复中断的更改`,"nativeMain.rollback":`还原待处理事务`,"nativeMain.empty":`尚无原生配置。请先保存当前登录。`,"nativeMain.active":`活动`,"nativeMain.switchTo":`将原生登录切换为 {label}`,"nativeMain.switch":`切换`,"nativeMain.restore":`返回之前显示的配置档案:{label}`,"nativeMain.restoreHint":`此快捷方式选择上次切换前显示的配置档案,并非服务器验证的事务历史记录,仅保留在此页面。`,"nativeMain.label":`配置名称`,"nativeMain.save":`将当前登录保存为配置`,"nativeMain.saveHint":`如果当前活动登录已注册,保存会更新其名称,不会添加新登录。`,"nativeMain.confirmHint":`仅更改以下路径中的原生登录。请先关闭该计算机上的 Codex。此面板不会编辑 Pool 策略、成员、供应商密钥或任务与历史数据。`,"nativeMain.stepClose":`在服务器计算机上关闭使用所示 CODEX_HOME 的原生 Codex。在检查结果之前,请保持 Codex 关闭。`,"nativeMain.stepConfirm":`勾选下方复选框,确认 Codex 已关闭,然后确认更改。`,"nativeMain.stepResult":`等待结果和更新后的活动配置,然后按照提示重新打开 Codex。`,"nativeMain.reopenHint":`检查更新后的活动配置,然后在服务器计算机上重新打开使用所示 CODEX_HOME 的原生 Codex。请遵循此处显示的任何重启要求。`,"nativeMain.retryHint":`刷新状态并检查活动配置。要重试登录更改,请重新选择操作并确认 Codex 已关闭。不会自动重试任何操作。`,"nativeMain.errorCodexBusy":`服务器计算机上的原生 Codex 仍在运行。重试前请关闭使用所示 CODEX_HOME 的 Codex。`,"nativeMain.errorProcessCheck":`服务器无法验证原生 Codex 是否在运行。重试前请确认该计算机上的 Codex 已关闭,并检查服务器诊断。`,"nativeMain.errorRequests":`主账号请求仍在运行或等待结束。请等待请求结束后再重试。`,"nativeMain.errorBusy":`另一项原生登录操作正在运行。请等待其完成后再试。`,"nativeMain.errorAuth":`无法读取当前原生登录或验证其是否匹配保存的配置。再次更改前请检查服务器诊断。`,"nativeMain.errorKeyStore":`无法打开保存的配置或操作系统密钥存储。再次更改前请检查服务器上的密钥存储和配置诊断。`,"nativeMain.errorStorage":`服务器无法安全访问登录文件夹或配置存储。再次更改前,请检查服务器诊断。`,"nativeMain.errorProfile":`保存的配置状态无法用于此操作。请刷新并检查配置列表;若问题持续,请检查诊断。`,"nativeMain.errorRecovery":`配置存储或中断的事务需要处理。请刷新状态并检查服务器诊断。仅在面板提供恢复功能时使用。`,"nativeMain.errorRolledBack":`服务器报告切换失败且原登录已恢复。再次尝试前请检查刷新的活动配置。`,"nativeMain.stopped":`我已停止使用此 CODEX_HOME 的原生 Codex,并了解之后可能需要重新启动。`,"nativeMain.cancel":`取消`,"nativeMain.confirm":`确认更改原生登录`,"nativeMain.unavailable":`目前无法更改配置档案。请先检查诊断代码。`},"zh-TW":{"nativeMain.title":`原生 Codex 主登入`,"nativeMain.manage":`管理主登入`,"nativeMain.close":`關閉主登入管理`,"nativeMain.separate":`這些操作會變更原生 Codex 登入,不會選擇下一次 Pool 請求使用的帳號。`,"nativeMain.home":`實際使用的 CODEX_HOME`,"nativeMain.current":`已註冊的作用中設定檔`,"nativeMain.unregistered":`尚未註冊`,"nativeMain.physicalHint":`此路徑屬於 OpenCodex 伺服器,可能位於另一台電腦。後端會在切換前驗證實際登入。`,"nativeMain.busyOther":`另一項原生登入操作正在進行。請先完成或取消。`,"nativeMain.working":`處理中…`,"nativeMain.changed":`路徑、作用中設定檔或復原狀態已變更。請查看更新後的狀態並再次確認。`,"nativeMain.error":`無法確認結果。未收到回應並不代表原本的登入已還原。`,"nativeMain.doctorHint":`在伺服器上執行 {cmd} 可查看詳細資訊。`,"nativeMain.saved":`已將目前登入儲存為設定檔。實際登入未變更。`,"nativeMain.lastResult":`最近確認的結果`,"nativeMain.restart":`登入已變更。伺服器要求重新啟動原生 Codex。`,"nativeMain.done":`操作已完成。伺服器未要求重新啟動 Codex。`,"nativeMain.refreshFailed":`部分帳號資訊更新失敗。已完成的變更並未撤銷。請在繼續操作前重新整理。`,"nativeMain.refresh":`重新整理狀態`,"nativeMain.unsupported":`不支援此憑證儲存方式。原生設定檔管理需要檔案憑證儲存。`,"nativeMain.recoveryHint":`中斷的交易需要復原。復原會完成狀態協調;還原會回復待處理的交易。兩項操作都需確認後才執行。`,"nativeMain.recover":`復原中斷的變更`,"nativeMain.rollback":`還原待處理交易`,"nativeMain.empty":`尚無原生設定檔。請先儲存目前登入。`,"nativeMain.active":`作用中`,"nativeMain.switchTo":`將原生登入切換為 {label}`,"nativeMain.switch":`切換`,"nativeMain.restore":`返回先前顯示的設定檔:{label}`,"nativeMain.restoreHint":`此捷徑選擇上次切換前顯示的設定檔,並非伺服器驗證的交易歷史紀錄,僅保留於此頁面。`,"nativeMain.label":`設定檔名稱`,"nativeMain.save":`將目前登入儲存為設定檔`,"nativeMain.saveHint":`若目前登入已註冊,儲存會更新名稱,不會新增登入。`,"nativeMain.confirmHint":`僅變更以下路徑中的原生登入。請先關閉該電腦上的 Codex。此面板不會編輯 Pool 策略、成員、供應商金鑰或工作與歷史資料。`,"nativeMain.stepClose":`在伺服器電腦上關閉使用所示 CODEX_HOME 的原生 Codex。在檢查結果之前,請保持 Codex 關閉。`,"nativeMain.stepConfirm":`勾選下方核取方塊,確認 Codex 已關閉,然後確認變更。`,"nativeMain.stepResult":`等待結果和更新後的作用中設定檔,然後依照指示重新開啟 Codex。`,"nativeMain.reopenHint":`檢查更新後的作用中設定檔,然後在伺服器電腦上重新開啟使用所示 CODEX_HOME 的原生 Codex。請遵循此處顯示的任何重新啟動要求。`,"nativeMain.retryHint":`重新整理狀態並檢查作用中設定檔。若要重試登入變更,請重新選擇操作並確認 Codex 已關閉。不會自動重試任何操作。`,"nativeMain.errorCodexBusy":`伺服器電腦上的原生 Codex 仍在執行。重試前請關閉使用所示 CODEX_HOME 的 Codex。`,"nativeMain.errorProcessCheck":`伺服器無法驗證原生 Codex 是否在執行。重試前請確認該電腦上的 Codex 已關閉,並檢查伺服器診斷。`,"nativeMain.errorRequests":`主帳號請求仍在執行或等待結束。請等待請求結束後再重試。`,"nativeMain.errorBusy":`另一項原生登入操作正在執行。請等待其完成後再試。`,"nativeMain.errorAuth":`無法讀取目前的原生登入或驗證其是否符合已儲存的設定檔。再次變更前請檢查伺服器診斷。`,"nativeMain.errorKeyStore":`無法開啟已儲存的設定檔或作業系統金鑰儲存區。再次變更前請檢查伺服器上的金鑰儲存區和設定檔診斷。`,"nativeMain.errorStorage":`伺服器無法安全存取登入資料夾或設定檔儲存區。再次變更前,請檢查伺服器診斷。`,"nativeMain.errorProfile":`已儲存的設定檔狀態無法用於此操作。請重新整理並檢查設定檔清單;若問題持續,請檢查診斷。`,"nativeMain.errorRecovery":`設定檔儲存區或中斷的交易需要處理。請重新整理狀態並檢查伺服器診斷。僅在面板提供復原功能時使用。`,"nativeMain.errorRolledBack":`伺服器回報切換失敗且原登入已還原。再次嘗試前請檢查更新的作用中設定檔。`,"nativeMain.stopped":`我已停止使用此 CODEX_HOME 的原生 Codex,並了解之後可能需要重新啟動。`,"nativeMain.cancel":`取消`,"nativeMain.confirm":`確認變更原生登入`,"nativeMain.unavailable":`目前無法變更設定檔。請先檢查診斷代碼。`},ru:{"nativeMain.title":`Основной вход в Codex`,"nativeMain.manage":`Управление основным входом`,"nativeMain.close":`Закрыть управление входом`,"nativeMain.separate":`Эти действия меняют вход самого Codex, а не аккаунт для следующего запроса Pool.`,"nativeMain.home":`Фактический CODEX_HOME`,"nativeMain.current":`Зарегистрированный активный профиль`,"nativeMain.unregistered":`Не зарегистрирован`,"nativeMain.physicalHint":`Этот путь относится к серверу OpenCodex, возможно на другом компьютере. Сервер проверяет фактический вход перед переключением.`,"nativeMain.busyOther":`Выполняется другая операция входа. Сначала завершите или отмените её.`,"nativeMain.working":`Обработка…`,"nativeMain.changed":`Путь, активный профиль или состояние восстановления изменились. Проверьте обновлённые данные и подтвердите снова.`,"nativeMain.error":`Не удалось подтвердить результат. Отсутствие ответа не означает, что исходный вход был восстановлен.`,"nativeMain.doctorHint":`Выполните {cmd} на сервере, чтобы увидеть подробности.`,"nativeMain.saved":`Текущий вход сохранён как профиль. Фактический вход не изменён.`,"nativeMain.lastResult":`Последний подтверждённый результат`,"nativeMain.restart":`Вход изменён. Сервер требует перезапуска нативного Codex.`,"nativeMain.done":`Операция завершена. Сервер не требует перезапуска Codex.`,"nativeMain.refreshFailed":`Не все данные аккаунтов обновлены. Завершённое изменение не отменено. Обновите состояние перед следующей операцией.`,"nativeMain.refresh":`Обновить состояние`,"nativeMain.unsupported":`Этот способ хранения учётных данных не поддерживается. Требуется файловое хранилище.`,"nativeMain.recoveryHint":`Прерванная транзакция требует восстановления. Восстановление согласует состояние, а откат отменяет незавершённую транзакцию. Оба действия требуют подтверждения.`,"nativeMain.recover":`Восстановить прерванное изменение`,"nativeMain.rollback":`Откатить незавершённую транзакцию`,"nativeMain.empty":`Профилей пока нет. Сначала сохраните текущий вход.`,"nativeMain.active":`Активен`,"nativeMain.switchTo":`Переключить вход Codex на {label}`,"nativeMain.switch":`Переключить`,"nativeMain.restore":`Вернуться к ранее показанному профилю: {label}`,"nativeMain.restoreHint":`Этот ярлык выбирает профиль, показанный перед последним переключением, а не подтверждённую сервером историю транзакций. Он хранится только на этой странице.`,"nativeMain.label":`Название профиля`,"nativeMain.save":`Сохранить текущий вход`,"nativeMain.saveHint":`Если активный вход уже зарегистрирован, обновляется его название. Новый вход не добавляется.`,"nativeMain.confirmHint":`Изменится только вход Codex по указанному пути. Сначала закройте Codex на том компьютере. Панель не меняет стратегию и состав Pool, ключи провайдеров, задачи или историю.`,"nativeMain.stepClose":`Закройте нативный Codex на серверном компьютере, где он использует указанный CODEX_HOME. Не открывайте его, пока не проверите результат.`,"nativeMain.stepConfirm":`Установите флажок ниже, чтобы подтвердить, что Codex закрыт, затем подтвердите изменение.`,"nativeMain.stepResult":`Дождитесь результата и обновлённого активного профиля, затем следуйте инструкциям, чтобы снова открыть Codex.`,"nativeMain.reopenHint":`Проверьте обновлённый активный профиль, затем снова откройте нативный Codex на серверном компьютере с указанным CODEX_HOME. Соблюдайте все указанные здесь требования к перезапуску.`,"nativeMain.retryHint":`Обновите состояние и проверьте активный профиль. Чтобы повторить смену входа, выберите действие снова и подтвердите, что Codex закрыт. Никакие действия не повторяются автоматически.`,"nativeMain.errorCodexBusy":`Нативный Codex всё ещё работает на компьютере сервера. Перед повтором закройте Codex, использующий указанный CODEX_HOME.`,"nativeMain.errorProcessCheck":`Сервер не смог проверить, работает ли нативный Codex. Перед повтором проверьте его остановку на этом компьютере и диагностику сервера.`,"nativeMain.errorRequests":`Запросы основного аккаунта ещё выполняются или завершаются. Дождитесь их окончания перед повтором.`,"nativeMain.errorBusy":`Выполняется другая операция нативного входа. Дождитесь её завершения, прежде чем повторить попытку.`,"nativeMain.errorAuth":`Не удалось прочитать текущий нативный вход или сверить его с сохранённым профилем. Перед новым изменением проверьте диагностику сервера.`,"nativeMain.errorKeyStore":`Не удалось открыть сохранённый профиль или системное хранилище ключей. Перед новым изменением проверьте их диагностику на сервере.`,"nativeMain.errorStorage":`Сервер не может безопасно получить доступ к папке входа или хранилищу профилей. Перед следующим изменением проверьте диагностику сервера.`,"nativeMain.errorProfile":`Состояние сохранённого профиля не подходит для этого действия. Обновите и проверьте список; если проблема остаётся, изучите диагностику.`,"nativeMain.errorRecovery":`Хранилище профилей или прерванная транзакция требуют внимания. Обновите состояние и проверьте диагностику сервера. Используйте восстановление только когда панель его предлагает.`,"nativeMain.errorRolledBack":`Сервер сообщает, что переключение не удалось и исходный вход восстановлен. Перед повтором проверьте обновлённый активный профиль.`,"nativeMain.stopped":`Я остановил Codex, использующий этот CODEX_HOME, и понимаю, что может потребоваться перезапуск.`,"nativeMain.cancel":`Отмена`,"nativeMain.confirm":`Подтвердить изменение входа`,"nativeMain.unavailable":`Изменение профилей недоступно. Перед продолжением проверьте диагностический код.`},ja:{"nativeMain.title":`ネイティブ Codex メインログイン`,"nativeMain.manage":`メインログインを管理`,"nativeMain.close":`ログイン管理を閉じる`,"nativeMain.separate":`この操作は Codex 本体のログインを変更します。次の Pool リクエストに使うアカウントの選択とは異なります。`,"nativeMain.home":`適用される CODEX_HOME`,"nativeMain.current":`登録済みの有効なプロファイル`,"nativeMain.unregistered":`未登録`,"nativeMain.physicalHint":`これは OpenCodex サーバーのパスであり、別のコンピューターの場合があります。切り替え前にサーバーが実際のログインを検証します。`,"nativeMain.busyOther":`別のログイン操作が実行中です。先に完了またはキャンセルしてください。`,"nativeMain.working":`処理中…`,"nativeMain.changed":`パス、有効なプロファイル、または復旧状態が変わりました。更新された情報を確認し、再度承認してください。`,"nativeMain.error":`結果を確認できませんでした。応答がないことは、元のログインが復元されたことを意味しません。`,"nativeMain.doctorHint":`詳細はサーバーで {cmd} を実行して確認してください。`,"nativeMain.saved":`現在のログインをプロファイルとして保存しました。実際のログインは変更していません。`,"nativeMain.lastResult":`最後に確認された結果`,"nativeMain.restart":`ログインを変更しました。サーバーはネイティブ Codex の再起動を要求しています。`,"nativeMain.done":`操作が完了しました。サーバーは Codex の再起動を要求していません。`,"nativeMain.refreshFailed":`一部のアカウント情報を更新できませんでした。完了した変更は取り消されていません。次の操作前に更新してください。`,"nativeMain.refresh":`状態を更新`,"nativeMain.unsupported":`この認証情報の保存方式には対応していません。ファイル方式が必要です。`,"nativeMain.recoveryHint":`中断された処理の復旧が必要です。復旧は状態を整合させ、復元は未完了の変更を戻します。どちらも確認後に実行されます。`,"nativeMain.recover":`中断された変更を復旧`,"nativeMain.rollback":`未完了の変更を復元`,"nativeMain.empty":`登録されたプロファイルがありません。まず現在のログインを保存してください。`,"nativeMain.active":`有効`,"nativeMain.switchTo":`ネイティブログインを {label} に切り替える`,"nativeMain.switch":`切り替え`,"nativeMain.restore":`以前表示されていたプロファイルに戻る: {label}`,"nativeMain.restoreHint":`最後の切り替え前に表示されていたプロファイルを選ぶショートカットです。サーバーが検証した取引履歴ではなく、このページだけに保持されます。`,"nativeMain.label":`プロファイル名`,"nativeMain.save":`現在のログインを保存`,"nativeMain.saveHint":`現在のログインが登録済みの場合は名前を更新します。新しいログインは追加しません。`,"nativeMain.confirmHint":`以下のパスの Codex ログインだけを変更します。そのコンピューターの Codex を先に終了してください。Pool の戦略・構成、プロバイダーのキー、タスクや履歴は編集しません。`,"nativeMain.stepClose":`サーバーのコンピューターで、表示された CODEX_HOME を使用するネイティブ Codex を終了してください。結果を確認するまで終了したままにしてください。`,"nativeMain.stepConfirm":`下のチェックボックスを選択して Codex が終了していることを確認し、その後で変更を確定してください。`,"nativeMain.stepResult":`結果と更新されたアクティブプロファイルを待ち、その後で案内に従って Codex を再度開いてください。`,"nativeMain.reopenHint":`更新されたアクティブプロファイルを確認し、サーバーのコンピューターで表示された CODEX_HOME を使用するネイティブ Codex を再度開いてください。ここに再起動が必要と表示された場合は、その案内に従ってください。`,"nativeMain.retryHint":`状態を更新し、アクティブプロファイルを確認してください。ログイン変更を再試行するには、操作を再度選択し、Codex が終了していることを確認してください。自動では再試行しません。`,"nativeMain.errorCodexBusy":`サーバーのコンピューターでネイティブ Codex がまだ動作しています。再試行の前に、表示された CODEX_HOME を使う Codex を終了してください。`,"nativeMain.errorProcessCheck":`サーバーはネイティブ Codex の動作状態を確認できませんでした。そのコンピューターで Codex が終了していることとサーバー診断を確認してから再試行してください。`,"nativeMain.errorRequests":`メインアカウントのリクエストが実行中、または終了待ちです。完了してから再試行してください。`,"nativeMain.errorBusy":`別のネイティブログイン操作が実行中です。完了するまで待ってから再試行してください。`,"nativeMain.errorAuth":`現在のネイティブログインを読み取るか、保存されたプロファイルと照合することができませんでした。次の変更前にサーバー診断を確認してください。`,"nativeMain.errorKeyStore":`保存されたプロファイルまたは OS のキーストアを開けませんでした。次の変更前にサーバーのキーストアとプロファイルの診断を確認してください。`,"nativeMain.errorStorage":`サーバーがログインフォルダーまたはプロファイル保存先に安全にアクセスできません。次の変更前にサーバー診断を確認してください。`,"nativeMain.errorProfile":`保存されたプロファイルの状態ではこの操作を実行できません。一覧を更新して確認し、問題が続く場合は診断を確認してください。`,"nativeMain.errorRecovery":`プロファイル保存先または中断された処理への対応が必要です。状態を更新し、サーバー診断を確認してください。復旧操作はパネルに表示される場合のみ使用してください。`,"nativeMain.errorRolledBack":`サーバーは切り替えに失敗し、元のログインを復元したと報告しています。再試行の前に更新されたアクティブプロファイルを確認してください。`,"nativeMain.stopped":`この CODEX_HOME を使う Codex を終了し、変更後に再起動が必要な場合があることを確認しました。`,"nativeMain.cancel":`キャンセル`,"nativeMain.confirm":`ログインの変更を確認`,"nativeMain.unavailable":`プロファイルを変更できません。続行する前に診断コードを確認してください。`},tr:{"nativeMain.title":`Yerel Codex ana oturumu`,"nativeMain.manage":`Ana oturumu yönet`,"nativeMain.close":`Oturum yönetimini kapat`,"nativeMain.separate":`Bu işlemler sonraki Pool isteğinin hesabını değil, yerel Codex oturumunu değiştirir.`,"nativeMain.home":`Geçerli CODEX_HOME`,"nativeMain.current":`Kayıtlı etkin profil`,"nativeMain.unregistered":`Kayıtlı değil`,"nativeMain.physicalHint":`Bu yol OpenCodex sunucusuna aittir; başka bir bilgisayarda olabilir. Sunucu her geçişten önce gerçek oturumu doğrular.`,"nativeMain.busyOther":`Başka bir yerel oturum işlemi sürüyor. Önce tamamlayın veya iptal edin.`,"nativeMain.working":`İşleniyor…`,"nativeMain.changed":`Yol, etkin profil veya kurtarma durumu değişti. Güncel durumu inceleyip yeniden onaylayın.`,"nativeMain.error":`Sonuç doğrulanamadı. Yanıt alınamaması, önceki girişin geri yüklendiği anlamına gelmez.`,"nativeMain.doctorHint":`Ayrıntılar için sunucuda {cmd} komutunu çalıştırın.`,"nativeMain.saved":`Geçerli oturum profil olarak kaydedildi. Gerçek oturum değiştirilmedi.`,"nativeMain.lastResult":`Son doğrulanan sonuç`,"nativeMain.restart":`Giriş değiştirildi. Sunucu yerel Codex’in yeniden başlatılmasını gerektiriyor.`,"nativeMain.done":`İşlem tamamlandı. Sunucu Codex uygulamasının yeniden başlatılmasını istemedi.`,"nativeMain.refreshFailed":`Tüm hesap bilgileri yenilenemedi. Tamamlanan değişiklik geri alınmadı. Sonraki işlemden önce yenileyin.`,"nativeMain.refresh":`Durumu yenile`,"nativeMain.unsupported":`Bu kimlik bilgisi deposu desteklenmiyor. Yerel profiller dosya tabanlı depo gerektirir.`,"nativeMain.recoveryHint":`Kesilen işlem kurtarma gerektiriyor. Kurtarma durumu uzlaştırır; geri yükleme bekleyen işlemi geri alır. Her iki işlem de onay gerektirir.`,"nativeMain.recover":`Kesilen değişikliği kurtar`,"nativeMain.rollback":`Bekleyen işlemi geri al`,"nativeMain.empty":`Henüz yerel profil yok. Önce geçerli oturumu kaydedin.`,"nativeMain.active":`Etkin`,"nativeMain.switchTo":`Yerel oturumu {label} profiline geçir`,"nativeMain.switch":`Geçiş yap`,"nativeMain.restore":`Önceden görüntülenen profile dön: {label}`,"nativeMain.restoreHint":`Bu kısayol son geçişinizden önce görüntülenen profili seçer; sunucu tarafından doğrulanmış işlem geçmişi değildir. Yalnızca bu sayfada tutulur.`,"nativeMain.label":`Profil adı`,"nativeMain.save":`Geçerli oturumu profil olarak kaydet`,"nativeMain.saveHint":`Etkin oturum zaten kayıtlıysa adı güncellenir. Yeni bir oturum eklenmez.`,"nativeMain.confirmHint":`Yalnızca aşağıdaki yoldaki yerel oturum değişir. Önce o bilgisayarda Codex uygulamasını kapatın. Bu panel Pool stratejisini ve üyelerini, sağlayıcı anahtarlarını, görevleri veya geçmişi değiştirmez.`,"nativeMain.stepClose":`Sunucu bilgisayarında gösterilen CODEX_HOME’u kullanan yerel Codex’i kapatın. Sonucu kontrol edene kadar kapalı tutun.`,"nativeMain.stepConfirm":`Codex’in kapalı olduğunu doğrulamak için aşağıdaki onay kutusunu işaretleyin, ardından değişikliği onaylayın.`,"nativeMain.stepResult":`Sonucu ve güncellenmiş etkin profili bekleyin, ardından Codex’i yeniden açma talimatlarını izleyin.`,"nativeMain.reopenHint":`Güncellenmiş etkin profili kontrol edin, ardından sunucu bilgisayarında gösterilen CODEX_HOME ile yerel Codex’i yeniden açın. Burada gösterilen yeniden başlatma gerekliliklerine uyun.`,"nativeMain.retryHint":`Durumu yenileyin ve etkin profili kontrol edin. Bir giriş değişikliğini tekrar denemek için işlemi yeniden seçin ve Codex’in kapalı olduğunu doğrulayın. Hiçbir işlem otomatik olarak tekrar denenmez.`,"nativeMain.errorCodexBusy":`Yerel Codex sunucu bilgisayarında hâlâ çalışıyor. Tekrar denemeden önce gösterilen CODEX_HOME için Codex’i kapatın.`,"nativeMain.errorProcessCheck":`Sunucu yerel Codex’in çalışıp çalışmadığını doğrulayamadı. Tekrar denemeden önce o bilgisayarda Codex’in kapalı olduğunu ve sunucu tanılamasını kontrol edin.`,"nativeMain.errorRequests":`Ana hesap istekleri hâlâ çalışıyor veya tamamlanmayı bekliyor. Tekrar denemeden önce bitmelerini bekleyin.`,"nativeMain.errorBusy":`Başka bir yerel giriş işlemi çalışıyor. Tekrar denemeden önce bitmesini bekleyin.`,"nativeMain.errorAuth":`Mevcut yerel giriş okunamadı veya kayıtlı profille doğrulanamadı. Başka bir değişiklikten önce sunucu tanılamasını inceleyin.`,"nativeMain.errorKeyStore":`Kayıtlı profil veya işletim sistemi anahtar deposu açılamadı. Başka bir değişiklikten önce sunucudaki anahtar deposu ve profil tanılamasını inceleyin.`,"nativeMain.errorStorage":`Sunucu giriş klasörüne veya profil deposuna güvenli bir şekilde erişemiyor. Başka bir değişiklikten önce sunucu tanılamasını kontrol edin.`,"nativeMain.errorProfile":`Kayıtlı profil durumu bu işlem için kullanılamıyor. Listeyi yenileyip inceleyin; sorun sürerse tanılamayı inceleyin.`,"nativeMain.errorRecovery":`Profil deposu veya kesintiye uğramış bir işlem dikkat gerektiriyor. Durumu yenileyip sunucu tanılamasını inceleyin. Kurtarma kontrollerini yalnızca panel sunduğunda kullanın.`,"nativeMain.errorRolledBack":`Sunucu geçişin başarısız olduğunu ve önceki girişin geri yüklendiğini bildiriyor. Tekrar denemeden önce yenilenmiş etkin profili kontrol edin.`,"nativeMain.stopped":`Bu CODEX_HOME ile çalışan Codex uygulamasını durdurdum ve yeniden başlatma gerekebileceğini anlıyorum.`,"nativeMain.cancel":`İptal`,"nativeMain.confirm":`Yerel oturum değişikliğini onayla`,"nativeMain.unavailable":`Profil değişiklikleri kullanılamıyor. Devam etmeden önce tanılama kodunu kontrol edin.`},vi:{"nativeMain.title":`Đăng nhập Codex gốc`,"nativeMain.manage":`Quản lý đăng nhập chính`,"nativeMain.close":`Đóng trình quản lý đăng nhập chính`,"nativeMain.separate":`Các điều khiển này thay đổi đăng nhập Codex gốc, không phải tài khoản được chọn cho yêu cầu Pool tiếp theo.`,"nativeMain.home":`CODEX_HOME đang có hiệu lực`,"nativeMain.current":`Hồ sơ đang hoạt động đã đăng ký`,"nativeMain.unregistered":`Chưa đăng ký`,"nativeMain.physicalHint":`Thư mục home này thuộc về máy chủ OpenCodex, có thể là một máy tính khác. Backend xác minh đăng nhập thực tế trước mọi lần chuyển đổi.`,"nativeMain.busyOther":`Một thao tác đăng nhập gốc khác đang chạy. Hãy hoàn tất hoặc hủy nó trước.`,"nativeMain.working":`Đang xử lý…`,"nativeMain.changed":`Thư mục home, hồ sơ đang hoạt động hoặc trạng thái khôi phục đã thay đổi. Hãy xem lại trạng thái vừa làm mới và xác nhận lại.`,"nativeMain.error":`Không thể xác nhận kết quả. Không nhận được phản hồi không có nghĩa là đăng nhập ban đầu đã được khôi phục.`,"nativeMain.doctorHint":`Chạy {cmd} trên máy chủ để biết chi tiết.`,"nativeMain.saved":`Đã lưu đăng nhập hiện tại thành một hồ sơ. Đăng nhập thực tế không bị thay đổi.`,"nativeMain.lastResult":`Kết quả được xác nhận gần nhất`,"nativeMain.restart":`Đã thay đổi đăng nhập. Máy chủ yêu cầu khởi động lại Codex gốc.`,"nativeMain.done":`Đã hoàn tất thao tác. Máy chủ không yêu cầu khởi động lại Codex gốc.`,"nativeMain.refreshFailed":`Không thể làm mới toàn bộ thông tin tài khoản. Một thay đổi đã hoàn tất sẽ không bị hoàn tác. Hãy làm mới trước khi thực hiện thao tác khác.`,"nativeMain.refresh":`Làm mới trạng thái`,"nativeMain.unsupported":`Kho lưu trữ thông tin đăng nhập này không được hỗ trợ. Quản lý hồ sơ gốc yêu cầu kho lưu trữ dạng tệp.`,"nativeMain.recoveryHint":`Một giao dịch bị gián đoạn cần được khôi phục. Khôi phục sẽ hoàn tất việc đối chiếu; phục hồi sẽ quay lui giao dịch đang chờ. Không thao tác nào chạy cho đến khi bạn xác nhận.`,"nativeMain.recover":`Khôi phục thay đổi bị gián đoạn`,"nativeMain.rollback":`Phục hồi giao dịch đang chờ`,"nativeMain.empty":`Chưa có hồ sơ gốc nào được đăng ký. Hãy lưu đăng nhập hiện tại trước.`,"nativeMain.active":`Đang hoạt động`,"nativeMain.switchTo":`Chuyển đăng nhập gốc sang {label}`,"nativeMain.switch":`Chuyển`,"nativeMain.restore":`Quay lại hồ sơ đã hiển thị trước đó: {label}`,"nativeMain.restoreHint":`Lối tắt này chọn hồ sơ được hiển thị trước lần chuyển đổi gần nhất của bạn, không phải lịch sử giao dịch được máy chủ xác minh. Nó chỉ được giữ trên trang này.`,"nativeMain.label":`Nhãn hồ sơ`,"nativeMain.save":`Lưu hiện tại thành hồ sơ`,"nativeMain.saveHint":`Với một đăng nhập đang hoạt động đã được đăng ký, việc lưu sẽ cập nhật nhãn của nó. Nó không thêm một đăng nhập mới.`,"nativeMain.confirmHint":`Thao tác này chỉ thay đổi đăng nhập gốc trong thư mục home bên dưới. Hãy đóng Codex gốc trên máy tính đó trước. Bảng này không chỉnh sửa chiến lược Pool, thành viên, khóa nhà cung cấp hay dữ liệu tác vụ/lịch sử.`,"nativeMain.stepClose":`Đóng Codex gốc trên máy tính của máy chủ đang dùng CODEX_HOME được hiển thị. Giữ Codex đóng cho đến khi bạn đã kiểm tra kết quả.`,"nativeMain.stepConfirm":`Chọn ô bên dưới để xác nhận Codex đã đóng, rồi xác nhận thay đổi.`,"nativeMain.stepResult":`Chờ kết quả và hồ sơ đang hoạt động được cập nhật, rồi làm theo hướng dẫn để mở lại Codex.`,"nativeMain.reopenHint":`Kiểm tra hồ sơ đang hoạt động đã cập nhật, rồi mở lại Codex gốc trên máy tính của máy chủ với CODEX_HOME được hiển thị. Làm theo mọi yêu cầu khởi động lại hiển thị tại đây.`,"nativeMain.retryHint":`Làm mới trạng thái và kiểm tra hồ sơ đang hoạt động. Để thử lại việc đổi đăng nhập, hãy chọn lại thao tác và xác nhận Codex đã đóng. Không thao tác nào được tự động thử lại.`,"nativeMain.errorCodexBusy":`Codex gốc vẫn đang chạy trên máy chủ. Đóng Codex dùng CODEX_HOME hiển thị trước khi thử lại.`,"nativeMain.errorProcessCheck":`Máy chủ không xác minh được Codex gốc có đang chạy hay không. Kiểm tra Codex đã đóng trên máy đó và xem chẩn đoán máy chủ trước khi thử lại.`,"nativeMain.errorRequests":`Yêu cầu của tài khoản chính vẫn đang chạy hoặc chờ hoàn tất. Chờ chúng kết thúc trước khi thử lại.`,"nativeMain.errorBusy":`Một thao tác đăng nhập gốc khác đang chạy. Chờ thao tác đó kết thúc trước khi thử lại.`,"nativeMain.errorAuth":`Không đọc được đăng nhập gốc hiện tại hoặc không xác minh được với hồ sơ đã lưu. Xem chẩn đoán máy chủ trước khi thay đổi tiếp.`,"nativeMain.errorKeyStore":`Không mở được hồ sơ đã lưu hoặc kho khóa của hệ điều hành. Xem chẩn đoán kho khóa và hồ sơ trên máy chủ trước khi thay đổi tiếp.`,"nativeMain.errorStorage":`Máy chủ không thể truy cập an toàn vào thư mục đăng nhập hoặc kho hồ sơ. Kiểm tra chẩn đoán máy chủ trước khi thực hiện thay đổi khác.`,"nativeMain.errorProfile":`Trạng thái hồ sơ đã lưu không dùng được cho thao tác này. Làm mới và xem danh sách; kiểm tra chẩn đoán nếu vấn đề tiếp diễn.`,"nativeMain.errorRecovery":`Kho hồ sơ hoặc giao dịch bị gián đoạn cần được xử lý. Làm mới trạng thái và xem chẩn đoán máy chủ. Chỉ dùng điều khiển khôi phục khi bảng cung cấp.`,"nativeMain.errorRolledBack":`Máy chủ báo việc chuyển đổi thất bại và đăng nhập ban đầu đã được khôi phục. Kiểm tra hồ sơ đang hoạt động đã cập nhật trước khi thử lại.`,"nativeMain.stopped":`Tôi đã dừng Codex gốc đang dùng CODEX_HOME này và hiểu rằng có thể cần khởi động lại.`,"nativeMain.cancel":`Hủy`,"nativeMain.confirm":`Xác nhận thay đổi đăng nhập gốc`,"nativeMain.unavailable":`Không thể thay đổi hồ sơ. Hãy kiểm tra mã chẩn đoán trước khi tiếp tục.`},pt:{"nativeMain.title":`Login principal do Codex nativo`,"nativeMain.manage":`Gerenciar login principal`,"nativeMain.close":`Fechar o gerenciador de login principal`,"nativeMain.separate":`Estes controles alteram o login do Codex nativo, não a conta selecionada para a próxima requisição do Pool.`,"nativeMain.home":`CODEX_HOME efetivo`,"nativeMain.current":`Perfil ativo registrado`,"nativeMain.unregistered":`Não registrado`,"nativeMain.physicalHint":`Este diretório home pertence ao servidor do OpenCodex, que pode ser outro computador. O backend verifica o login físico antes de qualquer troca.`,"nativeMain.busyOther":`Outra operação de login nativo está em andamento. Conclua ou cancele-a primeiro.`,"nativeMain.working":`Processando…`,"nativeMain.changed":`O diretório home, o perfil ativo ou o estado de recuperação mudou. Revise o estado atualizado e confirme novamente.`,"nativeMain.error":`Não foi possível confirmar o resultado. A ausência de resposta não significa que o login original foi restaurado.`,"nativeMain.doctorHint":`Execute {cmd} no servidor para ver os detalhes.`,"nativeMain.saved":`Login atual salvo como perfil. O login físico não foi alterado.`,"nativeMain.lastResult":`Último resultado confirmado`,"nativeMain.restart":`Login alterado. O servidor exige a reinicialização do Codex nativo.`,"nativeMain.done":`Operação concluída. O servidor não solicitou a reinicialização do Codex nativo.`,"nativeMain.refreshFailed":`Não foi possível atualizar todas as informações da conta. Uma alteração já concluída não foi desfeita. Atualize antes de outra operação.`,"nativeMain.refresh":`Atualizar status`,"nativeMain.unsupported":`Este armazenamento de credenciais não é suportado. O gerenciamento de perfis nativos exige o armazenamento de credenciais em arquivo.`,"nativeMain.recoveryHint":`Uma transação interrompida precisa de recuperação. Recuperar conclui a reconciliação; restaurar reverte a transação pendente. Nenhuma das ações é executada até você confirmar.`,"nativeMain.recover":`Recuperar alteração interrompida`,"nativeMain.rollback":`Restaurar transação pendente`,"nativeMain.empty":`Nenhum perfil nativo registrado ainda. Salve primeiro o login atual.`,"nativeMain.active":`Ativo`,"nativeMain.switchTo":`Trocar o login nativo para {label}`,"nativeMain.switch":`Trocar`,"nativeMain.restore":`Voltar ao perfil exibido anteriormente: {label}`,"nativeMain.restoreHint":`Este atalho seleciona o perfil exibido antes da sua última troca, não um histórico de transações verificado pelo servidor. Ele é mantido apenas nesta página.`,"nativeMain.label":`Rótulo do perfil`,"nativeMain.save":`Salvar atual como perfil`,"nativeMain.saveHint":`Para um login ativo já registrado, salvar atualiza o rótulo. Não adiciona um novo login.`,"nativeMain.confirmHint":`Isto altera apenas o login nativo no diretório home abaixo. Feche primeiro o Codex nativo naquele computador. Este painel não edita estratégia do Pool, membros, chaves de provedor nem dados de tarefas/histórico.`,"nativeMain.stepClose":`Feche o Codex nativo no computador do servidor que usa o CODEX_HOME exibido. Mantenha-o fechado até verificar o resultado.`,"nativeMain.stepConfirm":`Marque a caixa de seleção abaixo para confirmar que o Codex está fechado e depois confirme a alteração.`,"nativeMain.stepResult":`Aguarde o resultado e o perfil ativo atualizado e depois siga as instruções para reabrir o Codex.`,"nativeMain.reopenHint":`Verifique o perfil ativo atualizado e depois reabra o Codex nativo no computador do servidor com o CODEX_HOME exibido. Siga qualquer exigência de reinicialização indicada aqui.`,"nativeMain.retryHint":`Atualize o status e verifique o perfil ativo. Para tentar novamente uma alteração de login, selecione a ação novamente e confirme que o Codex está fechado. Nada é repetido automaticamente.`,"nativeMain.errorCodexBusy":`O Codex nativo ainda está em execução no computador do servidor. Feche-o para o CODEX_HOME exibido antes de tentar novamente.`,"nativeMain.errorProcessCheck":`O servidor não pôde verificar se o Codex nativo está em execução. Verifique se ele está fechado nesse computador e consulte o diagnóstico do servidor antes de tentar novamente.`,"nativeMain.errorRequests":`As solicitações da conta principal ainda estão em execução ou terminando. Aguarde sua conclusão antes de tentar novamente.`,"nativeMain.errorBusy":`Outra operação de login nativo está em andamento. Aguarde sua conclusão antes de tentar novamente.`,"nativeMain.errorAuth":`O login nativo atual não pôde ser lido ou verificado com o perfil salvo. Consulte o diagnóstico do servidor antes de outra alteração.`,"nativeMain.errorKeyStore":`O perfil salvo ou o armazenamento de chaves do sistema não pôde ser aberto. Consulte seus diagnósticos no servidor antes de outra alteração.`,"nativeMain.errorStorage":`O servidor não consegue acessar com segurança a pasta de login ou o armazenamento de perfis. Verifique o diagnóstico do servidor antes de outra alteração.`,"nativeMain.errorProfile":`O estado do perfil salvo não pode ser usado nesta ação. Atualize e verifique a lista; consulte o diagnóstico se o problema persistir.`,"nativeMain.errorRecovery":`O armazenamento de perfis ou uma transação interrompida requer atenção. Atualize o status e consulte o diagnóstico do servidor. Use a recuperação somente quando o painel a oferecer.`,"nativeMain.errorRolledBack":`O servidor informa que a troca falhou e o login original foi restaurado. Verifique o perfil ativo atualizado antes de tentar novamente.`,"nativeMain.stopped":`Parei o Codex nativo que usa este CODEX_HOME e entendo que pode ser necessário reiniciá-lo.`,"nativeMain.cancel":`Cancelar`,"nativeMain.confirm":`Confirmar alteração do login nativo`,"nativeMain.unavailable":`As alterações de perfil estão indisponíveis. Verifique o código de diagnóstico antes de continuar.`}};function Xv(e){return(t,n)=>{let r=Yv[e][t];for(let[e,t]of Object.entries(n??{}))r=r.split(`{${e}}`).join(String(t));return r}}var Zv=`INVALID_REQUEST.CODEX_HOME_UNAVAILABLE.UNSUPPORTED_AUTH_STORE.AUTH_MISSING.AUTH_INVALID.AUTH_UNREADABLE.AUTH_TEMP_CLEANUP_REQUIRED.ACTIVE_PROFILE_MISMATCH.PROFILE_NOT_FOUND.PROFILE_ALREADY_EXISTS.PROFILE_DECRYPT_FAILED.KEYRING_UNAVAILABLE.KEYRING_KEY_MISSING.PROFILE_LOCK_UNAVAILABLE.NATIVE_PROFILE_BUSY.NATIVE_MAIN_OWNER_BUSY.NATIVE_MAIN_OWNER_UNAVAILABLE.NATIVE_MAIN_CLAIM_BUSY.NATIVE_MAIN_CLAIM_UNAVAILABLE.CODEX_BUSY.CODEX_PROCESS_CHECK_UNAVAILABLE.MAIN_REQUESTS_ACTIVE.RECOVERY_REQUIRED.AUTH_RESTORE_FAILED.SWITCH_ROLLED_BACK.PROFILE_METADATA_TOO_LARGE.PROFILE_STORAGE_UNSAFE.LEGACY_PROFILE_STATE.INTERNAL_ERROR.VAULT_INVALID.STAGING_CLEANUP_REQUIRED.NETWORK_ERROR.INVALID_RESPONSE.STATE_CHANGED`.split(`.`),Qv=class extends Error{code;constructor(e){super(e),this.code=e}};function $v(e){return e instanceof Qv?e.code:`NETWORK_ERROR`}function ey(){throw new Qv(`INVALID_RESPONSE`)}function ty(e){return!e||typeof e!=`object`||Array.isArray(e)?ey():e}function ny(e){return typeof e!=`string`||!e.trim()?ey():e}function ry(e){return e===null?null:ny(e)}function iy(e){return typeof e==`boolean`?e:ey()}function ay(e,t){return typeof e==`string`&&t.includes(e)?e:ey()}function oy(e){let t=ty(e);return{id:ny(t.id),label:ny(t.label),identityHint:ny(t.identityHint),state:ay(t.state,[`active`,`inactive`])}}function sy(e){let t=ty(e);if(!Array.isArray(t.profiles)||t.profiles.length>32)return ey();let n=t.profiles.map(oy),r=ry(t.activeProfileId);if(new Set(n.map(e=>e.id)).size!==n.length)return ey();let i=n.filter(e=>e.state===`active`);return(r===null?n.length!==0:i.length!==1||i[0].id!==r)?ey():{effectiveCodexHome:ny(t.effectiveCodexHome),activeProfileId:r,profiles:n}}function cy(e){let t=ty(e);return{effectiveCodexHome:ny(t.effectiveCodexHome),activeProfileId:ry(t.activeProfileId),supported:iy(t.supported),authStatus:ay(t.authStatus,[`ok`,`missing`,`invalid`,`unreadable`]),keyStore:ay(t.keyStore,[`available`,`missing-key`,`unavailable`]),vaultStatus:ay(t.vaultStatus,[`ok`,`missing`,`invalid`]),recoveryPending:iy(t.recoveryPending)}}async function ly(e,t,n,r,i){n.throwIfAborted();let a=await(i??fetch)(`${e}/api/native-main-profiles${t}`,{method:r?`POST`:`GET`,signal:n,cache:`no-store`,...r?{headers:{"content-type":`application/json`},body:JSON.stringify(r)}:{}}),o;try{o=await a.json()}catch{throw new Qv(`INVALID_RESPONSE`)}if(n.throwIfAborted(),!a.ok){let e=o&&typeof o==`object`?o.code:void 0;throw new Qv(typeof e==`string`&&Zv.includes(e)?e:`INTERNAL_ERROR`)}return o}async function uy(e,t,n){let[r,i]=await Promise.allSettled([ly(e,``,t,void 0,n).then(sy),ly(e,`/doctor`,t,void 0,n).then(cy)]);if(t.throwIfAborted(),i.status===`rejected`)throw i.reason;if(r.status===`rejected`){if(!i.value.recoveryPending)throw r.reason;return{doctor:i.value,list:null}}if(r.value.effectiveCodexHome!==i.value.effectiveCodexHome||r.value.activeProfileId!==i.value.activeProfileId)throw new Qv(`STATE_CHANGED`);return{doctor:i.value,list:r.value}}function dy(e){let t=e.doctor;return t.supported?t.recoveryPending?`RECOVERY_REQUIRED`:t.authStatus===`ok`?t.keyStore===`available`?t.vaultStatus===`invalid`?`VAULT_INVALID`:null:t.keyStore===`missing-key`?`KEYRING_KEY_MISSING`:`KEYRING_UNAVAILABLE`:t.authStatus===`missing`?`AUTH_MISSING`:t.authStatus===`invalid`?`AUTH_INVALID`:`AUTH_UNREADABLE`:`UNSUPPORTED_AUTH_STORE`}function fy(e){let t=e.doctor;return!!e.list&&t.supported&&t.authStatus===`ok`&&t.keyStore===`available`&&t.vaultStatus!==`invalid`&&!t.recoveryPending}function py(e,t){let n=e.doctor;return n.supported?t.kind===`recover`?n.recoveryPending:fy(e)&&!!e.list?.profiles.some(e=>e.id===t.target&&e.label===t.label&&e.state===`inactive`):!1}function my(e,t){return e.doctor.effectiveCodexHome===t.doctor.effectiveCodexHome&&e.doctor.activeProfileId===t.doctor.activeProfileId&&e.doctor.recoveryPending===t.doctor.recoveryPending}async function hy(e,t,n,r){let i=ty(await ly(e,`/register`,n,{label:t.trim()},r)),a=ny(i.effectiveCodexHome);return oy(i.profile).state===`active`?a:ey()}async function gy(e,t,n,r,i){if(!n)throw new Qv(`INVALID_REQUEST`);let a=ty(await ly(e,t.kind===`switch`?`/switch`:`/recover`,r,t.kind===`switch`?{target:t.target,confirmedStopped:!0}:{rollback:t.rollback,confirmedStopped:!0},i));if(a.ok!==!0)return ey();if(t.kind===`switch`){let e=oy(a.activeProfile);if(e.id!==t.target||e.state!==`active`)return ey()}let o=t.kind===`recover`&&a.restartRequired===void 0&&a.recovered===!1?!1:iy(a.restartRequired);return{effectiveCodexHome:ny(a.effectiveCodexHome),restartRequired:o,...typeof a.recovered==`boolean`?{recovered:a.recovered}:{}}}var _y=2e4,vy=Symbol(`account-refresh-timeout`),yy=class{state={open:!1,busy:!1,blocked:!1,snapshot:null,label:``,action:null,confirmedStopped:!1,previous:null,error:null,result:null,refreshFailed:!1};listener=null;epoch=0;pending=null;onChanged=()=>{};restartRequired=!1;resultHome=null;apiBase;accountRefreshTimeoutMs;fetchImpl;constructor(e,t=_y,n){this.apiBase=e,this.accountRefreshTimeoutMs=t,this.fetchImpl=n}attach(e){let t=++this.epoch;return this.listener=e,e(this.state),()=>{this.epoch===t&&(this.epoch++,this.listener=null,this.pending?.abort(),this.pending=null,this.state.busy&&(this.state={...this.state,busy:!1,snapshot:null,action:null,confirmedStopped:!1,previous:null,refreshFailed:!0}))}}updateOptions(e,t){this.onChanged=t,this.state.blocked!==e&&this.set({blocked:e,action:null,confirmedStopped:!1})}set(e){this.state={...this.state,...e},this.listener?.(this.state)}current(e){return this.epoch===e&&this.listener!==null}accept(e){let t=this.state.previous,n=this.resultHome!==null&&this.resultHome!==e.doctor.effectiveCodexHome;n&&(this.restartRequired=!1,this.resultHome=null),this.set({snapshot:e,...n?{result:null}:{},previous:t&&t.home===e.doctor.effectiveCodexHome&&t.active===e.doctor.activeProfileId?t:null})}setLabel(e){this.pending||this.set({label:e})}setStopped(e){!this.pending&&this.state.action&&!this.state.blocked&&this.set({confirmedStopped:e})}select(e){this.pending||(!e||!this.state.blocked&&!this.state.refreshFailed&&this.state.snapshot&&py(this.state.snapshot,e))&&this.set({action:e,confirmedStopped:!1,error:null})}async toggle(){if(this.pending)return;let e=!this.state.open;this.set({open:e,action:null,confirmedStopped:!1}),e&&await this.refresh()}async run(e){if(!this.listener||this.pending||this.state.blocked)return;let t=this.epoch,n=new AbortController;this.pending=n;let r=setTimeout(()=>n.abort(),45e3);this.set({busy:!0});try{await e(t,n.signal)}catch(e){this.current(t)&&this.set({error:$v(e),snapshot:null})}finally{clearTimeout(r),this.current(t)&&(this.pending=null,this.set({busy:!1}))}}async refresh(){this.state.action||await this.run(async(e,t)=>{let n=this.state.refreshFailed;this.set({error:null});let r=await uy(this.apiBase,t,this.fetchImpl);this.current(e)&&(this.accept(r),this.set({refreshFailed:!1}),n&&await this.refreshAccount(e))})}async refreshAccount(e){if(!this.current(e))return;let t=new AbortController,n,r=(async()=>{try{return await this.onChanged(t.signal)}catch{return!1}})(),i=new Promise(e=>{n=setTimeout(()=>{t.abort(),e(vy)},this.accountRefreshTimeoutMs)});try{let t=await Promise.race([r,i]);this.current(e)&&(t===!1||t===vy)&&this.set({refreshFailed:!0})}finally{clearTimeout(n)}}async reconcile(e){if(!this.current(e))return;let t=new AbortController;this.pending=t;let n=setTimeout(()=>t.abort(),2e4);try{let n=await uy(this.apiBase,t.signal,this.fetchImpl);if(!this.current(e))return;this.accept(n)}catch{this.current(e)&&this.set({snapshot:null,refreshFailed:!0})}finally{clearTimeout(n)}await this.refreshAccount(e)}async register(){let e=this.state.snapshot,t=this.state.label.trim();e&&!this.state.refreshFailed&&t&&!this.state.action&&fy(e)&&await this.mutate(e,{label:t})}async confirm(){let{snapshot:e,action:t,confirmedStopped:n,refreshFailed:r}=this.state;e&&t&&n&&!r&&py(e,t)&&await this.mutate(e,{action:t})}async mutate(e,t){await this.run(async(n,r)=>{this.set({error:null,result:this.restartRequired?`restart`:null,refreshFailed:!1});let i=!1;try{let a=await uy(this.apiBase,r,this.fetchImpl);if(r.throwIfAborted(),!this.current(n)||this.state.blocked)return;if(this.accept(a),!my(e,a)||(`action`in t?!py(a,t.action):!fy(a)))throw new Qv(`STATE_CHANGED`);if(i=!0,`label`in t){let i=await hy(this.apiBase,t.label,r,this.fetchImpl);if(!this.current(n))return;if(i!==e.doctor.effectiveCodexHome)throw new Qv(`STATE_CHANGED`);this.resultHome=i,this.set({label:``,result:this.restartRequired?`restart`:`saved`})}else{let i=await gy(this.apiBase,t.action,!0,r,this.fetchImpl);if(!this.current(n))return;if(i.effectiveCodexHome!==e.doctor.effectiveCodexHome)throw new Qv(`STATE_CHANGED`);this.resultHome=i.effectiveCodexHome,this.restartRequired||=i.restartRequired,this.set({previous:t.action.kind===`switch`?{id:e.doctor.activeProfileId,home:e.doctor.effectiveCodexHome,active:t.action.target}:null,result:this.restartRequired?`restart`:`done`})}}catch(e){this.current(n)&&this.set({error:$v(e),previous:null})}finally{this.current(n)&&this.set({action:null,confirmedStopped:!1}),i&&await this.reconcile(n)}})}},by={INVALID_REQUEST:`nativeMain.error`,CODEX_HOME_UNAVAILABLE:`nativeMain.errorStorage`,UNSUPPORTED_AUTH_STORE:`nativeMain.unsupported`,AUTH_MISSING:`nativeMain.errorAuth`,AUTH_INVALID:`nativeMain.errorAuth`,AUTH_UNREADABLE:`nativeMain.errorAuth`,AUTH_TEMP_CLEANUP_REQUIRED:`nativeMain.errorRecovery`,ACTIVE_PROFILE_MISMATCH:`nativeMain.errorAuth`,PROFILE_NOT_FOUND:`nativeMain.errorProfile`,PROFILE_ALREADY_EXISTS:`nativeMain.errorProfile`,PROFILE_DECRYPT_FAILED:`nativeMain.errorKeyStore`,KEYRING_UNAVAILABLE:`nativeMain.errorKeyStore`,KEYRING_KEY_MISSING:`nativeMain.errorKeyStore`,PROFILE_LOCK_UNAVAILABLE:`nativeMain.errorStorage`,NATIVE_PROFILE_BUSY:`nativeMain.errorBusy`,NATIVE_MAIN_OWNER_BUSY:`nativeMain.errorBusy`,NATIVE_MAIN_OWNER_UNAVAILABLE:`nativeMain.errorStorage`,NATIVE_MAIN_CLAIM_BUSY:`nativeMain.errorBusy`,NATIVE_MAIN_CLAIM_UNAVAILABLE:`nativeMain.errorStorage`,CODEX_BUSY:`nativeMain.errorCodexBusy`,CODEX_PROCESS_CHECK_UNAVAILABLE:`nativeMain.errorProcessCheck`,MAIN_REQUESTS_ACTIVE:`nativeMain.errorRequests`,RECOVERY_REQUIRED:`nativeMain.errorRecovery`,AUTH_RESTORE_FAILED:`nativeMain.errorRecovery`,SWITCH_ROLLED_BACK:`nativeMain.errorRolledBack`,PROFILE_METADATA_TOO_LARGE:`nativeMain.errorProfile`,PROFILE_STORAGE_UNSAFE:`nativeMain.errorStorage`,LEGACY_PROFILE_STATE:`nativeMain.errorProfile`,INTERNAL_ERROR:`nativeMain.error`,VAULT_INVALID:`nativeMain.errorRecovery`,STAGING_CLEANUP_REQUIRED:`nativeMain.errorRecovery`,NETWORK_ERROR:`nativeMain.error`,INVALID_RESPONSE:`nativeMain.error`,STATE_CHANGED:`nativeMain.changed`},xy=`ocx account main doctor`;function Sy({t:e}){let[t,n=``]=e(`nativeMain.doctorHint`).split(`{cmd}`);return(0,Q.jsxs)(Q.Fragment,{children:[t,(0,Q.jsx)(`code`,{className:`chip`,children:xy}),n]})}function Cy({t:e,id:t,open:n,busy:r,blocked:i,snapshot:a,label:o,action:s,confirmedStopped:c,previousId:l,error:u,result:d,refreshFailed:f,summaryRef:p,confirmationRef:m,onToggle:h,onRefresh:g,onLabel:_,onRegister:v,onSelect:y,onStopped:b,onConfirm:x}){let S=r||i,C=S||f,w=a?dy(a):null,T=a?.list?.profiles??[],E=T.find(e=>e.id===a?.doctor.activeProfileId),D=T.find(e=>e.id===l&&e.state===`inactive`);return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`${t}-heading`,style:{marginBottom:12},children:[(0,Q.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`},children:[(0,Q.jsx)(`strong`,{id:`${t}-heading`,children:e(`nativeMain.title`)}),(0,Q.jsx)(`button`,{ref:p,type:`button`,className:`btn btn-sm btn-ghost`,"aria-expanded":n,"aria-controls":`${t}-panel`,onClick:h,disabled:r,children:e(n?`nativeMain.close`:`nativeMain.manage`)})]}),n&&(0,Q.jsxs)(`div`,{id:`${t}-panel`,"aria-busy":r,children:[(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.separate`)}),a&&(0,Q.jsxs)(`dl`,{children:[(0,Q.jsx)(`dt`,{children:e(`nativeMain.home`)}),(0,Q.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:(0,Q.jsx)(`code`,{children:a.doctor.effectiveCodexHome})}),a.list&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{children:e(`nativeMain.current`)}),(0,Q.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:E?.label??e(`nativeMain.unregistered`)})]})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.physicalHint`)}),i&&(0,Q.jsx)(`p`,{role:`status`,className:`notice notice-warn`,children:e(`nativeMain.busyOther`)}),r&&(0,Q.jsx)(`p`,{role:`status`,children:e(`nativeMain.working`)}),u&&(0,Q.jsxs)(`div`,{role:`alert`,className:`notice notice-err native-main-notice`,children:[(0,Q.jsx)(`p`,{children:e(by[u])}),(0,Q.jsx)(`p`,{children:e(`nativeMain.retryHint`)}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`code`,{children:u}),` `,(0,Q.jsx)(Sy,{t:e})]})]}),d&&!r&&!u&&!s&&(0,Q.jsxs)(`div`,{role:`status`,className:`notice native-main-notice`,children:[(0,Q.jsx)(`strong`,{children:e(`nativeMain.lastResult`)}),(0,Q.jsx)(`p`,{children:e(d===`saved`?`nativeMain.saved`:d===`restart`?`nativeMain.restart`:`nativeMain.done`)}),d!==`saved`&&a&&!f&&(0,Q.jsx)(`p`,{children:e(`nativeMain.reopenHint`)})]}),f&&(0,Q.jsx)(`p`,{role:`alert`,className:`notice notice-warn`,children:e(`nativeMain.refreshFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,disabled:S||!!s,children:e(`nativeMain.refresh`)}),a&&!a.doctor.supported&&(0,Q.jsx)(`p`,{role:`alert`,children:e(`nativeMain.unsupported`)}),w&&a?.doctor.supported&&!a.doctor.recoveryPending&&(0,Q.jsxs)(`p`,{role:`status`,children:[e(`nativeMain.unavailable`),` `,(0,Q.jsx)(`code`,{children:w})]}),a?.doctor.recoveryPending&&(0,Q.jsxs)(`div`,{className:`notice notice-warn`,children:[(0,Q.jsx)(`p`,{children:e(`nativeMain.recoveryHint`)}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!a.doctor.supported,onClick:()=>y({kind:`recover`,rollback:!1}),children:e(`nativeMain.recover`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!a.doctor.supported,onClick:()=>y({kind:`recover`,rollback:!0}),children:e(`nativeMain.rollback`)})]})]}),a?.list&&(0,Q.jsxs)(Q.Fragment,{children:[T.length===0&&(0,Q.jsx)(`p`,{children:e(`nativeMain.empty`)}),(0,Q.jsx)(`ul`,{style:{listStyle:`none`,padding:0},children:T.map(t=>(0,Q.jsxs)(`li`,{className:`row`,style:{padding:`8px 0`,flexWrap:`wrap`},children:[(0,Q.jsx)(`strong`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.label}),` `,(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.identityHint}),t.state===`active`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:e(`nativeMain.active`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!py(a,{kind:`switch`,target:t.id,label:t.label}),"aria-label":e(`nativeMain.switchTo`,{label:t.label}),onClick:()=>y({kind:`switch`,target:t.id,label:t.label}),children:e(`nativeMain.switch`)})]},t.id))}),D&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!py(a,{kind:`switch`,target:D.id,label:D.label}),onClick:()=>y({kind:`switch`,target:D.id,label:D.label}),children:e(`nativeMain.restore`,{label:D.label})}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.restoreHint`)})]}),(0,Q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),v()},children:[(0,Q.jsx)(`label`,{htmlFor:`${t}-label`,children:e(`nativeMain.label`)}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Q.jsx)(`input`,{id:`${t}-label`,className:`input min-w-0 flex-[1_1_14rem]`,value:o,onChange:e=>_(e.target.value),disabled:C||!!s||!fy(a),maxLength:80,autoComplete:`off`}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-sm`,disabled:C||!!s||!o.trim()||!fy(a),children:e(`nativeMain.save`)})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.saveHint`)})]})]}),s&&a&&(0,Q.jsxs)(`div`,{ref:m,role:`group`,tabIndex:-1,"aria-labelledby":`${t}-confirm-title`,className:`notice notice-warn`,style:{marginTop:12,display:`block`},onKeyDown:e=>{e.key===`Escape`&&!r&&(e.preventDefault(),y(null))},children:[(0,Q.jsx)(`h3`,{id:`${t}-confirm-title`,style:{overflowWrap:`anywhere`},children:e(s.kind===`switch`?`nativeMain.switchTo`:s.rollback?`nativeMain.rollback`:`nativeMain.recover`,{label:s.kind===`switch`?s.label:``})}),(0,Q.jsx)(`p`,{children:e(`nativeMain.confirmHint`)}),(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:a.doctor.effectiveCodexHome}),(0,Q.jsxs)(`ol`,{children:[(0,Q.jsx)(`li`,{children:e(`nativeMain.stepClose`)}),(0,Q.jsx)(`li`,{children:e(`nativeMain.stepConfirm`)}),(0,Q.jsx)(`li`,{children:e(`nativeMain.stepResult`)})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsxs)(`label`,{htmlFor:`${t}-stopped`,children:[(0,Q.jsx)(`input`,{id:`${t}-stopped`,type:`checkbox`,checked:c,disabled:C,onChange:e=>b(e.target.checked)}),` `,e(`nativeMain.stopped`)]})}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:r,onClick:()=>y(null),children:e(`nativeMain.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-primary`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:C||!c||!py(a,s),onClick:x,children:e(`nativeMain.confirm`)})]})]})]})]})}function wy(e){return(0,Q.jsx)(Ty,{...e},e.apiBase)}function Ty({apiBase:e,disabled:t=!1,onChanged:n}){let{locale:r}=s(),i=Xv(r),a=(0,Z.useId)(),[o]=(0,Z.useState)(()=>new yy(e)),[c,l]=(0,Z.useState)(o.state),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(!1);return(0,Z.useLayoutEffect)(()=>o.attach(l),[o]),(0,Z.useLayoutEffect)(()=>{o.updateOptions(t,n)},[o,t,n]),(0,Z.useLayoutEffect)(()=>{c.action?(f.current=!0,d.current?.focus()):!c.busy&&f.current&&(f.current=!1,u.current?.focus())},[c.action,c.busy]),(0,Q.jsx)(Cy,{t:i,id:a,...c,previousId:c.previous?.id??null,summaryRef:u,confirmationRef:d,onToggle:()=>{o.toggle()},onRefresh:()=>{o.refresh()},onLabel:e=>o.setLabel(e),onRegister:()=>{o.register()},onSelect:e=>o.select(e),onStopped:e=>o.setStopped(e),onConfirm:()=>{o.confirm()}})}var Ey={"reset-first":{on:`accountPool.strategyHintResetFirst`,off:`codexAuth.autoSwitchQuotaOffDesc`},quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function Dy({threshold:e,draft:t,strategy:n=`quota`,hydrated:r=!0,saving:i,loadError:a,feedback:o,onDraftChange:s,onEditingChange:c,onCommit:l,onCancel:u,onToggle:d,onRetry:f}){let p=b(),m=(0,Z.useRef)(!1),h=e>0,g=Ey[n][h?`on`:`off`],_=i||!r,v=i?p(`common.saving`):o?.message??``,y=i?`pending`:o?.tone,x=v?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,Q.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,Q.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,Q.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,Q.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,Q.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,Q.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(c(!1),m.current?m.current=!1:h&&!_&&l())},children:[a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,Q.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:_,"aria-disabled":_,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{_||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||_||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(p_,{disabled:_,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(f_(t,1,1,100))},onDecrement:()=>{c(!0),s(f_(t,-1,1,100))}})]})]}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:_,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})})]}),v&&(0,Q.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${y===`err`?` is-error`:``}`,role:y===`err`?`alert`:`status`,"aria-atomic":`true`,children:v})]})}function Oy(){let[e,t]=(0,Z.useState)(!1);return{open:e,id:(0,Z.useId)(),toggle:()=>t(e=>!e)}}var ky={"reset-first":`accountPool.strategyResetFirst`,quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},Ay={"reset-first":`accountPool.strategyHintResetFirst`,quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function jy({strategy:e,codex:t=!1,threshold:n,stickyDraft:r,disabled:i=!1,strategySelectId:a=`account-pool-strategy`,stickyInputId:o=`account-pool-sticky-limit`,onStrategyChange:s,onStickyDraftChange:c,onStickyCommit:l}){let u=b(),d=Oy(),f=cv.filter(e=>t||e!==`reset-first`).map(e=>({value:e,label:u(ky[e])})),p=n===void 0?null:e===`round-robin`?u(`accountPool.thresholdNotUsed`):n>0?u(e===`fill-first`?`accountPool.drainAtThreshold`:e===`reset-first`?`accountPool.resetBelowThreshold`:`accountPool.switchAtThreshold`,{threshold:String(n)}):u(`accountPool.proactiveSwitchingOff`);return(0,Q.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsxs)(`span`,{className:`acc-strategy-title flex items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`${a}-label`,children:u(`accountPool.strategy`)}),(0,Q.jsx)(j_,{open:d.open,controls:d.id,name:u(`accountPool.strategy`),onToggle:d.toggle})]}),(0,Q.jsxs)(M_,{id:d.id,open:d.open,className:`acc-strategy-help mt-1.5 flex flex-col gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`desc`,children:u(`accountPool.strategyDesc`)}),(0,Q.jsx)(`span`,{className:`desc`,children:u(Ay[e])}),(0,Q.jsx)(`span`,{className:`desc`,children:u(`accountPool.unboundDefinition`)})]})]}),(0,Q.jsxs)(`div`,{className:`setting-controls`,children:[(0,Q.jsx)(Vn,{id:a,value:e,options:f,disabled:i,label:u(`accountPool.strategy`),onChange:e=>s(e)}),p&&(0,Q.jsx)(`span`,{className:`badge badge-muted account-pool-threshold-badge`,"data-testid":`account-pool-threshold-summary`,children:p})]})]}),e===`round-robin`&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`label`,{className:`setting-label`,htmlFor:o,children:[(0,Q.jsx)(`span`,{className:`title`,children:u(`accountPool.stickyLimit`)}),(0,Q.jsx)(`span`,{className:`desc`,children:u(`accountPool.stickyLimitHelp`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{id:o,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:r,disabled:i,"aria-label":u(`accountPool.stickyLimitAria`),onChange:e=>c(e.target.value),onBlur:()=>l(),onKeyDown:e=>{e.nativeEvent.isComposing||i||e.key===`Enter`&&(e.preventDefault(),l())}}),(0,Q.jsx)(p_,{disabled:i,incrementLabel:u(`accountPool.stickyLimitInc`),decrementLabel:u(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=f_(r,1,1,100);c(e),l(e)},onDecrement:()=>{let e=f_(r,-1,1,100);c(e),l(e)}})]})})]})]})}function My(e){if(!e||typeof e!=`object`)return null;let t=e;if(!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)&&!(`autoSwitchThreshold`in t))return null;let n=typeof t.autoSwitchThreshold==`number`?t.autoSwitchThreshold:void 0;return{strategy:mv(t.accountPoolStrategy),stickyLimit:gv(t.accountPoolStickyLimit),threshold:n}}function Ny({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r,threshold:i}){let a=b(),[o,s]=(0,Z.useState)(uv),[c,l]=(0,Z.useState)(1),[u,d]=(0,Z.useState)(`1`),[f,p]=(0,Z.useState)(void 0),[m,h]=(0,Z.useState)(!1),g=(0,Z.useRef)(!1),[_,v]=(0,Z.useState)(!1),y=(0,Z.useRef)(!1),x=(0,Z.useRef)(!1),S=(0,Z.useRef)(0),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(null),D=(0,Z.useCallback)(e=>{let t=mv(e.accountPoolStrategy),n=gv(e.accountPoolStickyLimit);typeof e.autoSwitchThreshold==`number`&&p(e.autoSwitchThreshold),s(t),r?.(t),l(n),d(String(n)),g.current=!0,h(!0),w(!1),E(null)},[r]),O=(0,Z.useCallback)(e=>{let t=My(e);t&&D({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit,autoSwitchThreshold:t.threshold})},[D]),k=(0,Z.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(y.current){x.current=!0;return}D(n)}catch{y.current||w(!0)}},[e,D]),A=(0,Z.useCallback)(()=>{x.current&&(x.current=!1,queueMicrotask(()=>{y.current?x.current=!0:k()}))},[k]);(0,Z.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>S.current,acceptActiveRead:(e,t)=>{t===S.current&&(y.current?x.current=!0:O(e))},rejectActiveRead:()=>{g.current||w(!0)}});return!y.current&&n&&O(n()),e},[t,O,n]),(0,Z.useEffect)(()=>{n&&!t&&(y.current||O(n()))},[n,O,t]),(0,Z.useEffect)(()=>{t||k()},[k,t]);let j=(0,Z.useCallback)(async t=>{if(y.current)return;let n=o,i=c;t.strategy!==void 0&&(s(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(l(t.stickyLimit),d(String(t.stickyLimit))),y.current=!0,v(!0),E(null),S.current+=1;let u=await wv(e,t);S.current+=1,u.ok?(s(u.strategy),r?.(u.strategy),l(u.stickyLimit),d(String(u.stickyLimit)),g.current=!0,h(!0)):(E(a(`accountPool.strategyUpdateFailed`)),s(n),r?.(n),l(i),d(String(i))),y.current=!1,v(!1),A()},[e,r,A,c,o,a]),M=_||C||!m;return(0,Q.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":_||!m&&!C,children:[C&&(0,Q.jsx)(`div`,{className:`card-sub`,role:`alert`,children:a(`accountPool.strategyLoadFailed`)}),C&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{k()},children:a(`common.retry`)}),!C&&(0,Q.jsx)(jy,{codex:!0,strategy:o,threshold:i===void 0?f:i,stickyDraft:u,disabled:M,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{M||e===o||j({strategy:e})},onStickyDraftChange:d,onStickyCommit:e=>{if(M)return;let t=_v(e??u);t===null?(d(String(c)),E(a(`accountPool.stickyLimitInvalid`))):t===c?d(String(t)):j({stickyLimit:t})}}),T&&(0,Q.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:T})]})}function Py({t:e,open:t,onToggle:n,children:r}){return(0,Q.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,Q.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function Fy(e,t,n){let r=Y_(e,n),[a,o]=(0,Z.useState)(80),[s,c]=(0,Z.useState)(`80`),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(80),y=(0,Z.useRef)(!1),b=(0,Z.useRef)(80),x=(0,Z.useRef)(!1),S=(0,Z.useRef)(!1),C=(0,Z.useRef)(!1),w=(0,Z.useRef)(0),T=(0,Z.useRef)(null),E=(0,Z.useRef)(null),D=(0,Z.useCallback)(e=>{_.current=e,y.current=!0,u(!0),o(e),e>0&&(b.current=e),c(String(e>0?e:b.current))},[]),O=(0,Z.useCallback)(e=>{x.current||S.current?T.current=e:(T.current=null,D(e))},[D]),k=(0,Z.useCallback)(()=>{let e=T.current;return e!==null&&(T.current=null,D(e),!0)},[D]),A=(0,Z.useCallback)(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null),g(null)},[]),j=(0,Z.useCallback)((e,t)=>{E.current!==null&&window.clearTimeout(E.current),g({tone:t?`err`:`ok`,message:e}),E.current=window.setTimeout(()=>{g(null),E.current=null},5e3)},[]);(0,Z.useEffect)(()=>()=>{E.current!==null&&window.clearTimeout(E.current)},[]);let M=(0,Z.useCallback)(()=>(y.current||f(!1),w.current),[]),N=(0,Z.useCallback)((e,t)=>{f(!1);let n=Av(e),r=kv(x.current,S.current,t,w.current);r===`defer`?T.current=Ev(n):r===`apply`&&O(Ev(n))},[O]),P=(0,Z.useCallback)(e=>{y.current||x.current||S.current||(f(!1),D(Ev(Av(e))))},[D]),F=(0,Z.useCallback)(()=>{y.current||f(!0)},[]),I=(0,Z.useCallback)(async(n,a,o=!0)=>{if(S.current)return!1;S.current=!0,x.current=!1,A(),m(!0),w.current+=1;let s=r;try{let r=await Mv(e,n,(e,t)=>i(s,e,t));return w.current+=1,v(s)?(r?(T.current=null,D(n),o&&j(t.updated,!1)):(k()||D(a),j(t.updateFailed,!0)),r):!1}finally{S.current=!1,m(!1)}},[e,D,A,t.updateFailed,t.updated,k,r,j]),L=(0,Z.useCallback)(()=>{x.current=!1;let e=_.current;k()||c(String(e>0?e:b.current)),j(t.invalid,!0)},[t.invalid,k,j]),R=(0,Z.useCallback)(()=>{x.current=!1,C.current=!0,A();let e=_.current;k()||c(String(e>0?e:b.current))},[A,k]),z=(0,Z.useCallback)(async()=>{if(C.current)return C.current=!1,!0;if(!y.current||S.current)return!1;let e=_.current;x.current=!1;let t=Dv(s);return t===null?(L(),!1):t===e?(k()||c(String(t)),!0):I(t,e)},[s,k,L,I]),B=(0,Z.useCallback)(async()=>{if(!y.current||S.current)return!1;let e=_.current;x.current=!1;let t=jv(e,s,b.current),n=await I(t.threshold,e);return n?(b.current=t.lastEnabled,t.threshold===0&&c(String(t.lastEnabled)),n):!1},[s,I]);return{threshold:a,draft:s,hydrated:l,saving:p,loadError:d,feedback:h,beginServerRead:M,acceptServerRead:N,hydrateServerValue:P,rejectServerRead:F,setDraft:(0,Z.useCallback)(e=>{y.current&&(x.current=!0,C.current=!1,A(),c(e))},[A]),setEditing:(0,Z.useCallback)(e=>{x.current=e},[]),commit:z,cancel:R,toggle:B,retry:(0,Z.useCallback)(()=>{f(!1),A()},[A])}}function Iy({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=b(),a=rv(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=tv.map(e=>({value:String(e),label:sv(i,e)})),l=av(a)?c:[{value:String(a),label:sv(i,a)},...c];return(0,Q.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,Q.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,Q.jsx)(Vn,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(rv(Number.parseInt(e,10)))}),(0,Q.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function Ly({value:e}){let t=b(),n=rv(e);return n===0?null:(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:sv(t,n)})}function Ry({summary:e,busy:t,onToggleAll:n}){let r=b(),i=(0,Z.useId)(),a=e.total>0&&e.enabled===e.total,o=e.enabled>0&&!a;return(0,Q.jsxs)(`span`,{className:`codex-credit-spend`,"aria-busy":t||void 0,children:[(0,Q.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:r(`codexAuth.creditSpend`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${a?`on`:``}`,"aria-label":r(`codexAuth.creditSpendAria`),"aria-describedby":i,"aria-pressed":o?`mixed`:a,title:r(`codexAuth.creditsAfterLimitHint`),disabled:t||e.total===0,onClick:()=>n(!a),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:i,className:`sr-only`,children:r(`codexAuth.creditsAfterLimitHint`)})]})}function zy({accountLabel:e,enabled:t,saving:n,disabled:r,hint:i,onChange:a}){let o=b(),s=(0,Z.useId)(),c=t===!0,l=i??o(`codexAuth.creditsAfterLimitHint`);return(0,Q.jsxs)(`div`,{className:`codex-account-credits`,title:l,"aria-busy":n||void 0,children:[(0,Q.jsx)(`span`,{className:`codex-account-credits__label`,children:o(`codexAuth.creditsAfterLimit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle codex-account-credits__toggle ${c?`on`:``}`,disabled:r||n,"aria-pressed":c,"aria-label":o(`codexAuth.creditsAfterLimitAria`,{email:e}),"aria-describedby":s,onClick:()=>a(!c),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:s,className:`sr-only`,children:l})]})}function By({enabled:e}){let t=b();return e===!0?(0,Q.jsx)(`span`,{className:`badge badge-amber`,title:t(`codexAuth.creditsAfterLimitHint`),children:t(`codexAuth.creditsOn`)}):null}var Vy=864e13,Hy=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Uy=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0,Wy=e=>Uy(e)&&e<=Vy;function Gy(e){if(!(!Hy(e)||!Wy(e.resetAtMs)||!Wy(e.observedAt)||!Uy(e.usedPercent)||e.usedPercent>100||e.source!==`wham`&&e.source!==`response-header`))return{resetAtMs:e.resetAtMs,usedPercent:e.usedPercent,source:e.source,observedAt:e.observedAt}}function Ky(e){if(!Array.isArray(e))return;let t=e.slice(0,2).flatMap(e=>{if(!Hy(e)||e.family!==`account`&&e.family!==`spark`||!Array.isArray(e.windows)||e.windows.length!==2)return[];let t=Gy(e.windows[0]),n=Gy(e.windows[1]);return t&&n?[{family:e.family,windows:[t,n]}]:[]});return t.length>0?t:void 0}function qy(e,t,n){let r=Ky(e)?.[0];if(!r)return;let i=e=>new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(new Date(e)),a=e=>`${Math.round(e.usedPercent)}% → ${i(e.resetAtMs)} (${e.source}, ${i(e.observedAt)})`;return t(`codexAuth.weeklyConflict`,{first:a(r.windows[0]),second:a(r.windows[1])})}function Jy({active:e=!1,paused:t=!1,dot:n,name:r,sub:i,chips:a,actions:o,more:s,children:c}){return(0,Q.jsxs)(`div`,{className:X(`card acc-row`,e&&`card-active is-active`,t&&`is-paused`,s?`has-more`:void 0),children:[(0,Q.jsxs)(`div`,{className:`acc-row__head flex min-w-0 items-start gap-3`,children:[(0,Q.jsx)(`span`,{className:`flex h-5 items-center`,children:(0,Q.jsx)(A_,{tone:n})}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,Q.jsx)(`strong`,{className:`acc-row__name min-w-0 truncate text-[14px] leading-5 font-semibold tracking-[-0.005em] text-fg`,children:r}),a&&(0,Q.jsx)(`span`,{className:`card-badges acc-chips flex flex-wrap items-center gap-1`,children:a})]}),i&&(0,Q.jsx)(`div`,{className:`acc-row__sub min-w-0 truncate text-[12.5px] leading-[18px] text-fg-muted`,children:i})]}),o&&(0,Q.jsx)(`div`,{className:`acc-row__actions flex shrink-0 flex-wrap items-center justify-end gap-1`,children:o})]}),c,s]})}function Yy(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`currentColor`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`}),(0,Q.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`})]})}function Xy({label:e,title:t,open:n,onToggle:r,heading:i,children:a}){return(0,Q.jsxs)(`details`,{className:`codex-account-more acc-more`,open:n,onToggle:r?e=>r(e.currentTarget.open):void 0,children:[(0,Q.jsx)(`summary`,{className:`acc-more__summary`,"aria-label":e,title:t,children:(0,Q.jsx)(Yy,{})}),(0,Q.jsxs)(`div`,{className:`codex-account-more-body acc-settings`,children:[i&&(0,Q.jsx)(`div`,{className:`acc-settings__heading`,children:i}),a]})]})}function Zy({label:e,children:t,className:n}){return(0,Q.jsxs)(`div`,{className:X(`acc-setting`,n),children:[e&&(0,Q.jsx)(`span`,{className:`acc-setting__label`,children:e}),(0,Q.jsx)(`div`,{className:`acc-setting__control`,children:t})]})}function Qy({credits:e,t,locale:n}){if(!e)return null;let r=e.balance!==void 0&&/^\d+(\.\d+)?$/.test(e.balance)?Number(e.balance):void 0,i=r!==void 0&&Number.isFinite(r);if(!i&&e.unlimited!==!0&&e.overageLimitReached!==!0)return null;let a=new Intl.NumberFormat(n,{maximumFractionDigits:2}),o=i?a.format(r):``,s=e.overageLimitReached===!0,c=e.unlimited===!0,l=s?`${o?`${o} · `:``}${t(`codexAuth.creditsOverage`)}`:c?t(`codexAuth.creditsUnlimited`):o,u=!s&&(c||i&&r>0),d=e=>e?e.map(e=>a.format(e)).join(`–`):`—`,f=e.approxLocalMessages||e.approxCloudMessages?t(`codexAuth.creditsApprox`,{local:d(e.approxLocalMessages),cloud:d(e.approxCloudMessages)}):void 0;return(0,Q.jsxs)(`div`,{className:`quota-row quota-row--codex-credits`,title:f,children:[(0,Q.jsx)(`span`,{className:`quota-label`,children:t(`codexAuth.credits`)}),(0,Q.jsx)(`span`,{className:`quota-reset-label`,children:t(`codexAuth.creditsRemaining`)}),(0,Q.jsx)(`span`,{className:`quota-reset-day`}),(0,Q.jsx)(`span`,{className:`quota-reset-time`}),(0,Q.jsx)(`div`,{className:`bar`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`bar-fill bar-green`,style:{"--bar-scale":u?`1`:`0`}})}),(0,Q.jsx)(`span`,{className:`quota-val`,children:l})]})}function $y(e,t){return`${e??``}\0${JSON.stringify(t)}`}var eb={month:`short`,day:`numeric`,year:`numeric`},tb={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},nb=new Map;function rb(e,t){let n=$y(e,t),r=nb.get(n);return r||(r=new Intl.DateTimeFormat(e,t),nb.set(n,r)),r}function ib(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:rb(t,eb).format(n)}function ab(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:rb(t,tb).format(n)}var ob=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function sb(e,t){return!Number.isFinite(e)||e<0?`—`:`~${ob.format(e)}`}function cb(e,t){return ib(e,t)}function lb(e,t){return ab(e,t)}function ub(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function db({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=ub(n),s=o<=7;return(0,Q.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(Xe,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,Q.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:cb(t,i)})}),(0,Q.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:lb(n,i),days:String(o)})})]})]})}function fb({t:e,onUnpin:t}){return(0,Q.jsx)(`button`,{type:`button`,className:`badge badge-muted badge-clickable`,onClick:e=>{e.stopPropagation(),t()},title:`${e(`codexAuth.pinnedHint`)} ${e(`codexAuth.unpinHint`)}`,"aria-label":`${e(`codexAuth.pinned`)} — ${e(`codexAuth.unpinHint`)}`,children:e(`codexAuth.pinned`)})}function pb({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(Xe,{width:12}),`0`]}):r===void 0?null:(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,Q.jsx)(Xe,{width:12}),r]})}function mb({t:e,paused:t,saving:n}){let r=e(`codexAuth.pause`),i=e(`codexAuth.resume`),a=e(`common.saving`),o=n?a:t?i:r,s=Math.max(r.length,i.length,a.length);return(0,Q.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function hb({pool:e,creditsVisible:t,loading:n=!1,activeId:r,accountModeState:i,switchActionLabel:a,threshold:o,onOpenReset:c,onSwitch:l,onTogglePause:u,pauseUpdatingId:d,pauseBusy:f,onPriorityChange:p,priorityUpdatingId:m,onAutoSwitchThresholdChange:h,autoSwitchDisabled:g,switchingId:_,pinnedId:v=null,onUnpin:y,onReauth:x,onEditAlias:S,onRemove:C,onToggleCreditsAfterLimit:w,creditsAfterLimitUpdatingId:T=null,onCopyDoctor:E,doctorCopyOutcomeFor:D}){let O=b(),{locale:k}=s(),A=e=>!e.paused&&r===e.id,j=z_(),[M,N]=(0,Z.useState)(new Set);return(0,Q.jsx)(Q.Fragment,{children:e.map(e=>{let r=t===!0&&e.credits!==void 0,s=e.health?.status,b=e.selectionExcludedReason===`plan_excluded`,P=!!e.needsReauth||__(s),F=y_(s),I=qy(e.weeklyQuotaConflicts,O,k),L=e.health?.reason===`validation_pending`,R=S_(O,e.health),z=C_(O,`codex`,e.id,e.health),B=A(e),V=e.alias??e.email,H=E&&b_(s);return(0,Q.jsxs)(Jy,{active:B,paused:e.paused,dot:P?`warn`:e.paused?`idle`:B?`active`:`ok`,name:V,sub:e.alias?e.email:void 0,chips:(0,Q.jsxs)(Q.Fragment,{children:[B&&!b&&!P&&!F&&!L&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:O(i===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)}),e.plan&&(0,Q.jsx)(`span`,{className:`badge badge-plan`,children:e.plan}),b&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:O(`codexAuth.planExcludedHint`,{plan:e.selectionExcludedPlan??e.plan??``}),children:O(`codexAuth.planExcluded`)}),e.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:e.pauseDetails?r_(O,k,e.pauseDetails):O(`codexAuth.pausedHint`),children:O(`codexAuth.paused`)}),(0,Q.jsx)(Ly,{value:e.priority}),(0,Q.jsx)(By,{enabled:e.creditsAfterLimit}),e.id===v&&!e.paused&&(0,Q.jsx)(fb,{t:O,onUnpin:()=>y(e)}),(0,Q.jsx)(pb,{t:O,account:e,onClick:()=>c(e)}),R&&(0,Q.jsx)(`span`,{className:g_(s),children:R}),P&&!R&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:O(`codexAuth.needsReauth`)})]}),actions:(0,Q.jsxs)(Q.Fragment,{children:[!e.paused&&!b&&(!B||v!==e.id)&&!P&&!F&&!L&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>l(e),children:a}),P&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>x(e.id),children:O(`codexAuth.reauthenticate`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`acc-icon-btn codex-auth-action-btn`,onClick:()=>u(e),disabled:f,"aria-busy":d===e.id||void 0,title:e.paused?O(`codexAuth.pausedHint`):O(`codexAuth.pause`),"aria-label":e.paused?`${O(`codexAuth.resume`)}. ${O(`codexAuth.pausedHint`)}`:O(`codexAuth.pause`),children:[e.paused?(0,Q.jsx)(Ee,{width:15}):(0,Q.jsx)(me,{width:15}),(0,Q.jsx)(`span`,{className:`sr-only`,children:(0,Q.jsx)(mb,{t:O,paused:e.paused,saving:d===e.id})})]})]}),more:(0,Q.jsxs)(Xy,{label:`${O(`codexAuth.moreActions`)} — ${e.email}`,title:O(`codexAuth.moreActions`),open:M.has(e.id),onToggle:t=>N(n=>{let r=new Set(n);return t?r.add(e.id):r.delete(e.id),r}),children:[(rv(e.priority)!==0||M.has(e.id))&&(0,Q.jsx)(Zy,{children:(0,Q.jsx)(Iy,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:m!==null||_!==null,onChange:t=>p(e,t)})}),(0,Q.jsx)(Zy,{children:(0,Q.jsx)(m_,{accountLabel:V,globalThreshold:o,override:e.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${e.id}`,disabled:g,onChange:t=>h(e,t)},e.id)}),w&&(0,Q.jsx)(Zy,{children:(0,Q.jsx)(zy,{accountLabel:V,enabled:e.creditsAfterLimit,saving:T===e.id,disabled:T!==null,onChange:t=>w(e,t)})}),(0,Q.jsxs)(Zy,{label:(0,Q.jsxs)(`span`,{className:`mono`,children:[O(`prov.accountId`),`: `,d_(e.id)]}),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j.copy(e.id,e.id),children:j.outcomeFor(e.id)===`copied`?O(`startup.copied`):O(`codexAuth.copyId`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void S(e),children:O(`prov.editAlias`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm acc-danger-btn`,"aria-label":`${O(`common.remove`)} — ${e.email}`,title:`${O(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),C(e.id)},children:[(0,Q.jsx)(Ie,{width:14}),` `,O(`common.remove`)]})]})]}),children:[(z||F||P)&&(0,Q.jsxs)(`div`,{className:`acc-row__notes`,children:[z&&(0,Q.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Q.jsx)(`span`,{children:z}),H&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-auth-action-btn`,onClick:()=>E(e.id),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:E_(O,D?.(e.id))})})]}),!z&&H&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-auth-action-btn`,onClick:()=>E(e.id),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:E_(O,D?.(e.id))})})}),F&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:O(`pws.healthCooldownHint`)}),P&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:O(`codexAuth.tokenExpired`)})]}),!P&&!F&&(0,Q.jsxs)(`div`,{className:`acc-row__meters`,children:[(0,Q.jsx)(mh,{quota:e.quota,plan:e.plan,threshold:e.autoSwitchThresholdOverride??o,t:O,pending:e.quota==null&&(n||!r),afterWeekly:r&&!n?(0,Q.jsx)(Qy,{credits:e.credits,t:O,locale:k}):void 0}),I&&(0,Q.jsx)(`div`,{className:`card-sub text-warning`,role:`note`,children:I})]})]},e.id)})})}function gb({onReauth:e}){let t=b();return(0,Q.jsx)(k_,{tone:`warn`,className:`acc-row-banner`,action:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)}),children:t(`codexAuth.tokenExpired`)})}function _b({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,threshold:a,unpin:o=!1,onCancel:s,onConfirm:c}){let l=b(),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=u.current;e&&!e.open&&e.showModal()},[]);let d=(0,Z.useCallback)(e=>{e.preventDefault(),s()},[s]),f=se(e.quota,e.plan),p=a!==void 0&&a>0&&f!==null&&f>=a;return(0,Q.jsxs)(`dialog`,{ref:u,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:d,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":l(`common.close`),tabIndex:-1,onClick:s}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsx)(`h3`,{id:`codex-switch-title`,children:o?l(`codexAuth.unpinTitle`):n===`direct`?l(`codexAuth.preparePoolTitle`):e.id===`__main__`?l(`codexAuth.switchBack`):l(`codexAuth.switchTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o?l(`codexAuth.unpinDesc`):n===`direct`?l(`codexAuth.preparePoolDesc`):e.id===`__main__`?l(`codexAuth.switchBackDesc`):l(`codexAuth.switchDesc`)}),(0,Q.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,Q.jsx)(`strong`,{children:e.id===`__main__`?t||l(`codexAuth.codexApp`):e.email}),e.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),!o&&e.id!==`__main__`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,children:[(0,Q.jsx)(St,{width:14}),` `,l(`codexAuth.cacheWarning`)]}),!o&&p&&(0,Q.jsxs)(`div`,{className:`notice-warn`,"data-testid":`codex-switch-threshold-warning`,children:[(0,Q.jsx)(St,{width:14}),` `,l(`codexAuth.switchExceedsThresholdWarning`,{threshold:a})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:l(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r||i,onClick:c,children:l(r?`pws.accountSwitching`:o?`codexAuth.unpinAction`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function vb({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:c,onRedeem:l}){let{locale:u,t:d}=s(),f=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=f.current;e&&!e.open&&e.showModal()},[]);let p=(0,Z.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,Q.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:p,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,onClick:a}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(St,{width:22})}),(0,Q.jsx)(`h3`,{id:`codex-reset-title`,children:d(`codexAuth.confirmResetTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.confirmWhichCredit`,{date:cb(n[0].granted_at,u)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.irreversible`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:c,children:d(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:l,disabled:i,children:d(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,Q.jsx)(Xe,{width:16}),` `,d(`codexAuth.resetCreditsTitle`)]}),(0,Q.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Q.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:d(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`common.loading`)}),n&&n.length>0&&(0,Q.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,Q.jsx)(db,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:u,t:d},`${e.granted_at}:${e.expires_at}`))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:d(`codexAuth.useOneCredit`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:d(`codexAuth.fifoNote`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:d(`codexAuth.noResetCredits`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.earnCreditsHint`)})]})})]})})]})}function yb({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:a,onSwitch:o,onTogglePause:c,pauseUpdatingId:l,pauseBusy:u,onPriorityChange:d,priorityUpdatingId:f,onAutoSwitchThresholdChange:p,autoSwitchDisabled:m,switchingId:h,pinnedId:g=null,onUnpin:_,onOpenReset:v,onCopyDoctor:y,doctorCopyOutcomeFor:b,onManageMainHardLock:x,mainReauth:S,onToggleCreditsAfterLimit:C,creditsAfterLimitUpdatingId:w=null,creditsVisible:T,loading:E=!1}){let{locale:D}=s(),O=T===!0&&t?.credits!==void 0,k=e(`codexAuth.codexApp`),A=t?.id??`__main__`,j={id:`__main__`,email:t?.email||k,plan:t?.plan,isMain:!0,paused:t?.paused??!1,priority:t?.priority??0,autoSwitchThresholdOverride:t?.autoSwitchThresholdOverride??null,hasCredential:!0,quota:t?.quota??null,quotaAutoRefresh:t?.quotaAutoRefresh??{fiveHourAvailable:!1,weeklyAvailable:!1,fiveHourEnabled:!1,weeklyEnabled:!1}},M=!!t?.needsReauth||__(t?.health?.status),N=y_(t?.health?.status),P=t?.mainAccountHardLock,F=P?.enabled===!0&&P.state===`blocked`,I=S_(e,t?.health),L=t?C_(e,`codex`,A,t.health):null,R=y&&b_(t?.health?.status),z=t?.alias??(t?.email||e(`codexAuth.mainAccount`)),B=R?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-auth-action-btn`,onClick:()=>y(A),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:E_(e,b?.(A))})}):null;return(0,Q.jsxs)(Jy,{active:n&&!F,paused:t?.paused,dot:M||F?`warn`:t?.paused?`idle`:n?`active`:`ok`,name:t?.email||e(`codexAuth.appLogin`),chips:(0,Q.jsxs)(Q.Fragment,{children:[!t?.paused&&!F&&n&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:e(r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)}),(0,Q.jsxs)(`span`,{className:`badge badge-plan acc-main-tag`,title:e(`codexAuth.appLogin`),children:[(0,Q.jsx)(_t,{width:11,"aria-hidden":`true`}),` `,e(`codexAuth.mainAccount`)]}),t?.plan&&(0,Q.jsx)(`span`,{className:`badge badge-plan`,children:t.plan}),t?.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,Q.jsx)(Ly,{value:j.priority}),(0,Q.jsx)(By,{enabled:t?.creditsAfterLimit}),g===`__main__`&&!t?.paused&&(0,Q.jsx)(fb,{t:e,onUnpin:()=>_(j)}),t&&(0,Q.jsx)(pb,{t:e,account:{...t,id:`__main__`},onClick:()=>v({...t,id:`__main__`})}),I&&(0,Q.jsx)(`span`,{className:g_(t?.health?.status),children:I}),M&&!I&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&!F&&!n&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.current`)})]}),actions:(0,Q.jsxs)(Q.Fragment,{children:[!t?.paused&&!F&&(!n||g!==`__main__`)&&!M&&!N&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(j),children:a}),t&&(0,Q.jsxs)(`button`,{type:`button`,className:`acc-icon-btn codex-auth-action-btn`,onClick:()=>c(j),disabled:u,"aria-busy":l===`__main__`||void 0,title:t.paused?e(`codexAuth.pausedHint`):e(`codexAuth.pause`),"aria-label":t.paused?`${e(`codexAuth.resume`)}. ${e(`codexAuth.pausedHint`)}`:e(`codexAuth.pause`),children:[t.paused?(0,Q.jsx)(Ee,{width:15}):(0,Q.jsx)(me,{width:15}),(0,Q.jsx)(`span`,{className:`sr-only`,children:(0,Q.jsx)(mb,{t:e,paused:!!t.paused,saving:l===`__main__`})})]})]}),more:t?(0,Q.jsxs)(Xy,{label:`${e(`codexAuth.moreActions`)} — ${e(`codexAuth.mainAccount`)}`,title:e(`codexAuth.moreActions`),children:[(0,Q.jsx)(Zy,{children:(0,Q.jsx)(Iy,{value:j.priority,selectId:`codex-account-priority-${j.id}`,disabled:f!==null||h!==null,onChange:e=>d(j,e)})}),(0,Q.jsx)(Zy,{children:(0,Q.jsx)(m_,{accountLabel:j.email,globalThreshold:i,override:j.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${j.id}`,disabled:m,onChange:e=>p(j,e)},j.id)}),t.hasCredential&&C&&(0,Q.jsx)(Zy,{children:(0,Q.jsx)(zy,{accountLabel:z,enabled:t.creditsAfterLimit,saving:w===`__main__`,disabled:w!==null,hint:e(`codexAuth.creditsAfterLimitMainHint`),onChange:e=>C(j,e)})})]}):void 0,children:[(P?.enabled||P?.externalUsage||L||N||M||R)&&(0,Q.jsxs)(`div`,{className:`acc-row__notes`,children:[P?.enabled&&(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-status${F?` is-blocked`:``}`,children:[(0,Q.jsx)(`p`,{role:`status`,children:e(F?`codexAuth.mainHardLockBlocked`:P.state===`ready`?`codexAuth.mainHardLockMonitoring`:`codexAuth.mainHardLockUnknown`,Pv(P.thresholds))}),x?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:x,children:e(`codexAuth.mainHardLockManage`)}):(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>En(`codex-set`),children:e(`codexAuth.mainHardLockManage`)})]}),P?.externalUsage&&(0,Q.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Q.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainExternalUsageWarning`)})}),L&&(0,Q.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Q.jsx)(`span`,{children:L}),B]}),!L&&B&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:B}),N&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),M&&(0,Q.jsxs)(`div`,{className:`card-sub faint acc-reauth`,children:[(0,Q.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainTokenExpired`)}),S&&(S.state.phase===`idle`||S.state.phase===`failed`||S.state.phase===`cancelled`)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{S.start()},children:e(`codexAuth.mainReauthDevice`)}),S.state.phase===`failed`&&(0,Q.jsxs)(`span`,{className:`badge badge-amber`,children:[e(`codexAuth.mainReauthFailed`),`: `,S.state.code]})]}),S&&S.state.phase===`starting`&&(0,Q.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S&&(S.state.phase===`pending`||S.state.phase===`committing`)&&(0,Q.jsxs)(`span`,{className:`codex-main-reauth-pending`,children:[(0,Q.jsx)(H_,{hint:{url:S.state.verificationUrl,deviceCode:S.state.deviceCode}}),(0,Q.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S.state.cancelFailed&&(0,Q.jsx)(`span`,{role:`status`,className:`badge badge-amber`,children:e(`codexAuth.mainReauthFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{S.cancel()},children:e(`codexAuth.mainReauthCancel`)})]}),S&&S.state.phase===`succeeded`&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.mainReauthSucceeded`)})]})]}),!M&&!N&&(0,Q.jsx)(`div`,{className:`acc-row__meters`,children:(0,Q.jsx)(mh,{quota:t?.quota??null,plan:t?.plan,threshold:j.autoSwitchThresholdOverride??i,t:e,pending:t!=null&&t.quota==null&&(E||!O),afterWeekly:O&&!E?(0,Q.jsx)(Qy,{credits:t?.credits,t:e,locale:D}):void 0})})]})}function bb({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c,creditsVisible:l,creditsBusy:u,onToggleCredits:d,creditSpendControl:f}){return(0,Q.jsxs)(`div`,{className:t?`row acc-head acc-head--embedded`:`page-head codex-auth-page-head acc-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,Q.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,Q.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),l!==void 0&&d&&(0,Q.jsxs)(`span`,{className:`codex-auth-credits-toggle`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:e(`codexAuth.creditsToggle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${l?`on`:``}`,onClick:d,disabled:!!u,"aria-pressed":l,"aria-label":e(`codexAuth.creditsToggle`),title:e(`codexAuth.creditsToggleHint`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),f,t&&(0,Q.jsx)(xb,{t:e,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,onRefresh:s,onPauseExhausted:c})]})]})}function xb({t:e,refreshingQuota:t,pausingExhausted:n,pauseBusy:r,onRefresh:i,onPauseExhausted:a}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:a,disabled:t||n||!!r,children:[(0,Q.jsx)(me,{width:14}),` `,e(n?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:i,disabled:t||n||!!r,children:[(0,Q.jsx)(`span`,{className:X(`inline-flex`,t&&`animate-spin`),children:(0,Q.jsx)(Ke,{width:14})}),` `,e(t?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})}function Sb(e){return(0,Q.jsx)(`div`,{className:`codex-auth-actions-row`,children:(0,Q.jsx)(xb,{...e})})}function Cb({t:e,loadState:t,refreshFailed:n,accountsCount:r,onRetry:i}){return t===`loading`&&r===0?(0,Q.jsxs)(`div`,{className:`codex-auth-load-skeleton acc-row-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,Q.jsxs)(`div`,{className:`card acc-row`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`acc-row__head flex items-center gap-3`,children:[(0,Q.jsx)(`span`,{className:`inline-block size-2 rounded-full bg-fg-subtle`}),(0,Q.jsx)(`span`,{className:`acc-skel h-3.5 w-48 rounded-full`}),(0,Q.jsx)(`span`,{className:`acc-skel h-4 w-16 rounded-full`})]}),(0,Q.jsx)(`div`,{className:`acc-row__meters`,children:(0,Q.jsx)(mh,{quota:null,threshold:0,t:e,pending:!0})})]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,Q.jsx)(k_,{tone:`err`,role:`alert`,className:`pwi-auth-state pwi-auth-state--error acc-row-banner`,action:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)}),children:e(`codexAuth.loadFailed`)}):n&&r>0?(0,Q.jsx)(k_,{tone:`warn`,role:`status`,className:`pwi-auth-state pwi-auth-state--stale acc-row-banner`,action:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)}),children:e(`codexAuth.accountsRefreshFailed`)}):null}function wb({t:e,onAdd:t}){return(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm acc-add-btn`,onClick:t,children:[(0,Q.jsx)(Vt,{width:14}),` `,e(`codexAuth.add`)]})}function Tb(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Eb(e,t,n,r){try{let i=await Xn(await fetch(`${e}/api/codex-auth/reset-credits/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t})}));return i?i.code===`reset`||i.code===`already_redeemed`?(await r(!0),{ok:!0,close:!0,toast:Tb(n,typeof i.remaining==`number`&&Number.isFinite(i.remaining)?Math.max(0,i.remaining):void 0)}):{ok:!1,close:!0,toast:n(i.code===`nothing_to_reset`?`codexAuth.resetNothingToReset`:i.code===`no_credit`?`codexAuth.resetNoCredit`:`codexAuth.resetError`)}:{ok:!1,toast:n(`codexAuth.resetError`)}}catch{return{ok:!1,toast:n(`codexAuth.resetError`)}}}function Db({windows:e,ready:t,busy:n,loadError:r,feedback:i,onToggle:a,onRetry:o}){let s=b(),c=e.filter(e=>e.available),l=e.some(e=>e.enabled),u=c.length?c.every(e=>e.enabled):l,d=l&&!u,f=c.length===0&&!l,p=n?s(`common.saving`):r?s(`codexAuth.quotaAutoRefreshLoadFailed`):t?i?.message??(f?s(`codexAuth.quotaAutoRefreshEmpty`):d?s(`codexAuth.quotaAutoRefreshMixed`):``):s(`common.loading`),m=!n&&(r||i?.failed);return(0,Q.jsxs)(`div`,{id:`codex-quota-activation`,className:`card card-row codex-quota-activation`,"aria-busy":n||!t&&!r||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-quota-activation__copy`,children:[(0,Q.jsx)(`strong`,{children:s(`codexAuth.quotaAutoRefresh`)}),(0,Q.jsx)(`div`,{id:`codex-quota-activation-desc`,className:`card-sub`,children:s(`codexAuth.quotaAutoRefreshAllHint`)}),p&&(0,Q.jsx)(`div`,{className:`card-sub${m?` is-error`:``}`,role:m?`alert`:`status`,children:p})]}),(0,Q.jsxs)(`div`,{className:`codex-quota-activation__controls`,children:[m&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:o,children:s(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${t&&u?`on`:``}`,"aria-label":s(`codexAuth.quotaAutoRefresh`),"aria-describedby":`codex-quota-activation-desc`,"aria-pressed":t?d?`mixed`:u:void 0,disabled:!t||n||f,onClick:()=>a(!u),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]})]})}function Ob(e){return{enabled:e.filter(e=>e.creditsAfterLimit===!0).length,total:e.length}}function kb(e){let t=e&&typeof e==`object`&&`codexQuotaAutoRefresh`in e?e.codexQuotaAutoRefresh:null;if(!t||typeof t!=`object`||Array.isArray(t)||Object.values(t).some(e=>!e||typeof e!=`object`||Array.isArray(e)||[e.fiveHour,e.weekly].some(e=>e!==void 0&&typeof e!=`boolean`)))throw Error(`Invalid quota activation settings`);return t}function Ab(e,t){return e.flatMap(e=>{let n=e.isMain?`__main__`:e.id,r=e.quotaAutoRefresh??Ve(e.quota);return[`fiveHour`,`weekly`].map(e=>({id:n,window:e,available:r[e===`fiveHour`?`fiveHourAvailable`:`weeklyAvailable`],enabled:t[n]?.[e]===!0}))})}var jb=[`.pws-detail-panel`,`.pws-detail`,`.pws-main`,`.page-head`],Mb=`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function Nb(e){if(!e||!e.isConnected||typeof e.focus!=`function`||e===document.body||e===document.documentElement||e.disabled===!0)return!1;for(let t=e;t&&t!==document.documentElement;t=t.parentElement){let e=t;if(e.hidden||t.hasAttribute(`inert`)||t.getAttribute(`aria-hidden`)===`true`||e.style?.display===`none`||e.style?.visibility===`hidden`||e.style?.visibility===`collapse`)return!1;if(typeof window<`u`&&typeof window.getComputedStyle==`function`){let e=window.getComputedStyle(t);if(e.display===`none`||e.visibility===`hidden`||e.visibility===`collapse`)return!1}}return!0}function Pb(e){if(!(Nb(e)&&(e.focus(),document.activeElement===e))){for(let e of jb)for(let t of document.querySelectorAll(e))for(let e of t.querySelectorAll(Mb))if(Nb(e)&&(e.focus(),document.activeElement===e))return}}function Fb(e){let t=b(),n=(0,Z.useId)(),r=(0,Z.useRef)(null),i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=document.activeElement;return i.current?.focus(),()=>{Pb(e)}},[]);let a=e.selection?.status===`pending`,o=e.failed||!e.providerKnown,s=e.loading?t(`prov.modelsNoticeChecking`):o?t(`prov.modelsNoticeFailed`):a?t(`prov.modelsNoticePending`):e.initialRegistration&&e.selection?.status===`all-off`?t(`prov.modelsNoticeOff`):t(`prov.modelsNoticeReady`);return(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":n,onKeyDown:t=>{if(t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.onClose()),t.key!==`Tab`)return;let n=r.current?.querySelectorAll(`button:not([disabled])`),i=n?.[0],a=n?.[n.length-1];t.shiftKey&&document.activeElement===i?(t.preventDefault(),a?.focus()):!t.shiftKey&&document.activeElement===a&&(t.preventDefault(),i?.focus())},children:(0,Q.jsxs)(`div`,{className:`modal-card`,ref:r,children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h2`,{id:n,style:{fontSize:`var(--text-subtitle)`,margin:0},children:t(`prov.modelsNoticeTitle`)})}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`strong`,{style:{overflowWrap:`anywhere`},children:e.provider})}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:s}),e.initialRegistration&&e.selection?.modelCount!==void 0&&(0,Q.jsx)(`p`,{className:`muted`,children:t(`prov.modelsNoticeCount`,{count:e.selection.modelCount})}),e.catalogRefreshPending&&(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}),!e.loading&&(a||o)&&e.onRetry&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{e.onRetry?.(),i.current?.focus()},children:t(`common.retry`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:e.onClose,children:t(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,ref:i,onClick:e.onOpenModels,children:t(`prov.modelsNoticeOpen`)})]})]})})}var Ib=`ocx doctor`;function Lb({apiBase:e,targetKey:t,accountModeState:n=null,banner:r=null,embedded:a=!1,onActiveNeedsReauthChange:o,controller:s,advancedExtras:c=null,hasMainHardLockSetting:l=!1}){let u=b(),f=Y_(e,t),p=Fy(e,{updated:u(`codexAuth.autoSwitchUpdated`),updateFailed:u(`codexAuth.autoSwitchUpdateFailed`),invalid:u(`codexAuth.autoSwitchThresholdInvalid`)},t),[m,h]=(0,Z.useState)(null),{beginServerRead:g,acceptServerRead:_,rejectServerRead:y,hydrateServerValue:x}=p,S=zv(e,!s,t),C=s??S,{accounts:w,activeId:T,loadState:E,refreshFailed:D,switchingId:O,pauseUpdatingId:k,priorityUpdatingId:A,autoSwitchUpdatingId:j,pausingExhausted:M,activePinnedId:N,load:P}=C,F=Jv(e,()=>{P()},t),I=F.state.phase===`starting`||F.state.phase===`pending`||F.state.phase===`committing`,[L,R]=(0,Z.useState)(null),[z,B]=(0,Z.useState)(null),V=e=>w.some(t=>t.id===e.id||e.isMain&&t.isMain),H=L&&V(L)?L:null,U=z&&V(z)?z:null,[W,ee]=(0,Z.useState)(!1),[G,te]=(0,Z.useState)(null),[ne,K]=(0,Z.useState)(!1),q=(0,Z.useRef)(!1),J=(0,Z.useCallback)(()=>{let e=document.getElementById(`codex-main-hard-lock-setting`);e?.focus(),e?.scrollIntoView({block:`nearest`})},[]);(0,Z.useEffect)(()=>{ne&&q.current&&(q.current=!1,J())},[ne,J]);let re=()=>{ne?J():(q.current=!0,K(!0))},[Y,ie]=(0,Z.useState)(null),[ae,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(null),le=(0,Z.useRef)(null),[ue,de]=(0,Z.useState)(!1),[fe,pe]=(0,Z.useState)(null),[me,he]=(0,Z.useState)(null),ge=(0,Z.useRef)(0),_e=(0,Z.useRef)(null),ve=(0,Z.useRef)(null),[ye,be]=(0,Z.useState)(0),[xe,Se]=(0,Z.useState)(e),[Ce,we]=(0,Z.useState)(null),Te=(0,Z.useRef)(null),Ee=me?.apiBase===e&&me.revision===ye?me:null,De=Ee?.settings??null,Oe=Ee?.error??!1,ke=fe===e;xe!==e&&(Se(e),be(e=>e+1),he(null),pe(null),we(null));let[Ae,je]=(0,Z.useState)(null),[Me,Ne]=(0,Z.useState)(!1),[Pe,Fe]=(0,Z.useState)(!1),[Ie,Le]=(0,Z.useState)(null),[Re,ze]=(0,Z.useState)(!1),Be=z_(),Ve=t??e,[He,Ue]=(0,Z.useState)(Ve);He!==Ve&&(Ue(Ve),ee(!1),ie(null),te(null),R(null),B(null),je(null),Ne(!1),Le(null),oe(null),ce(null),be(e=>e+1),he(null),pe(null),we(null));let We=(0,Z.useCallback)((e,t=`ok`)=>{le.current&&clearTimeout(le.current),oe(e),ce(t),le.current=setTimeout(()=>{oe(null),ce(null),le.current=null},5e3)},[]);(0,Z.useEffect)(()=>()=>{le.current&&clearTimeout(le.current)},[]);let Ge=Bv(e,P,We,u,{revision:ye,onRead:(t,n)=>{let r=ge.current;t.then(t=>{n.aborted||ge.current!==r||(he({apiBase:e,revision:ye,settings:kb(t),error:!1}),pe(null))}).catch(()=>{n.aborted||ge.current!==r||(he({apiBase:e,revision:ye,settings:null,error:!0}),pe(null))})}}),Ke=(0,Z.useCallback)(e=>{Be.copy(Ib,e)},[Be]),{subscribeLoadObserver:qe,readLastThreshold:Je}=C;(0,Z.useEffect)(()=>qe({beginActiveRead:g,acceptActiveRead:_,rejectActiveRead:y}),[qe,g,_,y]),(0,Z.useEffect)(()=>{let e=Je();e!==void 0&&x(e)},[Je,x]),(0,Z.useEffect)(()=>{if(!W&&!I)return;let e=C.pauseRefresh();return()=>C.resumeRefresh(e)},[C,W,I]);let Ye=T&&T!==`__main__`?w.find(e=>e.id===T):null,Xe=!Ye?.paused&&v_(Ye);(0,Z.useEffect)(()=>{o?.(Xe)},[Xe,o]);let Ze=(0,Z.useCallback)(e=>{ie(e),ee(!0)},[]),Qe=(0,Z.useCallback)(()=>{ee(!1),ie(null)},[]),$e=(0,Z.useCallback)(e=>{C.syncAfterAccountAdded(),We(u(e.validationPending?`pws.healthLabel.validationPending`:e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.validationPending||e.catalogRefreshPending?`warn`:`ok`),Qe(),te(e.validationPending?null:{catalogRefreshPending:e.catalogRefreshPending})},[Qe,C,We,u]),et=async e=>{let t=await C.switchAccount(e);if(!t.ok){if(t.reason===`busy`||t.reason===`stale`)return;We(u(`codexAuth.switchFailed`),`err`);return}R(null);let r=t.activeId,i=r&&r!==`__main__`?w.find(e=>e.id===r)?.email??u(`pws.accountOrdinal`,{count:`1`}):u(`codexAuth.mainAccount`);We(u(n===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},tt=async()=>{if(!U)return;let e=await C.switchAccount(null,{expectedPinnedAccountId:U.id});if(e.ok)B(null),We(u(`codexAuth.unpinned`),`ok`);else{if(e.reason===`busy`||e.reason===`stale`)return;B(null),We(u(e.reason===`pin_changed`?`codexAuth.unpinChanged`:`codexAuth.unpinFailed`),`err`)}},nt=async e=>{let t=await Yu({message:u(`prov.aliasPrompt`),initialValue:e.alias??``,maxLength:80,validate:e=>P_(e,u)});if(t===null)return;let n=await C.saveAlias(e.id,t);(n.ok||n.reason!==`busy`&&n.reason!==`stale`)&&We(u(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},rt=async e=>{let t=!e.paused,n=await C.setAccountPaused(e.id,t);(n.ok||n.reason!==`busy`&&n.reason!==`stale`)&&(R(t=>t?.id===e.id?null:t),We(u(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},it=async e=>{let t=await C.setAllCreditsAfterLimit(e);(t.ok||t.reason!==`busy`&&t.reason!==`stale`)&&We(u(t.ok?e?`codexAuth.creditsAllOnSucceeded`:`codexAuth.creditsAllOffSucceeded`:`codexAuth.creditsAllUpdateFailed`),t.ok?`ok`:`err`)},at=async(e,t)=>{if(t===e.priority)return;let n=await C.setAccountPriority(e.id,t);(n.ok||n.reason!==`busy`&&n.reason!==`stale`)&&We(u(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},ot=async(e,t)=>{if(t===e.autoSwitchThresholdOverride)return!0;let n=await C.setAccountAutoSwitchThreshold(e.id,t);return!n.ok&&(n.reason===`busy`||n.reason===`stale`)?!1:(We(u(n.ok?`accountPool.autoSwitchUpdated`:`accountPool.autoSwitchUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`),n.ok)},st=async(e,t)=>{let n=await C.setAccountCreditsAfterLimit(e.id,t);(n.ok||n.reason!==`busy`&&n.reason!==`stale`)&&We(u(n.ok?t?`codexAuth.creditsOnSucceeded`:`codexAuth.creditsOffSucceeded`:`codexAuth.creditsUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},ct=async e=>{let t=w.find(t=>t.id===e)?.email??u(`pws.accountOrdinal`,{count:`1`});if(!await Ju({message:u(`codexAuth.removeConfirm`,{id:t}),confirmLabel:u(`common.remove`),tone:`danger`}))return;let n=await C.removeAccount(e);(n.ok||n.reason!==`busy`&&n.reason!==`stale`)&&(n.ok?n.catalogRefreshPending&&We(u(`codexAuth.catalogRefreshPending`),`warn`):We(u(`codexAuth.removeFailed`),`err`))},lt=async()=>{de(!0);try{let e=await P(!0,{validatePending:!0});We(u(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{de(!1)}},ut=async t=>{let n=_e.current;if(ve.current||!n||n.signal.aborted||De===null||E!==`ready`)return;let r={...f},a=d(3e4);ve.current=a,ge.current+=1;let o=()=>_e.current===n&&!n.signal.aborted&&v(r),s=Ab(w,De);pe(e),we(null);let c=!1;try{for(let e of s){if(t&&!e.available)continue;let n=t;if(e.enabled!==n){if(!o())return;if(a.signal.aborted){c=!0;break}try{if(!(await i(r,`${r.apiBase}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:a.signal,body:JSON.stringify({codexQuotaAutoRefresh:{id:e.id,window:e.window,enabled:n}})})).ok)throw Error(`save`)}catch{c=!0}}}if(!o())return;a.clear();let n=d(15e3);ve.current=n;try{let a=await i(r,`${r.apiBase}/api/settings`,{signal:n.signal});if(!a.ok)throw Error(`read`);let l=kb(await a.json());if(!o())return;c||=s.some(e=>(!t||e.available)&&l[e.id]?.[e.window]===!0!==t),he({apiBase:e,revision:ye,settings:l,error:!1})}catch{if(!o())return;c=!0,he({apiBase:e,revision:ye,settings:null,error:!0})}finally{n.clear()}if(!o())return;Te.current=c?{apiBase:e,identity:Ve,enabled:t}:null,we({apiBase:e,message:u(c?`codexAuth.quotaAutoRefreshPartial`:`codexAuth.quotaAutoRefreshUpdated`),failed:c})}finally{a.clear(),o()&&(ve.current=null,pe(null))}};(0,Z.useEffect)(()=>{let e=new AbortController;return _e.current=e,()=>{e.abort(),ve.current?.controller.abort(),ve.current?.clear(),ve.current=null}},[e,ye]);let dt=async()=>{let e=await C.pauseExhaustedAccounts();(e.ok||e.reason!==`busy`&&e.reason!==`stale`)&&We(e.ok?e.pausedCount>0?u(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):u(`codexAuth.pauseExhaustedNone`):u(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},ft=async t=>{je(t),Ne(!1),Le(null),ze(!0);try{let n=await Xn(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));if(n){let e=(n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime());Le(e)}}catch{}finally{ze(!1)}},pt=async t=>{Fe(!0);try{let n=await Eb(e,t,u,P);n.close&&(je(null),Ne(!1)),n.toast&&We(n.toast,n.ok?`ok`:`err`)}finally{Fe(!1)}},X=w.find(e=>e.isMain),mt=w.filter(e=>!e.isMain),ht=Ob([...X?.hasCredential?[X]:[],...mt]),gt=!X?.paused&&(!T||T===`__main__`),_t=u(n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),vt=k!==null||M,yt=p.threshold,bt=!p.hydrated||j!==null,xt=!a;return(0,Q.jsxs)(`div`,{className:`acc-v2 flex flex-col ${a?`gap-3`:`gap-4`}`,children:[(0,Q.jsx)(bb,{t:u,embedded:a,creditsVisible:Ge.visible,creditsBusy:Ge.busy,onToggleCredits:()=>{Ge.toggle()},creditSpendControl:E===`loading`&&w.length===0?void 0:(0,Q.jsx)(Ry,{summary:ht,busy:C.creditsAfterLimitUpdatingId!==null,onToggleAll:e=>{it(e)}}),refreshingQuota:ue,actionFeedback:ae,actionFeedbackTone:se,pausingExhausted:M,pauseBusy:vt,onRefresh:()=>{lt()},onPauseExhausted:()=>{dt()}}),r,!a&&(0,Q.jsx)(Sb,{t:u,refreshingQuota:ue,pausingExhausted:M,pauseBusy:vt,onRefresh:()=>{lt()},onPauseExhausted:()=>{dt()}}),(0,Q.jsx)(Cb,{t:u,loadState:E,refreshFailed:D,accountsCount:w.length,onRetry:()=>{P()}}),(E!==`loading`||w.length!==0)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(D_,{className:`acc-accounts acc-accounts--main`,children:(0,Q.jsx)(yb,{t:u,main:X,creditsVisible:Ge.visible,loading:E===`loading`,isMainActive:gt,accountModeState:n,threshold:yt,switchActionLabel:_t,onSwitch:R,onUnpin:B,onTogglePause:rt,pauseUpdatingId:k,pauseBusy:vt,onPriorityChange:(e,t)=>{at(e,t)},priorityUpdatingId:A,onAutoSwitchThresholdChange:ot,autoSwitchDisabled:bt,onToggleCreditsAfterLimit:(e,t)=>{st(e,t)},creditsAfterLimitUpdatingId:C.creditsAfterLimitUpdatingId,switchingId:O,pinnedId:N,onOpenReset:ft,onCopyDoctor:xt?Ke:void 0,doctorCopyOutcomeFor:xt?Be.outcomeFor:void 0,onManageMainHardLock:l?re:void 0,mainReauth:F})}),(0,Q.jsx)(`div`,{className:`acc-native-main`,children:(0,Q.jsx)(wy,{apiBase:e,disabled:I,onChanged:()=>P(!1)})}),(0,Q.jsxs)(D_,{className:`acc-accounts`,title:u(`codexAuth.accountPool`),meta:mt.length>0?String(mt.length):void 0,actions:(0,Q.jsx)(wb,{t:u,onAdd:()=>ee(!0)}),children:[Xe&&Ye&&(0,Q.jsx)(gb,{onReauth:()=>Ze(Ye.id)}),mt.length===0&&(0,Q.jsxs)(`div`,{className:`acc-pool-empty`,children:[(0,Q.jsx)(`p`,{className:`acc-pool-empty__title`,children:u(`codexAuth.noPool`)}),(0,Q.jsx)(`p`,{className:`acc-pool-empty__hint`,children:u(`accountsV2.emptyPoolHint`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ee(!0),children:[(0,Q.jsx)(Vt,{width:14}),` `,u(`codexAuth.add`)]})]}),(0,Q.jsx)(hb,{pool:mt,creditsVisible:Ge.visible,loading:E===`loading`,activeId:T,accountModeState:n,switchActionLabel:_t,threshold:yt,onOpenReset:ft,onSwitch:R,onUnpin:B,onTogglePause:rt,pauseUpdatingId:k,pauseBusy:vt,onPriorityChange:(e,t)=>{at(e,t)},priorityUpdatingId:A,onAutoSwitchThresholdChange:ot,autoSwitchDisabled:bt,onToggleCreditsAfterLimit:(e,t)=>{st(e,t)},creditsAfterLimitUpdatingId:C.creditsAfterLimitUpdatingId,switchingId:O,pinnedId:N,onReauth:Ze,onEditAlias:nt,onRemove:ct,onCopyDoctor:xt?Ke:void 0,doctorCopyOutcomeFor:xt?Be.outcomeFor:void 0})]})]}),(0,Q.jsx)(Ny,{apiBase:e,subscribeLoadObserver:C.subscribeLoadObserver,readLastActive:C.readLastActive,onStrategyResolved:h,threshold:p.threshold}),(0,Q.jsxs)(Py,{t:u,open:ne,onToggle:()=>K(e=>!e),children:[(0,Q.jsx)(Db,{windows:Ab(w,De??{}),ready:De!==null&&E===`ready`,busy:ke,loadError:Oe||E===`error`,feedback:Ce?.apiBase===e?Ce:null,onToggle:e=>{ut(e)},onRetry:()=>{Oe||De===null||E!==`ready`?(be(e=>e+1),P()):Te.current?.identity===Ve&&ut(Te.current.enabled)}}),m!==null&&(0,Q.jsx)(Dy,{threshold:p.threshold,draft:p.draft,strategy:m,hydrated:p.hydrated,saving:p.saving,loadError:p.loadError,feedback:p.feedback,onDraftChange:p.setDraft,onEditingChange:p.setEditing,onCommit:p.commit,onCancel:p.cancel,onToggle:p.toggle,onRetry:()=>{p.retry(),P()}}),c]}),H&&(0,Q.jsx)(_b,{confirm:H,mainEmail:X?.email,accountModeState:n,switchingId:O,orderBusy:A!==null,threshold:m&&m!==`round-robin`?yt:void 0,onCancel:()=>R(null),onConfirm:()=>{et(H.id===`__main__`?`__main__`:H.id)}}),U&&(0,Q.jsx)(_b,{unpin:!0,confirm:U,mainEmail:X?.email,accountModeState:n,switchingId:O,orderBusy:A!==null,onCancel:()=>B(null),onConfirm:()=>{tt()}}),Ae&&(0,Q.jsx)(vb,{resetPopup:Ae,resetConfirm:Me,creditDetails:Ie,creditDetailsLoading:Re,redeeming:Pe,onClose:()=>{je(null),Ne(!1),Le(null)},onShowConfirm:()=>Ne(!0),onCancelConfirm:()=>Ne(!1),onRedeem:()=>{pt(Ae.id)}}),W&&(0,Q.jsx)(ev,{apiBase:e,targetKey:t,reauthAccountId:Y??void 0,onClose:Qe,onAdded:$e}),G&&(0,Q.jsx)(Fb,{provider:`openai`,loading:!1,failed:!1,providerKnown:!0,initialRegistration:!1,catalogRefreshPending:G.catalogRefreshPending,onClose:()=>te(null),onOpenModels:()=>{te(null),En(`models`)}})]})}var Rb=`https://opencodex.me/guides/claude-code/#claude-oauth-account-pool-experimental`,zb={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function Bb(e,t,n,r){let i=e(zb[r]);return t===`round-robin`?e(`anthropicPool.enabledRoundRobinDesc`):t===`fill-first`?n===0?e(`anthropicPool.enabledFillFirstNoThresholdDesc`):e(`anthropicPool.enabledFillFirstDesc`,{threshold:n,window:i}):n===0?e(`anthropicPool.enabledNoProactiveDesc`,{window:i}):e(`anthropicPool.enabledDesc`,{threshold:n,window:i})}function Vb({apiBase:e,targetKey:t,provider:n=`anthropic`,accountCount:r,onThresholdChange:a}){let o=b(),s=Y_(e,t),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(`80`),[f,p]=(0,Z.useState)(`1`),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[y,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(0),[O,k]=(0,Z.useState)(!1),A=(0,Z.useRef)(a),j=(0,Z.useRef)(!0),M=(0,Z.useRef)(e),N=(0,Z.useRef)(n),P=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>(j.current=!0,()=>{j.current=!1,P.current?.abort(),P.current=null}),[]),(0,Z.useLayoutEffect)(()=>{A.current=a,M.current=e,N.current=n},[e,n,a]),(0,Z.useEffect)(()=>{let t=!1,r=new AbortController;return Promise.resolve().then(()=>xv(e,n,(e,t)=>fetch(e,t),{signal:r.signal})).then(e=>{if(!e)throw Error(`load`);return e}).then(e=>{if(t)return;let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=gv(e.stickyLimit);l({enabled:e.enabled===!0,threshold:n,strategy:mv(e.strategy),stickyLimit:r,quotaWindow:hv(e.quotaWindow),nativeMessages:e.nativeMessages===!0}),d(String(n)),A.current?.(n),p(String(r)),x(!1),T(!1),_(null),C(!1),k(!1)}).catch(()=>{t||r.signal.aborted||(x(!0),k(!1))}),()=>{t=!0,r.abort()}},[e,n,E]);let F=(0,Z.useCallback)(async t=>{let r=e,a=n,u=s;P.current?.abort();let f=new AbortController;P.current=f;let m=()=>j.current&&M.current===r&&N.current===a&&P.current===f&&!f.signal.aborted,g=c;h(!0),_(null),C(!1);try{let e=await Cv(r,a,{enabled:t.enabled,threshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit,quotaWindow:t.quotaWindow,nativeMessages:t.nativeMessages},(e,t)=>i(u,e,t),{signal:f.signal});if(!m()||!v(u))return;if(!e)throw Error(`save`);let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:t.threshold,o=mv(e?.strategy??t.strategy),s=gv(e?.stickyLimit??t.stickyLimit),c=hv(e?.quotaWindow??t.quotaWindow);l({enabled:e.enabled??t.enabled,threshold:n,strategy:o,stickyLimit:s,quotaWindow:c,nativeMessages:e.nativeMessages===!0}),d(String(n)),A.current?.(n),p(String(s)),C(e.warning===`config_bookkeeping_failed`)}catch(e){if(!m())return;if(e instanceof Sv){l(null),T(!0),x(!1),_(null);return}_(o(`anthropicPool.saveFailed`)),g&&(l(g),d(String(g.threshold)),p(String(g.stickyLimit)))}finally{let e=P.current===f;e&&(P.current=null),e&&j.current&&M.current===r&&N.current===a&&h(!1)}},[e,n,s,c,o]),I=c?.enabled===!0,L=c?.threshold??80,R=c?.strategy??`quota`,z=c?.stickyLimit??1,B=c?.quotaWindow??`five-hour`,V=c?.nativeMessages??!0,H=R===`round-robin`,U=O||c===null&&!y&&!w,W=U||m||y||w,ee=W||!I&&r<2;return(0,Q.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":U||m,children:[(0,Q.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,Q.jsxs)(`div`,{style:{flex:1},children:[(0,Q.jsx)(`strong`,{children:o(`anthropicPool.title`)}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:w?o(`anthropicPool.saveStateUnknown`):y?o(`anthropicPool.loadFailed`):U?o(`common.loading`):I?Bb(o,R,L,B):o(`anthropicPool.disabledDesc`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${I?`on`:``}`,disabled:ee,"aria-pressed":w?void 0:I,"aria-label":o(`anthropicPool.title`),title:o(I?`anthropicPool.on`:`anthropicPool.off`),onClick:()=>{F({enabled:!I,threshold:L,strategy:R,stickyLimit:z,quotaWindow:B,nativeMessages:V})},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),(0,Q.jsx)(`p`,{className:`card-sub anthropic-pool-card__notice`,children:o(`anthropicPool.experimentalWarning`)}),r<2&&(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:o(`anthropicPool.needTwoAccounts`)}),(0,Q.jsxs)(`details`,{className:`anthropic-pool-card__details`,children:[(0,Q.jsx)(`summary`,{children:o(`anthropicPool.detailsSummary`)}),(0,Q.jsx)(`p`,{children:o(`anthropicPool.detailsEnabling`)}),(0,Q.jsx)(`p`,{children:o(`anthropicPool.detailsFailover`)}),(0,Q.jsx)(`p`,{children:o(`anthropicPool.detailsActivity`)}),(0,Q.jsxs)(`label`,{className:`anthropic-pool-card__native-messages`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:c?V:!1,disabled:W||!c,"aria-label":o(`anthropicPool.nativeMessagesLabel`),"aria-describedby":`anthropic-pool-native-messages-help`,onChange:e=>{F({enabled:I,threshold:L,strategy:R,stickyLimit:z,quotaWindow:B,nativeMessages:e.target.checked})}}),(0,Q.jsxs)(`span`,{className:`anthropic-pool-card__native-messages-copy`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:o(`anthropicPool.nativeMessagesLabel`)}),(0,Q.jsx)(`span`,{id:`anthropic-pool-native-messages-help`,className:`card-sub`,children:o(`anthropicPool.nativeMessagesHelp`)})]})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`a`,{href:Rb,target:`_blank`,rel:`noreferrer`,children:o(`anthropicPool.detailsGuide`)})})]}),I&&c&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:o(`anthropicPool.threshold`)}),(0,Q.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:u,disabled:W,"aria-label":o(`anthropicPool.thresholdAria`),onChange:e=>d(e.target.value),onBlur:()=>{let e=Number(u);!Number.isInteger(e)||e<0||e>100?(d(String(L)),_(o(`anthropicPool.thresholdInvalid`))):e!==L&&F({enabled:!0,threshold:e,strategy:R,stickyLimit:z,quotaWindow:B,nativeMessages:V})}}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:o(`anthropicPool.thresholdHelp`)})]}),(0,Q.jsx)(jy,{strategy:R,stickyDraft:f,disabled:W,strategySelectId:`anthropic-pool-strategy`,stickyInputId:`anthropic-pool-sticky-limit`,onStrategyChange:e=>{e!==R&&F({enabled:!0,threshold:L,strategy:e,stickyLimit:z,quotaWindow:B,nativeMessages:V})},onStickyDraftChange:p,onStickyCommit:e=>{let t=_v(e??f);t===null?(p(String(z)),_(o(`accountPool.stickyLimitInvalid`))):t===z?p(String(t)):F({enabled:!0,threshold:L,strategy:R,stickyLimit:t,quotaWindow:B,nativeMessages:V})}}),(0,Q.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:o(`accountPool.quotaWindow`)}),(0,Q.jsx)(Vn,{id:`anthropic-pool-quota-window`,value:B,options:lv.map(e=>({value:e,label:o(zb[e])})),disabled:W||H,label:o(`accountPool.quotaWindow`),onChange:e=>{let t=hv(e);t!==B&&F({enabled:!0,threshold:L,strategy:R,stickyLimit:z,quotaWindow:t,nativeMessages:V})}}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:o(`accountPool.quotaWindowDesc`)}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:o(H?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),w&&(0,Q.jsxs)(`div`,{role:`alert`,className:`anthropic-pool-card__save-warning`,children:[(0,Q.jsx)(`p`,{children:o(`anthropicPool.saveStateUnknown`)}),y&&(0,Q.jsx)(`p`,{children:o(`anthropicPool.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:O,onClick:()=>{x(!1),k(!0),D(e=>e+1)},children:o(`anthropicPool.reloadSettings`)})]}),S&&(0,Q.jsx)(`div`,{role:`status`,className:`anthropic-pool-card__save-warning`,children:o(`anthropicPool.saveWarning`)}),g&&(0,Q.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:g})]})}function Hb({serverDefault:e=!0}){let t=b(),n=(0,Z.useId)(),r=(0,Z.useId)(),i=(0,Z.useId)(),[a,o]=(0,Z.useState)(G_);return(0,Q.jsxs)(`label`,{className:`open-browser-pref`,htmlFor:n,children:[(0,Q.jsxs)(`span`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{id:n,type:`checkbox`,role:`switch`,"aria-labelledby":r,"aria-describedby":i,checked:!(a??e),onChange:e=>{let t=!e.target.checked;o(t),q_(t)}}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]}),(0,Q.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,Q.jsx)(`span`,{id:r,className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,Q.jsx)(`span`,{id:i,className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}function Ub(e){return e?.status===`ready`?e.coupons:[]}function Wb(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join(`-`)}}var Gb={auth_failed:`grokCoupon.authFailed`,no_account:`grokCoupon.noAccount`,no_coupons_available:`grokCoupon.noneAvailable`,operation_id_owned_by_another_account:`grokCoupon.identityMismatch`,capacity:`grokCoupon.capacity`,unavailable:`grokCoupon.capacity`,network:`grokCoupon.networkError`,redeem_failed:`grokCoupon.redeemFailed`};function Kb({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(Xe,{width:12}),`0`]});let r=e.status===`ready`?e.coupons.length:null,i=r===null?n(`grokCoupon.badgeErrorAria`):n(`grokCoupon.badgeAria`,{count:String(r)});return(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${r?`badge-amber`:`badge-muted`} badge-clickable`,"data-grok-coupon-badge":r===null?`error`:String(r),onClick:e=>{e.stopPropagation(),t()},"aria-label":i,title:i,children:[(0,Q.jsx)(Xe,{width:12}),r===null?(0,Q.jsx)(St,{width:11}):r]})}function qb({coupon:e,index:t,isNext:n,locale:r,t:i}){let a=e.validityEnd?ub(e.validityEnd):null;return(0,Q.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(Xe,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:n?i(`grokCoupon.couponNext`):i(`grokCoupon.couponLabel`,{n:String(t+1)})}),n&&(0,Q.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:i(`grokCoupon.couponNextBadge`)})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[e.validityStart&&(0,Q.jsx)(`span`,{children:i(`grokCoupon.validFrom`,{date:cb(e.validityStart,r)})}),a!==null&&(0,Q.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`grokCoupon.expires`,{date:lb(e.validityEnd,r),days:String(a)})})]})]})}function Jb({accountId:e,accountLabel:t,entry:n,controller:r,onClose:i}){let{locale:a,t:o}=s(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),g=r.uncertain[e],[_,v]=(0,Z.useState)(null),y=(0,Z.useRef)(void 0);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,Z.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,Z.useCallback)(e=>{e.preventDefault(),i()},[i]),x=Ub(n),S=x[0],C=()=>{if(g)return;let e=Wb();e?(y.current=e,v(null),d(!0)):v({tone:`warn`,key:`grokCoupon.noOperationId`})},w=async()=>{if(f||g)return;let t=y.current;if(!S?.tokenId){v({tone:`warn`,key:`grokCoupon.noneAvailable`});return}if(!t){v({tone:`warn`,key:`grokCoupon.noOperationId`});return}p(!0);let n=await r.redeem(e,{tokenId:S.tokenId,operationId:t});p(!1),n.ok?(y.current=void 0,d(!1),v({tone:`ok`,key:n.replayed?`grokCoupon.redeemReplayed`:`grokCoupon.redeemSuccess`})):n.uncertain||n.code===`aborted`?(n.operationId&&(y.current=n.operationId),d(!1),v(null),r.refresh(e)):(n.code===`operation_id_owned_by_another_account`&&(y.current=void 0),v({tone:`warn`,key:Gb[n.code]??`grokCoupon.redeemFailed`}))},T=async()=>{g&&!m&&(h(!0),await r.refresh(e),h(!1))},E=g?Ub(n).some(e=>e.tokenId===g.tokenId):!1,D=String(x.length),O=e=>(0,Q.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:o(e.key,{count:D})});return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`grok-coupon-title`,onCancel:b,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(St,{width:22})}),(0,Q.jsx)(`h3`,{id:`grok-coupon-title`,children:o(`grokCoupon.title`)}),(0,Q.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:o(`grokCoupon.unknownOutcome`)}),!m&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(E?`grokCoupon.unresolved`:`grokCoupon.consumedElsewhere`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{T()},disabled:m,children:o(m?`grokCoupon.checking`:`grokCoupon.checkResult`)})]})]}):u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(St,{width:22})}),(0,Q.jsx)(`h3`,{id:`grok-coupon-title`,children:o(`grokCoupon.confirmTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o(`grokCoupon.confirmDesc`,{count:D})}),S?.validityEnd&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`grokCoupon.confirmWhich`,{date:cb(S.validityEnd,a)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`grokCoupon.irreversible`)}),_&&O(_)]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(!1),disabled:f,children:o(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,onClick:()=>{w()},disabled:f,children:o(f?`grokCoupon.redeeming`:`grokCoupon.redeem`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`grok-coupon-title`,children:[(0,Q.jsx)(Xe,{width:16}),` `,o(`grokCoupon.title`)]}),(0,Q.jsx)(`div`,{className:`card-sub`,children:t}),(0,Q.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`common.loading`)}):n.status===`error`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,role:`alert`,children:o(n.reason===`auth`?`grokCoupon.loadFailedAuth`:`grokCoupon.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{r.refresh(e)},children:o(`grokCoupon.retry`)})]}):x.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:o(`grokCoupon.available`,{count:D})}),(0,Q.jsx)(`div`,{className:`credit-list`,children:x.map((e,t)=>(0,Q.jsx)(qb,{coupon:e,index:t,isNext:t===0,locale:a,t:o},e.tokenId))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:C,disabled:f,children:o(`grokCoupon.useOne`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:o(`grokCoupon.fifoNote`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:o(`grokCoupon.none`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o(`grokCoupon.desc`)})]}),_&&O(_)]})]})})]})}var Yb=2e4,Xb=6e4,Zb=3,Qb={},$b=[`five_hour`,`seven_day`,`seven_day_overage_included`],ex=new Set([`unknown_outcome`,`journal_write_failed`,`in_flight`]);function tx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nx(e){return e==null?null:typeof e==`string`?e:void 0}function rx(e){if(!tx(e))return null;let{id:t,label:n,resetsTotal:r,resetsLeft:i,paused:a,usableNow:o,useRequiresLimit:s}=e,c=nx(e.startsAt),l=nx(e.endsAt);if(typeof t!=`string`||t===``||typeof n!=`string`||typeof r!=`number`||typeof i!=`number`||typeof a!=`boolean`||typeof o!=`boolean`||typeof s!=`boolean`||c===void 0||l===void 0||!Array.isArray(e.clears))return null;let u={};if(tx(e.percentUsed))for(let t of $b){let n=e.percentUsed[t];typeof n==`number`&&(u[t]=n)}return{id:t,label:n,resetsTotal:r,resetsLeft:i,startsAt:c,endsAt:l,paused:a,usableNow:o,useRequiresLimit:s,percentUsed:u,clears:$b.filter(t=>e.clears.includes(t))}}function ix(e){if(!tx(e)||typeof e.eligible!=`boolean`||!Array.isArray(e.grants))return null;let t=[];for(let n of e.grants){let e=rx(n);if(!e)return null;t.push(e)}let n=null,r=e.pendingOperation;return tx(r)&&typeof r.operationId==`string`&&typeof r.grantId==`string`&&typeof r.retryableUntil==`number`&&(n={operationId:r.operationId,grantId:r.grantId,retryableUntil:r.retryableUntil}),{eligible:e.eligible,atLimit:e.atLimit===!0,grants:t,pendingOperation:n,journalAvailable:e.journalAvailable!==!1}}function ax(e){return e.eligible?e.grants.reduce((e,t)=>e+t.resetsLeft,0):0}function ox(e,t){return t.paused?`paused`:t.usableNow?t.resetsLeft<=0?`exhausted`:t.useRequiresLimit&&!e.atLimit?`not_limited`:null:`not_usable`}function sx(e,t){return e.eligible&&e.journalAvailable&&ox(e,t)===null}function cx(e){if(!e.endsAt)return 1/0;let t=Date.parse(e.endsAt);return Number.isNaN(t)?1/0:t}function lx(e){let t;for(let n of e.grants)sx(e,n)&&(!t||cx(n)<cx(t))&&(t=n);return t}function ux(e){return tx(e)&&tx(e.error)&&typeof e.error.code==`string`&&e.error.code!==``?e.error.code:`failed`}function dx({apiBase:e,provider:t=`anthropic`,accountIds:n,enabled:r}){let i=`${e}\0${t}`,[a,o]=(0,Z.useState)(()=>({namespace:i,entries:{}})),s=(0,Z.useRef)(0),c=(0,Z.useRef)(new Map),l=(0,Z.useRef)({active:0,waiting:[]}),u=n.join(`\0`);(0,Z.useLayoutEffect)(()=>{s.current+=1,c.current.clear();let e=l.current;l.current={active:0,waiting:[]};for(let t of e.waiting.splice(0))t();return()=>{s.current+=1}},[i]);let f=(0,Z.useCallback)((e,t)=>{o(n=>({namespace:i,entries:{...n.namespace===i?n.entries:{},[e]:t}}))},[i]),p=(0,Z.useCallback)(async(n,r)=>{if(s.current!==r)return;let i=(c.current.get(n)??0)+1;c.current.set(n,i);let a=l.current;a.active>=Zb&&await new Promise(e=>a.waiting.push(e)),a.active+=1;let o=()=>s.current===r&&c.current.get(n)===i,u=d(Yb);try{if(!o())return;let r=await fetch(`${e}/api/anthropic/reset-grants?accountId=${encodeURIComponent(n)}${t===`anthropic`?``:`&provider=${encodeURIComponent(t)}`}`,{signal:u.signal}),i=r.ok?await r.json().catch(()=>null):null,a=tx(i)&&(i.provider===t||t===`anthropic`&&i.provider===void 0)?ix(i):null;if(!o())return;f(n,a?{status:`ready`,snapshot:a}:{status:`error`,reason:r.status===401?`auth`:`upstream`})}catch{if(!o())return;f(n,{status:`error`,reason:`upstream`})}finally{u.clear(),--a.active,a.waiting.shift()?.()}},[e,t,f]);(0,Z.useEffect)(()=>{if(!r||u===``)return;let e=++s.current;return Promise.resolve().then(()=>{for(let t of u.split(`\0`))p(t,e)}),()=>{s.current+=1}},[r,u,p]);let m=(0,Z.useCallback)(async(e,t={})=>{t.keepSnapshot||f(e,{status:`loading`}),await p(e,s.current)},[p,f]),h=(0,Z.useCallback)(async(n,r)=>{let i=s.current,a=d(Xb);try{let o=await fetch(`${e}/api/anthropic/reset-grants/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t===`anthropic`?{}:{provider:t},accountId:n,grantId:r.grantId,operationId:r.operationId}),signal:a.signal});if(!o.ok){let e=ux(await o.json().catch(()=>null));return ex.has(e)?{kind:`unknown`,code:e}:{kind:`refused`,code:e}}let c=await o.json().catch(()=>null);return!tx(c)||typeof c.code!=`string`||c.provider!==t&&(t!==`anthropic`||c.provider!==void 0)?{kind:`unknown`,code:`unknown_outcome`}:(i===s.current&&p(n,i),{kind:`settled`,code:c.code,replayed:c.replayed===!0,resetsLeft:typeof c.resetsLeft==`number`?c.resetsLeft:null})}catch{return{kind:`unknown`,code:`aborted`}}finally{a.clear()}},[e,t,p]);return{entries:a.namespace===i?a.entries:Qb,refresh:m,spend:h}}function fx(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join(`-`)}}var px={reset:`anthropicGrant.resultReset`,already_used:`anthropicGrant.resultAlreadyUsed`,not_limited:`anthropicGrant.resultNotLimited`,cooldown:`anthropicGrant.resultCooldown`,ineligible:`anthropicGrant.resultIneligible`,unavailable:`anthropicGrant.resultUnavailable`,rate_limited:`anthropicGrant.resultRateLimited`,auth_error:`anthropicGrant.resultAuthError`},mx={grant_not_usable:`anthropicGrant.notUsableNow`,operation_identity_mismatch:`anthropicGrant.identityMismatch`,unresolved_prior_operation:`anthropicGrant.unresolvedPrior`,unknown_outcome_expired:`anthropicGrant.expired`,session_required:`anthropicGrant.sessionRequired`,ledger_busy:`anthropicGrant.journalBusy`,ledger_unavailable:`anthropicGrant.journalBusy`,ledger_capacity:`anthropicGrant.journalBusy`,auth_failed:`anthropicGrant.resultAuthError`};function hx({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(Xe,{width:12}),`0`]});let r=e.status===`ready`?ax(e.snapshot):null,i=e.status===`ready`&&lx(e.snapshot)!==void 0,a=r===null?n(`anthropicGrant.badgeErrorAria`):n(`anthropicGrant.badgeAria`,{count:String(r)});return(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${i?`badge-amber`:`badge-muted`} badge-clickable`,"data-anthropic-grant-badge":r===null?`error`:String(r),onClick:e=>{e.stopPropagation(),t()},"aria-label":a,title:a,children:[(0,Q.jsx)(Xe,{width:12}),r===null?(0,Q.jsx)(St,{width:11}):r]})}var gx={five_hour:`anthropicGrant.windowFiveHour`,seven_day:`anthropicGrant.windowWeekly`,seven_day_overage_included:`anthropicGrant.windowOverage`},_x={five_hour:`anthropicGrant.clearsFiveHour`,seven_day:`anthropicGrant.clearsWeekly`,seven_day_overage_included:`anthropicGrant.clearsOverage`},vx={paused:`anthropicGrant.paused`,not_usable:`anthropicGrant.notUsable`,exhausted:`anthropicGrant.exhausted`,not_limited:`anthropicGrant.requiresLimit`};function yx(e){return e!==null&&!Number.isNaN(Date.parse(e))?e:null}function bx(e){return e.label||e.id}function xx(e,t,n){let r=e.clears.map(e=>n(_x[e]));try{return new Intl.ListFormat(t,{type:`conjunction`}).format(r)}catch{return r.join(`, `)}}function Sx({grant:e,snapshot:t,checked:n,tabStop:r,selectable:i,optionRef:a,onSelect:o,onKeyDown:s,locale:c,t:l}){let u=yx(e.startsAt),d=yx(e.endsAt),f=d?ub(d):null,p=ox(t,e),m=p?l(vx[p]):null;return(0,Q.jsxs)(`div`,{ref:a,role:`radio`,"aria-checked":n,"aria-disabled":!i||void 0,tabIndex:r?0:-1,className:`credit-item anthropic-grant-option${n?` credit-next`:``}`,"data-anthropic-grant":e.id,onClick:o,onKeyDown:s,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(`span`,{className:`anthropic-grant-radio`,"aria-hidden":`true`}),(0,Q.jsx)(Xe,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:bx(e)}),(0,Q.jsx)(`span`,{className:`badge badge-muted text-micro anthropic-grant-count`,children:l(`anthropicGrant.resetsLeft`,{left:String(e.resetsLeft),total:String(e.resetsTotal)})})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[u&&(0,Q.jsx)(`span`,{children:l(`anthropicGrant.validFrom`,{date:cb(u,c)})}),d&&f!==null&&(0,Q.jsx)(`span`,{className:f<=7?`credit-urgent`:``,children:l(`anthropicGrant.expires`,{date:lb(d,c),days:String(f)})})]}),e.clears.length>0&&(0,Q.jsx)(`div`,{className:`anthropic-grant-windows`,children:e.clears.map(t=>(0,Q.jsx)(`span`,{className:`anthropic-grant-window`,children:l(gx[t],{percent:String(e.percentUsed[t]??0)})},t))}),m&&(0,Q.jsx)(`div`,{className:`faint text-caption anthropic-grant-note`,children:m})]})}function Cx(e){return e.kind===`settled`?e.replayed&&e.code===`reset`?{tone:`ok`,key:`anthropicGrant.replayed`}:{tone:e.code===`reset`?`ok`:`warn`,key:px[e.code]??`anthropicGrant.failed`,count:e.resetsLeft===null?`?`:String(e.resetsLeft)}:{tone:`warn`,key:mx[e.code]??`anthropicGrant.failed`}}var wx=new Set([`unknown_outcome_expired`,`operation_identity_mismatch`]);function Tx({accountId:e,accountLabel:t,entry:n,controller:r,onClose:i}){let{locale:a,t:o}=s(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(new Map),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let{refresh:C}=r,[w,T]=(0,Z.useState)(!0);(0,Z.useEffect)(()=>{let t=!0;return C(e,{keepSnapshot:!0}).catch(()=>void 0).finally(()=>{t&&T(!1)}),()=>{t=!1}},[e,C]),(0,Z.useEffect)(()=>{u&&l.current?.focus()},[u]);let E=(0,Z.useCallback)(e=>{e.preventDefault(),i()},[i]),D=n?.status===`ready`?n.snapshot:null,O=D?.pendingOperation,k=y??(O?{grantId:O.grantId,operationId:O.operationId}:null),A=(D&&f!==null?D.grants.find(e=>e.id===f&&sx(D,e)):void 0)??(D?lx(D):void 0),j=k!==null||h||u!==null,M=u&&D?D.grants.find(e=>e.id===u.grantId):void 0,N=u!==null&&D!==null&&(!M||!sx(D,M));N&&!h&&(d(null),p(null),S({tone:`warn`,key:`anthropicGrant.notUsableNow`}));let P=(e,t)=>{!j&&D&&sx(D,e)&&(p(e.id),t&&m.current.get(e.id)?.focus())},F=(e,t)=>{if(!D)return;let n=D.grants,r=n.filter(e=>sx(D,e)),i=n.findIndex(e=>e.id===t.id),a=e=>{for(let t=1;t<=n.length;t+=1){let r=n[((i+e*t)%n.length+n.length)%n.length];if(r&&sx(D,r))return r}},o;switch(e.key){case` `:case`Enter`:e.preventDefault(),P(t,!1);return;case`ArrowDown`:case`ArrowRight`:o=a(1);break;case`ArrowUp`:case`ArrowLeft`:o=a(-1);break;case`Home`:o=r[0];break;case`End`:o=r[r.length-1];break;default:return}e.preventDefault(),o&&P(o,!0)},I=()=>{if(w||!A||k||!D||!sx(D,A))return;let e=fx();e?(S(null),d({grantId:A.id,operationId:e,grant:A})):S({tone:`warn`,key:`anthropicGrant.noOperationId`})},L=async t=>{if(h)return;let n=k!==null&&k.operationId===t.operationId;g(!0);let i=await r.spend(e,t);g(!1),d(null),i.kind===`unknown`||i.kind===`refused`&&n&&!wx.has(i.code)?(b(t),S(i.kind===`refused`?Cx(i):null)):(b(null),S(Cx(i)),i.kind===`refused`&&r.refresh(e))},R=async()=>{_||(v(!0),await r.refresh(e),v(!1))},z=e=>(0,Q.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:o(e.key,{count:e.count??``})}),B=u?yx(u.grant.endsAt):null,V=A?.id??D?.grants[0]?.id,H=(D?D.grants.filter(e=>sx(D,e)).length:0)>1&&A!==void 0&&A.id===(D?lx(D)?.id:void 0),U=k&&D?D.grants.find(e=>e.id===k.grantId):void 0,W=D?ax(D):0;return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`anthropic-grant-title`,onCancel:E,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:k?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(St,{width:22})}),(0,Q.jsx)(`h3`,{id:`anthropic-grant-title`,children:o(`anthropicGrant.title`)}),(0,Q.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:o(`anthropicGrant.unknownOutcome`)}),k&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`anthropicGrant.confirmWhich`,{label:U?bx(U):k.grantId})}),x&&z(x)]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{R()},disabled:_||h,children:o(_?`anthropicGrant.checking`:`anthropicGrant.checkResult`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,"data-anthropic-grant-retry":!0,onClick:()=>{L(k)},disabled:h||_,children:o(h?`anthropicGrant.redeeming`:`anthropicGrant.retrySame`)})]})]}):u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(St,{width:22})}),(0,Q.jsx)(`h3`,{id:`anthropic-grant-title`,children:o(`anthropicGrant.confirmTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o(`anthropicGrant.confirmDesc`)}),(0,Q.jsx)(`p`,{className:`faint text-label`,"data-anthropic-grant-confirm-which":u.grantId,children:o(`anthropicGrant.confirmWhich`,{label:bx(u.grant)})}),B&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`anthropicGrant.confirmExpires`,{date:lb(B,a)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:u.grant.clears.length>0?o(`anthropicGrant.confirmClears`,{windows:xx(u.grant,a,o)}):o(`anthropicGrant.confirmClearsUnknown`)}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`anthropicGrant.irreversible`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(null),disabled:h,children:o(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,"data-anthropic-grant-confirm":!0,onClick:()=>{L({grantId:u.grantId,operationId:u.operationId})},disabled:h||D===null||N,children:o(h?`anthropicGrant.redeeming`:`anthropicGrant.redeem`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`anthropic-grant-title`,children:[(0,Q.jsx)(Xe,{width:16}),` `,o(`anthropicGrant.title`)]}),(0,Q.jsx)(`div`,{className:`card-sub`,children:t}),(0,Q.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Q.jsx)(`p`,{className:`faint text-label`,children:o(`common.loading`)}):n.status===`error`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,role:`alert`,children:o(n.reason===`auth`?`anthropicGrant.loadFailedAuth`:`anthropicGrant.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{r.refresh(e)},children:o(`anthropicGrant.retry`)})]}):n.snapshot.eligible?n.snapshot.grants.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:o(`anthropicGrant.available`,{count:String(W)})}),!n.snapshot.journalAvailable&&(0,Q.jsx)(`p`,{className:`pws-status-warn`,style:{marginBottom:12},children:o(`anthropicGrant.journalBusy`)}),(0,Q.jsx)(`div`,{className:`credit-list`,role:`radiogroup`,"aria-label":o(`anthropicGrant.chooseLabel`),children:n.snapshot.grants.map(e=>(0,Q.jsx)(Sx,{grant:e,snapshot:n.snapshot,checked:e.id===A?.id,tabStop:e.id===V,selectable:sx(n.snapshot,e),optionRef:t=>{t?m.current.set(e.id,t):m.current.delete(e.id)},onSelect:()=>P(e,!0),onKeyDown:t=>F(t,e),locale:a,t:o},e.id))}),H&&(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8},children:o(`anthropicGrant.pickHint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,"data-anthropic-grant-use":!0,style:{marginTop:12,width:`100%`},onClick:I,disabled:!A||h||w,children:o(`anthropicGrant.useOne`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:o(`anthropicGrant.desc`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:o(`anthropicGrant.none`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o(`anthropicGrant.desc`)})]}):(0,Q.jsx)(`p`,{className:`faint`,children:o(`anthropicGrant.ineligible`)}),x&&z(x)]})]})})]})}var Ex=2e4,Dx=3e4,Ox=3,kx=`ocx.grok-coupon-holds.v1`,Ax=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,jx=new Set([`attempt_unresolved`,`attempt_in_progress`,`attempt_reconcile_failed`,`operation_state_changed`,`redeem_failed`,`attempt_mark_failed`,`operation_token_mismatch`]),Mx=new Set([`ledger_unavailable`,`capacity`]),Nx=new Set([`redeemed`,`auth_failed`,`fetch_resets_failed`,`no_coupons_available`,`coupon_unavailable`,`token_unresolved`]),Px=new Map,Fx=new Set,Ix;function Lx(e){if(!e||typeof e!=`object`)return!1;let{tokenId:t,operationId:n}=e;return typeof t==`string`&&t.trim()!==``&&typeof n==`string`&&Ax.test(n)}function Rx(){try{let e=window.sessionStorage.getItem(kx);if(e!==Ix){Ix=e;let t=e===null?null:JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))e.includes(`\0`)&&Lx(n)&&(Px.has(e)||(Px=new Map(Px).set(e,{tokenId:n.tokenId,operationId:n.operationId})))}}catch{}return Px}function zx(e){return Fx.add(e),()=>{Fx.delete(e)}}function Bx(){try{let e=JSON.stringify(Object.fromEntries(Px));window.sessionStorage.setItem(kx,e),Ix=e}catch{}for(let e of Fx)e()}function Vx(e,t){Px=new Map(Px).set(e,{...t}),Bx()}function Hx(e,t){Rx().get(e)?.operationId===t&&(Px=new Map(Px),Px.delete(e),Bx())}function Ux(e,t){return jx.has(e)||Mx.has(e)&&!!(t&&typeof t==`object`&&`operationId`in t)}function Wx(e){if(!e||typeof e!=`object`)return null;let t=e.tokens;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{tokenId:t,validityStart:r,validityEnd:i}=e;if(typeof t!=`string`||t===``)return null;n.push({tokenId:t,validityStart:typeof r==`string`?r:``,validityEnd:typeof i==`string`?i:``})}return n}function Gx(e){if(e&&typeof e==`object`){let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(typeof e==`string`&&e.trim()!==``)return e}}return`redeem_failed`}function Kx(e){if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&t.trim()!==``)return t}return null}function qx(e){if(!e.validityEnd)return 1/0;let t=Date.parse(e.validityEnd);return Number.isNaN(t)?1/0:t}function Jx(e){return e.toSorted((e,t)=>qx(e)-qx(t))}function Yx({apiBase:e,accountIds:t,enabled:n}){let[r,i]=(0,Z.useState)({}),a=(0,Z.useSyncExternalStore)(zx,Rx,Rx),o=(0,Z.useMemo)(()=>{let t=`${e}\u0000`;return Object.fromEntries([...a].filter(([e])=>e.startsWith(t)).map(([e,n])=>[e.slice(t.length),n]))},[e,a]),s=(0,Z.useRef)(0),c=(0,Z.useRef)(new Map),l=(0,Z.useRef)({active:0,waiting:[]}),u=t.join(`\0`),f=(0,Z.useCallback)(async(t,n)=>{let r=(c.current.get(t)??0)+1;c.current.set(t,r);let a=l.current;a.active>=Ox&&await new Promise(e=>a.waiting.push(e)),a.active+=1;let o=()=>s.current===n&&c.current.get(t)===r,u=d(Ex);try{let n=await fetch(`${e}/api/grok/reset-coupons?accountId=${encodeURIComponent(t)}`,{signal:u.signal}),r=n.ok?Wx(await n.json().catch(()=>null)):null;if(!o())return;i(e=>({...e,[t]:r?{status:`ready`,coupons:Jx(r)}:{status:`error`,reason:n.status===401?`auth`:`upstream`}}))}catch{if(!o())return;i(e=>({...e,[t]:{status:`error`,reason:`upstream`}}))}finally{u.clear(),--a.active,a.waiting.shift()?.()}},[e]);return(0,Z.useEffect)(()=>{if(!n||u===``)return;let e=++s.current;return Promise.resolve().then(()=>{for(let t of u.split(`\0`))f(t,e)}),()=>{s.current+=1}},[n,u,f]),{entries:r,uncertain:o,refresh:(0,Z.useCallback)(async e=>{i(t=>({...t,[e]:{status:`loading`}})),await f(e,s.current)},[f]),redeem:(0,Z.useCallback)(async(t,n)=>{let r=`${e}\u0000${t}`,i=(e,t=`attempt_unresolved`)=>({ok:!1,code:t,replayed:!1,operationId:e.operationId,uncertain:!0}),a=Rx().get(r);if(a)return i(a);Vx(r,n);let o=()=>Hx(r,n.operationId),c=d(Dx);try{let r=await fetch(`${e}/api/grok/reset-coupons/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t,tokenId:n.tokenId,operationId:n.operationId}),signal:c.signal});if(!r.ok){let e=await r.json().catch(()=>null),t=Gx(e);return Ux(t,e)?i(n,t):(o(),{ok:!1,code:t,replayed:!1})}let a=await r.json().catch(()=>null),l=!!(a&&typeof a==`object`&&a.replayed===!0),u=Kx(a);return u===null||!Nx.has(u)?i(n,u??`attempt_unresolved`):(o(),await f(t,s.current),{ok:u===`redeemed`,code:u,replayed:l})}catch{return i(n,`aborted`)}finally{c.clear()}},[e,f])}}var Xx=new Set([`builder-id`,`google`,`github`,`iam-identity-center`]),Zx=new Set([`pending`,`select-profile`,`done`,`failed`,`expired`,`cancelled`]),Qx=`us-east-1.us-east-2.us-west-1.us-west-2.af-south-1.ap-east-1.ap-east-2.ap-northeast-1.ap-northeast-2.ap-northeast-3.ap-south-1.ap-south-2.ap-southeast-1.ap-southeast-2.ap-southeast-3.ap-southeast-4.ap-southeast-5.ap-southeast-6.ap-southeast-7.ca-central-1.ca-west-1.eu-central-1.eu-central-2.eu-north-1.eu-south-1.eu-south-2.eu-west-1.eu-west-2.eu-west-3.il-central-1.me-central-1.me-south-1.mx-central-1.sa-east-1`.split(`.`),$x=/^(?:af|ap|ca|eu|il|me|mx|sa|us)-(?:central|east|north|northeast|northwest|south|southeast|southwest|west)-[1-9][0-9]?$/;function eS({startUrl:e,region:t}){return/^https:\/\/[a-z0-9][a-z0-9-]{0,62}\.awsapps\.com\/start\/?(?:#\/)?$/.test(e)&&$x.test(t)}function tS(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.flowId!=`string`||!t.flowId||!Xx.has(t.method)||!Zx.has(t.state))return null;let n;if(t.state===`select-profile`){if(t.method!==`iam-identity-center`||!Array.isArray(t.profiles)||!t.profiles.length||t.profiles.length>64)return null;n=[];for(let e of t.profiles){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.arn!=`string`||t.arn.length>256||!/^arn:aws:codewhisperer:[a-z0-9-]+:\d{12}:profile\/[A-Za-z0-9-]+$/.test(t.arn)||typeof t.name!=`string`||!t.name||t.name.length>256||typeof t.region!=`string`||!$x.test(t.region))return null;n.push({arn:t.arn,name:t.name,region:t.region})}}return{flowId:t.flowId,method:t.method,state:t.state,...typeof t.userCode==`string`?{userCode:t.userCode}:{},...typeof t.verificationUri==`string`?{verificationUri:t.verificationUri}:{},...typeof t.verificationUriComplete==`string`?{verificationUriComplete:t.verificationUriComplete}:{},...typeof t.expiresAt==`number`&&Number.isFinite(t.expiresAt)?{expiresAt:t.expiresAt}:{},...t.warning===`duplicate_profile_arn`||t.warning===`manual_review_required`?{warning:t.warning}:{},...n?{profiles:n}:{}}}function nS(e,t){if(!e||[...e].some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127))return null;let n=/^https:\/\/([^/?#]+)/iu.exec(e)?.[1];if(!n||n.includes(`@`)||n.includes(`:`))return null;try{let n=new URL(e);if(n.protocol!==`https:`||n.username||n.password||n.port)return null;let r=n.hostname.toLowerCase(),i=/^device\.sso\.([a-z0-9-]+)\.amazonaws\.com$/.exec(r)?.[1];return!(t===`iam-identity-center`&&/^[a-z0-9][a-z0-9-]{0,62}\.awsapps\.com$/.test(r)&&/^\/start\/?$/.test(n.pathname))&&!(i&&$x.test(i))&&r!==`kiro.dev`&&!r.endsWith(`.kiro.dev`)?null:n.href}catch{return null}}function rS(e,t){return t!==`kiro`||e.autoSelectable!==!1||e.skipReason===`needs_reauth`||e.skipReason===`paused`||e.skipReason===`cooldown`&&e.health?.status===`cooldown`?null:e.skipReason===`suspended`?`kiroSelection.suspended`:e.skipReason===`quota_exhausted`?`kiroSelection.quotaExhausted`:e.skipReason===`cooldown`?`kiroSelection.cooldown`:`kiroSelection.generic`}var iS=new Map;function aS(e,t){return JSON.stringify([e.targetKey,e.apiBase,t])}function oS(e,t){let n=aS(e,t),r=iS.get(n);if(r)return r;let a=(async()=>{await i(e,`${e.apiBase}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t}),keepalive:!0})})().catch(()=>{}).finally(()=>{iS.get(n)===a&&iS.delete(n)});return iS.set(n,a),a}async function sS(e,t,n){let r=aS(e,t),i=iS.get(r);return i?(await i,sS(e,t,n)):n()}var cS=new Map,lS=new Map,uS=new Map,dS=(e,t)=>JSON.stringify([e,t]),fS=e=>new Promise(t=>setTimeout(t,e)),pS=65536;function mS(e){try{e.body?.cancel().catch(()=>{})}catch{}}function hS(e,t,n=45e3,r){let a=new AbortController,o,s=!1,c,l=new Promise(e=>{c=e}),u=e=>{s||(s=!0,clearTimeout(f),c(e))},d=()=>{if(!s){a.abort();try{o?.cancel().catch(()=>{})}catch{}u({kind:`retry`})}},f=setTimeout(d,Math.max(0,n));return(async()=>{try{if(r&&!v(r)){u({kind:`missing`});return}let n=`${e}/api/oauth/status?provider=kiro&flowId=${encodeURIComponent(t)}`,c=r?await i(r,n,{signal:a.signal}):await fetch(n,{signal:a.signal});if(s){mS(c);return}if(c.status===404){mS(c),u({kind:`missing`});return}if(!c.ok||!c.body){mS(c),u({kind:`retry`});return}o=c.body.getReader();let l=new TextDecoder,f=``,p=0;for(;;){let e=await o.read();if(s)return;if(e.done)break;if(p+=e.value.byteLength,p>pS){d();return}f+=l.decode(e.value,{stream:!0})}f+=l.decode();let m;try{m=JSON.parse(f)}catch{u({kind:`retry`});return}let h=tS(m);u(h?{kind:`view`,view:h}:{kind:`retry`})}catch{u({kind:`retry`})}})(),{result:l,cancel:d}}async function gS(e,t){let n;try{return await Promise.race([e.result,new Promise(r=>{n=setTimeout(()=>{e.cancel(),r({kind:`retry`})},Math.max(0,t))})])}finally{n&&clearTimeout(n)}}function _S(e,t){let n=uS.get(e)??new Set;return n.add(t),uS.set(e,n),()=>{n.delete(t),n.size===0&&uS.delete(e)}}function vS(e,t,n){let r=dS(e,t);if(lS.has(r))return lS.get(r);lS.set(r,n);for(let t of uS.get(e)??[])t(n);return n}function yS(e,t,n,r=`status`){return n.flowId!==t||r===`cancel`&&n.state!==`failed`?null:n.state===`done`?vS(e,t,`added`):n.state===`failed`?vS(e,t,`failed`):n.state===`expired`||n.state===`cancelled`?vS(e,t,`ended`):null}function bS(e,t,n,r,i){let a=dS(e,t),o=cS.get(a);if(o)return o;let s=lS.get(a);if(s)return Promise.resolve(s);let c=Math.min(Date.now()+96e4,(n??Date.now()+9e5)+6e4),l=(async()=>{let n=r;for(;Date.now()<c;){let r=c-Date.now(),o=n??hS(e,t,Math.min(45e3,r),i);n=void 0;let s=await gS(o,r);if(lS.has(a))return lS.get(a);if(s.kind===`missing`)return vS(e,t,`ended`);if(s.kind===`view`){let n=yS(e,t,s.view);if(n)return n}let l=c-Date.now();if(l<=0)break;await fS(Math.min(2e3,l))}return n?.cancel(),vS(e,t,`ended`)})().finally(()=>{cS.delete(a)});return cS.set(a,l),l}var xS=(e,t)=>new Promise(n=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n()};t.addEventListener(`abort`,i,{once:!0})}),SS=Symbol(`closed`),CS=(e,t)=>new Promise(n=>{if(e.closed){n(SS);return}let r=!1,i=t=>{r||(r=!0,e.closedController.signal.removeEventListener(`abort`,a),n(t))},a=()=>i(SS);e.closedController.signal.addEventListener(`abort`,a,{once:!0}),t.then(t=>i(e.closed?SS:t),()=>i(SS))});function wS(e,t,n=xS,r){let[a,o]=(0,Z.useState)({phase:`idle`}),s=Y_(e,r),c=(0,Z.useRef)(null),l=(0,Z.useRef)(!0),u=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{u.current=t},[t]);let d=(0,Z.useCallback)(async(t,n)=>{try{return await i(n,`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,flowId:t.flowId}),keepalive:!0})}catch{return null}},[e]),f=(0,Z.useCallback)(t=>{let n=t.view;n&&!t.terminal&&bS(e,n.flowId,n.expiresAt,t.inFlight,t.capture)},[e]),p=(0,Z.useCallback)(async()=>{let t=c.current;if(!t||t.closed||(t.closed=!0,t.closedController.abort(),c.current=null,t.waitController?.abort(),l.current&&o({phase:`cancelled`}),!t.view||t.terminal))return;let n=d(t.view,t.capture);f(t);let r=await n,i=r?.ok?tS(await r.json().catch(()=>null)):null;i&&yS(e,t.view.flowId,i,`cancel`)},[e,d,f]);return(0,Z.useEffect)(()=>(l.current=!0,()=>{l.current=!1,p()}),[p]),{state:a,start:(0,Z.useCallback)(async(t,r)=>{if(c.current)return;let a=s,p={closed:!1,closedController:new AbortController,capture:a};c.current=p,o({phase:`starting`});let m;try{m=await sS(a,`kiro`,()=>i(a,`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,method:t,...t===`iam-identity-center`?r:{}})}))}catch{!p.closed&&l.current&&o({phase:`failed`,error:`network`}),c.current===p&&(c.current=null);return}let h=m.ok?tS(await m.json().catch(()=>null)):null;if(!h||h.method!==t)!p.closed&&l.current&&o({phase:`failed`,error:m.ok?`invalid`:`start`}),c.current===p&&(c.current=null);else if(p.view=h,p.closed){let t=d(h,p.capture);f(p);let n=await t,r=n?.ok?tS(await n.json().catch(()=>null)):null;r&&yS(e,h.flowId,r,`cancel`)}else if(h.state!==`pending`&&h.state!==`select-profile`)h.state===`done`?u.current?.(`kiro`,`added`):h.state===`failed`&&u.current?.(`kiro`,`failed`),l.current&&o({phase:h.state,view:h}),p.terminal=h.state===`done`?`added`:h.state===`failed`?`failed`:`ended`,c.current=null;else{for(o({phase:h.state,view:h});!p.closed&&!p.terminal;){let t=new AbortController;if(p.waitController=t,await n(2e3,t.signal),p.waitController=void 0,p.closed||p.terminal)break;if(p.view?.expiresAt&&Date.now()>=p.view.expiresAt){p.terminal=`ended`,l.current&&o({phase:`expired`,view:p.view});break}let r=h.flowId,i=hS(e,r,void 0,p.capture);p.inFlight=i;let a=await CS(p,i.result);if(a===SS||p.terminal)break;if(p.inFlight=void 0,a.kind===`missing`){p.terminal=`ended`,u.current?.(`kiro`,`ended`),o({phase:`ended`,view:p.view});break}let s=a.kind===`view`?a.view:null;if(s&&s.flowId===r){if(p.view=s,s.state===`pending`||s.state===`select-profile`)p.selecting||o({phase:s.state,view:s});else{p.terminal=s.state===`done`?`added`:s.state===`failed`?`failed`:`ended`,(s.state===`done`||s.state===`failed`)&&u.current?.(`kiro`,p.terminal),o({phase:s.state,view:s});break}}}c.current===p&&(c.current=null)}},[e,d,f,n,s]),selectProfile:(0,Z.useCallback)(async t=>{let n=c.current;if(!n||n.closed||n.terminal||n.selecting||n.view?.state!==`select-profile`)return;let r=n.view;n.selecting=!0,o({phase:`selecting`,view:r});let a=null;try{let o=await i(n.capture,`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,flowId:r.flowId,profileArn:t})});o.ok&&(a=tS(await o.json()))}catch{}n.selecting=!1,!(n.closed||n.terminal||!l.current)&&(!a||a.flowId!==r.flowId||a.method!==`iam-identity-center`?o({phase:`select-profile`,view:r,error:`profile`}):(n.view=a,(a.state===`done`||a.state===`failed`)&&(n.terminal=a.state===`done`?`added`:`failed`,u.current?.(`kiro`,n.terminal),n.waitController?.abort()),o({phase:a.state,view:a})))},[e]),close:p,reset:(0,Z.useCallback)(()=>{c.current||o({phase:`idle`})},[])}}function TS({disabled:e,onCli:t,onMethod:n}){let r=b();return(0,Q.jsxs)(`div`,{className:`kiro-login-choices`,role:`group`,"aria-label":r(`kiroLogin.chooseMethod`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:t,children:r(`kiroLogin.cli`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`iam-identity-center`),children:r(`kiroLogin.iam`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`builder-id`),children:r(`kiroLogin.builderId`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`google`),children:r(`kiroLogin.google`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`github`),children:r(`kiroLogin.github`)})]})}function ES({disabled:e,onStart:t,onBack:n}){let r=b(),i=(0,Z.useId)(),a=i+`regions`,[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1);return(0,Q.jsxs)(`form`,{className:`kiro-iam-form`,onSubmit:e=>{e.preventDefault();let n={startUrl:o.trim(),region:c.trim()};eS(n)?(d(!1),t(n)):d(!0)},children:[(0,Q.jsx)(`p`,{className:`muted`,children:r(`kiroLogin.iamDescription`)}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${i}-portal`,children:r(`kiroLogin.startUrl`)}),(0,Q.jsx)(`input`,{className:`input`,id:`${i}-portal`,type:`url`,required:!0,maxLength:2048,value:o,disabled:e,placeholder:`https://example.awsapps.com/start`,autoComplete:`url`,"aria-describedby":u?`${i}-error`:void 0,"aria-invalid":u||void 0,onChange:e=>{s(e.target.value),d(!1)}}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${i}-region`,children:r(`kiroLogin.region`)}),(0,Q.jsx)(`input`,{className:`input`,id:`${i}-region`,list:a,required:!0,maxLength:32,value:c,disabled:e,placeholder:`us-east-1`,autoComplete:`off`,"aria-invalid":u||void 0,"aria-describedby":u?`${i}-error`:void 0,onChange:e=>{l(e.target.value),d(!1)}}),(0,Q.jsx)(`datalist`,{id:a,children:Qx.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),u&&(0,Q.jsx)(`p`,{id:`${i}-error`,role:`alert`,className:`notice-warn`,children:r(`kiroLogin.invalidIam`)}),(0,Q.jsxs)(`div`,{className:`kiro-device-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:n,children:r(`kiroLogin.back`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:e,children:r(`kiroLogin.continue`)})]})]})}function DS({profiles:e,disabled:t,onSelect:n}){let r=b(),i=(0,Z.useId)(),[a,o]=(0,Z.useState)(``);return(0,Q.jsxs)(`form`,{className:`kiro-iam-form`,onSubmit:t=>{t.preventDefault(),e.some(e=>e.arn===a)&&n(a)},children:[(0,Q.jsx)(`p`,{children:r(`kiroLogin.selectProfile`)}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:i,children:r(`kiroLogin.profile`)}),(0,Q.jsx)(Vn,{fullWidth:!0,id:i,value:a,required:!0,disabled:t,onChange:o,options:[{value:``,label:r(`kiroLogin.selectProfile`)},...e.map(e=>({value:e.arn,label:`${e.name} (${e.region})`}))]}),a&&(0,Q.jsx)(`code`,{className:`kiro-device-destination`,children:a}),(0,Q.jsx)(`div`,{className:`kiro-device-actions`,children:(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:t||!a,children:r(`kiroLogin.saveAccount`)})})]})}function OS({apiBase:e,targetKey:t,triggerRef:n,addAccount:r,busy:i,onCli:a,onClose:o,onSettled:s,pollDelay:c}){let l=b(),u=(0,Z.useId)(),d=Br(!0,n),f=wS(e,s,c,t),[p,m]=(0,Z.useState)(!1),h=z_(),{state:g}=f,_=g.view,v=_?.verificationUriComplete??_?.verificationUri,y=nS(v,_?.method),x=()=>{f.close(),o()},S=g.phase===`done`||g.phase===`failed`||g.phase===`expired`||g.phase===`ended`;return(0,Q.jsxs)(`dialog`,{ref:d,className:`kiro-device-dialog`,"aria-modal":`true`,"aria-labelledby":u,onCancel:e=>{e.preventDefault(),x()},children:[(0,Q.jsx)(`h2`,{id:u,children:l(`kiroLogin.title`)}),g.phase===`idle`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:l(r?`kiroLogin.addDescription`:`kiroLogin.loginDescription`)}),p?(0,Q.jsx)(ES,{disabled:i,onBack:()=>m(!1),onStart:e=>{f.start(`iam-identity-center`,e)}}):(0,Q.jsx)(TS,{disabled:i,onCli:()=>{o(),a(r)},onMethod:e=>{e===`iam-identity-center`?m(!0):f.start(e)}})]}),g.phase===`starting`&&(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:l(`kiroLogin.starting`)}),_?.profiles&&(g.phase===`select-profile`||g.phase===`selecting`)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(DS,{profiles:_.profiles,disabled:g.phase===`selecting`,onSelect:e=>{f.selectProfile(e)}}),g.error===`profile`&&(0,Q.jsx)(`p`,{role:`alert`,className:`notice-warn`,children:l(`kiroLogin.profileFailed`)})]}),_&&(g.phase===`pending`||g.phase===`done`||g.phase===`failed`||g.phase===`expired`||g.phase===`ended`)&&(0,Q.jsxs)(Q.Fragment,{children:[_.userCode&&(0,Q.jsxs)(`div`,{className:`kiro-device-code`,children:[(0,Q.jsx)(`span`,{className:`kiro-device-code-value`,children:_.userCode}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>h.copy(_.userCode,_.flowId),children:h.outcomeFor(_.flowId)===`copied`?l(`kiroLogin.copied`):h.outcomeFor(_.flowId)===`unavailable`?l(`kiroLogin.copyUnavailable`):l(`kiroLogin.copyCode`)})]}),v&&(y?(0,Q.jsx)(`a`,{href:y,target:`_blank`,rel:`noopener noreferrer`,children:l(`kiroLogin.openVerification`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`kiro-device-destination`,children:v}),(0,Q.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.unexpectedHost`)})]})),_.warning===`duplicate_profile_arn`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.duplicate`)}),_.warning===`manual_review_required`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.manualReview`)})]}),(0,Q.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[g.phase===`pending`&&l(`kiroLogin.pending`),g.phase===`selecting`&&l(`kiroLogin.selecting`),g.phase===`done`&&l(`kiroLogin.done`),g.phase===`expired`&&l(`kiroLogin.expired`),g.phase===`ended`&&l(`kiroLogin.ended`),g.phase===`failed`&&l(g.error===`start`?`kiroLogin.startFailed`:`kiroLogin.failed`)]}),(0,Q.jsxs)(`div`,{className:`kiro-device-actions`,children:[(g.phase===`failed`||g.phase===`expired`||g.phase===`ended`)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f.reset,children:l(`kiroLogin.tryAgain`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:x,children:l(S?`common.close`:`common.cancel`)})]})]})}var kS=new Set([`anthropic`,`anthropic2`,`google-antigravity`,`meta-muse`]),AS=new Set([`github-copilot`,`cursor`,`zed`]),jS=`google-antigravity`;function MS(e){let t=e.trim().toLowerCase();return kS.has(t)?`high`:AS.has(t)?`elevated`:null}function NS(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function PS(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function FS(e,t){let n=e.trim().toLowerCase();return n===`anthropic`||n===`anthropic2`?{tone:`warning`,title:`oauthTos.anthropicTitle`,body:`oauthTos.anthropicBody`,conditions:`oauthTos.anthropicConditions`,saferPath:`oauthTos.anthropicSaferPath`,acknowledge:`oauthTos.anthropicAcknowledge`,continue:`oauthTos.anthropicContinue`}:n===jS?{tone:`danger`,title:`oauthTos.antigravityTitle`,body:`oauthTos.antigravityBody`,conditions:`oauthTos.antigravityConditions`,saferPath:`oauthTos.antigravitySaferPath`,acknowledge:`oauthTos.antigravityAcknowledge`,continue:`oauthTos.antigravityContinue`}:{tone:`warning`,title:NS(t),body:PS(t),conditions:null,saferPath:null,acknowledge:`oauthTos.acknowledge`,continue:`oauthTos.continue`}}function IS(e,t){return t&&e.trim().toLowerCase()===jS?{acknowledgeAntigravityRisk:!0}:{}}function LS({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=b(),a=(0,Z.useId)(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),m=MS(e);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let h=(0,Z.useCallback)(e=>{e.preventDefault(),n()},[n]);if(!m)return null;let g=FS(e,m),_=g.tone===`danger`,v=g.conditions?i(g.conditions).split(`
5
- `).filter(e=>e.trim()):[];return(0,Q.jsxs)(`dialog`,{ref:c,"aria-labelledby":a,"aria-describedby":g.conditions?`${o} ${s}`:o,className:`modal-overlay`,onCancel:h,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,Q.jsxs)(`div`,{className:_?`modal-card oauth-tos-card oauth-tos-card--danger`:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:_?520:460},children:[_?(0,Q.jsxs)(`h3`,{id:a,className:`oauth-tos-danger-title`,children:[(0,Q.jsx)(St,{width:22,height:22,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:i(g.title,{provider:t})})]}):(0,Q.jsx)(`h3`,{id:a,children:i(g.title,{provider:t})}),(0,Q.jsxs)(`div`,{id:o,className:_?`notice-err oauth-tos-danger-body`:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(St,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g.body,{provider:t})})]}),v.length>1&&(0,Q.jsx)(`ul`,{id:s,className:`oauth-tos-conditions`,children:v.map(e=>(0,Q.jsx)(`li`,{children:e},e))}),v.length===1&&(0,Q.jsx)(`p`,{id:s,className:`modal-desc`,style:{marginTop:12},children:v[0]}),g.saferPath&&(0,Q.jsx)(`p`,{className:_?`oauth-tos-safer text-label`:`muted text-label`,style:{marginTop:12},children:i(g.saferPath)}),(0,Q.jsxs)(`label`,{className:_?`oauth-tos-ack oauth-tos-ack--danger`:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,Q.jsx)(`span`,{className:`text-label`,children:i(g.acknowledge)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:_?`btn btn-primary oauth-tos-continue--danger`:`btn btn-primary`,disabled:!u||f,onClick:()=>{u&&!l.current&&(l.current=!0,p(!0),r())},children:i(g.continue)})]})]})]})}var RS=262144,zS=[],BS=[];function VS(e){return!!e.needsReauth||__(e.health?.status)}function HS({initialState:e,onUpdateProvider:t}){let n=b(),[r,i]=(0,Z.useState)(e),[a,o]=(0,Z.useState)(e),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``);e!==a&&(o(e),i(e));let d=r===`mixed`,f=async()=>{if(!t||s)return;let e=r===!1;c(!0),u(``);try{let r=await t(`xai`,{xaiResponsesOptIn:e});if(!r.ok){u(r.error??n(`prov.updateFail`));return}i(r.xaiResponsesOptInState??e)}catch{u(n(`prov.networkError`))}finally{c(!1)}};return(0,Q.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-optin-label`,children:n(`pws.xaiChatOptIn`)}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[n(`pws.xaiChatOptInDesc`),d&&(0,Q.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,n(`pws.xaiChatOptInMixed`)]})]}),l&&(0,Q.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:l})]}),(0,Q.jsx)(Rn,{on:r===!1,mixed:d,onClick:()=>{f()},disabled:!t||s,label:n(`pws.xaiChatOptIn`)})]})}var US=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),WS=new Set([`imported`,`updated`,`failed`,`unsupported`]),GS={imported:new Set([`imported`]),updated:new Set([`updated`]),failed:new Set([`invalid_record`,`credential_rejected`,`identity_mismatch`,`missing_project`,`persist_failed`]),unsupported:new Set([`unsupported_provider`,`unsupported_format`])};function KS(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qS(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function JS(e){if(!KS(e)||Object.keys(e).some(e=>!US.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!qS(t)||!qS(n)||!qS(r)||!qS(i)||!qS(a)||!Array.isArray(o)||o.length!==t||n+r+i+a!==t)return null;let s={imported:0,updated:0,failed:0,unsupported:0};for(let[e,t]of o.entries()){if(!KS(t)||Object.keys(t).some(e=>![`index`,`status`,`code`].includes(e)))return null;let n=String(t.status),r=String(t.code);if(t.index!==e||!WS.has(n)||!GS[n]?.has(r))return null;s[n]+=1}return s.imported!==n||s.updated!==r||s.failed!==i||s.unsupported!==a?null:{importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a}}function YS({item:e,apiBase:t,targetKey:n,oauth:r,accounts:a=zS,keys:o=BS,accountLoadState:c=`ready`,switchingAccountId:l=null,pausingAccountId:u=null,busy:d=!1,loginHint:f,loginCapture:p,authHandlers:m,onCodexActiveNeedsReauthChange:h,codexController:g,onUpdateProvider:_}){let y=b(),x=Y_(t,n),{locale:S}=s(),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(null),D=(0,Z.useRef)(null),O=(0,Z.useRef)(null),k=t=>{e.name===`kiro`?E({addAccount:t}):m?.onLogin(e.name,t)},[A,j]=(0,Z.useState)(``),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(`idle`),[R,z]=(0,Z.useState)(null),B=(0,Z.useRef)(null),[V,H]=(0,Z.useState)(null),[U,W]=(0,Z.useState)(``),[ee,G]=(0,Z.useState)(!1),[te,ne]=(0,Z.useState)(``),[K,q]=(0,Z.useState)(!0),J=JSON.stringify([t,e.name,a.find(e=>e.active)?.id,o.find(e=>e.active)?.id]),[re,Y]=(0,Z.useState)({identity:J,refreshing:!1,result:null}),ie=re.identity===J&&re.refreshing,ae=re.identity===J?re.result:null,oe=(0,Z.useRef)(0);(0,Z.useEffect)(()=>(oe.current+=1,()=>{oe.current+=1}),[J]);let se=m?.onRefreshQuota,ce=ug({...e,hasApiKey:e.hasApiKey||o.length>0}),le=ce===`oauth-accounts`,ue=ce===`api-keys`,de=le&&e.name===`xai`&&a.length>0,fe=Yx({apiBase:t,accountIds:(0,Z.useMemo)(()=>de?a.filter(e=>!VS(e)).map(e=>e.id):[],[de,a]),enabled:de}),[pe,me]=(0,Z.useState)(null),he=fg(e.name)&&pg(e.name,e),ge=le&&he&&a.length>0,_e=(0,Z.useMemo)(()=>ge?a.filter(e=>!VS(e)).map(e=>e.id):[],[ge,a]),ve=dx({apiBase:t,provider:fg(e.name)?e.name:`anthropic`,accountIds:_e,enabled:ge}),ye=`${t}\0${e.name}`,[be,xe]=(0,Z.useState)(null),Se=be?.scope===ye?be.account:null,Ce=e=>{xe(e?{scope:ye,account:e}:null)},we=async()=>{if(!se||ie)return;let t=++oe.current;Y({identity:J,refreshing:!0,result:null});try{let n=await se(e.name);oe.current===t&&Y({identity:J,refreshing:!1,result:{ok:n,text:y(n?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}})}catch{oe.current===t&&Y({identity:J,refreshing:!1,result:{ok:!1,text:y(`codexAuth.quotaRefreshFailed`)}})}};if(ce===`codex-accounts`)return(0,Q.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":y(`pws.availableAccounts`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:y(`pws.availableAccounts`)}),(0,Q.jsx)(`div`,{className:`pwi-auth-body`,children:(0,Q.jsx)(Lb,{apiBase:t,targetKey:n,embedded:!0,controller:g,onActiveNeedsReauthChange:h})})]});if(!ce||!m)return null;let Te=a_(e.name),Ee=f?.provider===Te?f:null,De=async()=>{let e=U.trim();if(e&&!ee){if(!p)q(!1),ne(y(`prov.targetChanged`));else{G(!0),ne(``);try{let n=await i(p,`${t}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:Te,input:e})});if(!v(p)){q(!1),ne(y(`prov.targetChanged`));return}if(!n.ok){let e=await n.json().catch(()=>({}));q(!1),ne(e.error===`target_changed`?y(`prov.targetChanged`):y(`prov.pasteFail`,{error:e.error||n.statusText}));return}W(``),q(!0),ne(y(`prov.pasteOk`))}catch{q(!1),ne(y(`modal.networkError`))}finally{G(!1)}}}},Oe=c===`ready`&&a.length>0||r?.loggedIn===!0,ke=Oe||c===`error`&&r?.loggedIn!==!1,Ae=a.find(e=>e.active&&e.needsReauth),je=!!Ae,Me=le?a:o,Ne=!!se&&!(Me.length>0&&Me.every(e=>e.quotaMode===`unsupported`)),Pe=async()=>{let t=A.trim();if(t){N(!0);try{await m.onAddApiKey(e.name,t)&&(j(``),w(!1))}finally{N(!1)}}},Fe=async(n,r)=>{if(!n||P)return;if(!r){H({file:n});return}F(!0),L(`idle`),z(null);let a=x;try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>RS){L(`invalid`);return}let o;try{o=JSON.parse(await n.text())}catch{L(`invalid`);return}let s=await i(a,`${t}/api/oauth/accounts/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`google-antigravity`,format:`cockpit-tools`,document:o,...IS(`google-antigravity`,r)})});if(!s.ok){L(`failed`);return}let c=JS(await s.json().catch(()=>null));if(!c){L(`failed`);return}z(c),L(`complete`);try{await m.onRetryAccounts?.(e.name)}catch{}}catch{L(`failed`)}finally{B.current&&(B.current.value=``),F(!1)}};return(0,Q.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":y(le?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-head`,children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:y(le?`pws.availableAccounts`:`pws.apiKeys`)}),(le&&Oe||ue)&&Ne&&(0,Q.jsxs)(`div`,{className:`pwi-auth-head-actions`,children:[ae&&(0,Q.jsx)(`span`,{role:`status`,className:ae.ok?`pws-status-ok`:`pws-status-warn`,children:ae.text}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ie||d||!!l,onClick:()=>{we()},children:[(0,Q.jsx)(Ke,{width:14,height:14,"aria-hidden":`true`}),` `,y(ie?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,Q.jsx)(HS,{initialState:e.xaiResponsesOptInState??!0,onUpdateProvider:_}),le&&(0,Q.jsxs)(Q.Fragment,{children:[he&&(0,Q.jsx)(Vb,{apiBase:t,targetKey:n,provider:fg(e.name)?e.name:`anthropic`,accountCount:a.length,onThresholdChange:t=>{m?.onAccountPoolThreshold?.(e.name,t)}},`${t}:${e.name}`),e.name===`google-antigravity`&&(0,Q.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:y(`pws.cockpitImportDescription`)}),(0,Q.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:y(`pws.cockpitImportFileLabel`)}),(0,Q.jsx)(`input`,{ref:B,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:P,onChange:e=>{Fe(e.currentTarget.files?.[0],!1)}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P,onClick:()=>B.current?.click(),children:y(P?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),V&&(0,Q.jsx)(LS,{providerId:`google-antigravity`,providerLabel:`Google Antigravity`,onCancel:()=>{H(null),B.current&&(B.current.value=``)},onContinue:()=>{let e=V;H(null),Fe(e.file,!0)}}),(0,Q.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[I===`invalid`&&y(`pws.cockpitImportInvalid`),I===`failed`&&y(`pws.cockpitImportFailed`),I===`complete`&&R&&y(`pws.cockpitImportComplete`,{imported:R.importedCount,updated:R.updatedCount,failed:R.failedCount,unsupported:R.unsupportedCount})]})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${je?`pwi-auth-dot--warn`:Oe?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`pwi-auth-status-text`,children:Oe?y(`pws.loggedInTitle`):r?.error||(r?.loggedIn===!1?y(`pws.notLoggedInTitle`):y(`startup.unverified`))}),(0,Q.jsxs)(`span`,{className:`pwi-auth-actions`,children:[Ae&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:d,onClick:()=>void m.onReauth(e.name,Ae.id),children:y(`pws.reauthenticate`)}),ke?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m.onLogout(e.name),children:y(`prov.logout`)}):(0,Q.jsxs)(`button`,{ref:e.name===`kiro`?D:void 0,type:`button`,className:`btn btn-primary btn-sm`,disabled:d||e.name===`kiro`&&!!T,onClick:()=>k(!1),children:[d?(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,Q.jsx)(_t,{style:{width:13,height:13},"aria-hidden":`true`}),y(d?`prov.waitingBrowser`:`prov.login`)]})]})]}),!d&&(0,Q.jsx)(Hb,{}),d&&Ee&&(0,Q.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,Q.jsx)(`div`,{className:`pwi-auth-wait-title`,children:y(`prov.waitingBrowser`)}),(0,Q.jsx)(H_,{hint:{url:Ee.url,deviceCode:Ee.deviceCode,instructions:Ee.instructions,browserLaunch:Ee.browserLaunch},paste:{value:U,busy:ee,message:te,ok:K,onChange:W,onSubmit:()=>{De()}}}),m.onCancelLogin&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m.onCancelLogin?.(Te),children:y(`common.cancel`)})]})]}),m.pendingAffinityResets?.[e.name]&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:y(`prov.affinityResetPending`)}),m.onRetryAffinityReset&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!!(l||u),onClick:()=>void m.onRetryAffinityReset?.(e.name),children:y(`common.retry`)})]}),c===`loading`&&a.length===0&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),y(`pws.accountsLoading`)]}),c===`error`&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:y(`pws.accountsLoadFailed`)}),m.onRetryAccounts&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m.onRetryAccounts?.(e.name),children:y(`pws.retryAccounts`)})]}),a.length>0&&a_(e.name)!==e.name&&(0,Q.jsx)(`div`,{className:`pwi-auth-state`,role:`note`,children:y(`pws.sharedAccountsNote`,{provider:l_(a_(e.name))})}),a.length>0&&(0,Q.jsx)(`ul`,{className:`pwi-auth-list`,children:a.map(t=>{let n=dg(a,t,y),r=he?t_(t.plan):e.name===`google-antigravity`?t.plan:void 0,i=l===t.id,o=u===t.id,s=t.health?.status,c=VS(t),f=y_(s),p=d_(t.id),h=S_(y,t.health),g=he?null:C_(y,e.name,t.id,t.health);return(0,Q.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!t.paused&&!c&&!f&&!l&&!u&&m.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${r?` — ${r}`:``}${t.active?` — ${y(`pws.accountCurrent`)}`:``}`,disabled:!!(t.paused||c||f||l||u),children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${c?`pwi-auth-dot--warn`:t.active&&!t.paused?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Q.jsxs)(`span`,{className:`pwi-auth-row-heading`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),r&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:r})]}),!he&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:`${y(`prov.accountId`)}: ${p}`}),g&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:g}),f&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:y(`pws.healthCooldownHint`)}),t.paused&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:y(`pws.accountPausedHint`)})]}),h&&(0,Q.jsx)(`span`,{className:g_(s),children:h}),c&&!h&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:y(`pws.reauth`)}),rS(t,e.name)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:y(rS(t,e.name))}),t.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:t.pauseDetails?r_(y,S,t.pauseDetails):void 0,children:y(`codexAuth.paused`)}),t.active&&!t.paused&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:y(`prov.accountActive`)}),i&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:y(`pws.accountSwitching`)})]}),typeof t.paused==`boolean`&&m.onPauseAccount&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":`${y(t.paused?`codexAuth.resume`:`codexAuth.pause`)} — ${n}`,title:t.paused?y(`pws.accountPausedHint`):void 0,"aria-busy":o,disabled:d||!!l||!!u,onClick:()=>void m.onPauseAccount(e.name,t,!t.paused),children:y(t.paused?`codexAuth.resume`:`codexAuth.pause`)}),c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||!!l||!!u,onClick:()=>void m.onReauth(e.name,t.id),children:y(`pws.reauthenticate`)}),de&&!c&&(0,Q.jsx)(Kb,{entry:fe.entries[t.id],t:y,onClick:()=>me(t)}),ge&&!c&&(0,Q.jsx)(hx,{entry:ve.entries[t.id],t:y,onClick:()=>Ce(t)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m.onEditAlias(e.name,`oauth`,t.id,t.alias),children:y(`prov.editAlias`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${y(`common.remove`)} — ${n}`,title:`${y(`common.remove`)} — ${n}`,disabled:!!l||!!u,onClick:()=>void m.onRemoveAccount(e.name,t),children:(0,Q.jsx)(et,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-acct-quota`,children:[he&&t.autoSwitchThresholdOverride!==void 0&&t.autoSwitchThreshold!==void 0&&m.onAccountThreshold&&(0,Q.jsx)(m_,{accountLabel:n,inputId:`anthropic-threshold-${t.id}`,globalThreshold:t.autoSwitchThreshold,override:t.autoSwitchThresholdOverride,hintText:y(`pws.anthropicAccountThresholdHint`),disabled:d||!!l||!!u,onChange:n=>m.onAccountThreshold(e.name,t,n)}),(0,Q.jsx)(mg,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure,quotaReadAt:t.quotaReadAt})]})]},t.id)})}),pe&&(0,Q.jsx)(Jb,{accountId:pe.id,accountLabel:dg(a,pe,y),entry:fe.entries[pe.id],controller:fe,onClose:()=>me(null)}),Se&&(0,Q.jsx)(Tx,{accountId:Se.id,accountLabel:dg(a,Se,y),entry:ve.entries[Se.id],controller:ve,onClose:()=>Ce(null)},`${t}:${e.name}:${Se.id}`),c===`ready`&&Oe&&a.length===0&&(0,Q.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:y(`pws.noAccounts`)}),Oe&&(0,Q.jsxs)(`div`,{className:`pwi-auth-actions`,children:[(0,Q.jsx)(`button`,{ref:e.name===`kiro`?O:void 0,type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(!0),disabled:d||!!l||e.name===`kiro`&&!!T,children:y(`pws.addAccount`)}),Ne&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ie||d||!!l,onClick:()=>{we()},children:[(0,Q.jsx)(Ke,{width:14,height:14,"aria-hidden":`true`}),` `,y(ie?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),e.name===`kiro`&&T&&(0,Q.jsx)(OS,{apiBase:t,targetKey:n,triggerRef:T.addAccount?O:D,addAccount:T.addAccount,busy:d,onClose:()=>E(null),onCli:t=>{m.onLogin(e.name,t)},onSettled:m.onNativeLoginSettled}),ue&&(0,Q.jsxs)(Q.Fragment,{children:[o.length>0&&(0,Q.jsx)(`ul`,{className:`pwi-auth-list`,children:o.map(t=>{let n=l===t.id,r=u===t.id;return(0,Q.jsxs)(`li`,{className:`pwi-auth-acct${t.active&&!t.disabled?` pwi-auth-acct--active`:``}`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-row${t.active&&!t.disabled?` pwi-auth-row--active`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void m.onSwitchApiKey(e.name,t),"aria-current":t.active&&!t.disabled?`true`:void 0,disabled:t.active&&!t.disabled||d||!!l||!!u,"aria-label":t.disabled?`${y(`pws.resumeAndActivateKey`)} — ${t.label??t.masked}`:void 0,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${t.active&&!t.disabled?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,Q.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,y(`prov.accountId`),`: `,t.id]}),t.disabled&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:y(`pws.accountPausedHint`)})]}),t.disabled&&(0,Q.jsxs)(`span`,{className:`badge badge-muted`,title:t.pauseDetails?r_(y,S,t.pauseDetails):void 0,children:[y(`codexAuth.paused`),` · `,y(`codexAuth.resume`)]}),t.active&&!t.disabled&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:y(`prov.accountActive`)}),n&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:y(`pws.accountSwitching`)})]}),m.onPauseApiKey&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":`${y(t.disabled?`codexAuth.resume`:`codexAuth.pause`)} — ${t.label??t.masked}`,title:t.disabled?y(`pws.accountPausedHint`):void 0,"aria-busy":r,disabled:d||!!l||!!u,onClick:()=>void m.onPauseApiKey(e.name,t,!t.disabled),children:y(t.disabled?`codexAuth.resume`:`codexAuth.pause`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||!!l||!!u,onClick:()=>void m.onEditAlias(e.name,`api-key`,t.id,t.label),children:y(`prov.editAlias`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${y(`common.remove`)} — ${t.label??t.masked}`,disabled:d||!!l||!!u,title:`${y(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void m.onRemoveApiKey(e.name,t),children:(0,Q.jsx)(et,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:(0,Q.jsx)(mg,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure,quotaReadAt:t.quotaReadAt})})]},t.id)})}),C?(0,Q.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Q.jsx)(`input`,{className:`input`,type:`password`,value:A,onChange:e=>j(e.target.value),placeholder:y(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:M}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Pe(),disabled:M||!A.trim(),children:y(M?`pws.saving`:`pws.addKey`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{w(!1),j(``)},children:y(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>w(!0),children:y(`pws.addKey`)})]})]})]})}function XS(e,t,n){let r=e?.find(e=>e.id===t);if(!r)return n;if(r.baseUrl)return r.baseUrl;let i=new Set((e??[]).map(e=>e.baseUrl?.trim().replace(/\/+$/,``)).filter(e=>!!e)),a=n.trim().replace(/\/+$/,``);return i.has(a)?``:n}function ZS(e,t){if(!e?.length)return`custom`;let n=t.trim().replace(/\/+$/,``);for(let t of e)if(t.baseUrl&&t.baseUrl.trim().replace(/\/+$/,``)===n)return t.id;return e.some(e=>e.id===`custom`)?`custom`:e[0].id}function QS(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var $S=`https://chatgpt.com/backend-api/codex`;function eC(e){try{let t=new URL(e.trim());if(t.username||t.password||t.search||t.hash)return;let n=t.pathname.replace(/\/+$/,``);return`${t.origin}${n}`}catch{return}}function tC(e){return[`openai`,...Object.entries(e).filter(([,e])=>e.authMode===`forward`).map(([e])=>e).filter(e=>e!==`openai`).sort((e,t)=>e.localeCompare(t))]}function nC(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||eC(e.baseUrl)!==$S?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function rC(e){return e.id===`openai`}function iC(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function aC(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return e.responsesPath?.trim()&&(t.responsesPath=e.responsesPath.trim()),e.adapter.trim()===`google`&&e.googleMode===`vertex`&&(t.googleMode=`vertex`,t.liveModels=!1,e.project?.trim()&&(t.project=e.project.trim()),e.location?.trim()&&(t.location=e.location.trim())),(e.authMode===`key`||e.authMode===`forward`)&&(t.authMode=e.authMode),e.authMode===`key`&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),e.adapter.trim()===`anthropic`&&e.authMode===`key`&&e.apiKeyTransport===`bearer`&&(t.apiKeyTransport=`bearer`),e.defaultModel.trim()&&(t.defaultModel=e.defaultModel.trim()),e.allowPrivateNetwork&&(t.allowPrivateNetwork=!0),kh(e)&&e.preserveResponsesReasoningContent===!0&&(t.preserveResponsesReasoningContent=!0),t}function oC(e,t){return rC(e)?sC(e):{name:t.name.trim(),provider:aC(t)}}function sC(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var cC=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function lC(e,t,n=fetch){if(t===`disabled`){if((await n(`${e}/api/providers?name=openai`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:!1})})).ok)return;throw new cC(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new cC(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new cC(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(sC(i))})).ok)throw new cC(`codexAuth.enableOpenaiFailed`)}function uC({checked:e,onChange:t}){let n=b();return(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Q.jsx)(`input`,{name:`preserveResponsesReasoningContent`,type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:n(`pws.responsesReasoningReplay`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:n(`pws.responsesReasoningReplayHint`)})]})]})}var dC=[`responses`,`chat`,`messages`],fC=[`responses`,`chat`,`messages`,`other`],pC=[`responses`,`chat`,`messages`,`other`,`ir`,`responses-internal`],mC=[`native`,`translated`,`legacy-bridge`,`blocked`],hC=[`preserved`,`degraded`,`unknown`],gC=[`same-wire-native`,`cross-wire-codec`,`cross-wire-ir`,`combo-or-policy-route`,`responses-only-feature`,`hosted-tool`,`vision-preprocessing`,`tool-result-image`,`auth-mode-not-native`,`effort-row`,`fast-row`,`caller-credential-required`,`not-migrated`,`surface-disabled`,`feature-unrepresentable`,`compatibility-reject`,`unknown-model`,`upstream-other`,`rollout-disabled`,`bridge-only-policy`,`oauth-account-pool`,`anthropic-beta-dropped`,`opaque-state-stripped`,`advisor-tool-shadowed-by-proxy-advisor`,`advisor-tool-outside-model-scope`],_C=new Set(dC),vC=new Set(fC),yC=new Set(pC),bC=new Set(mC),xC=new Set(hC),SC=new Set(gC);function CC(e){return typeof e==`string`&&_C.has(e)}function wC(e){return typeof e==`string`&&vC.has(e)}function TC(e){return typeof e==`string`&&yC.has(e)}function EC(e){return typeof e==`string`&&bC.has(e)}function DC(e){return typeof e==`string`&&xC.has(e)}function OC(e){return typeof e==`string`&&SC.has(e)}function kC(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic-messages`:return`messages`;default:return}}function AC(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic`:return`messages`;default:return`other`}}var jC=[`request.tools`,`request.hosted_tools`,`request.images`,`request.documents`,`request.multiple_choices`,`request.logprobs`,`request.logit_bias`,`request.seed`,`request.audio`,`request.prediction`,`request.response_format`,`request.reasoning`,`request.thinking_budget`,`request.top_k`,`request.cache_control`,`request.previous_response_id`,`request.store`,`request.background`,`request.compaction`],MC=new Set(jC);function NC(e){return typeof e==`string`&&MC.has(e)}var PC={"request.tools":[`responses`,`chat`,`messages`],"request.hosted_tools":[`responses`],"request.images":[`responses`,`chat`,`messages`],"request.documents":[`responses`,`chat`,`messages`],"request.multiple_choices":[`chat`],"request.logprobs":[`responses`,`chat`],"request.logit_bias":[`chat`],"request.seed":[`chat`],"request.audio":[`chat`],"request.prediction":[`chat`],"request.response_format":[`responses`,`chat`],"request.reasoning":[`responses`,`chat`,`messages`],"request.thinking_budget":[`messages`],"request.top_k":[`messages`],"request.cache_control":[`messages`],"request.previous_response_id":[`responses`],"request.store":[`responses`],"request.background":[`responses`],"request.compaction":[`responses`]},FC={pathHops:6,reasonCodes:8,featureEffects:24,candidates:16,attempts:16,identifierLength:200},IC=[`hard-pin`,`operator`,`registry`,`provider-default`];function LC(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var RC=new Set([`passthrough`,`translated`,`degraded`,`unsupported`]);function zC(e,t,n){return Array.isArray(e)&&e.length<=t&&e.every(n)}function BC(e){return typeof e==`string`&&e.length>0&&e.length<=FC.identifierLength&&!/[\u0000-\u001f\u007f]/.test(e)}function VC(e){return LC(e)&&NC(e.feature)&&typeof e.disposition==`string`&&RC.has(e.disposition)}function HC(e){return zC(e,FC.pathHops,TC)&&e.length>0}function UC(e){return zC(e,FC.reasonCodes,OC)}function WC(e){return zC(e,FC.featureEffects,NC)}function GC(e){return LC(e)&&BC(e.provider)&&BC(e.model)&&BC(e.adapter)&&wC(e.upstream)&&EC(e.mode)&&(e.mode===`blocked`?Array.isArray(e.requestPath):HC(e.requestPath))&&(e.mode===`blocked`?Array.isArray(e.responsePath):HC(e.responsePath))&&DC(e.fidelity)&&UC(e.reasonCodes)&&zC(e.featureEffects,FC.featureEffects,VC)&&WC(e.unknownFeatures)&&typeof e.eligible==`boolean`}function KC(e){return LC(e)&&e.schemaVersion===1&&(e.basis===`preview`||e.basis===`dispatch`)&&typeof e.contractVersion==`string`&&typeof e.policyRevision==`string`&&CC(e.inbound)&&BC(e.requestedModel)&&(e.routeKind===`direct`||e.routeKind===`combo`||e.routeKind===`policy`||e.routeKind===`unknown`)&&EC(e.mode)&&UC(e.reasonCodes)&&zC(e.candidates,FC.candidates,GC)&&WC(e.guaranteedFeatures)&&WC(e.partialFeatures)}function qC(e){return LC(e)&&typeof e.ordinal==`number`&&Number.isInteger(e.ordinal)&&e.ordinal>0&&wC(e.upstream)&&EC(e.mode)&&e.mode!==`blocked`&&HC(e.requestPath)&&(e.responsePath===void 0||HC(e.responsePath))}function JC(e){return!(!LC(e)||e.v!==1||!CC(e.inbound)||!EC(e.mode)||e.upstream!==void 0&&!wC(e.upstream)||!(e.mode===`blocked`?Array.isArray(e.requestPath)&&e.requestPath.length===0&&Array.isArray(e.responsePath)&&e.responsePath.length===0:HC(e.requestPath)&&HC(e.responsePath))||!UC(e.reasonCodes)||typeof e.contractVersion!=`string`||e.featureEffects!==void 0&&!zC(e.featureEffects,FC.featureEffects,VC)||e.attempts!==void 0&&!zC(e.attempts,FC.attempts,qC)||e.planMismatch!==void 0&&e.planMismatch!==!0)}function YC(e){if(JC(e))return{v:1,inbound:e.inbound,mode:e.mode,...e.upstream===void 0?{}:{upstream:e.upstream},requestPath:[...e.requestPath],responsePath:[...e.responsePath],reasonCodes:[...e.reasonCodes],...e.featureEffects?{featureEffects:e.featureEffects.map(e=>({...e}))}:{},...e.attempts?{attempts:e.attempts.map(e=>({...e,requestPath:[...e.requestPath],...e.responsePath?{responsePath:[...e.responsePath]}:{}}))}:{},...e.planMismatch?{planMismatch:!0}:{},contractVersion:e.contractVersion}}var XC=new Set(IC);function ZC(e){return typeof e==`string`&&XC.has(e)}function QC(e){return LC(e)&&BC(e.model)&&BC(e.adapter)&&ZC(e.source)}function $C(e){return LC(e)&&BC(e.name)&&BC(e.adapter)&&ZC(e.adapterSource)&&(e.authMode===null||BC(e.authMode))&&wC(e.upstream)&&zC(e.modelOverrides,64,QC)&&(e.modelOverridesTruncated===void 0||e.modelOverridesTruncated===!0)}var ew=32,tw=new Map;function nw(e,t,n){return JSON.stringify([e,t.model,t.inbound,[...new Set(t.features)].sort(),n])}function rw(e,t){for(tw.delete(e),tw.set(e,t);tw.size>ew;){let e=tw.keys().next().value;if(e===void 0)break;tw.delete(e)}}function iw(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function aw(e){if(!iw(e)||e.schemaVersion!==1||typeof e.policyRevision!=`string`||!Array.isArray(e.features)||!e.features.every(NC)||!iw(e.surfaces))return null;let t={};for(let[n,r]of Object.entries(e.surfaces)){if(!CC(n)||!iw(r)||typeof r.enabled!=`boolean`)return null;t[n]={enabled:r.enabled}}return!t.responses||!t.chat||!t.messages?null:{policyRevision:e.policyRevision,features:[...e.features],surfaces:t}}async function ow(e,t){let n=await fetch(`${e}/api/protocols`,{signal:t});if(n.status===404)return null;if(!n.ok)throw Error(`HTTP ${n.status}`);let r=aw(await n.json());if(!r)throw Error(`invalid protocol info`);return r}async function sw(e,t,n){try{let r=await ow(e,n);if(!r)return{kind:`unavailable`};let i=nw(e,t,r.policyRevision),a=tw.get(i);if(a)return{kind:`plan`,plan:a};let o=await fetch(`${e}/api/protocols/plan`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({model:t.model,inbound:t.inbound,features:[...t.features]}),signal:n});if(o.status===404)return{kind:`unavailable`};if(!o.ok)return{kind:`error`};let s=await o.json();return KC(s)?(rw(nw(e,t,s.policyRevision),s),{kind:`plan`,plan:s}):{kind:`error`}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)throw e;return{kind:`error`}}}async function cw(e,t,n){try{let r=await fetch(`${e}/api/protocols/settings`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t),signal:n});if(r.status===404||r.status===405)return{kind:`unavailable`};let i=await r.json().catch(()=>null);if(!r.ok){let e=iw(i)&&iw(i.error)&&typeof i.error.code==`string`?i.error.code:void 0;return e?{kind:`error`,code:e}:{kind:`error`}}let a=aw(i);return a?{kind:`ok`,info:a}:{kind:`error`}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)throw e;return{kind:`error`}}}async function lw(e,t,n){try{let r=await fetch(`${e}/api/protocols?${new URLSearchParams({provider:t}).toString()}`,{signal:n});if(r.status===404)return{kind:`unavailable`};if(!r.ok)return{kind:`error`};let i=await r.json();return!iw(i)||i.provider===void 0?{kind:`unavailable`}:!$C(i.provider)||i.provider.name!==t?{kind:`error`}:{kind:`summary`,summary:i.provider}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)throw e;return{kind:`error`}}}var uw={native:`logs.protocol.mode.native`,translated:`logs.protocol.mode.translated`,"legacy-bridge":`logs.protocol.mode.legacyBridge`,blocked:`logs.protocol.mode.blocked`},dw={passthrough:`logs.protocol.disposition.passthrough`,translated:`logs.protocol.disposition.translated`,degraded:`logs.protocol.disposition.degraded`,unsupported:`logs.protocol.disposition.unsupported`},fw={responses:`logs.protocol.wire.responses`,chat:`logs.protocol.wire.chat`,messages:`logs.protocol.wire.messages`,other:`logs.protocol.wire.other`,ir:`logs.protocol.hop.ir`,"responses-internal":`logs.protocol.hop.internal`},pw=` → `;function mw(e,t){return t(fw[e])}function hw(e,t){return e.map(e=>mw(e,t)).join(pw)}function gw(e,t){let n=mw(e.inbound,t);if(e.mode===`blocked`)return n;let r=e.upstream??e.requestPath[e.requestPath.length-1];return r?`${n}${pw}${mw(r,t)}`:n}var _w={"hard-pin":`pws.protocol.source.hardPin`,operator:`pws.protocol.source.operator`,registry:`pws.protocol.source.registry`,"provider-default":`pws.protocol.source.providerDefault`};function vw({adapter:e}){let t=b();return(0,Q.jsxs)(`span`,{className:`ppp-wire`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{className:`muted`,children:mw(AC(e),t)})]})}function yw({apiBase:e,providerName:t,savedAdapter:n,draftAdapter:r,refreshKey:i}){let a=b(),o=JSON.stringify([e??``,t,n,i??``]),[s,c]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{if(e===void 0)return;let n=new AbortController;return lw(e,t,n.signal).then(e=>{n.signal.aborted||c(e.kind===`summary`?{key:o,kind:`summary`,summary:e.summary}:{key:o,kind:e.kind===`unavailable`?`hidden`:`error`})}).catch(()=>{}),()=>n.abort()},[e,t,o]);let l=s?.key===o?s:null;if(e===void 0||!l||l.kind===`hidden`)return null;let u=r&&r!==n?r:null;return(0,Q.jsxs)(`section`,{className:`ppp-card`,"aria-labelledby":`ppp-title`,"data-testid":`provider-protocol-panel`,children:[(0,Q.jsx)(`h3`,{id:`ppp-title`,children:a(`pws.protocol.title`)}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:a(`pws.protocol.note`)}),l.kind===`error`?(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:a(`pws.protocol.loadFailed`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dl`,{className:`ppp-kv`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`pws.protocol.adapterLabel`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(vw,{adapter:l.summary.adapter})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`pws.protocol.source`)}),(0,Q.jsx)(`dd`,{"data-adapter-source":l.summary.adapterSource,children:a(_w[l.summary.adapterSource])})]}),l.summary.authMode&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`pws.authMode`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:l.summary.authMode})})]})]}),u&&(0,Q.jsx)(`p`,{className:`ppp-pending`,role:`status`,children:a(`pws.protocol.pending`,{adapter:u})}),(0,Q.jsx)(`h4`,{children:a(`pws.protocol.overrides`)}),l.summary.modelOverrides.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:a(`pws.protocol.noOverrides`)}):(0,Q.jsxs)(`table`,{className:`ppp-overrides`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.model`)}),(0,Q.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.wire`)}),(0,Q.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.source`)})]})}),(0,Q.jsx)(`tbody`,{children:l.summary.modelOverrides.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.model})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(vw,{adapter:e.adapter})}),(0,Q.jsx)(`td`,{"data-adapter-source":e.source,children:a(_w[e.source])})]},e.model))})]}),l.summary.modelOverridesTruncated&&(0,Q.jsx)(`p`,{className:`muted small`,children:a(`pws.protocol.overridesTruncated`,{count:l.summary.modelOverrides.length})})]})]})}function bw({value:e,onChange:t,status:n=[]}){let r=b(),i=(n,r)=>{let i={...e.keys};r.trim()?i[n]=Number(r):delete i[n],t({...e,keys:Object.keys(i).length?i:void 0})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:r(`pws.keySelection`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:r(`pws.keySelection`),value:e.keySelection??`active`,options:[{value:`active`,label:r(`pws.keyActive`)},{value:`round-robin`,label:r(`pws.keyRoundRobin`)}],onChange:n=>t({...e,keySelection:n})})]}),(0,Q.jsx)(`h4`,{children:r(`pws.keyLimits`)}),(0,Q.jsx)(`div`,{className:`pwi-key-limits`,style:{display:`flex`,flexWrap:`wrap`,gap:12},children:[`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`].map((t,n)=>(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flex:`1 1 160px`,minWidth:0},children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:r([`pws.pacingRpm`,`pws.pacingDelay`,`pws.pacingConcurrency`][n])}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:t===`requestsPerMinute`?1/60:1,step:t===`requestsPerMinute`?`any`:1,value:e.keys?.[t]??``,onChange:e=>i(t,e.target.value)})]},t))}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:r(`pws.keySharedQuota`)}),n.length>0&&(0,Q.jsxs)(`table`,{style:{width:`100%`,tableLayout:`fixed`,overflowWrap:`anywhere`},children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`pws.keyHandle`)}),(0,Q.jsx)(`th`,{children:r(`pws.keyStarts`)}),(0,Q.jsx)(`th`,{children:r(`pws.keyInFlight`)}),(0,Q.jsx)(`th`,{children:r(`pws.pacingQueued`)}),(0,Q.jsx)(`th`,{children:r(`pws.keyWait`)})]})}),(0,Q.jsx)(`tbody`,{children:n.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.id})}),(0,Q.jsx)(`td`,{children:e.starts}),(0,Q.jsx)(`td`,{children:e.inFlight}),(0,Q.jsx)(`td`,{children:e.queued}),(0,Q.jsx)(`td`,{children:e.cooldownUntil?r(`pws.keyCooldown`):`${e.nextSlotInMs} ms`})]},e.id))})]})]})}var xw=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],Sw=[];function Cw(){return Symbol(`provider-draft-owner`)}function ww(e){let t=e.targetKey??``,n=(0,Z.useMemo)(()=>e.draftStore??Ah(),[e.draftStore]);return(0,Q.jsx)(Tw,{...e,targetKey:t,draftStore:n},`${t}\u0000${e.item.name}`)}function Tw({item:e,availableModels:t=Sw,apiBase:n,targetKey:r,targetLabel:i,draftStore:a,onUpdateProvider:o,onDirtyChange:s,onRegisterSave:c,onRegisterDiscard:l,accountModeFocusToken:u=0,onAccountModeFocused:f}){let p=b(),[m]=(0,Z.useState)(Cw),h=(0,Z.useRef)(0),[g]=(0,Z.useState)(()=>{let t=Lh(e),n=a.claim(r,e.name,m,{draft:t,baseline:t});return{draft:n.draft,baseline:n.baseline}}),_=he(e.name,e),[v,y]=(0,Z.useState)(g.draft.adapter),[x,S]=(0,Z.useState)(g.draft.baseUrl),[C,w]=(0,Z.useState)(g.draft.project),[T,E]=(0,Z.useState)(g.draft.location),[D,O]=(0,Z.useState)(g.draft.defaultModel),[k,A]=(0,Z.useState)(g.draft.authMode),[j,M]=(0,Z.useState)(g.draft.apiKeyTransport),[N,P]=(0,Z.useState)(g.draft.note),[F,I]=(0,Z.useState)(g.draft.allowPrivateNetwork),[L,R]=(0,Z.useState)(g.draft.preserveReasoningReplay),[z,B]=(0,Z.useState)(g.draft.liveModels),[V,H]=(0,Z.useState)(g.draft.cursorHttpVersion),[U,W]=(0,Z.useState)(g.baseline),[ee,G]=(0,Z.useState)(!1),te=Y_(n??``,r),[ne,K]=(0,Z.useState)(null),[q,J]=(0,Z.useState)(e.codexAccountMode??`pool`),[re,Y]=(0,Z.useState)(!1),[ie,ae]=(0,Z.useState)(null),oe=(0,Z.useRef)(null),se=(0,Z.useRef)(0);(0,Z.useEffect)(()=>{if(!u||u===se.current)return;se.current=u;let e=oe.current;if(e){e.scrollIntoView?.({block:`center`});let t=e.querySelector(`#pws-codex-account-mode`);t&&!t.disabled?t.focus():e.focus()}f?.()},[u,f]);let[ce,le]=(0,Z.useState)(),[ue,de]=(0,Z.useState)(n===void 0?`idle`:`loading`),[fe,pe]=(0,Z.useState)(()=>`custom`),[me,ge]=(0,Z.useState)(g.draft.pacingEnabled),[_e,ve]=(0,Z.useState)(g.draft.keyPacing),[ye,be]=(0,Z.useState)(g.draft.pacingRpm),[xe,Se]=(0,Z.useState)(g.draft.pacingDelay),[Ce,we]=(0,Z.useState)(g.draft.pacingConcurrency),[Te,Ee]=(0,Z.useState)(()=>({...g.draft.pacingModels})),[De,Oe]=(0,Z.useState)(``),[ke,Ae]=(0,Z.useState)(``),[Me,Ne]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)(``),[Ie,Le]=(0,Z.useState)(null),Re=(0,Z.useMemo)(()=>({adapter:v,baseUrl:x,project:C,location:T,defaultModel:D,authMode:k,apiKeyTransport:j,note:N,allowPrivateNetwork:F,preserveReasoningReplay:L,liveModels:z,cursorHttpVersion:V,pacingEnabled:me,keyPacing:_e,pacingRpm:ye,pacingDelay:xe,pacingConcurrency:Ce,pacingModels:Te}),[v,F,j,k,x,V,D,_e,z,T,N,Ce,xe,me,Te,ye,L,C]),ze=e=>{y(e.adapter),S(e.baseUrl),w(e.project),E(e.location),O(e.defaultModel),A(e.authMode),M(e.apiKeyTransport),P(e.note),I(e.allowPrivateNetwork),R(e.preserveReasoningReplay),B(e.liveModels),H(e.cursorHttpVersion),ge(e.pacingEnabled),ve({...e.keyPacing,...e.keyPacing.keys?{keys:{...e.keyPacing.keys}}:{}}),be(e.pacingRpm),Se(e.pacingDelay),we(e.pacingConcurrency),Ee(Object.fromEntries(Object.entries(e.pacingModels).map(([e,t])=>[e,{...t}])))},Be=Uh(Re,e),Ve=Wh(Re,e),He=zh(Re)!==zh(U),Ue=He||Be||Ve,We=Gh(U,e),Ge=Hh(U,Re,e.requestPacing),Ke=He&&We||Ge.length>0,Je=(0,Z.useRef)(r),Ye=(0,Z.useRef)(x),Xe=(0,Z.useRef)(Re);(0,Z.useLayoutEffect)(()=>{Je.current=r,Ye.current=x,Xe.current=Re});let Ze=Lh(e),Qe=zh(Ze),[$e,et]=(0,Z.useState)(Qe);$e!==Qe&&(et(Qe),He||(ze(Ze),W(Ze),pe(ZS(ce,Ze.baseUrl)),K(null),ae(null))),(0,Z.useEffect)(()=>{a.writeOwned(r,e.name,m,{draft:Re,baseline:U})},[U,Re,m,a,He,e.name,r]);let tt=e.codexAccountMode??`pool`,[nt,rt]=(0,Z.useState)(tt);nt!==tt&&(rt(tt),J(tt)),(0,Z.useEffect)(()=>{if(n===void 0)return;let t=!1,r=e.name;return fetch(`${n}/api/provider-presets`).then(e=>Xn(e)).then(e=>{if(t)return;if(!e){le(void 0),de(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;le(n),de(`ready`),pe(ZS(n,Ye.current))}).catch(()=>{t||(le(void 0),de(`error`))}),()=>{t=!0}},[n,e.name]),(0,Z.useEffect)(()=>{if(n===void 0)return;let t=!0,r=!1,i=()=>{if(r)return;r=!0;let i=d(1e4);fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`,{signal:i.signal}).then(e=>Xn(e)).then(e=>{t&&e&&Le(e)}).catch(()=>void 0).finally(()=>{i.clear(),r=!1})};i();let a=$u(i,2e3);return()=>{t=!1,a()}},[n,e.name]);let it=!ct(e.name)&&kh({adapter:v,baseUrl:x,authMode:k}),at=qe(e)&&(e.name===`google-vertex`||v.trim()===`google`);(0,Z.useEffect)(()=>(s?.(Ue),()=>s?.(!1)),[Ue,s]);let ot=(0,Z.useMemo)(()=>{let n=new Set(t);return D.trim()&&n.add(D.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,D,e.defaultModel]),st=(0,Z.useMemo)(()=>{let e=[...xw];return v&&!e.includes(v)&&e.unshift(v),e},[v]),lt=ct(e.name),ut=ue===`ready`&&!!(ce&&ce.length>0),dt=v.trim()===`anthropic`&&k===`key`,ft=e.name===`openai`?nC(e):`invalid`,pt=ft===`ready`||ft===`disabled`,X=lt&&ue!==`error`,mt=async()=>{if(!o)return K({ok:!1,text:p(`pws.updatesUnavailable`)}),!1;if(re)return!1;if(Ke)return K({ok:!1,text:p(`pws.draftConflictResolveFirst`)}),!1;let t=r,n=e.name,i=h.current,s=zh(Re),c=Fh(Re),l=ut?QS(ce,fe,x):x.trim();if(!v.trim()||!l)return K({ok:!1,text:p(`pws.adapterBaseRequired`)}),!1;G(!0),K(null);try{let r=ye.trim()!==``&&(Mh(ye)===void 0||Number(ye)>6e4),u=xe.trim()!==``&&(Nh(xe)===void 0||Number(xe)>36e5);if(Ce.trim()!==``&&Nh(Ce)===void 0)return K({ok:!1,text:p(`pws.pacingCapInvalid`)}),!1;if(r||u)return K({ok:!1,text:p(`pws.pacingValueInvalid`)}),!1;if(Object.entries(_e.keys??{}).some(([e,t])=>!Number.isFinite(t)||t<=0||e!==`requestsPerMinute`&&!Number.isSafeInteger(t)||e===`requestsPerMinute`&&(t<1/60||t>6e4)||e===`minIntervalMs`&&t>36e5))return K({ok:!1,text:p(`pws.keyLimitInvalid`)}),!1;if(me&&!c.requestsPerMinute&&!c.minIntervalMs&&!c.maxConcurrentRequests&&!c.models&&!c.keys&&c.keySelection!==`round-robin`)return K({ok:!1,text:p(`pws.pacingRuleRequired`)}),!1;let{patch:d}=Kh(Re,U,e,l);if(Object.keys(d).length===0)return W(Re),a.clear(t,n),K({ok:!0,text:p(`pws.settingsSaved`)}),!0;let f=await o(e.name,d,te);if(h.current!==i)return f.ok;if(Je.current!==t){if(f.ok){let e=a.read(t,n);e&&zh(e.draft)!==s?a.writeOwned(t,n,m,{draft:e.draft,baseline:Re}):a.writeOwned(t,n,m,{draft:Re,baseline:Re})}return f.ok}if(K(f.ok?{ok:!0,text:p(`pws.settingsSaved`)}:{ok:!1,text:f.error||p(`prov.saveFailed`)}),f.ok){let e=Xe.current;W(Re),zh(e)===s?a.writeOwned(t,n,m,{draft:Re,baseline:Re}):a.writeOwned(t,n,m,{draft:e,baseline:Re})}return f.ok}finally{Je.current===t&&G(!1)}},ht=(0,Z.useRef)(mt);(0,Z.useEffect)(()=>{ht.current=mt}),(0,Z.useEffect)(()=>{if(c)return c(()=>ht.current()),()=>c(null)},[c]);let gt=async(e,t=te)=>{if(re||ee||e===q)return;if(!o){ae({ok:!1,text:p(`pws.updatesUnavailable`)});return}let n=r;Y(!0),ae(null);try{let r=await o(`openai`,{codexAccountMode:e},t);if(Je.current!==n)return;r.ok?(J(e),ae({ok:!0,text:p(`pws.accountModeSaved`)})):ae({ok:!1,text:r.error||p(`pws.accountModeFailed`)})}catch{ae({ok:!1,text:p(`pws.accountModeFailed`)})}finally{Y(!1)}},vt=async e=>{let t=te;await Ju({message:p(`pws.accountModeConfirm`)})&&await gt(e,t)},yt=()=>{let t=Lh(e);ze(t),W(t),K(null),h.current+=1,a.clearOwned(r,e.name,m),a.claim(r,e.name,m,{draft:t,baseline:t}),pe(ZS(ce,t.baseUrl))},bt=(0,Z.useRef)(yt);(0,Z.useEffect)(()=>{bt.current=yt}),(0,Z.useEffect)(()=>{if(l)return l(()=>bt.current()),()=>l(null)},[l]);let xt=()=>yt(),St=()=>{let t=Lh(e),n=qh(U,Re,t);ze(n),W(t),pe(ZS(ce,n.baseUrl)),K(null)},Ct=(e,t)=>{switch(e){case`token-plan`:return p(`modal.endpoint.tokenPlan`);case`payg`:return p(`modal.endpoint.payAsYouGo`);case`custom`:return p(`modal.endpoint.custom`);default:return t}},wt=()=>{let e=De.trim(),t=Mh(ke),n=Nh(Me),r=Nh(Pe);ke.trim()!==``&&(t===void 0||Number(ke)>6e4)||Me.trim()!==``&&(n===void 0||Number(Me)>36e5)||Pe.trim()!==``&&r===void 0?K({ok:!1,text:Pe.trim()!==``&&r===void 0?p(`pws.pacingCapInvalid`):p(`pws.pacingValueInvalid`)}):!e||t===void 0&&n===void 0&&r===void 0||(Ee(i=>({...i,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n},...r===void 0?{}:{maxConcurrentRequests:r}}})),Oe(``),Ae(``),Ne(``),Fe(``))};return(0,Q.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,Q.jsx)(_t,{style:{width:12,height:12}}),` `,p(`pws.providerId`)]}),(0,Q.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.adapter`)}),lt?(0,Q.jsx)(`input`,{className:`input`,value:v,readOnly:!0,disabled:!0}):(0,Q.jsx)(Vn,{fullWidth:!0,label:p(`modal.adapter`),value:v,onChange:y,options:st.map(e=>({value:e,label:e}))})]}),(0,Q.jsx)(yw,{apiBase:n,providerName:e.name,savedAdapter:e.adapter,draftAdapter:v.trim(),refreshKey:`${e.baseUrl}|${e.authMode??``}`}),ut?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.endpoint`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:p(`modal.endpoint`),value:fe,onChange:e=>{pe(e),S(XS(ce,e,x))},options:ce.map(e=>({value:e.id,label:Ct(e.id,e.label)}))})]}),fe===`custom`&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.baseUrl`)}),(0,Q.jsx)(`input`,{className:`input`,value:x,onChange:e=>S(e.target.value),placeholder:p(`modal.baseUrlPlaceholder`)})]})]}):(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.baseUrl`)}),(0,Q.jsx)(`input`,{className:`input`,value:x,onChange:e=>S(e.target.value),readOnly:X,disabled:X})]}),at&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.vertexProject`)}),(0,Q.jsx)(`input`,{className:`input`,value:C,onChange:e=>w(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.vertexLocation`)}),(0,Q.jsx)(`input`,{className:`input`,value:T,onChange:e=>E(e.target.value),placeholder:`us-central1`})]})]}),v.trim()===`cursor`&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.cursorTransport`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:p(`pws.cursorTransport`),value:V,onChange:e=>H(e),options:[{value:`http2`,label:p(`pws.cursorTransportHttp2`)},{value:`http1.1`,label:p(`pws.cursorTransportHttp1`)}]}),(0,Q.jsx)(`span`,{className:`pwi-settings-hint`,children:p(`pws.cursorTransportDesc`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.cell.defaultModel`)}),ot.length>0?(0,Q.jsx)(Vn,{fullWidth:!0,label:p(`pws.cell.defaultModel`),value:D,onChange:O,options:[{value:``,label:p(`pws.defaultModelNone`)},...ot.map(e=>({value:e,label:e}))]}):(0,Q.jsx)(`input`,{className:`input`,value:D,onChange:e=>O(e.target.value),placeholder:p(`pws.optionalPlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.authMode`)}),lt?(0,Q.jsx)(`input`,{className:`input`,value:je(e,p),readOnly:!0,disabled:!0}):(0,Q.jsx)(Vn,{fullWidth:!0,label:p(`pws.authMode`),value:k,onChange:A,options:[{value:`key`,label:p(`modal.badge.apiKey`)},{value:`forward`,label:p(`pws.auth.chatgptPassthrough`)},{value:`oauth`,label:p(`modal.badge.oauth`)},{value:`local`,label:p(`modal.badge.local`)}]})]}),pt&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,ref:oe,tabIndex:-1,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`codexAuth.accountModeTitle`)}),(0,Q.jsx)(Vn,{fullWidth:!0,id:`pws-codex-account-mode`,label:p(`codexAuth.accountModeTitle`),value:q,disabled:re||ee,onChange:e=>{let t=e;t!==q&&vt(t)},options:[{value:`pool`,label:p(`codexAuth.accountModePool`)},{value:`direct`,label:p(`codexAuth.accountModeDirect`)}]}),(0,Q.jsx)(`span`,{className:`pwi-settings-hint`,children:p(q===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),re&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:p(`pws.accountSwitching`)}),ie&&(0,Q.jsx)(`span`,{role:ie.ok?`status`:`alert`,className:ie.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:ie.text})]}),dt&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`modal.apiKeyTransport`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:p(`modal.apiKeyTransport`),value:j,onChange:e=>M(e),options:[{value:`x-api-key`,label:p(`modal.apiKeyTransportNative`)},{value:`bearer`,label:p(`modal.apiKeyTransportBearer`)}]})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.note`)}),(0,Q.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:N,onChange:e=>P(e.target.value),rows:2})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:F,onChange:e=>I(e.target.checked)}),(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.allowPrivateNetwork`)})]}),it&&(0,Q.jsx)(uC,{checked:L,onChange:R}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:z,disabled:!_,onChange:e=>B(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.liveModels`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:p(`pws.liveModelsDesc`)})]})]}),(0,Q.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,Q.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`pwi-pacing-title`,children:p(`pws.pacingTitle`)}),(0,Q.jsx)(`p`,{children:p(`pws.pacingDesc`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:me,onChange:e=>ge(e.target.checked)}),` `,p(`pws.pacingEnabled`)]})]}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingRpm`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ye,onChange:e=>be(e.target.value),placeholder:`38`})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingDelay`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:xe,onChange:e=>Se(e.target.value),placeholder:`1600`})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingConcurrency`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:Ce,onChange:e=>we(e.target.value),placeholder:`8`})]})]}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:p(`pws.pacingSlowerWins`)}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:Ie?.queued??0}),` `,p(`pws.pacingQueued`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[Ie?.nextSlotInMs??0,` ms`]}),` `,p(`pws.pacingNextSlot`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:Ie?.lastModelId??p(`pws.pacingNone`)}),` `,p(`pws.pacingLastModel`)]})]}),k!==`oauth`&&k!==`forward`&&(0,Q.jsx)(bw,{value:_e,onChange:ve,status:Ie?.keys}),(0,Q.jsx)(`h4`,{children:p(`pws.pacingModelOverrides`)}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingModel`)}),(0,Q.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:De,onChange:e=>Oe(e.target.value)}),(0,Q.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,Q.jsx)(`option`,{value:e},e))})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingRpm`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ke,onChange:e=>Ae(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingDelay`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:Me,onChange:e=>Ne(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:p(`pws.pacingConcurrency`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:Pe,onChange:e=>Fe(e.target.value)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:wt,children:p(`pws.pacingAdd`)})]}),Object.entries(Te).length>0&&(0,Q.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(Te).map(([e,t])=>(0,Q.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{children:[t.requestsPerMinute===void 0?void 0:`${t.requestsPerMinute} ${p(`pws.pacingRpmUnit`)}`,t.minIntervalMs===void 0?void 0:`${t.minIntervalMs} ms`,t.maxConcurrentRequests===void 0?void 0:`${t.maxConcurrentRequests} ${p(`pws.pacingCapUnit`)}`].filter(e=>e!==void 0).join(` · `)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ee(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":p(`pws.pacingRemoveModel`,{model:e}),children:p(`pws.pacingRemove`)})]},e))})]}),Ke&&(0,Q.jsxs)(`div`,{className:`pwi-settings-conflict`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:p(`pws.draftConflict`)}),Ge.length>0&&(0,Q.jsxs)(`div`,{className:`pwi-settings-conflict-fields`,children:[(0,Q.jsx)(`p`,{children:p(`pws.draftConflictFields`)}),(0,Q.jsx)(`ul`,{children:Ge.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsx)(`code`,{children:e})},e))})]}),(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:xt,disabled:ee,children:p(`pws.draftConflictUseSaved`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:St,disabled:ee,children:p(`pws.draftConflictKeepDraft`)})]})]}),Ue&&(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,Q.jsxs)(`span`,{className:`muted`,children:[p(`pws.settingsUnsavedBar`),` `,(0,Q.jsx)(`span`,{className:`pwi-settings-target`,children:p(`pws.draftTarget`,{target:i??Jh(r)})})]}),(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:yt,disabled:ee,children:p(`pws.discardSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void mt(),disabled:ee||re||Ke,children:p(ee?`pws.saving`:`pws.saveSettings`)})]})]}),ne&&(0,Q.jsx)(`div`,{role:ne.ok?`status`:`alert`,className:ne.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:ne.text})]})}function Ew({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=b();return(0,Q.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,Q.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,Q.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function Dw({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=b();return(0,Q.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,Q.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,Q.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function Ow({item:e,preset:t,usageTotals:n,modelUsage:r,quotaReport:i,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:c,modelRevision:l,modelRowsReady:u,onOpenModels:d,onOpenConnect:f,onCreateJevAuto:p,modelsLoading:m,modelsLoadFailed:h,onRetryModels:g,oauthEmail:_,onDeselect:v,apiBase:y,oauth:x,accounts:S,accountLoadState:C,accountsFocusToken:w=0,accountsFocusProvider:T=null,settingsFocusToken:E=0,settingsFocusProvider:D=null,settingsFocusField:O=null,switchingAccountId:k,pausingAccountId:A,keys:j,busyProvider:M,loginHint:N,loginCapture:P,authHandlers:F,onCodexActiveNeedsReauthChange:I,codexController:L,onUpdateProvider:R,targetKey:z,targetLabel:B,draftStore:V,isDefault:H,onRemoveProvider:U,onSetDisabled:W,onSetDefault:ee,onRefreshQuota:G}){let te=b(),ne=a_(e.name),K=z??``,q=B??Jh(K),J=(0,Z.useMemo)(()=>V??Ah(),[V]),[Y,ie]=(0,Z.useState)(`overview`),[ae,oe]=(0,Z.useState)(!1),[se,ce]=(0,Z.useState)(null),[le,ue]=(0,Z.useState)(!1),fe=(0,Z.useRef)(null),pe=(0,Z.useRef)(null),me=(0,Z.useCallback)(e=>{pe.current=e},[]),[he,ge]=(0,Z.useState)(K);he!==K&&(ge(K),ce(null));let[ve,be]=(0,Z.useState)(0),[xe,Se]=(0,Z.useState)(0),[Ce,we]=(0,Z.useState)(0),[Te,Ee]=(0,Z.useState)(0),De=(0,Z.useCallback)(e=>{fe.current=e},[]),Oe=e.disabled===!0,ke=(0,Z.useMemo)(()=>Ue(e),[e]),Ae=(0,Z.useMemo)(()=>ye(e),[e]),je=(0,Z.useMemo)(()=>ug(e),[e]),Me=S?.find(e=>e.active),Ne=je===`oauth-accounts`?S?.find(e=>e.active):je===`api-keys`?j?.find(e=>e.active):void 0,Pe=T===e.name?w:0,Fe=_e(e.name,e),Ie=JSON.stringify([Fe?L?.activeId??``:``,Fe?(L?.accounts??[]).map(e=>[e.id,e.isMain===!0,e.paused===!0,e.priority??0,e.hasCredential===!0]):[],S?.find(e=>e.active)?.id??``,(S??[]).map(e=>[e.id,e.active,e.paused===!0,e.needsReauth===!0,e.expiresAt??null]),j?.find(e=>e.active)?.id??``,(j??[]).map(e=>[e.id,e.active,e.disabled===!0]),x?.loggedIn===void 0?``:String(x.loggedIn),x?.needsReauth===void 0?``:String(x.needsReauth),_??``]),Le=Hg(e,y,Ie,a,Te);Y!==`overview`&&Le.completionProbe?.status===`testing`&&Le.clearIfTesting();let Re=Y_(y,z),ze=(0,Z.useMemo)(()=>R?async(e,t,n)=>{let r=await R(e,t,n??Re),i=Object.keys(t).some(e=>e!==`note`&&e!==`setDefault`);return r.ok&&i&&Ee(e=>e+1),r}:void 0,[R,Re]),Be=(0,Z.useMemo)(()=>{if(!F)return;let e=()=>Ee(e=>e+1);return{...F,async onAddApiKey(t,n){let r=await F.onAddApiKey(t,n);return r&&e(),r},...F.onNativeLoginSettled?{async onNativeLoginSettled(t,n){await F.onNativeLoginSettled?.(t,n),n===`added`&&e()}}:{}}},[F]),Ve=(0,Z.useMemo)(()=>[{id:`overview`,label:te(`pws.tab.overview`)},{id:`models`,label:te(`pws.tab.models`)},{id:`usage`,label:te(`pws.tab.usage`)},...je?[{id:`accounts`,label:te(je===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:te(`pws.tab.settings`)}],[je,te]),He=(0,Z.useCallback)(e=>{ae&&Y===`settings`&&e!==`settings`?ce({next:e,targetKey:K}):ie(e)},[Y,ae,K]);Pe!==ve&&(!Pe||je)&&(be(Pe),Pe&&je&&(ae&&Y===`settings`?ce({next:`accounts`,targetKey:K}):ie(`accounts`)));let We=D===e.name?E:0;We!==xe&&(Se(We),We&&(ie(`settings`),we(O===`account-mode`?We:0)));let Ge=(0,Z.useCallback)(()=>we(0),[]),Ke=(0,Z.useCallback)(()=>{ae&&Y===`settings`?ce({next:`deselect`,targetKey:K}):v()},[ae,Y,v,K]),qe=(0,Z.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%Ve.length;else if(e.key===`ArrowLeft`)n=(t-1+Ve.length)%Ve.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=Ve.length-1;else return;e.preventDefault(),He(Ve[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[He,Ve]),Je=`pws-tab-${Y}`,Ye=`pws-panel-${Y}`,Xe=re(e.name,te);return(0,Q.jsxs)(`div`,{className:`pws-detail`,children:[(0,Q.jsx)(`div`,{className:`pws-detail-head`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:Ke,children:[(0,Q.jsx)(lt,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),te(`pws.allProviders`)]})}),(0,Q.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,Q.jsx)(de,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,Q.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,Q.jsxs)(`h2`,{className:`pws-detail-title`,children:[Xe,Xe!==e.name&&(0,Q.jsx)(`code`,{className:`pws-detail-id`,children:e.name}),Ae&&(0,Q.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:te(`modal.badge.local`)}),!Ae&&ke&&(0,Q.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:te(`modal.badge.free`)})]})}),(0,Q.jsxs)(`div`,{className:`pws-detail-actions`,children:[!H&&!Oe&&ee&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ee(e.name),children:te(`prov.setDefault`)}),U&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>U(e.name),"aria-label":te(`pws.removeConfirmTitle`),title:te(`pws.removeConfirmTitle`),children:(0,Q.jsx)(et,{style:{width:15,height:15},"aria-hidden":`true`})}),W&&(0,Q.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,Q.jsx)(`span`,{className:`pws-detail-toggle-label`,children:te(`pws.enabledLabel`)}),(0,Q.jsx)(Rn,{on:!Oe,onClick:()=>W(e.name,!Oe),disabled:H,label:te(`pws.enabledLabel`)})]})]})]}),(0,Q.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:Ve.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":Y===e.id,tabIndex:Y===e.id?0:-1,className:`pws-detail-tab${Y===e.id?` pws-detail-tab--active`:``}`,onClick:()=>He(e.id),onKeyDown:e=>qe(e,t),children:e.label},e.id))}),(0,Q.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:Ye,"aria-labelledby":Je,tabIndex:0,children:[Y===`overview`&&(0,Q.jsx)(Ug,{item:e,preset:t,apiBase:y,connectionIdentity:Ie,probeController:Le,availableModels:a,selectedModels:s,modelRows:c,modelRowsReady:u,modelsLoading:m,modelsLoadFailed:h,onRetryModels:g,onOpenAccounts:je?()=>He(`accounts`):void 0,onOpenModelsTab:()=>He(`models`),onOpenModels:d,onOpenConnect:f,usageTotals:n,quotaReport:i,currentQuotaReading:Ne,onRefreshQuota:G,oauthEmail:_,currentAccountLabel:je===`oauth-accounts`&&C===`ready`&&Me?dg(S??[],Me,te):void 0,oauth:x,onEditSettings:()=>He(`settings`),onViewUsage:()=>He(`usage`),onCreateJevAuto:p,onUpdateProvider:ze,reauthBusy:M===ne,onCancelLogin:F?.onCancelLogin?()=>void F.onCancelLogin?.(ne):void 0,onReauthenticate:e.activeNeedsReauth?()=>{if(e.authMode===`oauth`){let t=S??[],n=t.find(e=>e.active&&e.needsReauth)??t.find(e=>e.needsReauth);F?.onReauth(e.name,n?.id)}else He(`accounts`)}:void 0}),Y===`models`&&(0,Q.jsx)(Yg,{item:e,apiBase:y,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:c,modelRevision:l,modelRowsReady:u,onOpenModels:d,modelsLoading:m,modelsLoadFailed:h,needsReauth:(S??[]).some(e=>e.active&&e.needsReauth)||x?.needsReauth===!0,onRetryModels:g,onOpenAccounts:je?()=>He(`accounts`):void 0},e.name),Y===`usage`&&(0,Q.jsx)(Zg,{item:e,usageTotals:n,quotaReport:i,currentQuotaReading:Ne,quotaIdentity:Ie,modelUsage:r,...G?{onRefreshQuota:G}:{}}),Y===`accounts`&&(0,Q.jsx)(YS,{item:e,apiBase:y,targetKey:z,oauth:x,accounts:S,keys:j,accountLoadState:C,switchingAccountId:k,pausingAccountId:A,busy:M===ne,loginHint:N,loginCapture:P,authHandlers:Be,onUpdateProvider:ze,onCodexActiveNeedsReauthChange:I,codexController:L}),Y===`settings`&&(0,Q.jsx)(ww,{item:e,apiBase:y,targetKey:K,targetLabel:q,draftStore:J,availableModels:a,onUpdateProvider:ze,onDirtyChange:oe,onRegisterSave:De,onRegisterDiscard:me,accountModeFocusToken:Ce,onAccountModeFocused:Ge},`${K}\u0000${e.name}`)]}),se&&(0,Q.jsx)(Dw,{saving:le,onCancel:()=>{le||ce(null)},onDiscard:()=>{if(le)return;let t=se;ce(null),oe(!1),t&&t.targetKey===K&&(pe.current?pe.current():J.clear(t.targetKey,e.name),t.next===`deselect`?v():ie(t.next))},onSave:()=>{(async()=>{if(le)return;let e=se;if(!e||e.targetKey!==K)ce(null);else{ue(!0);try{if(!(await fe.current?.()??!1))return;ce(null),oe(!1),e.next===`deselect`?v():ie(e.next)}finally{ue(!1)}}})()}})]})}async function kw(e,t,n){try{return jw(await e.json(),t,n)}catch{}return t}function Aw(e){return typeof e==`object`&&!!e&&e.error===`target_changed`}function jw(e,t,n){if(Aw(e))return n??t;let r=typeof e==`object`&&e?e.error:void 0;return typeof r==`string`&&r.trim()?r.trim():t}var Mw=Object.freeze(Object.create(null)),Nw=new Map,Pw=new Set,Fw=new Map;function Iw(e,t,n){let r=Rw(e),i=r[t];if(i===n||i&&n&&i.kind===n.kind&&i.accountId===n.accountId&&(i.kind!==`pause`||n.kind===`pause`&&i.paused===n.paused))return;let a=Object.assign(Object.create(null),r);n?a[t]=n:delete a[t],Object.keys(a).length?Nw.set(e,a):Nw.delete(e);for(let e of Pw)e()}function Lw(e,t){let n=Fw.get(e);n||(n=new Map,Fw.set(e,n));let r=n.get(t);r||(r={base:void 0,operations:[],observedDebt:0,clearedDebt:0},n.set(t,r));let i=r.observedDebt,a={active:!0,settled:!1};return r.operations.push(a),(n=e=>e,o=!1,s)=>{if(a.settled)return;if(a.settled=!0,s?.kind===`unpersisted`?(r.observedDebt++,r.debtAccountId=s.accountId):s?.kind===`confirmed`&&(r.clearedDebt=Math.max(r.clearedDebt,i)),a.active){if(a.reduce=n,o){let e=r.operations.splice(0,r.operations.indexOf(a)+1);for(let t of e)t.active=!1;r.base=n(void 0)}for(;r.operations[0]?.reduce;){let e=r.operations.shift();r.base=e.reduce(r.base),e.active=!1}}let c=r.base;for(let e of r.operations)e.reduce&&(c=e.reduce(c));r.observedDebt<=r.clearedDebt?r.debtAccountId=void 0:!c&&r.debtAccountId!==void 0&&(c={kind:`reset`,accountId:r.debtAccountId}),Iw(e,t,c)}}function Rw(e){return Nw.get(e)??Mw}function zw(e){return Pw.add(e),()=>{Pw.delete(e)}}function Bw(e,t,n){Lw(e,t)(()=>n,!0)}var Vw=e=>{let t=a_(e);return t===e?void 0:t};function Hw(e,t){return t===void 0?e:e.map(e=>({...e,active:e.id===t}))}function Uw(e,t){let n=new Map(t.map(e=>[e.id,e]));return Kw(e,t,!1).map(e=>Gw(e)?{...e,quotaPending:n.get(e.id)?.quotaPending??!1,quotaUnavailable:n.get(e.id)?.quotaMode===e.quotaMode?n.get(e.id)?.quotaUnavailable??!1:!1,quotaReadAt:n.get(e.id)?.quotaMode===e.quotaMode?n.get(e.id)?.quotaReadAt:void 0,quotaUnknownReason:n.get(e.id)?.quotaMode===e.quotaMode?n.get(e.id)?.quotaUnknownReason:void 0,quotaFailure:e.quotaMode===`probe`&&n.get(e.id)?.quotaMode===e.quotaMode&&n.get(e.id)?.quotaUnavailable?_l(n.get(e.id)?.quotaFailure):void 0}:e)}function Ww(e,t){let n=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=n.get(e.id);if(!t||t.quotaMode!==e.quotaMode)return e;let r=Kw([t],[e],!0)[0];return{...e,quota:r.quota,quotaPending:r.quotaPending,quotaUnavailable:r.quotaUnavailable,quotaFailure:r.quotaFailure,quotaReadAt:r.quotaReadAt,quotaUnknownReason:r.quotaUnknownReason}})}var Gw=e=>e.quotaMode===`probe`||e.quotaMode===`passive`;function Kw(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=Gw(e);if(!t&&e.quotaMode!==`unsupported`)return{...e,quotaMode:void 0,quotaPending:void 0,quotaFailure:void 0};let i=t&&(!n||e.quotaUnavailable===!0);return{...e,quota:e.quotaMode===`unsupported`?null:e.quota===void 0?i?r.get(e.id)?.quota:void 0:e.quota,quotaPending:!n&&e.quotaMode===`probe`,quotaUnavailable:n?e.quotaUnavailable===!0:!1,quotaFailure:n&&e.quotaMode===`probe`&&e.quotaUnavailable===!0?_l(e.quotaFailure):void 0}})}function qw(e,t){let n=t&&new Map(t.map(e=>[e.id,e.quotaMode]));return e.map(e=>Gw(e)&&(!n||n.get(e.id)===e.quotaMode)?{...e,quotaUnavailable:!0,quotaPending:!1,quotaFailure:void 0}:e)}function Jw(e,t=!1){let n={};for(let[t,r]of Object.entries(e))v_(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}async function Yw(e,t,n,r){let a=d(2e4),o=()=>a.controller.abort();n?.aborted&&o(),n?.addEventListener(`abort`,o,{once:!0}),r.add(a.controller);try{let n=await i(e,t,{signal:a.signal});if(!n.ok)throw Error(String(n.status));let r=await n.json();if(a.signal.aborted)throw Error(`Quota roster deadline exceeded`);return r}finally{a.clear(),n?.removeEventListener(`abort`,o),r.delete(a.controller)}}function Xw(e){let{apiBase:t,targetKey:n=t,t:r,config:a,aliveRef:o,notify:s,fetchConfig:c,fetchOauth:l,fetchProviderQuotas:u,codexActiveNeedsReauth:f,invalidateOauthStatusReads:p,setOauthStatus:m}=e,h=n===t?t:`${t}\u0000${n}`,g=Y_(t,n),_=(0,Z.useMemo)(()=>({apiBase:t,targetKey:n}),[t,n]),[y,b]=(0,Z.useState)(_),[x,S]=(0,Z.useState)({}),[C,w]=(0,Z.useState)({}),[T,E]=(0,Z.useState)({}),D=Object.values(T)[0]??null,O=e=>E(e?{[e.provider]:e}:{}),[k,A]=(0,Z.useState)({}),j=(0,Z.useSyncExternalStore)(zw,()=>Rw(h),()=>Rw(h)),M=Object.values(k)[0]??null,[N,P]=(0,Z.useState)({}),[F,I]=(0,Z.useState)({}),[L,R]=(0,Z.useState)(null),[z,B]=(0,Z.useState)(``),[V,H]=(0,Z.useState)(h);V!==h&&(H(h),R(null),B(``));let U=(0,Z.useRef)({}),W=(0,Z.useRef)({}),ee=(0,Z.useRef)({}),G=(0,Z.useRef)(new Map),te=(0,Z.useRef)(new Set),ne=(0,Z.useRef)(new Map),K=(0,Z.useRef)(new Map),q=(0,Z.useRef)(!0),J=(0,Z.useRef)(h),re=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{re.current=t},[t]),(0,Z.useLayoutEffect)(()=>{J.current=h},[h]);let Y=(0,Z.useCallback)(e=>v(e)&&e.apiBase===re.current,[]),[ie,ae]=(0,Z.useState)(h);ie!==h&&(ae(h),S({}),w({}),E({}),A({}),I({}),b(_)),(0,Z.useEffect)(()=>{let e=U.current,t=te.current,n=W.current,r=ee.current,i=G.current,a=ne.current,o=K.current;return q.current=!0,()=>{q.current=!1;for(let t of Object.keys(e))e[t]+=1;for(let e of Object.keys(n))n[e]+=1;for(let e of Object.keys(r))r[e]+=1;i.clear(),a.clear(),o.clear();for(let e of t)e.abort();t.clear()}},[t,_,h]);let oe=(0,Z.useRef)(null),se=(0,Z.useRef)(null),ce=(0,Z.useCallback)(async(e,t)=>await Yw(g,e,t,te.current),[g]),le=(0,Z.useCallback)(async(e,n=!1)=>{if(!o.current||!q.current||J.current!==h||!Y(g))return!1;let r=[...new Set(e)];return w(e=>{let t={...e};for(let e of r)t[e]=`loading`;return t}),(await Promise.all(r.map(async e=>{let r=`oauth:${e}`,i=(U.current[r]??0)+1;U.current[r]=i;let a=(W.current[r]??0)+1;W.current[r]=a;let s=()=>o.current&&q.current&&J.current===h&&Y(g)&&U.current[r]===i,c=()=>s()&&W.current[r]===a,l=`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`;try{let t=await ce(l);if(!Array.isArray(t.accounts))throw Error(`Invalid account roster`);if(!s())return!1;let i=Hw(t.accounts,t.activeAccountId);if(S(n=>c()?{...n,[e]:{activeAccountId:t.activeAccountId??null,accounts:Kw(i,n[e]?.accounts??[],!1)}}:n),w(t=>c()?{...t,[e]:G.current.has(r)?`loading`:`ready`}:t),!i.some(Gw))return!0;let a=async()=>{let a=(ee.current[r]??0)+1;ee.current[r]=a;let s=()=>o.current&&q.current&&J.current===h&&Y(g)&&ee.current[r]===a;try{let r=await ce(`${l}&quota=1${n?`&refresh=1`:``}`);if(!Array.isArray(r.accounts))throw Error(`Invalid account quota roster`);if(!s())return!1;let i=Hw(r.accounts,r.activeAccountId);return S(n=>s()?c()?{...n,[e]:{activeAccountId:r.activeAccountId===void 0?t.activeAccountId??null:r.activeAccountId,accounts:Kw(i,n[e]?.accounts??[],!0)}}:{...n,[e]:{...n[e],accounts:Ww(n[e]?.accounts??[],i)}}:n),!i.filter(e=>e.paused!==!0&&Gw(e)).some(e=>e.quotaUnavailable===!0)}catch{return s()&&S(t=>s()&&t[e]?{...t,[e]:{...t[e],accounts:qw(t[e].accounts,i.filter(e=>e.paused!==!0))}}:t),!1}};return n?await a():(a(),!0)}catch{return c()&&(w(t=>c()?{...t,[e]:`error`}:t),S(t=>c()&&t[e]?{...t,[e]:{...t[e],accounts:qw(t[e].accounts)}}:t)),!1}}))).every(Boolean)},[o,t,Y,ce,g,h]),ue=(0,Z.useCallback)(async(e,n=!1)=>!o.current||!q.current||J.current!==h||!Y(g)?!1:(await Promise.all([...new Set(e)].map(async e=>{let r=`key:${e}`,i=(U.current[r]??0)+1;U.current[r]=i;let a=(W.current[r]??0)+1;W.current[r]=a;let s=()=>o.current&&q.current&&J.current===h&&Y(g)&&U.current[r]===i,c=()=>s()&&W.current[r]===a,l=`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,u=()=>(c()&&I(t=>c()?{...t,[e]:qw(t[e]??[])}:t),!1);try{let t=await ce(l);if(!Array.isArray(t.keys))throw Error(`Invalid key roster`);if(!s())return!1;let i=Hw(t.keys,t.activeId);if(I(t=>c()?{...t,[e]:Kw(i,t[e]??[],!1)}:t),!i.some(Gw))return!0;let a=async()=>{let t=(ee.current[r]??0)+1;ee.current[r]=t;let a=()=>o.current&&q.current&&J.current===h&&Y(g)&&ee.current[r]===t;try{let t=await ce(`${l}&quota=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.keys))throw Error(`Invalid key quota roster`);if(!a())return!1;let r=Hw(t.keys,t.activeId);return I(t=>a()?{...t,[e]:c()?Kw(r,t[e]??[],!0):Ww(t[e]??[],r)}:t),!r.filter(e=>e.disabled!==!0&&Gw(e)).some(e=>e.quotaUnavailable===!0)}catch{return a()&&I(t=>a()?{...t,[e]:qw(t[e]??[],i.filter(e=>e.disabled!==!0&&Gw(e)))}:t),a()&&!i.some(e=>e.disabled!==!0&&Gw(e))}};return n?await a():(a(),!0)}catch{return u()}}))).every(Boolean),[t,o,Y,ce,g,h]),de=(0,Z.useCallback)(async(e,n)=>{if(!o.current||!q.current||J.current!==h||!Y(g)||n?.aborted)return!1;let r=e?[e]:Object.entries(a?.providers??{}).flatMap(([e,t])=>t.authMode===`oauth`&&e!==`openai`?[{provider:e,kind:`oauth`}]:t.hasApiKey&&t.authMode!==`oauth`&&t.authMode!==`forward`?[{provider:e,kind:`api-key`}]:[]);return(await Promise.all(r.map(async({provider:e,kind:r})=>{let i=`${r===`oauth`?`oauth`:`key`}:${e}`;if(G.current.has(i))return!1;let a=(W.current[i]??0)+1;W.current[i]=a;let s=()=>o.current&&q.current&&J.current===h&&Y(g)&&W.current[i]===a&&!G.current.has(i),c=()=>s()&&!n?.aborted;r===`oauth`&&w(t=>c()?{...t,[e]:`loading`}:t);try{if(r===`oauth`){let r=await ce(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.accounts))throw Error(`Invalid account roster`);if(!c())return!1;let i=Hw(r.accounts,r.activeAccountId);S(t=>c()?{...t,[e]:{activeAccountId:r.activeAccountId===void 0?i.find(e=>e.active)?.id??null:r.activeAccountId,accounts:Uw(i,t[e]?.accounts??[])}}:t),w(t=>c()?{...t,[e]:`ready`}:t)}else{let r=await ce(`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.keys)||!c())return!1;let i=Hw(r.keys,r.activeId);I(t=>c()?{...t,[e]:Uw(i,t[e]??[])}:t)}return!0}catch{return r===`oauth`&&w(t=>s()?{...t,[e]:`error`}:t),!1}}))).every(Boolean)},[o,t,Y,a,ce,g,h]),fe=(e,t)=>{let n=`${t===`oauth`?`oauth`:`key`}:${e}`;return U.current[n]=(U.current[n]??0)+1,W.current[n]=(W.current[n]??0)+1,t===`oauth`&&o.current&&q.current&&J.current===h&&Y(g)&&w(t=>({...t,[e]:`loading`})),n},pe=e=>{let t=`oauth:${e}`;if(!o.current||!q.current||J.current!==h||!Y(g)||G.current.has(t))return null;fe(e,`oauth`);let n=Symbol();return G.current.set(t,n),()=>{G.current.get(t)===n&&(fe(e,`oauth`),G.current.delete(t))}},me=async(e,t)=>!o.current||!q.current||J.current!==h||!Y(g)?!1:(fe(e,`oauth`),S(n=>{let r=n[e];return r?{...n,[e]:{...r,accounts:r.accounts.map(e=>({...e,autoSwitchThreshold:t,effectiveAutoSwitchThreshold:typeof e.autoSwitchThresholdOverride==`number`?e.autoSwitchThresholdOverride:t}))}}:n}),le([e])),he=async(e,n,a=!1)=>{let c=g;if(n.active&&!a||n.needsReauth||n.paused||K.current.has(e)||ne.current.has(e)||G.current.has(`oauth:${e}`))return;let d={provider:e,accountId:n.id};K.current.set(e,d),E(t=>({...t,[e]:d}));let f=fe(e,`oauth`),p=Symbol();G.current.set(f,p);let m=()=>o.current&&q.current&&J.current===h&&Y(c)&&G.current.get(f)===p,_=Ee(e,n),v=Lw(h,e);try{let a=await i(c,`${t}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:n.id})});if(!a.ok){let t=await a.json().catch(()=>({}));if(t.code===`affinity_reset_not_persisted`&&t.retryable===!0&&t.selectionCommitted===!0){if(v(()=>({kind:`active`,accountId:n.id}),!0,{kind:`unpersisted`,accountId:n.id}),!m())return;let i=t.activeAccountId??n.id;S(t=>t[e]?{...t,[e]:{...t[e],activeAccountId:i,accounts:Hw(t[e].accounts,i)}}:t),s(r(`prov.affinityResetPending`),!1)}else m()&&s(r(`prov.accountSwitchFail`),!1);return}let o=await a.json().catch(()=>({}));if(v(()=>void 0,!0,{kind:`confirmed`}),!m())return;fe(e,`oauth`);let d=o.activeAccountId===void 0?n.id:o.activeAccountId;S(t=>t[e]?{...t,[e]:{...t[e],activeAccountId:d,accounts:Hw(t[e].accounts,d)}}:t),G.current.delete(f);let p=await de({provider:e,kind:`oauth`});if(await Promise.all([l(),u(!0)]),!p){s(r(`pws.accountsLoadFailed`),!1);return}s(r(`prov.accountSwitched`,{email:_}),!0)}catch{m()&&s(r(`prov.accountSwitchFail`),!1)}finally{v(),m()&&(fe(e,`oauth`),G.current.delete(f),de({provider:e,kind:`oauth`})),K.current.get(e)===d&&(K.current.delete(e),o.current&&q.current&&J.current===h&&Y(c)&&E(t=>{let n={...t};return delete n[e],n}))}},ge=async(e,n,a)=>{let c=g,l=`oauth:${e}`;if(K.current.has(e)||ne.current.has(e)||G.current.has(l))return!1;let u=fe(e,`oauth`),f=Symbol();G.current.set(u,f);let p=()=>o.current&&q.current&&J.current===h&&Y(c)&&G.current.get(u)===f,m=Ee(e,n);try{let r=d(2e4);te.current.add(r.controller);let o;try{let s=await i(c,`${t}/api/oauth/accounts/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:r.signal,body:JSON.stringify({provider:e,accountId:n.id,threshold:a})});if(!s.ok)throw Error(`account threshold write failed`);if(o=await s.json(),r.signal.aborted)throw Error(`account threshold deadline exceeded`)}finally{r.clear(),te.current.delete(r.controller)}let s=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100;if(!o||o.autoSwitchThresholdOverride!==null&&!s(o.autoSwitchThresholdOverride)||!s(o.autoSwitchThreshold)||!s(o.effectiveAutoSwitchThreshold))throw Error(`invalid threshold response`);return p()?(fe(e,`oauth`),S(t=>{let r=t[e];return r?{...t,[e]:{...r,accounts:r.accounts.map(e=>e.id===n.id?{...e,autoSwitchThresholdOverride:o.autoSwitchThresholdOverride,autoSwitchThreshold:o.autoSwitchThreshold,effectiveAutoSwitchThreshold:o.effectiveAutoSwitchThreshold}:e)}}:t}),!0):!1}catch{return p()&&s(r(`accountPool.autoSwitchUpdateFailed`,{email:m}),!1),!1}finally{p()&&(fe(e,`oauth`),G.current.delete(u),de({provider:e,kind:`oauth`}))}},_e=async(e,n,a,c=!1)=>{let d=g,f=Vw(e);if(f&&a&&!c&&(!await Ju({message:r(`prov.accountPauseConfirmShared`,{email:Ee(e,n),provider:l_(f)}),confirmLabel:r(`codexAuth.pause`),tone:`danger`})||!o.current||!q.current||J.current!==h||!Y(d))||K.current.has(e)||ne.current.has(e)||G.current.has(`oauth:${e}`))return;let p={provider:e,accountId:n.id};ne.current.set(e,p),A(t=>({...t,[e]:{...p,paused:a}}));let m=fe(e,`oauth`),_=Symbol();G.current.set(m,_);let v=()=>o.current&&q.current&&J.current===h&&Y(d)&&G.current.get(m)===_,y=Ee(e,n),b=Lw(h,e),C;try{let o=await i(d,`${t}/api/oauth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:n.id,paused:a,...c?{retryAffinityReset:!0}:{}})});if(o.ok)C=await o.json().catch(()=>({}));else if(C=await o.json().catch(()=>({})),C.code!==`affinity_reset_not_persisted`||C.retryable!==!0||C.pauseCommitted!==!0){v()&&s(r(a?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:y}),!1);return}let l=!o.ok;if(l?b(()=>({kind:`pause`,accountId:n.id,paused:a}),!0,{kind:`unpersisted`,accountId:n.id}):c||C.activeAccountChanged?b(()=>void 0,!0,{kind:`confirmed`}):b(e=>e?.kind===`pause`&&e.accountId===n.id?{...e,paused:a}:e),!v())return;fe(e,`oauth`);let u=C.activeAccountId===void 0?x[e]?.activeAccountId??null:C.activeAccountId;if(S(t=>{let r=t[e];if(!r)return t;let i=r.accounts.map(e=>e.id===n.id?{...e,paused:a}:e);return{...t,[e]:{activeAccountId:u,accounts:Hw(i,u)}}}),l){s(r(`prov.affinityResetPending`),!1);return}G.current.delete(m)}catch{v()&&s(r(a?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:y}),!1);return}finally{b(),v()&&(fe(e,`oauth`),G.current.delete(m),de({provider:e,kind:`oauth`})),ne.current.get(e)===p&&(ne.current.delete(e),o.current&&q.current&&J.current===h&&Y(d)&&A(t=>{let n={...t};return delete n[e],n}))}if(o.current&&q.current&&J.current===h&&Y(d)){s(r(a?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`,{email:y}),!0);try{let t=await de({provider:e,kind:`oauth`});C.activeAccountChanged&&await Promise.all([l(),u(!0)]),t||s(r(`pws.accountsLoadFailed`),!1)}catch{o.current&&q.current&&s(r(`pws.accountsLoadFailed`),!1)}}},ve=async(e,n)=>{let a=g,c=`oauth:${e}`;if(G.current.has(c)||K.current.has(e)||ne.current.has(e))return;Bw(h,e,{kind:`reset`,accountId:n});let l=Rw(h)[e],u={provider:e,accountId:n},d=Symbol();fe(e,`oauth`),G.current.set(c,d),K.current.set(e,u),E(t=>({...t,[e]:u}));let f=()=>o.current&&q.current&&J.current===h&&Y(a)&&G.current.get(c)===d&&Rw(h)[e]===l,p=Lw(h,e);try{let o=await i(a,`${t}/api/oauth/accounts/affinity-reset`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e})});if(!o.ok){let e=await o.json().catch(()=>({}))??{};e.code===`affinity_reset_not_persisted`&&e.retryable===!0&&p(void 0,!1,{kind:`unpersisted`,accountId:n}),f()&&s(r(`prov.affinityResetPending`),!1);return}let c=await o.json().catch(()=>({}))??{},l=f();if(c.affinityResetConfirmed===!0&&p(()=>void 0,!0,{kind:`confirmed`}),l){let t=c.affinityResetConfirmed===!0&&!Rw(h)[e];s(r(t?`prov.affinityResetComplete`:`prov.affinityResetPending`),t)}}catch{f()&&s(r(`prov.affinityResetPending`),!1)}finally{p(),G.current.get(c)===d&&(G.current.delete(c),o.current&&q.current&&J.current===h&&Y(a)&&(fe(e,`oauth`),de({provider:e,kind:`oauth`}))),K.current.get(e)===u&&(K.current.delete(e),o.current&&q.current&&J.current===h&&Y(a)&&E(t=>{let n={...t};return delete n[e],n}))}},ye=async e=>{let t=j[e];if(!t||!o.current||!q.current||J.current!==h||!Y(g))return;if(t.kind===`reset`)return ve(e,t.accountId);let n=x[e]?.accounts.find(e=>e.id===t.accountId);if(n)t.kind===`active`&&(n.paused||n.needsReauth)?s(r(`prov.affinityResetRetryUnavailable`),!1):t.kind===`active`?await he(e,n,!0):await _e(e,n,t.paused,!0);else{if(C[e]===`ready`)return ve(e,t.accountId);s(r(`prov.affinityResetRetryUnavailable`),!1)}},be=async(e,n)=>{let a=g;if(n.active&&!n.disabled||K.current.has(e)||ne.current.has(e)||G.current.has(`key:${e}`))return;let l={provider:e,accountId:n.id};K.current.set(e,l),E(t=>({...t,[e]:l}));let d=fe(e,`api-key`),f=Symbol();G.current.set(d,f);let p=()=>o.current&&q.current&&J.current===h&&Y(a)&&G.current.get(d)===f,m=!1;try{if(n.disabled){let o=await i(a,`${t}/api/providers/keys/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:n.id,paused:!1})});if(!p())return;if(!o.ok){s(r(`prov.keySwitchFail`),!1);return}m=!0}let o=await i(a,`${t}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:n.id})});if(!p())return;if(!o.ok){let e=await o.json().catch(()=>({}));p()&&s(m?r(`prov.keyResumedSwitchFailed`):jw(e,r(`prov.keySwitchFail`),r(`prov.targetChanged`)),!1);return}let l=await o.json().catch(()=>({}));if(!p())return;fe(e,`api-key`);let d=l.activeId===void 0?n.id:l.activeId;I(t=>t[e]?{...t,[e]:Hw(t[e],d)}:t),s(r(`prov.keySwitched`,{key:n.label??n.masked}),!0),c(),u(!0)}catch{p()&&s(r(m?`prov.keyResumedSwitchFailed`:`prov.keySwitchFail`),!1)}finally{K.current.get(e)===l&&(K.current.delete(e),o.current&&q.current&&J.current===h&&Y(a)&&E(t=>{let n={...t};return delete n[e],n})),p()&&(fe(e,`api-key`),G.current.delete(d),de({provider:e,kind:`api-key`}))}},xe=async(e,n,a)=>{let l=g;if(K.current.has(e)||ne.current.has(e)||G.current.has(`key:${e}`))return;let d={provider:e,accountId:n.id};ne.current.set(e,d),A(t=>({...t,[e]:{...d,paused:a}}));let f=fe(e,`api-key`),p=Symbol();G.current.set(f,p);let m=()=>o.current&&q.current&&J.current===h&&Y(l)&&G.current.get(f)===p,_=n.label??n.masked,v;try{let o=await i(l,`${t}/api/providers/keys/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:n.id,paused:a})});if(!m())return;if(!o.ok){let e=await o.json().catch(()=>({}));m()&&s(jw(e,r(a?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:_}),r(`prov.targetChanged`)),!1);return}if(v=await o.json().catch(()=>({})),!m())return;fe(e,`api-key`),I(t=>{let r=t[e];if(!r)return t;let i=r.map(e=>e.id===n.id?{...e,disabled:a,...a?{}:{pauseDetails:void 0}}:e),o=i.findIndex(e=>e.id===n.id),s=o>=0?[...i.slice(o+1),...i.slice(0,o)]:i,c=a&&n.active?s.find(e=>!e.disabled)?.id??null:!a&&!i.some(e=>e.active&&!e.disabled)?n.id:i.find(e=>e.active)?.id??null,l=v.activeId===void 0?v.activeAccountId===void 0?c:v.activeAccountId:v.activeId;return{...t,[e]:Hw(i,l)}}),G.current.delete(f)}catch{m()&&s(r(a?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:_}),!1);return}finally{m()&&(fe(e,`api-key`),G.current.delete(f),de({provider:e,kind:`api-key`})),ne.current.get(e)===d&&(ne.current.delete(e),o.current&&q.current&&J.current===h&&Y(l)&&A(t=>{let n={...t};return delete n[e],n}))}if(o.current&&q.current&&J.current===h&&Y(l)){s(r(a?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`,{email:_}),!0);try{let t=await de({provider:e,kind:`api-key`});(v.activeAccountChanged??!0)&&await Promise.all([c(),u(!0)]),t||s(r(`pws.accountsLoadFailed`),!1)}catch{o.current&&q.current&&J.current===h&&Y(l)&&s(r(`pws.accountsLoadFailed`),!1)}}},Se=async(e,n)=>{let a=g,l=()=>o.current&&q.current&&J.current===h&&Y(a);if(!await Ju({message:r(`prov.keyRemoveConfirm`,{key:n.label??n.masked}),confirmLabel:r(`common.remove`),tone:`danger`})||!l())return;let d=await i(a,`${t}/api/providers/keys?name=${encodeURIComponent(e)}&id=${encodeURIComponent(n.id)}`,{method:`DELETE`});l()&&d.ok&&(s(r(`prov.keyRemoved`,{key:n.label??n.masked}),!0),ue(Object.keys(F)),c(),u(!0))},Ce=async(e,n)=>{let a=g,l=()=>o.current&&q.current&&J.current===h&&Y(a),d=n.trim();if(!d)return!1;try{let n=await i(a,`${t}/api/providers/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,key:d})});if(!l())return!1;if(!n.ok){let e=await n.json().catch(()=>({}));return s(jw(e,r(`prov.keyAddFail`),r(`prov.targetChanged`)),!1),!1}return s(r(`prov.keyAdded`,{name:e}),!0),R(null),await Promise.all([ue(Object.keys(F).includes(e)?Object.keys(F):[...Object.keys(F),e]),c(),u(!0)]),!0}catch{return s(r(`prov.keyAddFail`),!1),!1}},we=async e=>{await Ce(e,z)&&B(``)},Te=async(e,n,a,c)=>{let l=g,u=()=>o.current&&q.current&&J.current===h&&Y(l),d=await Yu({message:r(`prov.aliasPrompt`),initialValue:c??``,maxLength:80,validate:e=>P_(e,r)});if(d===null)return;let f=d.trim(),p=await i(l,n===`oauth`?`${t}/api/oauth/accounts/alias`:`${t}/api/providers/keys/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n===`oauth`?{provider:e,accountId:a,alias:f}:{name:e,id:a,alias:f})});if(u()){if(p.ok)n===`oauth`?await le([e]):await ue(Object.keys(F).includes(e)?Object.keys(F):[...Object.keys(F),e]),s(r(`prov.aliasSaved`),!0);else{let e=await p.json().catch(()=>({}));s(jw(e,r(`prov.aliasSaveFailed`),r(`prov.targetChanged`)),!1)}}},Ee=(e,t)=>dg(x[e]?.accounts??[t],t,r),De=async(e,n)=>{let a=g,c=Ee(e,n),d=Vw(e),f=await Ju({message:d?r(`prov.accountRemoveConfirmShared`,{email:c,provider:l_(d)}):r(`prov.accountRemoveConfirm`,{email:c}),confirmLabel:r(`common.remove`),tone:`danger`}),_=`oauth:${e}`;if(!f||!o.current||!q.current||J.current!==h||!Y(a)||G.current.has(_)||K.current.has(e)||ne.current.has(e))return;fe(e,`oauth`);let v=Symbol();G.current.set(_,v);let y=p?.(e,!0)===!0,b=()=>m?.(t=>{if(!(e in t))return t;let n={...t};return delete n[e],n});y&&b();let x=!1,S=()=>{!x&&y&&(x=!0,p?.(e,!1)===!0&&(b(),l().catch(()=>{})))},C=Rw(h)[e],w=()=>o.current&&q.current&&J.current===h&&Y(a)&&G.current.get(_)===v,T=!1,E=Lw(h,e);try{let d=await i(a,`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}&id=${encodeURIComponent(n.id)}${C?`&retryAffinityReset=true`:``}`,{method:`DELETE`}),f,p=!1;if(d.ok)f=await d.json().catch(()=>({}))??{};else if(f=await d.json().catch(()=>({}))??{},p=f.code===`affinity_reset_not_persisted`&&f.retryable===!0&&f.deletionCommitted===!0,!p){w()&&(f.deletionCommitted===!1?s(r(`prov.accountRemoveFail`,{email:c}),!1):s(r(`prov.accountRemoveUnverified`,{email:c}),!1));return}if(S(),T=!0,p?E(()=>({kind:`reset`,accountId:n.id}),!0,{kind:`unpersisted`,accountId:n.id}):f.affinityResetConfirmed===!0?E(()=>void 0,!0,{kind:`confirmed`}):E(e=>e?.accountId===n.id?{kind:`reset`,accountId:n.id}:e),!w())return;p?s(r(`prov.affinityResetPending`),!1):s(r(`prov.accountRemoved`,{email:c}),!0),await le([e]),y||l().catch(()=>{o.current&&q.current&&J.current===h&&Y(a)&&s(r(`pws.accountsLoadFailed`),!1)}),await u(!0)}catch{w()&&s(r(T?`pws.accountsLoadFailed`:`prov.accountRemoveUnverified`,{email:c}),!1)}finally{S(),E(),G.current.get(_)===v&&(G.current.delete(_),o.current&&q.current&&J.current===h&&Y(a)&&(fe(e,`oauth`),de({provider:e,kind:`oauth`})))}},Oe=(0,Z.useMemo)(()=>a?Object.entries(a.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[a]);(0,Z.useEffect)(()=>{if(Oe.length===0)return;let e=`${h}:${t}:${Oe.join(`,`)}`;oe.current!==e&&(oe.current=e,Promise.resolve().then(()=>{le(Oe)}))},[t,le,Oe,h]);let ke=(0,Z.useMemo)(()=>a?Object.entries(a.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[a]);(0,Z.useEffect)(()=>{if(ke.length===0)return;let e=`${h}:${t}:${ke.join(`,`)}`;se.current!==e&&(se.current=e,Promise.resolve().then(()=>{ue(ke)}))},[t,ue,ke,h]);let Ae=(0,Z.useMemo)(()=>Jw(x,f),[x,f]);return{accountSets:y===_?x:{},accountLoadStates:y===_?C:{},switchingAccount:D,pausingAccount:M,switchingAccounts:T,pausingAccounts:k,pendingAffinityResets:j,retryAffinityReset:ye,openAccounts:N,keyPools:y===_?F:{},addingKeyFor:L,newKeyValue:z,setAccountSets:S,setAccountLoadStates:w,setSwitchingAccount:O,setOpenAccounts:P,setKeyPools:I,setAddingKeyFor:R,setNewKeyValue:B,fetchAccountSets:le,fetchKeyPools:ue,refreshAccountRosters:de,beginAccountLogout:pe,switchAccount:he,pauseAccount:_e,setAccountPoolThreshold:me,setAccountThreshold:ge,switchApiKey:be,pauseApiKey:xe,removeApiKey:Se,addApiKeyValue:Ce,addApiKey:we,editCredentialAlias:Te,removeAccount:De,oauthCardProviders:Oe,keyCardProviders:ke,activeAccountNeedsReauth:Ae}}function Zw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qw(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>Qw(e,t[n]));if(Zw(e)&&Zw(t)){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&Qw(e[n],t[n]))}return!1}function $w(e,t){return e?`${e}.${t}`:t}function eT(e,t,n,r=``){if(Qw(n,e))return{value:t,conflicts:[]};if(Qw(t,e)||Qw(n,t))return{value:n,conflicts:[]};if(!Zw(e)||!Zw(t)||!Zw(n))return{value:n,conflicts:[r||`$`]};let i=Object.create(null),a=[],o=new Set([...Object.keys(e),...Object.keys(t),...Object.keys(n)]);for(let s of o){let o=Object.hasOwn(e,s),c=Object.hasOwn(t,s),l=Object.hasOwn(n,s),u=e[s],d=t[s],f=n[s];if(!l){if(!o){c&&(i[s]=d);continue}if(!c||Qw(d,u))continue;a.push($w(r,s));continue}if(!o){if(!c||Qw(d,f)){i[s]=f;continue}a.push($w(r,s)),i[s]=f;continue}if(!c){if(Qw(f,u))continue;a.push($w(r,s)),i[s]=f;continue}let p=eT(u,d,f,$w(r,s));i[s]=p.value,a.push(...p.conflicts)}return{value:i,conflicts:a}}var tT=new Set([`hasApiKey`,`hasHeaders`,`vertexCredentialKind`,`vertexCredentialVerified`,`xaiResponsesOptInState`,`initialModelSelection`]);function nT(e){return{defaultProvider:e.defaultProvider,providers:Object.fromEntries(Object.entries(e.providers).map(([e,t])=>{let n={};for(let[e,r]of Object.entries(t))tT.has(e)||(n[e]=structuredClone(r));return[e,n]}))}}var rT={open:!1,draft:``,baseline:``,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``};function iT(e,t){return e.open&&e.draft!==e.baseline&&t!==``&&e.baseline!==t}function aT(e){let{apiBase:t,targetKey:n=t,config:r,notify:a,fetchConfig:o,fetchProviderQuotas:s,onSaved:c,t:l}=e,u=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{u.current=t},[t]);let d=(0,Z.useRef)(n);(0,Z.useLayoutEffect)(()=>{d.current=n},[n]);let[f,p]=(0,Z.useState)(()=>new Map),m=(0,Z.useMemo)(()=>r?JSON.stringify(nT(r),null,2):``,[r]),h=f.get(n),g=h?.open?h:h?h.draft===h.baseline&&m!==``&&h.baseline!==m?{...h,draft:m,baseline:m}:h:r?{...rT,draft:m,baseline:m}:rT,_=(0,Z.useCallback)((e,t=n)=>{p(n=>{let r=e(n.get(t)??rT),i=new Map(n);return i.set(t,r),i})},[n]),v=(0,Z.useCallback)(async()=>{let e=n,r=t,p=V(`shared`,t);if(p.apiBase!==r||n!==t&&p.targetKey!==n)return a(l(`prov.targetChanged`),!1),!1;let h=f.get(e)??rT;if(iT(h,m)||h.conflicts.length>0)return a(l(`pws.draftConflictResolveFirst`),!1),!1;let g=h.draft,v=h.baseline;_(e=>({...e,saving:!0}),e);let y;try{y=JSON.parse(g)}catch{return u.current===r&&d.current===e&&a(l(`prov.invalidJson`),!1),_(e=>({...e,saving:!1}),e),!1}try{let t=JSON.parse(v);if(Qw(y,t))return _(()=>({open:!1,draft:v,baseline:v,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}),e),u.current===r&&d.current===e&&a(l(`prov.saved`),!0),!0;let n=await i(p,`${r}/api/providers`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({baseline:t,next:y})});if(!n.ok){let t=await n.json().catch(()=>({}));return u.current===r&&d.current===e&&(a(t.error===`target_changed`?l(`prov.targetChanged`):t.error||l(`prov.saveFailed`),!1),t.code===`stale_provider_editor_baseline`&&o()),_(e=>({...e,saving:!1}),e),!1}let f=JSON.stringify(y,null,2);if(_(e=>e.draft===g?{open:!1,draft:f,baseline:f,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}:{...e,baseline:f,saving:!1,conflicts:[],conflictBase:``},e),u.current!==r||d.current!==e)return!0;a(l(`prov.saved`),!0),o(),s(!0);let m=Object.keys(y.providers).filter(e=>!Object.hasOwn(t.providers,e));return c(m),!0}catch{return u.current===r&&d.current===e&&a(l(`prov.saveFailed`),!1),_(e=>({...e,saving:!1}),e),!1}},[t,o,s,a,c,m,f,l,n,_]),y=(0,Z.useCallback)(()=>{let e=m||g.draft;_(()=>({open:!0,draft:e,baseline:e,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}))},[m,g.draft,_]),b=(0,Z.useCallback)(()=>{_(e=>{let t=m||e.baseline;return{open:!1,draft:t,baseline:t,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}})},[m,_]),x=(0,Z.useCallback)(()=>{g.open&&g.draft!==g.baseline?_(e=>({...e,leaveOpen:!0})):b()},[b,g.baseline,g.draft,g.open,_]),S=(0,Z.useCallback)(()=>{let e=m||g.baseline;_(()=>({open:!0,draft:e,baseline:e,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}))},[m,g.baseline,_]),C=(0,Z.useCallback)(e=>{_(t=>{if(m===``)return{...t,draft:e};try{let n=eT(JSON.parse(t.conflictBase||t.baseline),JSON.parse(m),JSON.parse(e));return{...t,draft:e,conflicts:n.conflicts,...n.conflicts.length===0?{conflictBase:``}:{}}}catch{return{...t,draft:e}}})},[m,_]),w=(0,Z.useCallback)(e=>{_(t=>({...t,leaveOpen:e}))},[_]),T=iT(g,m)||g.conflicts.length>0,E=(0,Z.useCallback)(()=>{let e=m||g.baseline;_(()=>({open:!0,draft:e,baseline:e,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}))},[m,g.baseline,_]),D=(0,Z.useCallback)(()=>{let e=m||g.baseline,t,n,r;try{t=JSON.parse(g.baseline),n=JSON.parse(e),r=JSON.parse(g.draft)}catch{return}let i=eT(t,n,r);if(Qw(i.value,n)){_(()=>({open:!1,draft:e,baseline:e,saving:!1,leaveOpen:!1,conflicts:[],conflictBase:``}));return}let a=JSON.stringify(i.value,null,2);_(t=>({...t,draft:a,baseline:e,conflicts:i.conflicts,conflictBase:i.conflicts.length>0?g.baseline:``}))},[m,g.baseline,g.draft,_]);return{draft:g.draft,setDraft:C,jsonEditorOpen:g.open,jsonBaseline:g.baseline,jsonSaving:g.saving,jsonLeaveOpen:g.leaveOpen,saveConfig:v,openJsonEditor:y,discardJsonEditor:b,requestCloseJsonEditor:x,restoreJsonEditor:S,jsonIsDirty:g.open&&g.draft!==g.baseline,jsonConflict:T,jsonConflicts:g.conflicts,useSavedJsonValues:E,keepJsonDraft:D,setJsonLeaveOpen:w}}function oT(e,t){let n=(0,Z.useRef)(e);(0,Z.useLayoutEffect)(()=>{n.current=e},[e]);let r=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{r.current=t});let i=(0,Z.useRef)(new Set);(0,Z.useEffect)(()=>{let e=e=>{let t=e.detail?.targetKey;t&&t===n.current&&!i.current.has(t)&&(i.current.add(t),r.current())};return window.addEventListener(k,e),()=>window.removeEventListener(k,e)},[])}var sT=186e4;function cT(e,t,n){return e?Math.max(n,Math.ceil(sT/t)):n}function lT({apiBase:e,targetKey:t,t:n,aliveRef:r,accountSets:a,setAccountSets:o,setBusy:s,setStatus:c,setLoginInfo:l,setOauthStatus:u,invalidateOauthStatusReads:d,captureOauthStatusRead:f,beginAccountLogout:p,notify:m,fetchConfig:h,fetchOauth:g,fetchAccountSets:_,fetchProviderQuotas:y,bumpModelsRefresh:b,onLoginSettled:x}){let S=(0,Z.useRef)(null);S.current===null&&(S.current=new Map);let C=Y_(e,t),w=(0,Z.useRef)(t??e);(0,Z.useLayoutEffect)(()=>{w.current=t??e},[e,t]);let T=(0,Z.useRef)(new Map),E=(0,Z.useRef)(new Map),D=(0,Z.useRef)(new Map);(0,Z.useEffect)(()=>{let e=[...E.current];T.current.clear(),E.current.clear(),D.current.clear(),s(null),l(null),c(``);for(let[t,n]of e)oS(n,t)},[s,l,c,t]);let O=(0,Z.useCallback)(e=>{let t=(S.current.get(e)??0)+1;return S.current.set(e,t),t},[]),k=(0,Z.useCallback)((e,t)=>oS(e,t),[]),A=(0,Z.useCallback)(async e=>{let t=Object.keys(a);await _(new Set(t).has(e)?t:[...t,e])},[a,_]),j=(0,Z.useCallback)(()=>{h(),y(!0),b()},[h,y,b]),M=(0,Z.useCallback)(async(e,t)=>{if(r.current){t===`added`&&x?.(e);try{await A(e)}catch{}r.current&&(t===`added`?m(n(`prov.loginOk`,{provider:l_(e),cmd:`ocx sync`}),!0):m(t===`ended`?n(`kiroLogin.ended`):n(`prov.loginError`,{provider:l_(e),error:n(`kiroLogin.failed`)}),!1),j())}},[r,x,A,m,n,j]);return(0,Z.useEffect)(()=>{let e=e=>{let t=[...T.current];T.current.clear();for(let[n,r]of t){let t=E.current.get(n);E.current.delete(n),t&&D.current.set(n,t),S.current.get(n)===r&&O(n),e&&(s(e=>e===n?null:e),l(e=>e?.provider===n?null:e)),t&&k(t,n)}},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[O,k,s,l]),{cancelLoginOAuth:(0,Z.useCallback)(async i=>{let a=O(i),o=t??e,c=E.current.get(i);T.current.delete(i),E.current.delete(i),c&&D.current.set(i,c),s(e=>e===i?null:e),l(e=>e?.provider===i?null:e),c&&await k(c,i),w.current===o&&r.current&&(c===void 0||v(c))&&S.current.get(i)===a&&m(n(`prov.loginCancelled`,{provider:l_(i)}),!1)},[r,e,O,k,m,s,l,n,t]),loginOAuth:async(p,h=!1,g,_=!1,y)=>{let b=C;E.current.set(p,b),D.current.delete(p);let M=O(p),N=t??e,P=()=>r.current&&w.current===N&&v(b);T.current.set(p,M);let F=g?.trim()||void 0;s(p),c(``),l(null);try{let t=await sS(b,p,()=>{if(P()&&S.current.get(p)===M)return i(b,`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:p,...K_(),...h||F?{addAccount:!0}:{},...F?{accountId:F,reauth:!0}:{},...y?{row:y}:{},...IS(p,_)})})});if(!t||S.current.get(p)!==M||!P())return;if(!t.ok){let e=await t.json().catch(()=>({}));if(!P()||S.current.get(p)!==M)return;m(jw(e,n(`prov.loginFailStart`,{provider:l_(p)}),n(`prov.targetChanged`)),!1);return}let s=await t.json();if(!P()||S.current.get(p)!==M)return;let c=J_(s.browserLaunch);(s.url||s.instructions||s.deviceCode)&&l({provider:p,url:s.url,instructions:s.instructions,deviceCode:s.deviceCode,browserLaunch:c});let g=a[p]?.accounts.length??0,v=!1,C=!!s.deviceCode;for(let t=0;t<cT(C,2e3,150)&&P()&&S.current.get(p)===M;t++){if(await new Promise(e=>setTimeout(e,2e3)),S.current.get(p)!==M||!P())return;let t=f?.(p),r=await i(b,`${e}/api/oauth/status?provider=${p}`).catch(()=>null),a=r?await Xn(r)??null:null;if(!P()||S.current.get(p)!==M)return;if(t&&!t()||!a)continue;if(a.error){if(d?.(p)===!1)return;u(e=>({...e,[p]:a})),m(/cancel/i.test(a.error)?n(`prov.loginCancelled`,{provider:l_(p)}):n(`prov.loginError`,{provider:l_(p),error:a.error}),!1),l(null),v=!0;break}let s=a.accounts?.length??0;if(h||F?s>g||a.done===!0:a.loggedIn||a.done===!0){if(d?.(p)===!1)return;u(e=>({...e,[p]:a}));let e=F?a.accounts?.find(e=>e.id===F):a.accounts?.find(e=>e.active)??a.accounts?.find(e=>e.id===a.activeAccountId);if(F&&!e){m(n(`prov.loginError`,{provider:l_(p),error:n(`prov.reauthAccountMissing`)}),!1),l(null),v=!0;break}if(e?.needsReauth){m(n(`prov.loginError`,{provider:l_(p),error:n(`prov.reauthIdentityMismatch`)}),!1),l(null),v=!0;break}if(a.accounts){let e=a.accounts.find(e=>e.active)?.id??null;o(t=>t[p]?t:{...t,[p]:{activeAccountId:a.activeAccountId??e,accounts:a.accounts}})}if(l(null),x?.(y??p),await A(p),!P()||S.current.get(p)!==M)return;h&&!F&&s<=g?m(n(`prov.loginSameAccount`,{provider:l_(p)}),!1):m(n(`prov.loginOk`,{provider:l_(p),cmd:`ocx sync`}),!0),j(),v=!0;break}a.hint&&(a.hint.deviceCode&&(C=!0),l({provider:p,url:a.hint.url,instructions:a.hint.instructions,deviceCode:a.hint.deviceCode,browserLaunch:c}))}if(!v&&S.current.get(p)===M&&r.current){if(await k(b,p),!P()||S.current.get(p)!==M)return;m(n(`prov.loginTimeout`,{provider:l_(p)}),!1),l(null)}}catch{if(S.current.get(p)===M){if(await k(b,p),!P()||S.current.get(p)!==M)return;m(n(`prov.loginRequestFail`,{provider:l_(p)}),!1)}}finally{T.current.get(p)===M&&(T.current.delete(p),E.current.delete(p),D.current.set(p,b)),P()&&S.current.get(p)===M&&s(e=>e===p?null:e)}},logoutOAuth:async a=>{let o=C,c=t??e,f=a_(a)===a?void 0:a_(a),x=[a_(a),...s_(a_(a))].filter(e=>e!==a);if(f&&(!await Ju({message:n(`prov.logoutConfirmShared`,{provider:l_(f)}),confirmLabel:n(`prov.logout`),tone:`danger`})||!r.current||w.current!==c||!v(o)))return;let S=p?.(a);if(p&&!S){r.current&&m(n(`prov.logoutBusy`),!1);return}if(d?.(a,!0)===!1){S?.();return}let T=()=>u(e=>{if(!(a in e))return e;let t={...e};return delete t[a],t});T(),O(a),s(e=>e===a?null:e),l(e=>e?.provider===a?null:e);for(let e of x)d?.(e);f&&(O(f),s(e=>e===f?null:e),l(e=>e?.provider===f?null:e));let E=!1,D=!1;try{(await i(o,`${e}/api/oauth/logout?provider=${encodeURIComponent(a)}`,{method:`POST`})).ok?E=!0:D=!0}catch{D=!0}finally{S?.()}if(w.current===c&&v(o)&&(D&&m(n(`prov.logoutFail`,{provider:l_(a)}),!1),d?.(a,!1)!==!1)){for(let e of x)d?.(e);if(T(),!E)_([a,...x]).catch(()=>{}),g();else try{await Promise.all([_([a,...x]),g(),h(),y(!0)]),b(),w.current===c&&v(o)&&m(f?n(`prov.logoutOkShared`,{provider:l_(f)}):n(`prov.logoutOk`,{provider:l_(a)}),!0)}catch{w.current===c&&v(o)&&m(n(`prov.logoutFail`,{provider:l_(a)}),!1)}}},onNativeLoginSettled:M,loginCapture:e=>E.current.get(e),loginEndedCapture:e=>D.current.get(e)}}function uT(e){let t=e.dependentShadowIntercept;return!t||typeof t.model!=`string`||t.enabled!==!0?null:{model:t.model,enabled:!0}}function dT(e,t,n){switch(e.code){case`last_provider`:return t(`prov.removeLastProvider`);case`provider_has_dependent_combos`:return t(`prov.removeHasDependentCombos`,{combos:(Array.isArray(e.combos)?e.combos.filter(e=>typeof e==`string`).join(`, `):``)||`—`});case`default_provider_disabled`:return t(`prov.defaultDisabled`);default:return jw(e,n,t(`prov.targetChanged`))}}function fT({apiBase:e,targetKey:t,t:n,removeBusyRef:r,workspaceSelected:a,setWorkspaceSelected:o,setRemoveConfirmName:s,notify:c,fetchConfig:l,fetchOauth:u,fetchProviderQuotas:d,refreshCodexAccount:f,onProviderRemoved:p}){let m=Y_(e,t),h=(0,Z.useRef)(null),g=(0,Z.useCallback)(async e=>{h.current={name:e,capture:m},s(e)},[m,s]),_=(0,Z.useCallback)(async t=>{let f=t;if(!f||r.current)return;let g=h.current,_=g?.name===f?g.capture:m;if(!v(_)){s(null),c(n(`prov.targetChanged`),!1);return}r.current=!0,s(null);let y=n(`prov.removeFail`,{name:f});try{let t=await i(_,`${e}/api/providers?name=${encodeURIComponent(f)}`,{method:`DELETE`});if(t.ok){h.current=null;let e=await t.json().catch(()=>({})),r=typeof e.defaultProvider==`string`?e.defaultProvider:null,i=uT(e);if(p?.(f),!v(_))return;i?c(n(`prov.removedShadowTarget`,{name:f,model:i.model}),!1,`warn`):c(r?n(`prov.removedDefault`,{name:f,defaultProvider:r}):n(`prov.removed`,{name:f}),!0),a===f&&o(null),l(),u(),d(!0)}else c(dT(await t.json().catch(()=>({})),n,y),!1)}catch{c(y,!1)}finally{r.current=!1}},[e,l,u,d,c,p,r,m,s,o,n,a]),y=(0,Z.useCallback)(async(t,r)=>{let a=m,o=await i(a,`${e}/api/providers?name=${encodeURIComponent(t)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:r})});if(!o.ok){c(await kw(o,n(r?`prov.disableFail`:`prov.enableFail`,{name:t}),n(`prov.targetChanged`)),!1);return}let s=await o.json().catch(()=>({}));if(!v(a))return;let f=uT(s);f?c(n(`prov.disabledShadowTarget`,{name:t,model:f.model}),!1,`warn`):c(n(r?`prov.disabled`:`prov.enabled`,{name:t}),!0),l(),u(),d(!0)},[e,l,u,d,c,m,n]),b=(0,Z.useCallback)(async(t,r,a)=>{let o=a??m;try{let a=await i(o,`${e}/api/providers?name=${encodeURIComponent(t)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!a.ok)return{ok:!1,error:await kw(a,n(`prov.updateFail`),n(`prov.targetChanged`))};let s=await a.json().catch(()=>({}));if(await l(),Object.hasOwn(r,`codexAccountMode`)){let e=[d(!0)];f&&e.push(Promise.resolve(f())),await Promise.all(e)}let c=s.xaiResponsesOptInState;return{ok:!0,...c===!0||c===!1||c===`mixed`?{xaiResponsesOptInState:c}:{}}}catch{return{ok:!1,error:n(`prov.networkError`)}}},[e,l,d,f,m,n]);return{removeProvider:g,confirmRemoveProvider:_,setProviderDisabled:y,setDefaultProvider:(0,Z.useCallback)(async t=>{let r=m;try{let a=await i(r,`${e}/api/providers?name=${encodeURIComponent(t)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({setDefault:!0})});return a.ok?v(r)?(c(n(`prov.setDefaultSuccess`,{name:t}),!0),await l(),!0):!1:(c(dT(await a.json().catch(()=>({})),n,n(`prov.setDefaultFail`,{name:t})),!1),!1)}catch{return c(n(`prov.setDefaultFail`,{name:t}),!1),!1}},[e,l,c,m,n]),updateProvider:b}}function pT({apiBase:e,targetKey:t,t:n,setConfig:r,setOauthProviders:i,setOauthStatus:a,notify:o,invalidateProviderQuotas:s,configCacheKey:c}){let l=(0,Z.useRef)(0),u=(0,Z.useRef)(0),d=(0,Z.useRef)(0),f=(0,Z.useMemo)(()=>({apiBase:e,targetKey:t}),[e,t]),p=(0,Z.useRef)(null),m=(0,Z.useRef)(new Map),h=(0,Z.useRef)(new Map),g=(0,Z.useRef)(new Map),_=(0,Z.useRef)(new Set),v=(0,Z.useRef)(new Set);(0,Z.useEffect)(()=>()=>{l.current+=1},[f]),(0,Z.useLayoutEffect)(()=>{p.current=f;let e=v.current;return()=>{p.current=null,u.current+=1,_.current.clear(),e.clear()}},[f]);let y=(0,Z.useCallback)((e,t)=>p.current!==f||t===void 0&&v.current.has(e)?!1:(m.current.set(e,(m.current.get(e)??0)+1),t===!0&&v.current.add(e),t===!1&&v.current.delete(e),!0),[f]),b=(0,Z.useCallback)(e=>{let t=m.current.get(e)??0;return()=>p.current===f&&!v.current.has(e)&&(m.current.get(e)??0)===t},[f]);return{fetchConfig:(0,Z.useCallback)(async()=>{if(p.current!==f)return`superseded`;let t=++l.current,i=()=>p.current!==f||t!==l.current;try{let t=await Yn(await fetch(`${e}/api/config`));if(i())return`superseded`;if(!t)throw Error(`config response missing`);return r(t??null),c&&t&&df(c,t),`applied`}catch{return i()?`superseded`:(o(n(`prov.loadConfigFail`),!1),`failed`)}},[e,c,o,r,n,f]),fetchOauth:(0,Z.useCallback)(async()=>{if(p.current!==f)return;let t=++u.current,n=new Map(m.current),r=e=>(n.get(e)??0)===(m.current.get(e)??0);try{let n=await Yn(await fetch(`${e}/api/oauth/providers`));if(!Array.isArray(n?.providers)||!n.providers.every(e=>typeof e==`string`))return;let o=n.providers;if(p.current!==f||t<d.current)return;d.current=t,_.current=new Set(o),i(o),a(e=>Object.fromEntries(Object.entries(e).filter(([e])=>_.current.has(e)||!r(e)))),await Promise.all(o.map(async t=>{let n=(h.current.get(t)??0)+1;h.current.set(t,n);let i=await fetch(`${e}/api/oauth/status?provider=${encodeURIComponent(t)}`).catch(()=>null),o=i?await Xn(i):null;o&&typeof o.loggedIn==`boolean`&&(p.current!==f||!_.current.has(t)||v.current.has(t)||!r(t)||n<(g.current.get(t)??0)||(g.current.set(t,n),a(e=>p.current===f&&_.current.has(t)&&!v.current.has(t)&&r(t)&&n===g.current.get(t)?{...e,[t]:o}:e)))}))}catch{}},[e,f,i,a]),fetchProviderQuotas:(0,Z.useCallback)(async(e=!1)=>{s(e)},[s]),invalidateOauthStatusReads:y,captureOauthStatusRead:b}}function mT(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}function hT({row:e,status:t,busyProvider:n,loginHint:r,paste:i,onLogin:a,onCancelLogin:o,onLogout:s,onManage:c}){let l=b(),u=n===e.id,d=!!t?.loggedIn,f=d?t?.email??e.statusLabel??l(`modal.accountLoggedIn`):t?.error??e.statusLabel??l(`modal.accountLoggedOut`),p=mT(e,n,r);return(0,Q.jsxs)(`div`,{className:`list-row provider-catalog-account-row${p?` provider-catalog-account-row--waiting`:``}`,children:[(0,Q.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,Q.jsx)(de,{name:e.id,cls:`provider-icon provider-icon-sm`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:e.label}),(0,Q.jsx)(`div`,{className:`sub`,children:f})]}),(0,Q.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,Q.jsxs)(Q.Fragment,{children:[d&&(0,Q.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:l(`modal.accountManage`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:d?`btn btn-ghost`:`btn btn-primary`,disabled:u,onClick:()=>{u||a(e.id)},children:l(u?`codexAuth.enablingOpenai`:d?`modal.accountAdd`:`modal.accountLogin`)})]}):d?(0,Q.jsxs)(Q.Fragment,{children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>c(e.id),children:l(`modal.accountManage`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:u,onClick:()=>{u||a(e.id,!0)},children:l(u?`prov.waitingBrowser`:`modal.accountAdd`)}),u&&o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:l(`common.cancel`)}),s&&!u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>s(e.id),children:l(`modal.accountLogout`)})]}):u?o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:l(`common.cancel`)}):a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>a(e.id),children:l(`modal.accountLogin`)})})]}),p&&r&&(0,Q.jsx)(H_,{hint:{url:r.url,deviceCode:r.deviceCode,instructions:r.instructions,browserLaunch:r.browserLaunch},...i?{paste:{value:i.value,busy:i.busy,message:i.message,ok:i.ok,onChange:i.onChange,onSubmit:()=>i.onSubmit(e.id)}}:{}})]})}var gT=[`accounts`,`free`,`local`,`paid`],_T={accounts:`modal.tab.accounts`,free:`modal.tab.free`,local:`modal.tab.local`,paid:`modal.tab.paid`},vT={},yT=[],bT={};function xT({presets:e,usageRank:t=vT,presetsLoading:n=!1,initialTier:r=`free`,query:i,onQueryChange:a,onSelectPreset:o,onSelectCustom:s,onShowNote:c,accountRows:l=yT,accountStatus:u=bT,busyProvider:d=null,loginHint:f=null,paste:p,onLogin:m,onCancelLogin:h,onLogout:g,onManage:_}){let v=b(),[y,x]=(0,Z.useState)(r),S=(0,Z.useId)(),C=e=>`${S}-${e}`,w=(0,Z.useRef)(null),T=i.trim().length>0;(0,Z.useEffect)(()=>{w.current&&(w.current.scrollTop=0)},[y,T]);let E=(0,Z.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),D=(0,Z.useMemo)(()=>{let e=Object.keys(t).length>0;return E.toSorted((n,r)=>{if(e){let e=t[n.id]??0,i=t[r.id]??0;if(i!==e)return i-e}return n.label.localeCompare(r.label,void 0,{sensitivity:`base`})||n.id.localeCompare(r.id)})},[E,t]),O=(0,Z.useMemo)(()=>bg(Og(D)),[D]),k=O[y],A=(0,Z.useMemo)(()=>T?Tg(l,i,d):l,[l,i,T,d]),j=(0,Z.useMemo)(()=>{let e=gT.filter(e=>e!==`accounts`);return T?e.map(e=>({tier:e,rows:wg(Eg(O[e].filter(e=>Cg(e,i)),A),i)})):y===`accounts`?[]:[{tier:y,rows:k}]},[T,y,k,O,i,A]),M=(0,Z.useMemo)(()=>({...Object.fromEntries(j.map(e=>[e.tier,e.rows.length])),accounts:A.length}),[j,A]),N=gT.reduce((e,t)=>e+(M[t]??0),0),P=gT.filter(e=>(M[e]??0)>0),F=T?N:y===`accounts`?A.length:j[0]?.rows.length??0,I=e=>{let t=w.current,n=t?.querySelector(`[data-catalog-group="${e}"]`);t&&n&&(t.scrollTop=n.offsetTop-t.offsetTop,d||n.focus({preventScroll:!0}))},L=e=>{if(e.key!==`ArrowDown`)return;let t=w.current?.querySelector(`button:not(:disabled), a[href]`);t&&(e.preventDefault(),t.focus())},R=(e,t)=>(0,Q.jsxs)(`h4`,{id:C(e),"data-catalog-group":e,className:`provider-catalog-group-head`,tabIndex:-1,children:[(0,Q.jsx)(`span`,{children:v(_T[e])}),(0,Q.jsx)(`span`,{className:`provider-catalog-group-count`,children:t})]}),z=e=>{let t=Ye(e),n=t?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:v(`modal.badge.subscriptionCli`)}):e.codexAccountMode===`direct`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:v(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:v(`modal.badge.pool`)}):e.auth===`oauth`?(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:v(`modal.badge.oauth`)}):e.auth===`forward`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:v(`modal.badge.codexLogin`)}):e.auth===`local`?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:v(`modal.badge.local`)}):e.keyOptional?null:(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:v(`modal.badge.apiKey`)}),r=(e.freeTier||e.keyOptional)&&e.auth===`key`&&!t?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:v(`modal.badge.free`)}):null,i=e.sponsor?(0,Q.jsx)(`span`,{className:`badge badge-accent provider-catalog-sponsor`,title:e.sponsorUrl,children:v(`modal.badge.sponsor`)}):null;return(0,Q.jsxs)(Q.Fragment,{children:[i,r,n]})};return(0,Q.jsxs)(`div`,{className:`provider-catalog`,children:[(0,Q.jsx)(`input`,{className:`input provider-catalog-search`,type:`search`,value:i,onChange:e=>a(e.target.value),onKeyDown:L,placeholder:v(`modal.search`),"aria-label":v(`modal.search`)}),T?(0,Q.jsx)(`div`,{className:`provider-catalog-tabs provider-catalog-tabs--chips`,children:gT.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`provider-catalog-tab provider-catalog-chip`,disabled:(M[e]??0)===0,...(M[e]??0)>0?{"aria-controls":C(e)}:{},onClick:()=>I(e),children:[v(_T[e]),(0,Q.jsx)(`span`,{className:`provider-catalog-chip-count`,children:M[e]??0})]},e))}):(0,Q.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:gT.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":y===e,"aria-controls":S,className:`provider-catalog-tab${y===e?` active`:``}`,onClick:()=>x(e),children:v(_T[e])},e))}),!T&&y===`accounts`&&(0,Q.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:v(`modal.accountsHint`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:T?N===0?v(`modal.noMatch`):v(`modal.searchResults`,{count:N,tiers:P.map(e=>v(_T[e])).join(`, `)}):``}),(0,Q.jsxs)(`div`,{className:`provider-catalog-rows`,id:S,ref:w,children:[n&&F===0&&(0,Q.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:v(`modal.catalogLoading`)}),(T||y===`accounts`)&&A.length>0&&(0,Q.jsxs)(Z.Fragment,{children:[T&&R(`accounts`,A.length),A.map(e=>(0,Q.jsx)(hT,{row:e,status:u[e.id],busyProvider:d,loginHint:f,...p?{paste:p}:{},...m?{onLogin:m}:{},...h?{onCancelLogin:h}:{},...g?{onLogout:g}:{},..._?{onManage:_}:{}},e.id))]},`accounts`),j.map(e=>e.rows.length===0?null:(0,Q.jsxs)(Z.Fragment,{children:[T&&R(e.tier,e.rows.length),e.rows.map(e=>(0,Q.jsxs)(`div`,{className:`provider-catalog-row-wrap`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>o(e),children:[(0,Q.jsx)(de,{name:e.id,adapter:e.adapter,cls:`provider-icon provider-icon-sm`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:e.label}),(0,Q.jsxs)(`div`,{className:`sub`,children:[(0,Q.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,Q.jsx)(`div`,{className:`provider-catalog-badges`,children:z(e)})]}),c&&xg(e.note)&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn provider-catalog-note-more`,onClick:()=>c(e),children:v(`modal.noteMore`)})]},e.id))]},e.tier)),!n&&F===0&&(0,Q.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:v(`modal.noMatch`)})]}),(0,Q.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,Q.jsx)(`div`,{style:{flex:1}}),!T&&y!==`accounts`&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:s,children:v(`modal.notListed`)})]})]})}function ST({providerId:e,label:t,adapter:n,note:r,onClose:i}){let a=b(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=c.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[]);let l=(0,Z.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Q.jsxs)(`dialog`,{ref:c,"aria-labelledby":o,"aria-describedby":s,className:`modal-overlay`,onCancel:l,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:i}),(0,Q.jsxs)(`div`,{className:`modal-card provider-note-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:o,className:`provider-note-title`,children:[(0,Q.jsx)(de,{name:e,adapter:n,cls:`provider-icon provider-icon-sm`}),t]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":a(`common.close`),onClick:i,children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsxs)(`div`,{id:s,className:`provider-note-body`,children:[(0,Q.jsx)(`code`,{className:`chip`,children:n}),(0,Q.jsx)(`p`,{className:`modal-desc provider-note-text`,children:r})]}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:a(`common.close`)})})]})]})}function CT(e){return e.oauthProvider&&o_(e.id,e.oauthProvider)?e.id:void 0}function wT({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,oauthDeviceCode:o,oauthInstructions:s,oauthBrowserLaunch:c,manualCode:l,manualCodeBusy:u,manualCodeMsg:d,manualCodeOk:f,ownerLoggedIn:p=!1,saving:m=!1,error:h=``,onRequestLogin:g,onUseExistingLogin:_,onCancelLogin:v,onUseApiKeyInstead:y,onManualCodeChange:x,onSubmitManualCode:S,onBack:C}){let w=b(),T=CT(e),E=T?l_(e.oauthProvider):e.label,D=T!==void 0&&p&&_!==void 0;return(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,Q.jsx)(`div`,{className:`muted text-control`,children:e.note??w(`modal.oauthDefaultNote`)}),T&&(0,Q.jsx)(`div`,{className:`muted text-control`,children:w(`modal.sharedLoginNote`,{label:e.label,provider:E})}),D?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:_,disabled:m||n,style:{width:`100%`,padding:`12px 16px`},children:[(0,Q.jsx)(_t,{}),w(`modal.addWithExistingLogin`,{label:e.label,provider:E})]}):t.includes(e.oauthProvider??``)?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>g(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,Q.jsx)(_t,{}),n?w(`modal.waitingBrowser`):w(`modal.logInWith`,{label:E})]}),!n&&(0,Q.jsx)(Hb,{})]}):(0,Q.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:w(`modal.oauthComingSoon`,{label:e.label})}),h&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h}),r&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,Q.jsx)(H_,{hint:{url:a,deviceCode:o,instructions:s,browserLaunch:c},paste:{value:l,busy:u,disabled:!e.oauthProvider,message:d,ok:f,onChange:x,onSubmit:()=>{e.oauthProvider&&S(e.oauthProvider)}}}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:y,children:w(`modal.useApiKeyInstead`)}),(0,Q.jsx)(`div`,{style:{flex:1}}),n&&e.oauthProvider&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>v(e.oauthProvider),children:w(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:C,children:w(`modal.back`)})]})]})}function TT({label:e,children:t}){return(0,Q.jsxs)(`label`,{style:{display:`block`},children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),t]})}var ET=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`];function DT(e){return e&&!ET.includes(e)?[e,...ET]:ET}function OT({preset:e,form:t,endpointChoice:n,error:r,saving:i,dup:a,isCustom:o,isLocal:s,isReservedForward:c,presetDescription:l,onFormChange:u,onEndpointChoiceChange:d,onSubmit:f,onUseOauthLogin:p,onBack:m}){let h=b(),g=Ye(t);return(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,Q.jsxs)(`details`,{className:`setup-guide`,children:[(0,Q.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,Q.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,Q.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,Q.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,Q.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,Q.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,Q.jsx)(TT,{label:h(`modal.providerName`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(TT,{label:h(`modal.adapter`),children:(0,Q.jsx)(Vn,{fullWidth:!0,label:h(`modal.adapter`),value:t.adapter,onChange:e=>u({...t,adapter:e}),options:DT(t.adapter).map(e=>({value:e,label:e}))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(TT,{label:h(`modal.endpoint`),children:(0,Q.jsx)(Vn,{fullWidth:!0,label:h(`modal.endpoint`),value:n,onChange:n=>{d(n),u({...t,baseUrl:XS(e.baseUrlChoices,n,t.baseUrl)})},options:e.baseUrlChoices.map(e=>({value:e.id,label:e.id===`token-plan`?h(`modal.endpoint.tokenPlan`):e.id===`payg`?h(`modal.endpoint.payAsYouGo`):e.id===`custom`?h(`modal.endpoint.custom`):e.label}))})}),n===`custom`&&(0,Q.jsx)(TT,{label:h(`modal.baseUrl`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,Q.jsx)(TT,{label:h(`modal.baseUrl`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,Q.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,Q.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,Q.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),o&&kh(t)&&(0,Q.jsx)(uC,{checked:t.preserveResponsesReasoningContent===!0,onChange:e=>u({...t,preserveResponsesReasoningContent:e})}),t.authMode===`forward`?(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,Q.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):g?(0,Q.jsxs)(`div`,{role:`note`,"data-subscription-cli-warning":``,className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,Q.jsx)(`strong`,{children:h(`modal.subscriptionCliTitle`)}),(0,Q.jsx)(`div`,{style:{marginTop:4},children:(0,Q.jsx)(z,{k:`modal.subscriptionCliWarning`,cmd:`claude -p`,vars:{apiProvider:Ze}})})]}):e.keyOptional?(0,Q.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,Q.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,Q.jsxs)(Q.Fragment,{children:[e.dashboardUrl&&(0,Q.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,Q.jsx)(fe,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,Q.jsx)(dt,{style:{width:13,height:13}})]}),(0,Q.jsx)(TT,{label:h(`modal.apiKey`),children:(0,Q.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>u({...t,apiKey:e.target.value}),placeholder:h(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,Q.jsx)(TT,{label:h(`modal.apiKeyTransport`),children:(0,Q.jsx)(Vn,{fullWidth:!0,label:h(`modal.apiKeyTransport`),value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e===`bearer`?`bearer`:void 0}),options:[{value:`x-api-key`,label:h(`modal.apiKeyTransportNative`)},{value:`bearer`,label:h(`modal.apiKeyTransportBearer`)}]})})]}),e.id===`google-vertex`&&t.adapter===`google`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-hint`,style:{margin:0},children:h(`modal.vertexAdcHint`)}),(0,Q.jsx)(`p`,{className:`muted text-hint`,style:{margin:0},children:h(`modal.vertexStaticHint`)}),(0,Q.jsx)(TT,{label:h(`modal.vertexProject`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.project??``,onChange:e=>u({...t,project:e.target.value})})}),(0,Q.jsx)(TT,{label:h(`modal.vertexLocation`),children:(0,Q.jsx)(`input`,{className:`input`,"aria-label":h(`modal.vertexLocation`),value:t.location??``,onChange:e=>u({...t,location:e.target.value}),placeholder:`us-central1`})})]}),!c&&(0,Q.jsx)(TT,{label:h(`modal.defaultModel`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,Q.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,Q.jsx)(`div`,{style:{flex:1}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var kT=2e3;function AT({apiBase:e,targetKey:t,t:n,aliveRef:r,onAdded:a}){let o=(0,Z.useRef)(new Map),s=(0,Z.useRef)(0),c=Y_(e,t),l=(0,Z.useRef)(new Map),u=(0,Z.useRef)(new Map),d=(0,Z.useRef)(new Map),f=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{f.current=t},[t]),(0,Z.useEffect)(()=>{let e=[...l.current],t=[...u.current];l.current.clear(),u.current.clear(),d.current.clear(),o.current.clear();for(let[t,n]of e)n.setOauthBusy(!1),n.setOauthUrl(``,t),n.setOauthMsg(``);for(let[e,n]of t)oS(n,e)},[t]);let p=(0,Z.useCallback)(e=>{let t=++s.current;return o.current.set(e,t),t},[]),m=(0,Z.useCallback)((e,t)=>oS(e,t),[]);return(0,Z.useEffect)(()=>{let e=e=>{let t=[...l.current],n=new Map(u.current);l.current.clear(),u.current.clear();for(let[e,t]of n)d.current.set(e,t);for(let[r,i]of t){p(r),e&&(i.setOauthBusy(!1),i.setOauthUrl(``,r),i.setOauthMsg(``));let t=n.get(r);t&&m(t,r)}},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[p,m]),{cancelLoginOAuth:(0,Z.useCallback)(async(e,t,i=e)=>{let a=p(e),s=u.current.get(e);l.current.delete(e),u.current.delete(e),s&&d.current.set(e,s),s&&await m(s,e),r.current&&o.current.get(e)===a&&(t.setOauthBusy(!1),t.setOauthUrl(``,e),t.setOauthMsgTone(`warn`),t.setOauthMsg(n(`prov.loginCancelled`,{provider:i})))},[r,p,m,n]),loginOAuth:(0,Z.useCallback)(async(s,h,g=!1,_)=>{let y={...c};u.current.set(s,y),d.current.delete(s);let{setOauthBusy:b,setOauthMsg:x,setOauthMsgTone:S,setOauthUrl:C,setManualCode:w,setManualCodeMsg:T,setManualCodeOk:E}=h,D=p(s),O=()=>o.current.get(s)===D&&(t===void 0||f.current===t)&&v(y),k=()=>{l.current.get(s)===h&&l.current.delete(s)};l.current.set(s,h),b(!0),x(``),S(`ok`),C(``,s),w(``),T(``),E(!0);try{let t=await sS(y,s,()=>{if(r.current&&O())return i(y,`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:s,..._?{row:_}:{},...K_(),...IS(s,g)})})});if(!t||!r.current||!O())return;if(!t.ok){k();let e=await t.json().catch(()=>({}));if(!r.current||!O())return;S(`warn`),x(e.error===`target_changed`?n(`prov.targetChanged`):e.error===`unknown oauth provider`?n(`modal.oauthComingSoonShort`):e.error||n(`modal.loginFailStart`));return}let o=await t.json();if(!r.current||!O())return;C(o.url??``,s,o.deviceCode,o.instructions,J_(o.browserLaunch)),o.url||o.deviceCode?x(n(`modal.waitingLogin`)):x(o.instructions||n(`modal.loggingIn`));let c=!!o.deviceCode;for(let t=0;t<cT(c,kT,150);t++){if(await new Promise(e=>setTimeout(e,kT)),!r.current||!O())return;let t=await i(y,`${e}/api/oauth/status?provider=${s}`).catch(()=>null),o=t?await Xn(t):null;if(!r.current||!O())return;if(o?.error){k(),S(`warn`),x(o.error===`target_changed`?n(`prov.targetChanged`):n(`modal.loginError`,{error:o.error}));return}if(o?.loggedIn&&o.status!==`pending`){k(),x(``),a(_??s);return}let l=o?.hint;l&&(l.deviceCode&&(c=!0),C(l.url??``,s,l.deviceCode,l.instructions),x(l.url||l.deviceCode?n(`modal.waitingLogin`):l.instructions||n(`modal.loggingIn`)))}if(await m(y,s),!r.current||!O())return;k(),S(`warn`),x(n(`modal.loginTimeout`))}catch{O()&&await m(y,s),O()&&k(),r.current&&O()&&(S(`warn`),x(n(`modal.networkError`)))}finally{u.current.get(s)===y&&(u.current.delete(s),d.current.set(s,y)),r.current&&O()?(b(!1),C(``,s)):r.current&&o.current.get(s)===D&&(t===void 0||f.current===t)&&(k(),b(!1),C(``,s),S(`warn`),x(n(`prov.targetChanged`)))}},[r,e,p,m,a,c,n,t]),submitManualCode:(0,Z.useCallback)(async(t,a,o,s,c)=>{let l=a.trim();if(!l||o)return;let{setManualCodeBusy:f,setManualCode:p,setManualCodeOk:m,setManualCodeMsg:h}=s;f(!0),h(``);let g=c?c.active(t):u.current.get(t);if(g)try{let a=await i(g,`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,input:l})});if(!r.current)return;if(!v(g)){m(!1),h(n(`prov.targetChanged`));return}if(!a.ok){let e=await a.json().catch(()=>({}));m(!1),h(e.error===`target_changed`?n(`prov.targetChanged`):n(`prov.pasteFail`,{error:e.error||a.statusText}));return}p(``),m(!0),h(n(`prov.pasteOk`))}catch{r.current&&(m(!1),h(n(`modal.networkError`)))}finally{r.current&&f(!1)}else{let e=c?c.ended(t):d.current.get(t);f(!1),m(!1),h(e&&v(e)?n(`prov.loginExpired`):n(`prov.targetChanged`))}},[r,e,n])}}function jT(e,t){return{preset:e?{id:`custom`,label:t,adapter:`openai-chat`,baseUrl:``,auth:`key`}:null,form:e?{name:``,adapter:`openai-chat`,baseUrl:``,authMode:`key`,apiKey:``,apiKeyTransport:void 0,defaultModel:``,allowPrivateNetwork:!1}:null,saving:!1,error:``,oauthBusy:!1,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,manualCode:``,manualCodeBusy:!1,manualCodeMsg:``,manualCodeOk:!0,endpointChoice:`custom`,oauthTosPending:null}}function MT(e,t){switch(t.type){case`choose-preset`:return{...e,preset:t.preset,form:t.form,endpointChoice:t.endpointChoice,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthBrowserLaunch:void 0,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`back`:return{...e,preset:null,form:null,endpointChoice:`custom`,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthBrowserLaunch:void 0,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`set-form`:return{...e,form:t.form};case`set-endpoint-choice`:return{...e,endpointChoice:t.choice};case`set-saving`:return{...e,saving:t.saving};case`set-error`:return{...e,error:t.error};case`set-oauth-busy`:return{...e,oauthBusy:t.busy};case`set-oauth-msg`:return{...e,oauthMsg:t.msg,oauthMsgTone:t.tone??e.oauthMsgTone};case`set-oauth-tone`:return{...e,oauthMsgTone:t.tone};case`set-oauth-url`:return e.preset?.oauthProvider===t.providerId?{...e,oauthUrl:t.url,oauthDeviceCode:t.deviceCode??``,oauthInstructions:t.instructions??``,oauthUrlProvider:t.providerId,oauthBrowserLaunch:t.url?t.browserLaunch??(e.oauthUrlProvider===t.providerId?e.oauthBrowserLaunch:void 0):void 0}:e;case`set-manual-code`:return{...e,manualCode:t.code};case`set-manual-code-busy`:return{...e,manualCodeBusy:t.busy};case`set-manual-code-msg`:return{...e,manualCodeMsg:t.msg,manualCodeOk:t.ok??e.manualCodeOk};case`set-oauth-tos-pending`:return{...e,oauthTosPending:t.providerId};case`use-oauth-login`:return{...e,form:t.form,error:``,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthBrowserLaunch:void 0,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthBrowserLaunch:void 0,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function NT({apiBase:e,targetKey:t,existingNames:n,onClose:r,onAdded:a,initialTier:o,initialCustom:s=!1,accountRows:c,accountStatus:l,accountBusy:u,accountLoginHint:d=null,accountLoginCaptures:f,onAccountLogin:p,onAccountCancelLogin:m,onAccountLogout:h,onAccountManage:g,onOpen:_}){let y=b(),x=(0,Z.useMemo)(()=>[{id:`custom`,label:y(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[y]),[S,C]=(0,Z.useReducer)(MT,s,e=>jT(e,y(`modal.customProvider`))),[w]=(0,Z.useState)(()=>V(`shared`,e)),T=t&&t.trim()?t:void 0,E=T??w.targetKey,D=(0,Z.useRef)(!0),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(``),P=bn(`add-provider-oauth:${T??e}`,[e,T],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),F=bn(`add-provider-presets:${T??e}`,[e,T],async t=>{let n=await fetch(`${e}/api/provider-presets`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Array.isArray(r.providers)&&r.providers.length>0?r.providers:null}),I=bn(ti(e,`all`,T),[e,T],async t=>await ei(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4}),L=P.data??[],R=F.data??x,z=F.loading,B=Object.fromEntries((I.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:H,form:U,saving:W,error:ee,oauthBusy:G,oauthMsg:te,oauthMsgTone:ne,oauthUrl:K,oauthUrlProvider:q,oauthDeviceCode:J,oauthInstructions:re,oauthBrowserLaunch:Y,manualCode:ie,manualCodeBusy:ae,manualCodeMsg:oe,manualCodeOk:se,endpointChoice:ce,oauthTosPending:le}=S;(0,Z.useEffect)(()=>{D.current=!0,O.current=document.activeElement,_?.();let e=k.current;if(e){let t=e.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);t&&t.focus()}return()=>{D.current=!1,O.current?.focus()}},[]),(0,Z.useEffect)(()=>{let e=e=>{let t=!le&&!A;e.key===`Escape`&&t&&(M?N(``):r())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,le,A,M]);let ue=e=>{let t=iC(e);return t?y(t):e.note},de=e=>{let t=ZS(e.baseUrlChoices,e.baseUrl);C({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?XS(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,...e.id===`google-vertex`?{googleMode:`vertex`,project:``,location:``}:{},allowPrivateNetwork:!1}})},fe=async(t=!1)=>{if(!U)return;if(E!==w.targetKey){C({type:`set-error`,error:y(`prov.targetChanged`)});return}let n=H?rC(H):!1,r=H?.baseUrlChoices?.length?QS(H.baseUrlChoices,ce,U.baseUrl):U.baseUrl.trim();if(!n&&!U.name.trim()){C({type:`set-error`,error:y(`modal.nameRequired`)});return}if(!n&&!r){C({type:`set-error`,error:y(`modal.baseUrlRequired`)});return}if(!n&&/\{[^}]*\}/.test(r)){C({type:`set-error`,error:y(`modal.baseUrlPlaceholderError`)});return}let o={...U,baseUrl:r},s;try{s=oC(H??{id:`custom`},o),t&&(s.provider.authMode=`oauth`)}catch{C({type:`set-error`,error:y(`modal.invalidPreset`)});return}C({type:`set-saving`,saving:!0}),C({type:`set-error`,error:``});try{let t=await i(w,`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s)});if(!t.ok){let e=await t.json().catch(()=>({}));C({type:`set-error`,error:e.error===`target_changed`?y(`prov.targetChanged`):e.error||y(`modal.failedStatus`,{status:t.status})});return}if(!v(w)){C({type:`set-error`,error:y(`prov.targetChanged`)});return}a(s.name)}catch{C({type:`set-error`,error:y(`modal.networkError`)})}finally{C({type:`set-saving`,saving:!1})}},{cancelLoginOAuth:pe,loginOAuth:me,submitManualCode:he}=AT({apiBase:e,targetKey:T,t:y,aliveRef:D,onAdded:a}),ge={setOauthBusy:e=>C({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>C({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>C({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t,n,r,i)=>C({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r,browserLaunch:i}),setManualCode:e=>C({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>C({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>C({type:`set-manual-code-msg`,msg:oe,ok:e})},_e=U?n.includes(U.name.trim())&&U.name.trim()!==``:!1,ve=H?CT(H):void 0,ye=e=>{G||(MS(e)?C({type:`set-oauth-tos-pending`,providerId:e}):me(e,ge,!1,ve))},be=d?[d.provider,d.url??``,d.deviceCode??``].join(`\0`):``;(0,Z.useEffect)(()=>{C({type:`set-manual-code`,code:``}),C({type:`set-manual-code-msg`,msg:``,ok:!0})},[be,e,T]);let xe=(e,t)=>{he(e,ie,ae,{setManualCodeBusy:e=>C({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>C({type:`set-manual-code`,code:e}),setManualCodeOk:e=>C({type:`set-manual-code-msg`,msg:oe,ok:e}),setManualCodeMsg:e=>C({type:`set-manual-code-msg`,msg:e})},t)},Se=H?.id===`custom`,Ce=U?.authMode===`local`,we=H?rC(H):!1;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":y(`modal.add`),className:`modal-overlay`,children:(0,Q.jsxs)(`div`,{ref:k,className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:H?y(`modal.addNamed`,{label:H.label}):y(`modal.add`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":y(`common.close`),onClick:r,children:(0,Q.jsx)(Ie,{})})]}),!H&&(0,Q.jsx)(ni,{data:I.data}),H?U&&(H.auth===`oauth`&&U.authMode===`oauth`?(0,Q.jsx)(wT,{preset:H,oauthSupported:L,oauthBusy:G,oauthMsg:te,oauthMsgTone:ne,oauthUrl:q===H.oauthProvider?K:``,oauthDeviceCode:q===H.oauthProvider?J:``,oauthInstructions:q===H.oauthProvider?re:``,oauthBrowserLaunch:q===H.oauthProvider?Y:void 0,manualCode:ie,manualCodeBusy:ae,manualCodeMsg:oe,manualCodeOk:se,ownerLoggedIn:ve!==void 0&&l?.[H.oauthProvider??``]?.loggedIn===!0,saving:W,error:ee,onRequestLogin:ye,onUseExistingLogin:()=>{fe(!0)},onCancelLogin:e=>{pe(e,ge,H.label)},onUseApiKeyInstead:()=>{G&&H.oauthProvider&&pe(H.oauthProvider,ge,H.label),C({type:`use-api-key-instead`,form:{...U,authMode:`key`}})},onManualCodeChange:e=>C({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{xe(e)},onBack:()=>{G&&H.oauthProvider&&pe(H.oauthProvider,ge,H.label),C({type:`back`})}}):(0,Q.jsx)(OT,{preset:H,form:U,endpointChoice:ce,error:ee,saving:W,dup:_e,isCustom:Se,isLocal:Ce,isReservedForward:we,presetDescription:ue,onFormChange:e=>C({type:`set-form`,form:e}),onEndpointChoiceChange:e=>C({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{fe()},onUseOauthLogin:()=>C({type:`use-oauth-login`,form:{...U,authMode:`oauth`}}),onBack:()=>C({type:`back`})})):(0,Q.jsx)(xT,{presets:R,usageRank:B,presetsLoading:z,initialTier:o,query:M,onQueryChange:N,onSelectPreset:e=>de(e),onSelectCustom:()=>de(x[0]),onShowNote:e=>j(e),accountRows:c,accountStatus:l,busyProvider:u,onLogin:p,onCancelLogin:m,onLogout:h,onManage:g,loginHint:d,paste:{value:ie,busy:ae,message:oe,ok:se,onChange:e=>C({type:`set-manual-code`,code:e}),onSubmit:e=>{xe(e,f)}}})]})}),le&&(0,Q.jsx)(LS,{providerId:le,providerLabel:H?.label??le,onCancel:()=>C({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=le;e&&(C({type:`set-oauth-tos-pending`,providerId:null}),me(e,ge,!0,ve))}},le),A?.note&&(0,Q.jsx)(ST,{providerId:A.id,label:A.label,adapter:A.adapter,note:A.note,onClose:()=>j(null)},A.id)]})}function PT({apiBase:e,targetKey:t,config:n,adding:r,modelsNotice:i,addIntent:a,busy:o,addModalAccountRows:s,accountLoginStatus:c,accountLoginHint:l,accountLoginCaptures:u,removeConfirmName:d,removeDefaultProvider:f,codexLoginOpen:p,jsonLeaveOpen:m,jsonSaving:h,oauthTosPending:g,onCloseAdd:_,onAdded:v,onAccountLogin:y,onAccountCancelLogin:b,onAccountLogout:x,onAccountManage:S,onOpenAdd:C,onCloseCodexLogin:w,onCodexAdded:T,onCancelRemove:E,onConfirmRemove:D,onCancelJsonLeave:O,onDiscardJson:k,onSaveJson:A,onCancelOauthTos:j,onContinueOauthTos:M}){let N=t??e,P=(0,Z.useRef)(N);return(0,Z.useEffect)(()=>{P.current!==N&&(P.current=N,w())},[N,w]),(0,Q.jsxs)(Q.Fragment,{children:[i&&(0,Q.jsx)(Fb,{...i}),r&&(0,Q.jsx)(NT,{apiBase:e,targetKey:t,existingNames:Object.keys(n.providers),initialTier:a?.tier,initialCustom:a?.custom,onClose:_,onAdded:v,accountRows:s,accountStatus:c,accountBusy:o,accountLoginHint:l??null,accountLoginCaptures:u,onAccountLogin:y,onAccountCancelLogin:b,onAccountLogout:x,onAccountManage:S,onOpen:C}),p&&(0,Q.jsx)(ev,{apiBase:e,targetKey:t,onClose:w,onAdded:T}),d&&(0,Q.jsx)(Ew,{providerName:d,defaultProviderName:f,onCancel:E,onConfirm:D}),m&&O&&k&&A&&(0,Q.jsx)(Dw,{saving:h??!1,onCancel:O,onDiscard:k,onSave:A}),g&&(0,Q.jsx)(LS,{providerId:g.provider,providerLabel:l_(g.provider),onCancel:j,onContinue:M},`${g.provider}:${g.addAccount?`add`:`login`}`)]})}function FT(e,t,n){return[...tC(e.providers).map(e=>({id:e,label:re(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:l_(e),kind:`oauth`}))]}function IT(e,t){let n={...t},r=t.openai;if(r)for(let[t,i]of Object.entries(e.providers))i.authMode===`forward`&&(n[t]=r);for(let[t,r]of Object.entries(n)){if(!fg(t)||!pg(t,e.providers[t]))continue;let i={...r};delete i.email,n[t]=i}return n}function LT(e,t){let[n,r]=(0,Z.useState)({apiBase:e,notice:null});n.apiBase!==e&&r({apiBase:e,notice:null});let i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{i.current=null},[e]);let a=(0,Z.useCallback)((t,n,a=!1)=>{let o=typeof t==`string`?[t]:t,s={provider:o.join(`, `),providers:o,apiBase:e,initialRegistration:n&&o.length===1,catalogRefreshPending:a};i.current=s,r({apiBase:e,notice:{context:s,loading:!0,failed:!1}})},[e]),o=(0,Z.useCallback)(()=>{i.current=null,r(e=>({...e,notice:null}))},[]),s=(0,Z.useCallback)(n=>{let a=i.current;a&&a.apiBase===e&&t().then(async e=>{e===`superseded`&&i.current===a&&(e=await t()),i.current===a&&r(t=>t.apiBase===a.apiBase?{...t,notice:{context:a,loading:!1,failed:!n||e!==`applied`}}:t)}).catch(()=>{i.current===a&&r(e=>e.apiBase===a.apiBase?{...e,notice:{context:a,loading:!1,failed:!0}}:e)})},[e,t]);return{notice:n.apiBase===e?n.notice:null,open:a,close:o,modelsSettled:s}}var RT=new Set([`home`,`setup`,`advanced`,`dashboard`,`startup`,`providers`,`models`,`subagents`,`advisor`,`logs`,`usage`,`storage`,`remote`,`remote-workspace`,`codex-set`,`integrations`,`claude`]);function zT(e){let t=wn(Cn(e??(typeof window<`u`?window.location.hash:``))).path,n=t.split(`/`)[0];return n===`debug`?`logs`:n===`codex-auth`?`codex-set`:n===`combos`||n===`routing`||n===`lab`?`models`:n===`api`||n===`grok`?`integrations`:t===`integrations/claude`||t===`integrations/claude/desktop`?`claude`:t===`claude/account`?`providers`:RT.has(n)?n:`home`}function BT(e){let t=Cn(e);return XT(t).replaceTo??t}var VT=[`dashboard/providers`,`dashboard/models`],HT=[`models/combos`,`models/routing`,`models/compatibility`],UT=`models/combos/jev-auto`;function WT(e){let t=e?.trim();return t&&t!==`jev`?`${UT}?${new URLSearchParams({decisionProvider:t})}`:UT}function GT(e){let{path:t,query:n}=wn(Cn(e));if(t!==`models/combos/jev-auto`)return;let r=new URLSearchParams(n).get(`decisionProvider`)?.trim();return r&&r!==`jev`?r:null}var KT=`integrations/keys.integrations/codex.integrations/claude.integrations/claude/desktop.integrations/grok.integrations/cursor.integrations/opencode.integrations/pi.integrations/gentle-shell.integrations/omp.integrations/hermes.integrations/openclaw.integrations/kimi.integrations/gajae.integrations/dsh.integrations/mcode.integrations/zcode.integrations/commandcode.integrations/prime.integrations/aside.integrations/raycast.integrations/omo.integrations/cline.integrations/kilo.integrations/droid.integrations/qoder.integrations/qoder-cn.integrations/workbuddy.integrations/workbuddy-ai.integrations/t3code`.split(`.`),qT=[`providers`,`models/compatibility`,UT],JT=`providers?provider=anthropic&tab=accounts`;function YT(e,t){return e===t||t===`claude`&&[`claude/code`,`claude/desktop`].includes(e)||t===`logs`&&e===`logs/debug`||t===`startup`&&e===`startup/desktop`||t===`usage`&&e===`usage/companion`||t===`codex-set`&&(e===`codex-set/prompt`||e===`codex-set/desktop`||e===`codex-set/cli`)||t===`models`&&(HT.includes(e)||e===`models/combos/jev-auto`)||t===`dashboard`&&(e===`dashboard/update`||VT.includes(e))||t===`integrations`&&KT.includes(e)}function XT(e){let{path:t,query:n}=wn(e);if(n||t!==e){let e=XT(t);return e.replaceTo===null&&qT.includes(t)?e:{page:e.page,replaceTo:e.replaceTo??t}}let r=zT(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`codex-auth`||e.startsWith(`codex-auth/`)?{page:`codex-set`,replaceTo:`codex-set`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`integrations/claude`?{page:`claude`,replaceTo:`claude/code`}:e===`integrations/claude/desktop`?{page:`claude`,replaceTo:`claude/desktop`}:e===`claude/account`?{page:`providers`,replaceTo:JT}:e===`claude/settings`?{page:`claude`,replaceTo:`claude/code`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:YT(e,r)?{page:r,replaceTo:null}:{page:r,replaceTo:r}}var ZT=`models/compatibility`,QT=`providers`,$T=200,eE={inbound:``,upstream:``};function tE(e){return e!==void 0&&CC(e)?e:``}function nE(e){let t=new URLSearchParams;e.inbound&&t.set(`inbound`,e.inbound),e.upstream&&t.set(`upstream`,e.upstream);let n=t.toString();return n?`${ZT}?${n}`:ZT}function rE(e,t){let n=wn(BT(e));return n.path===t?new URLSearchParams(n.query):null}function iE(e=window.location.hash){let t=rE(e,ZT);if(!t)return null;let n=t.get(`inbound`),r=t.get(`upstream`);return{inbound:CC(n)?n:``,upstream:CC(r)?r:``}}function aE(e){return`${QT}?${new URLSearchParams({provider:e}).toString()}`}function oE(e){return`${QT}?${new URLSearchParams({provider:e,tab:`accounts`}).toString()}`}function sE(e=window.location.hash){return rE(e,`providers`)?.get(`tab`)===`accounts`?`accounts`:`settings`}function cE(e){return`${QT}?${new URLSearchParams({provider:e,focus:`account-mode`}).toString()}`}function lE(e=window.location.hash){return rE(e,`providers`)?.get(`focus`)===`account-mode`?`account-mode`:null}function uE(e=window.location.hash){let t=rE(e,`providers`)?.get(`provider`)?.trim()??``;return t&&t.length<=$T?t:null}function dE(e){En(nE(e))}function fE(e){En(aE(e))}function pE(e,t=window){let n=oE(e);Cn(t.location.hash)===n?t.dispatchEvent(new t.Event(`hashchange`)):En(n,t)}function mE(e,t=window){let n=cE(e);Cn(t.location.hash)===n?t.dispatchEvent(new t.Event(`hashchange`)):En(n,t)}function hE(e,t,n,r){let[i,a]=(0,Z.useState)(()=>({name:uE(),tab:sE(),field:lE(),seq:0})),[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(t);if((0,Z.useEffect)(()=>{let e=()=>a(e=>({name:uE(),tab:sE(),field:lE(),seq:e.seq+1}));return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),i.name&&o?.seq!==i.seq&&e?.includes(i.name)){let e=i.tab===`accounts`?r:void 0;s({seq:i.seq,provider:i.name,tab:e?`accounts`:`settings`,field:e?null:i.field}),e?e(i.name):n(i.name)}return(0,Z.useEffect)(()=>{let e=c.current;if(c.current=t,e===t)return;let n=uE();n&&o?.seq===i.seq&&i.name===n&&(t===null?e===n:t!==n)&&Tn(QT)},[o,i,t]),o?.tab===`settings`?{token:o.seq+1,provider:o.provider,field:o.field}:{token:0,provider:null,field:null}}function gE(e){let[t,n]=(0,Z.useState)({epoch:0,force:!1}),r=(0,Z.useRef)(0),i=(0,Z.useRef)(!0),a=(0,Z.useRef)(new Map),o=(0,Z.useCallback)(()=>{for(let e of a.current.values())e.resolve(!1);a.current.clear()},[]);(0,Z.useEffect)(()=>(i.current=!0,()=>{i.current=!1,o()}),[e,o]);let s=(0,Z.useCallback)((e=!1)=>{o();let t=++r.current;return i.current&&n({epoch:t,force:e}),t},[o]),c=(0,Z.useCallback)((e,t,n)=>{let r=a.current.get(e);r&&i.current&&(r[t]=n,r.accounts!==void 0&&r.report!==void 0&&(a.current.delete(e),r.resolve(r.accounts&&r.report)))},[]);return{quotaRefresh:t,invalidateProviderQuotas:s,settleQuotaRefresh:(0,Z.useCallback)((e,t)=>c(t,`report`,e),[c]),beginQuotaRefresh:(0,Z.useCallback)(e=>{if(!i.current)return Promise.resolve(!1);let t=s(!0),n=new Promise(n=>{a.current.set(t,{resolve:n,accounts:!e||void 0})});return e&&Promise.resolve().then(e).then(e=>c(t,`accounts`,e),()=>c(t,`accounts`,!1)),n},[c,s])}}function _E(e,t,n){let r=(0,Z.useRef)(n);(0,Z.useLayoutEffect)(()=>{r.current=n});let i=(0,Z.useRef)(()=>{});return(0,Z.useEffect)(()=>{if(!t)return;let n=!1,a=null,o=250,s=null,c=()=>{a!==null&&window.clearTimeout(a),a=null},l=e=>{e.controller.abort(),e.reader?.cancel().catch(()=>{})},u=()=>{if(n||s)return;c();let t={controller:new AbortController,lastActivity:Date.now()};s=t,(async()=>{try{let i=await fetch(`${e}/api/accounts/events`,{signal:t.controller.signal,credentials:`same-origin`,headers:{Accept:`text/event-stream`}});if(!i.ok||!i.headers.get(`content-type`)?.includes(`text/event-stream`)||!i.body)throw Error(`Account selection stream unavailable`);if(n||t.controller.signal.aborted){await i.body.cancel();return}let a=i.body.getReader();t.reader=a,t.openedAt=Date.now();let o=new TextDecoder,s=new Map,c=new Map,l=!1,u=!1,d=()=>{u||(u=!0,Promise.resolve().then(async()=>{if(u=!1,n||t.controller.signal.aborted)return;let e=l?[void 0]:[...c.values()];l=!1,c.clear(),await Promise.all(e.map(e=>r.current(e)))}).catch(()=>{}))},f=``,p=``,m=[],h=0,g=()=>{let e;try{e=JSON.parse(m.join(`
6
- `))}catch{return}if(!(!e||typeof e!=`object`||typeof e.revision!=`number`||!Number.isSafeInteger(e.revision)||e.revision<0)){if(p===`ready`)s.clear(),l=!0,d();else if(p===`account-selection`&&typeof e.provider==`string`&&e.provider&&(e.kind===`oauth`||e.kind===`api-key`)){let t=`${e.kind}:${e.provider}`;if(e.revision<=(s.get(t)??-1))return;if(s.set(t,e.revision),c.set(t,{provider:e.provider,kind:e.kind}),e.kind===`oauth`){let t=a_(e.provider);for(let n of[t,...s_(t)])n!==e.provider&&c.set(`${e.kind}:${n}`,{provider:n,kind:e.kind})}d()}}};for(;!n&&!t.controller.signal.aborted;){let e=await a.read();if(e.done)break;t.lastActivity=Date.now(),f+=o.decode(e.value,{stream:!0});let n;for(;(n=f.indexOf(`
7
- `))!==-1;){let e=f.slice(0,n).replace(/\r$/,``);if(f=f.slice(n+1),h+=e.length,h>16384)throw Error(`Account selection event too large`);e?e.startsWith(`event:`)?p=e.slice(6).replace(/^ /,``):e.startsWith(`data:`)&&m.push(e.slice(5).replace(/^ /,``)):(g(),p=``,m=[],h=0)}if(f.length+h>16384)throw Error(`Account selection event too large`)}}catch{}finally{if(l(t),s===t&&(s=null,!n)){t.openedAt!==void 0&&Date.now()-t.openedAt>=1e4&&(o=250);let e=o;o=Math.min(o*2,5e3),a=window.setTimeout(()=>{a=null,u()},e)}}})()};return i.current=()=>{s&&Date.now()-s.lastActivity>6e4&&(l(s),s=null),u()},u(),()=>{n=!0,i.current=()=>{},c(),s&&l(s)}},[e,t]),(0,Z.useCallback)(()=>i.current(),[])}function vE({apiBase:e,targetKey:t,targetLabel:n}){let r=b(),i=t??e,a=n??Jh(i),o=(0,Z.useMemo)(()=>({apiBase:e,targetKey:i}),[e,i]),s=`ocx.providers.config.v1:${encodeURIComponent(i)}`,c=(0,Z.useMemo)(()=>sf(s),[s]),[l,u]=(0,Z.useState)(()=>({target:o,config:c})),d=l.target===o?l.config:c,f=(0,Z.useRef)(o);(0,Z.useLayoutEffect)(()=>{f.current=o},[o]);let p=(0,Z.useCallback)(e=>{f.current===o&&u(t=>{let n=t.target===o?t.config:c;return{target:o,config:typeof e==`function`?e(n):e}})},[c,o]),m=(0,Z.useMemo)(()=>Ah(),[]),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(``),[y,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(`err`),[w,T]=(0,Z.useState)(0),{oauthProviders:E,setOauthProviders:D,oauthStatus:O,setOauthStatus:k}=Hm(e,i),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(null),[B,V]=(0,Z.useState)(i);B!==i&&(V(i),z(null));let[H,U]=(0,Z.useState)(!1),[W,ee]=(0,Z.useState)(0),[G,te]=(0,Z.useState)(null),[ne,K]=(0,Z.useState)({token:0,provider:null}),q=(0,Z.useRef)(!0),J=(0,Z.useRef)(null),re=(0,Z.useRef)(!1),Y=(0,Z.useCallback)((e,t=!0,n)=>{v(e),x(t),C(n??(t?`ok`:`err`)),T(e=>e+1)},[]),ie=(0,Z.useCallback)(()=>{v(``),x(!1),C(`err`)},[]);oT(i,()=>Y(r(`prov.legacyTargetPreflight`),!1,`warn`));let ae=(0,Z.useCallback)(e=>{e.validationPending||e.catalogRefreshPending?(v(r(e.validationPending?`pws.healthLabel.validationPending`:`codexAuth.catalogRefreshPending`)),x(!1),C(`warn`),T(e=>e+1)):Y(r(`codexAuth.accountAdded`),!0)},[Y,r]);(0,Z.useEffect)(()=>(q.current=!0,()=>{q.current=!1}),[]),(0,Z.useEffect)(()=>{if(!_||!y)return;let e=window.setTimeout(ie,4500);return()=>window.clearTimeout(e)},[_,y,w,ie]);let oe=(0,Z.useCallback)(e=>{g(!1),L(null),F(e),K(t=>({token:t.token+1,provider:e}))},[]),se=hE(d?Object.keys(d.providers):null,P,F,oe),ce=bn(`add-provider-presets:${i}`,[e,i],async t=>{let n=await fetch(`${e}/api/provider-presets`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Array.isArray(r.providers)&&r.providers.length>0?r.providers:null});bn(ti(e,`all`,i),[e],async t=>await ei(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4});let{quotaRefresh:le,invalidateProviderQuotas:ue,settleQuotaRefresh:de,beginQuotaRefresh:fe}=gE(e),{fetchConfig:pe,fetchOauth:me,fetchProviderQuotas:he,invalidateOauthStatusReads:ge,captureOauthStatusRead:ve}=pT({apiBase:e,targetKey:i,t:r,setConfig:p,setOauthProviders:D,setOauthStatus:k,notify:Y,invalidateProviderQuotas:ue,configCacheKey:s}),ye=(0,Z.useCallback)(async()=>{await pe()},[pe]),be=LT(e,pe),xe=be.open,Se=(0,Z.useCallback)(e=>{oe(e),xe(e,!1)},[oe,xe]),Ce=zv(e,!0,i),we=Ce.activeNeedsReauth,Te=(0,Z.useMemo)(()=>{let e=Ce.accounts;if(e.length===0&&Ce.loadState===`loading`)return O;let t=e.find(e=>e.isMain)??e[0],n=!!t&&!!t.email&&t.email!==`Codex App login`,r=e.some(e=>!e.isMain&&(e.hasCredential||e.email)),i=n||r,a=n?t?.email:e.find(e=>!e.isMain&&e.email)?.email??void 0;return{...O,openai:{loggedIn:i,...a?{email:a}:{},...we?{needsReauth:!0}:{}}}},[O,Ce.accounts,Ce.loadState,we]),Ee=Xw({apiBase:e,targetKey:i,t:r,config:d,oauthStatus:Te,aliveRef:q,notify:Y,fetchConfig:ye,fetchOauth:me,fetchProviderQuotas:he,codexActiveNeedsReauth:we,invalidateOauthStatusReads:ge,setOauthStatus:k}),{accountSets:De,setAccountSets:Oe,accountLoadStates:ke,switchingAccounts:Ae,pausingAccounts:je,keyPools:Me,fetchAccountSets:Ne,fetchKeyPools:Pe,beginAccountLogout:Fe,refreshAccountRosters:Ie,oauthCardProviders:Le,keyCardProviders:Re,switchAccount:ze,pauseAccount:Be,setAccountPoolThreshold:Ve,setAccountThreshold:He,switchApiKey:Ue,pauseApiKey:We,removeApiKey:Ge,addApiKeyValue:Ke,editCredentialAlias:qe,removeAccount:Je,activeAccountNeedsReauth:Ye}=Ee,Xe=(0,Z.useCallback)(e=>e&&!(e.kind===`oauth`?Le:Re).includes(e.provider)?Promise.resolve(!0):Ie(e),[Ie,Le,Re]),Ze=_E(e,d!==null,Xe),Qe=JSON.stringify([i,e,Le.toSorted(),Re.toSorted()]),$e=(0,Z.useRef)(null);bn(`provider-rosters:${Qe}`,[Qe],async e=>$e.current===Qe?(Ze(),Ie(void 0,e)):($e.current=Qe,!0),{enabled:d!==null,pollMs:3e4});let{draft:et,setDraft:tt,jsonEditorOpen:nt,jsonSaving:rt,jsonLeaveOpen:it,saveConfig:at,openJsonEditor:ot,discardJsonEditor:st,requestCloseJsonEditor:ct,restoreJsonEditor:lt,jsonIsDirty:ut,jsonConflict:dt,jsonConflicts:ft,useSavedJsonValues:pt,keepJsonDraft:X,setJsonLeaveOpen:mt}=aT({apiBase:e,targetKey:i,config:d,notify:Y,fetchConfig:ye,fetchProviderQuotas:he,onSaved:e=>{e.length&&(e.length===1&&F(t=>t??e[0]),be.open(e,!0)),ee(e=>e+1)},t:r}),ht=(0,Z.useCallback)(e=>{let t=d?.providers[e],n=t?.authMode,r=t&&_e(e,t)?()=>Ce.load(!0,{validatePending:!0}):n===`oauth`?()=>Ne([e],!0):n===`forward`||n===`local`?void 0:()=>Pe([e],!0);return fe(r)},[d,Ce,Ne,Pe,fe]),gt=(0,Z.useCallback)(()=>fe(),[fe]);(0,Z.useEffect)(()=>{J.current!==i&&(J.current=i,Promise.resolve().then(()=>{ye(),me()}))},[e,i,ye,me]);let _t=()=>ee(e=>e+1),{cancelLoginOAuth:vt,loginOAuth:yt,logoutOAuth:bt,onNativeLoginSettled:xt,loginCapture:St,loginEndedCapture:Ct}=lT({apiBase:e,targetKey:i,t:r,aliveRef:q,accountSets:De,setAccountSets:Oe,setBusy:j,setStatus:v,setLoginInfo:N,setOauthStatus:k,invalidateOauthStatusReads:ge,captureOauthStatusRead:ve,beginAccountLogout:Fe,notify:Y,fetchConfig:ye,fetchOauth:me,fetchAccountSets:Ne,fetchProviderQuotas:he,bumpModelsRefresh:_t,onLoginSettled:Se}),wt=(0,Z.useRef)(xt);(0,Z.useEffect)(()=>{wt.current=xt},[xt]),(0,Z.useEffect)(()=>_S(e,e=>{wt.current(`kiro`,e).catch(()=>{})}),[e]);let{removeProvider:Tt,confirmRemoveProvider:Et,setProviderDisabled:Dt,setDefaultProvider:Ot,updateProvider:kt}=fT({apiBase:e,targetKey:i,t:r,removeBusyRef:re,workspaceSelected:P,setWorkspaceSelected:F,setRemoveConfirmName:z,notify:Y,fetchConfig:ye,fetchOauth:me,fetchProviderQuotas:he,onProviderRemoved:e=>m.clear(i,e),refreshCodexAccount:()=>Ce.load(!0)}),At=(e,t=!1,n)=>{let r=a_(e),i=r===e?void 0:e;A!==r&&(MS(r)?te({provider:r,addAccount:t,...n?{accountId:n}:{}}):yt(r,t,n,!1,i))};if(!d)return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`nav.providers`)})}),_?(0,Q.jsx)(zn,{tone:S,onDismiss:ie,dismissLabel:r(`common.close`),children:_}):(0,Q.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,Q.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`providers-workspace-main`,children:(0,Q.jsxs)(`p`,{className:`muted`,children:[(0,Q.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,r(`prov.loadingConfig`)]})})]})]});let jt=FT(d,E,r),Mt=IT(d,Te),Nt=e=>d.providers[e]?.authMode===`forward`,Pt=async(t,n=!1)=>{if(t===`openai`){if(A===`openai`)return;let t=d.providers.openai,n=nC(t);if(n===`invalid`){Y(r(`codexAuth.openaiMissing`),!1);return}if(n===`absent`||n===`disabled`){j(`openai`);try{await lC(e,n),await ye()}catch(e){e instanceof cC?Y(r(e.i18nKey),!1):Y(e instanceof Error?e.message:r(`prov.saveFailed`),!1);return}finally{q.current&&j(e=>e===`openai`?null:e)}}U(!0)}else Nt(t)?U(!0):(d.providers[t]?.authMode===`oauth`||E.includes(t))&&At(t,n)},Ft=e=>{oe(e)},It={onLogin:At,onNativeLoginSettled:xt,onCancelLogin:vt,onLogout:bt,onReauth:(e,t)=>At(e,!0,t),onSwitchAccount:ze,onPauseAccount:Be,pendingAffinityResets:Ee.pendingAffinityResets,onRetryAffinityReset:Ee.retryAffinityReset,onAccountPoolThreshold:Ve,onAccountThreshold:He,onRemoveAccount:Je,onRetryAccounts:async e=>{await Ne([e])},onAddApiKey:Ke,onSwitchApiKey:Ue,onPauseApiKey:We,onRemoveApiKey:Ge,onEditAlias:qe,onRefreshQuota:ht};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:r(`nav.providers`)}),(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>g(!0),children:[(0,Q.jsx)(Vt,{}),r(`prov.add`)]})})]}),_&&(0,Q.jsx)(zn,{tone:S,onDismiss:ie,dismissLabel:r(`common.close`),children:_}),(0,Q.jsx)(cg,{onRemoveProvider:Tt,providers:d.providers,apiBase:e,targetKey:i,targetLabel:a,defaultProvider:d.defaultProvider,selectedName:P,onSelect:F,onAddProvider:e=>{L(e??null),g(!0)},onEditConfig:ot,jsonEditor:{open:nt,draft:et,isDirty:ut,onDraftChange:tt,onSave:()=>at(),onClose:ct,onRestore:lt,conflict:dt,conflicts:ft,onUseSaved:pt,onKeepDraft:X},jsonSaving:rt,modelsRefreshToken:W,fetchDiscovery:!0,onModelsSettled:be.modelsSettled,activeAccountNeedsReauth:Ye,quotaRefreshEpoch:le.epoch,quotaForceRefresh:le.force,onQuotaRefreshSettled:de,onRefreshAllQuotas:gt,detail:(t,n)=>{let r=Mt[t.name]??O[t.name]??O[a_(t.name)];return(0,Q.jsx)(Ow,{item:t,preset:gg(t,ce.data??[]),usageTotals:n.usageTotals,modelUsage:n.modelUsage,quotaReport:n.quotaReport,availableModels:n.availableModels,hasLiveModels:n.hasLiveModels,selectedModels:n.selectedModels,modelRows:n.modelRows,modelRevision:n.modelRevision,modelRowsReady:n.modelRowsReady,onOpenModels:()=>En(`models`),onOpenConnect:()=>En(`integrations`),onCreateJevAuto:El(t)?()=>En(WT(t.name)):void 0,modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:r?.email,onDeselect:()=>F(null),apiBase:e,oauth:r,accounts:De[t.name]?.accounts??[],keys:Me[t.name]??[],accountLoadState:ke[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:ne.token,accountsFocusProvider:ne.provider,settingsFocusToken:se.token,settingsFocusProvider:se.provider,settingsFocusField:se.field,switchingAccountId:Ae[t.name]?.accountId??null,pausingAccountId:je[t.name]?.accountId??null,busyProvider:A,loginHint:M,loginCapture:St(a_(t.name)),authHandlers:It,onRefreshQuota:()=>ht(t.name),isDefault:t.name===d.defaultProvider,onRemoveProvider:Tt,onSetDisabled:Dt,onSetDefault:e=>{Ot(e)},onUpdateProvider:kt,targetKey:i,targetLabel:a,draftStore:m,codexController:Ce},t.name)}},i),(0,Q.jsx)(PT,{apiBase:e,targetKey:i,config:d,adding:h,modelsNotice:be.notice?{provider:be.notice.context.provider,initialRegistration:be.notice.context.initialRegistration,catalogRefreshPending:be.notice.context.catalogRefreshPending,loading:be.notice.loading,failed:be.notice.failed,providerKnown:be.notice.context.providers.every(e=>!!d.providers[e]),selection:be.notice.context.providers.length===1?d.providers[be.notice.context.provider]?.initialModelSelection:be.notice.context.providers.some(e=>d.providers[e]?.initialModelSelection?.status===`pending`)?{status:`pending`}:void 0,onClose:be.close,onOpenModels:()=>{be.close(),En(`models`)},onRetry:()=>{let e=be.notice.context;be.open(e.providers,e.initialRegistration,e.catalogRefreshPending),_t()}}:null,addIntent:I,busy:A,addModalAccountRows:jt,accountLoginStatus:Mt,accountLoginHint:M,accountLoginCaptures:{active:St,ended:Ct},removeConfirmName:R,removeDefaultProvider:R===d.defaultProvider?Object.entries(d.providers).find(([e,t])=>e!==R&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:H,jsonLeaveOpen:it,jsonSaving:rt,oauthTosPending:G,onCloseAdd:()=>{A&&vt(A),g(!1),L(null)},onAdded:e=>{g(!1),L(null),ie(),F(t=>t??e),be.open(e,!d.providers[e]),ye(),me(),he(!0),_t()},onAccountLogin:Pt,onAccountCancelLogin:e=>{vt(e)},onAccountLogout:e=>{bt(e)},onAccountManage:Ft,onOpenAdd:me,onCloseCodexLogin:()=>U(!1),onCodexAdded:e=>{U(!1),ae(e),e.validationPending||(F(e=>e??`openai`),be.open(`openai`,!d.providers.openai,e.catalogRefreshPending)),ye(),me(),he(!0),_t()},onCancelRemove:()=>z(null),onConfirmRemove:()=>{Et(R)},onCancelJsonLeave:()=>{rt||mt(!1)},onDiscardJson:st,onSaveJson:()=>{at()},onCancelOauthTos:()=>te(null),onContinueOauthTos:()=>{let e=G;e&&(te(null),yt(e.provider,e.addAccount,e.accountId,!0))}})]})}function yE({state:e,controller:t,actionRef:n}){let{t:r}=s();return e===`stale`?(0,Q.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`codex-stale-banner-text`,children:r(`models.staleBanner`)}),(0,Q.jsx)(`button`,{"data-models-reload-action":!0,ref:n,type:`button`,className:`btn btn-sm`,disabled:t.restarting,onClick:()=>{t.restart()},children:t.restarting?r(`dash.codexRestarting`):r(`dash.codexRestart`)})]}):null}function bE(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim().length>0)}function xE(e){return e===null||e===`alphabetical`||e===`provider`||e===`most-used`}function SE(e){if(typeof e!=`object`||!e)return!1;let t=e;return bE(t.pickerOrder)&&xE(t.pickerOrderMode)}function CE(e){if(!SE(e))return!1;let t=e;return bE(t.pickerAvailable)&&(!(`chosen`in t)||Array.isArray(t.chosen)&&t.chosen.every(e=>typeof e==`string`))}function wE(e){return Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&typeof e.provider==`string`&&typeof e.model==`string`&&(e.resolvedModel===void 0||typeof e.resolvedModel==`string`)&&typeof e.requests==`number`&&Number.isFinite(e.requests)&&e.requests>=0)}function TE(e){let t=e.indexOf(`/`);return t<0?[``,e]:[e.slice(0,t),e.slice(t+1)]}var EE=(e,t)=>e.localeCompare(t,`en`);function DE(e,t){let[n,r]=TE(e),[i,a]=TE(t);return EE(n,i)||EE(r,a)}function OE(e,t,n=[],r=[]){if(e==="default")return null;let i=[...new Set(t)];if(e===`alphabetical`)return i.sort((e,t)=>EE(TE(e)[1],TE(t)[1])||DE(e,t));if(e===`provider`)return i.sort(DE);let a=new Set(i),o=new Map,s=new Map;for(let e of r){if(!a.has(e.namespaced))continue;let t=JSON.stringify([e.provider,e.id]),n=o.get(t)??new Set;n.add(e.namespaced),o.set(t,n);let r=s.get(e.namespaced)??new Set;r.add(t),s.set(e.namespaced,r)}let c=e=>(s.get(e)?.size??0)>1?null:e,l=(e,t)=>{let n=o.get(JSON.stringify([e,t]));if(n)return n.size===1?c([...n][0]):null;if(t.startsWith(`${e}/`)&&a.has(t))return c(t);let r=`${e}/${t}`;return!t.includes(`/`)&&a.has(r)?c(r):void 0},u=new Map;for(let e of n){let t=l(e.provider,e.model);t&&u.set(t,(u.get(t)??0)+e.requests)}return i.sort((e,t)=>(u.get(t)??0)-(u.get(e)??0)||DE(e,t))}function kE(e,t,n){if(t.length===0)return`default`;if(t.some(e=>!e.includes(`/`)))return`custom`;if(n===`alphabetical`||n===`provider`||n===`most-used`)return n;let r=new Set(e);if(new Set(t).size!==t.length||t.length!==r.size||t.some(e=>!r.has(e)))return`custom`;for(let n of[`alphabetical`,`provider`]){let r=OE(n,e);if(r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n]))return n}return`custom`}function AE(e,t,n){let r=new Set(t.filter(e=>e.includes(`/`))),i=e=>{if(r.has(e))return e;let t=new Set(n.filter(t=>r.has(t.namespaced)&&e===`${t.provider}/${t.id}`).map(e=>e.namespaced));return t.size===1?[...t][0]:void 0};return[...new Set(e.map(e=>i(e.trim())).filter(e=>e!==void 0))]}function jE(e,t,n){return JSON.stringify([e,t,n.pickerAvailable,n.chosen??null,n.pickerOrder,n.pickerOrderMode])}function ME(e,t){let n=new Set(e.filter(e=>e.includes(`/`))),r=new Map,i=new Map;for(let e of t){if(!n.has(e.namespaced))continue;let t=`${e.provider}/${e.id}`,a=r.get(e.namespaced)??new Set,o=i.get(t)??new Set;a.add(t),o.add(e.namespaced),r.set(e.namespaced,a),i.set(t,o)}return[...n].every(e=>{let t=r.get(e);return t?.size===1&&i.get([...t][0])?.size===1})}function NE(e,t){if(e.chosen===void 0||e.pickerOrder.some(e=>!e.includes(`/`)))return null;let n=[...new Set(e.pickerAvailable.filter(e=>e.includes(`/`)))];if(!ME(n,t))return null;let r=new Map(e.chosen.map((e,t)=>[e,t])),i=new Map(t.map(e=>[e.namespaced,`${e.provider}/${e.id}`])),a=e=>r.get(e)??r.get(i.get(e)),o=n.filter(e=>a(e)!==void 0).sort((e,t)=>a(e)-a(t)),s=AE(e.pickerOrder,n,t);return{fixed:o,order:[...new Set([...o,...s,...n])]}}function PE(e,t,n,r){let i=[...e];return t===n||r.includes(t)||r.includes(n)||!i.includes(t)||!i.includes(n)||(i.splice(i.indexOf(t),1),i.splice(i.indexOf(n),0,t)),i}function FE(e,t,n,r){let i=[...e],a=i.indexOf(t),o=a+n;return a<0||o<0||o>=i.length||r.includes(t)||r.includes(i[o])||([i[a],i[o]]=[i[o],i[a]]),i}var IE=`application/x-ocx-picker-order`,LE=0;function RE(){let e=++LE;if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return`${e}:${crypto.randomUUID()}`}catch{}return`picker-${Date.now().toString(36)}-${e}`}function zE({apiBase:e,active:t,identities:n,onAccepted:r,onBusyChange:i}){let a=b(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)([]),[u,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(``),[y,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),w=(0,Z.useRef)({generation:0,flight:null,drag:null}),[T,E]=(0,Z.useState)({apiBase:e,active:t,onBusyChange:i}),D=JSON.stringify(n.map(({provider:e,id:t,namespaced:n})=>[e,t,n])),O=(0,Z.useRef)(D);(0,Z.useLayoutEffect)(()=>{O.current=D},[D]);let k=o!==null&&o.identities!==D,A=!t||u||!o||p!==null||k,j=o!==null&&JSON.stringify(c)!==JSON.stringify(o.order),M=(0,Z.useCallback)(()=>{w.current.drag=null,x(null),C(null)},[]);(T.apiBase!==e||T.active!==t||T.onBusyChange!==i)&&(E({apiBase:e,active:t,onBusyChange:i}),s(null),l([]),m(null),g(!1),f(!1));let[N,P]=(0,Z.useState)({disabled:A,snapshot:o,identitySignature:D});(N.disabled!==A||N.snapshot!==o||N.identitySignature!==D)&&(P({disabled:A,snapshot:o,identitySignature:D}),x(null),C(null)),(0,Z.useLayoutEffect)(()=>{let e=w.current;return e.generation++,()=>{e.generation++,e.flight?.controller.abort(),e.flight?.clear(),e.flight=null,e.drag=null,i(!1)}},[e,t,i]),(0,Z.useLayoutEffect)(()=>{w.current.drag=null},[A,o,D]);let F=async a=>{if(!t||w.current.flight||a&&(A||!j))return;let u=w.current.generation,p=d(15e3);w.current.flight=p,f(!0),i(!0),g(!1),M();let h=()=>w.current.generation===u&&w.current.flight===p,_=()=>h()&&!p.signal.aborted&&O.current===D;try{let t=await fetch(`${e}/api/subagent-models`,{signal:p.signal});if(!_())return;let i=await Yn(t);if(!_())return;if(!CE(i))throw Error(`Invalid picker settings`);let d=jE(e,u,i);if(a&&(!o||d!==o.signature||D!==o.identities)){m(`models.pickerOrder.changed`);return}let f=NE(i,n);if(!f){m(i.pickerOrder.some(e=>!e.includes(`/`))?`models.pickerOrder.nativeLocked`:i.chosen===void 0?`models.pickerOrder.unknownChosen`:`models.pickerOrder.catalogRequired`);return}if(!a){s({...f,signature:d,identities:D}),l(f.order),m(null),v(``);return}let h=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:p.signal,body:JSON.stringify({pickerOrder:c,pickerOrderMode:null})});if(!_())return;let g=await Yn(h);if(!_())return;if(!SE(g)||!(`ok`in g)||g.ok!==!0)throw Error(`Invalid picker receipt`);l(g.pickerOrder),m(`models.pickerOrder.savedReload`),r({pickerOrder:g.pickerOrder,pickerOrderMode:g.pickerOrderMode,catalogRefresh:`catalogRefresh`in g?g.catalogRefresh:void 0})}catch{h()&&O.current===D&&g(!0)}finally{p.clear(),h()&&(w.current.flight=null,f(!1),i(!1))}},I=(0,Z.useEffectEvent)(async()=>{let e=w.current,n=e.generation;await Promise.resolve(),t&&e.generation===n&&F(!1)});(0,Z.useEffect)(()=>{t&&I()},[e,t,i]);let L=(e,t)=>{A||(l(t),v(a(`models.pickerOrder.position`,{model:e,position:t.indexOf(e)+1,total:t.length})),M())},R=new Set(c),z=new Set(o?.fixed),B=e=>!A&&R.has(e)&&!z.has(e),V=(e,t)=>{w.current.drag&&w.current.drag.id!==t&&B(w.current.drag.id)&&B(t)&&e.dataTransfer.types.includes(IE)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,C(t))};return(0,Q.jsxs)(`section`,{className:`picker-order-editor`,"aria-label":a(`models.pickerOrder.custom`),"aria-busy":u,children:[(0,Q.jsx)(`p`,{className:`muted text-label`,children:a(`models.pickerOrder.editorHint`)}),(p||k)&&(0,Q.jsx)(`p`,{role:`alert`,children:a(p??`models.pickerOrder.changed`)}),h&&(0,Q.jsx)(`p`,{role:`alert`,children:a(`models.pickerOrder.requestFailed`)}),o&&c.length===0&&(0,Q.jsx)(`p`,{children:a(`models.pickerOrder.empty`)}),(0,Q.jsx)(`ol`,{className:`picker-order-list`,children:c.map((e,t)=>{let n=z.has(e);return(0,Q.jsxs)(`li`,{className:`picker-order-row${y===e?` cwi-target-row--dragging`:``}${S===e?` cwi-target-row--drop`:``}`,onDragOver:t=>V(t,e),onDragLeave:()=>C(null),onDrop:t=>{let n=w.current.drag;n&&n.id!==e&&n.token===t.dataTransfer.getData(IE)&&B(n.id)&&B(e)&&(t.preventDefault(),L(n.id,PE(c,n.id,e,o?.fixed??[]))),M()},onDragEnd:M,children:[(0,Q.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,disabled:A||n,draggable:!A&&!n,"aria-label":a(`models.pickerOrder.dragModel`,{model:e}),onDragStart:t=>{if(!B(e)){t.preventDefault();return}let n=RE();w.current.drag={id:e,token:n},x(e),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(IE,n)},children:(0,Q.jsx)(Be,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`code`,{className:`picker-order-name`,children:e}),n&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`models.pickerOrder.featured`)}),(0,Q.jsxs)(`span`,{className:`picker-order-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:A||n||t===0||z.has(c[t-1]),"aria-label":a(`models.pickerOrder.upModel`,{model:e}),onClick:()=>L(e,FE(c,e,-1,o?.fixed??[])),children:(0,Q.jsx)(ot,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:A||n||t===c.length-1||z.has(c[t+1]),"aria-label":a(`models.pickerOrder.downModel`,{model:e}),onClick:()=>L(e,FE(c,e,1,o?.fixed??[])),children:(0,Q.jsx)(Ot,{width:14,height:14,"aria-hidden":`true`})})]})]},e)})}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:_}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:A||!j,onClick:()=>void F(!0),children:a(u?`models.pickerOrder.applying`:`models.pickerOrder.saveDraft`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t||u,onClick:()=>void F(!1),children:a(`models.pickerOrder.reloadDraft`)})]})]})}function BE({apiBase:e,onSaved:t}){let n=b(),[r,i]=(0,Z.useState)(!0),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(!0),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(0),_=(0,Z.useCallback)(async()=>{if(h.current)return;let t=++g.current,n=d(15e3);try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let a=await r.json();if(h.current||t!==g.current)return;if(typeof a.fastRows!=`boolean`)throw Error(`shape`);m.current=a.fastRows,i(a.fastRows),o(!0),u(!1)}catch{!h.current&&t===g.current&&u(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{_()},0),t=$u(()=>{_()},3e4);return()=>{window.clearTimeout(e),t()}},[_]);let v=(0,Z.useCallback)(async()=>{if(h.current||!a)return;let r=m.current,s=!r;m.current=s,i(s),h.current=!0,c(!0),p(null),g.current+=1;let l=d(15e3);try{let r=await Yn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({fastRows:s}),signal:l.signal}))??{};if(r.ok!==!0||typeof r.fastRows!=`boolean`)throw Error(`unconfirmed`);m.current=r.fastRows,i(r.fastRows),o(!0),u(!1),p(r.catalogRefreshPending===!0?{tone:`warn`,message:n(`models.fastRows.refreshHint`)}:{tone:`ok`,message:n(r.fastRows?`models.fastRows.enabled`:`models.fastRows.disabled`)}),t?.()}catch{let a=d(15e3);try{let t=await fetch(`${e}/api/settings`,{signal:a.signal});if(!t.ok)throw Error(`reconcile`);let r=await t.json();if(typeof r.fastRows!=`boolean`)throw Error(`shape`);m.current=r.fastRows,i(r.fastRows),o(!0),u(!1),p(r.fastRows===s?{tone:`warn`,message:n(`models.fastRows.refreshHint`)}:{tone:`err`,message:n(`models.fastRows.updateFailed`)})}catch{m.current=r,i(r),p({tone:`err`,message:n(`models.fastRows.updateFailed`)})}finally{a.clear(),t?.()}}finally{l.clear(),h.current=!1,c(!1)}},[e,a,t,n]),y=l&&!a;return(0,Q.jsxs)(`div`,{className:`card card-row fast-rows-card`,"aria-busy":s||!a&&!y||void 0,children:[(0,Q.jsxs)(`div`,{className:`fast-rows-copy`,children:[(0,Q.jsx)(`strong`,{children:n(`models.fastRows.title`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:y?`status`:void 0,children:n(y?`models.fastRows.loadFailed`:a?`models.fastRows.desc`:`common.loading`)}),a&&l&&(0,Q.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:n(`models.fastRows.loadFailed`)})]}),(0,Q.jsxs)(`div`,{className:`fast-rows-controls`,children:[l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{_()},disabled:s,children:n(`common.retry`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{v()},disabled:s,"aria-pressed":r,"aria-label":n(`models.fastRows.title`),title:n(`models.fastRows.title`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),f&&(0,Q.jsx)(`div`,{className:`fast-rows-feedback is-${f.tone}`,role:f.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:f.message})]})}function VE({showOrderEditor:e,onSaved:t,...n}){return(0,Q.jsxs)(Q.Fragment,{children:[e&&(0,Q.jsx)(zE,{...n},n.apiBase),(0,Q.jsx)(BE,{apiBase:n.apiBase,onSaved:t})]})}var HE={operator:`models.displayNameSourceOperator`,provider:`models.displayNameSourceProvider`,fallback:`models.displayNameSourceFallback`};function UE({model:e,saving:t,requestError:n,currentNamePending:r=!1,mutationOutcomeUnknown:i=!1,onRetry:a,onEdit:o,onSave:s,onReset:c,onClose:l}){let u=b(),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(t),h=(0,Z.useId)(),g=(0,Z.useId)(),_=(0,Z.useId)(),[v,y]=(0,Z.useState)(e),[x,S]=(0,Z.useState)(e.displayNameOverride??``),[C,w]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=d.current;return e&&!e.open&&e.showModal(),f.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Z.useEffect)(()=>{let e=m.current&&!t&&!!n;m.current=t,e&&(i?p.current?.focus():f.current?.focus())},[n,t,i]),v!==e&&(y(e),S(e.displayNameOverride??``),w(null));let T=C?u(C):null,E=T??n,D=e.displayNameSource?HE[e.displayNameSource]:`models.displayNameSourceFallback`,O=()=>{t||l()};return(0,Q.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":h,onCancel:e=>{e.preventDefault(),O()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,disabled:t,onClick:O}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),t)return;if(a){a();return}if(i)return;let n=mp(x);w(n),n||s(x.trim())},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:h,children:u(`models.displayNameTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:O,children:u(`common.close`)})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameModelId`)}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-current`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameCurrent`)}),(0,Q.jsx)(`strong`,{children:r?u(`models.displayNameCurrentUnavailable`):e.displayName??e.namespaced}),!r&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:u(D)})]}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${h}-input`,children:u(`models.displayNameField`)}),(0,Q.jsx)(`input`,{ref:f,id:`${h}-input`,className:`input`,value:x,maxLength:129,placeholder:u(`models.displayNamePlaceholder`),"aria-describedby":`${g}${E?` ${_}`:``}`,"aria-invalid":T?!0:void 0,disabled:t||i,onChange:e=>{t||i||(o?.(),S(e.target.value),w(null))}}),(0,Q.jsx)(`p`,{id:g,className:`muted small`,children:u(`models.displayNameHelp`,{model:e.namespaced})}),E&&(0,Q.jsx)(`p`,{id:_,className:`model-display-name-error`,role:`alert`,children:E}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||i||!e.displayNameOverride,onClick:()=>{!t&&!i&&c()},children:u(`models.displayNameReset`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:t,onClick:O,children:u(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:p,type:`submit`,className:`btn btn-primary btn-sm`,disabled:t||i&&!a,children:u(t?`common.saving`:a?`common.retry`:`common.save`)})]})]})]})}var WE=[`input`,`output`,`cacheRead`,`cacheWrite`],GE={input:``,output:``,cacheRead:``,cacheWrite:``},KE={...GE,threshold:``,comparison:`gt`},qE=Symbol(`invalid model cost`),JE={input:`customInput`,output:`customOutput`,cacheRead:`customCacheRead`,cacheWrite:`customCacheWrite`};function YE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function XE(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function ZE(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=1e6}function QE(e){return YE(e)&&XE(e,WE)&&WE.every(t=>ZE(e[t]))}function $E(e){if(e!==void 0){if(!YE(e))return qE;if(!(e.mode===`automatic`&&XE(e,[`mode`])))return e.mode===`flat`&&XE(e,[`mode`])?{mode:`flat`}:e.mode!==`custom`||!Number.isSafeInteger(e.thresholdTokens)||Number(e.thresholdTokens)<=0||!XE(e,[`mode`,`thresholdTokens`,`comparison`,`rates`])||e.comparison!==`gt`&&e.comparison!==`gte`||!QE(e.rates)?qE:{mode:`custom`,thresholdTokens:Number(e.thresholdTokens),comparison:e.comparison,rates:{input:e.rates.input,output:e.rates.output,cacheRead:e.rates.cacheRead,cacheWrite:e.rates.cacheWrite}}}}function eD(e){if(!YE(e)||!XE(e,Object.hasOwn(e,`promptLengthPricing`)?[...WE,`promptLengthPricing`]:WE)||!WE.every(t=>ZE(e[t])))return qE;let t=$E(e.promptLengthPricing);if(t===qE)return qE;let n=Object.fromEntries(WE.map(t=>[t,e[t]]));return t===void 0?n:{...n,promptLengthPricing:t}}function tD(e,t){if(!WE.every(n=>e[n]===t[n]))return!1;let n=e.promptLengthPricing??{mode:`automatic`},r=t.promptLengthPricing??{mode:`automatic`};return n.mode===r.mode?n.mode!==`custom`||r.mode===`custom`&&n.thresholdTokens===r.thresholdTokens&&n.comparison===r.comparison&&WE.every(e=>n.rates[e]===r.rates[e]):!1}function nD(e,t){if(t===null)return e===null;let n=eD(e);return n!==qE&&tD(n,t)}var rD=e=>Object.fromEntries(WE.map(t=>[t,String(e[t])]));function iD(e){if(!e)return{rates:GE,mode:`automatic`,custom:KE};let t=e.promptLengthPricing;return!t||t.mode===`flat`?{rates:rD(e),mode:t?.mode??`automatic`,custom:KE}:{rates:rD(e),mode:`custom`,custom:{...rD(t.rates),threshold:String(t.thresholdTokens),comparison:t.comparison}}}var aD=e=>e.trim()===``?0:Number(e);function oD(e,t,n,r){if(r)return{field:r};if(!e.input.trim())return{field:`input`};if(!e.output.trim())return{field:`output`};let i={input:Number(e.input),output:Number(e.output),cacheRead:aD(e.cacheRead),cacheWrite:aD(e.cacheWrite)},a=WE.find(e=>!ZE(i[e]));if(a)return{field:a};if(t===`automatic`)return{cost:i};if(t===`flat`)return{cost:{...i,promptLengthPricing:{mode:`flat`}}};let o=n.threshold.trim();if(!/^[1-9]\d*$/.test(o)||!Number.isSafeInteger(Number(o)))return{field:`threshold`};if(!n.input.trim())return{field:`customInput`};if(!n.output.trim())return{field:`customOutput`};let s={input:Number(n.input),output:Number(n.output),cacheRead:aD(n.cacheRead),cacheWrite:aD(n.cacheWrite)},c=WE.find(e=>!ZE(s[e]));return c?{field:JE[c]}:{cost:{...i,promptLengthPricing:{mode:`custom`,thresholdTokens:Number(o),comparison:n.comparison,rates:s}}}}var sD={input:`pricing.override.input`,output:`pricing.override.output`,cacheRead:`pricing.override.cacheRead`,cacheWrite:`pricing.override.cacheWrite`},cD=6e4;function lD({model:e,apiBase:t,onRefresh:n,onClose:r}){let i=b(),a=(0,Z.useId)(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)({}),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(!1),[h,g]=(0,Z.useState)(`loading`),[_,v]=(0,Z.useState)(GE),[y,x]=(0,Z.useState)(`automatic`),[S,C]=(0,Z.useState)(KE),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(!1),M=`${t}/api/providers/${encodeURIComponent(e.provider)}/model-costs`,N=h===`saving`||h===`refreshing`,P=h!==`ready`,F=(0,Z.useCallback)((t=!1)=>{if(p.current)return;let n=d(cD);p.current=n,fetch(M,{signal:n.signal,cache:`no-store`}).then(async r=>{let i=await Yn(r);if(n.signal.throwIfAborted(),!YE(i)||i.provider!==e.provider||!YE(i.modelCosts))throw Error(`invalid model-costs response`);let a=Object.hasOwn(i.modelCosts,e.id)?i.modelCosts[e.id]:void 0,o=a===void 0?void 0:eD(a);if(o===qE)throw Error(`invalid model cost`);if(p.current!==n)return;let s=iD(o);v(s.rates),x(s.mode),C(s.custom),T(o!==void 0),D(null),k(null),j(t),g(`ready`)}).catch(()=>{p.current===n&&(g(t?`unknown`:`loadFailed`),D(t?`pricing.override.recoveryFailed`:`pricing.override.loadFailed`))}).finally(()=>{n.clear(),p.current===n&&(p.current=null)})},[M,e.id,e.provider,C,D,k,x]);(0,Z.useEffect)(()=>{let e=c.current;return e&&!e.open&&e.showModal(),F(),()=>{p.current?.controller.abort(),p.current?.clear(),p.current=null,e?.open&&e.close()}},[F]),(0,Z.useEffect)(()=>{h===`ready`?l.current?.focus():(h===`unknown`||h===`loadFailed`||h===`refreshFailed`)&&f.current?.focus()},[h]);let I=async t=>{if(p.current||(t===void 0?h!==`refreshFailed`:h!==`ready`))return;let i=d(cD);p.current=i,g(t===void 0?`refreshing`:`saving`),m.current=!0,D(null),k(null);let a=t===void 0;try{if(t!==void 0){let n=await Yn(await fetch(M,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e.id,cost:t}),signal:i.signal}));i.signal.throwIfAborted();let r=YE(n)?n.cost:void 0;if(!YE(n)||n.ok!==!0||n.provider!==e.provider||n.modelId!==e.id||!nD(r,t))throw Error(`invalid model-costs receipt`);if(p.current!==i)return;a=!0,g(`refreshing`)}if(!await n(i.signal))throw Error(`catalog refresh failed`);i.signal.throwIfAborted(),p.current===i&&r()}catch{if(p.current!==i)return;g(a?`refreshFailed`:`unknown`),D(a?`pricing.override.refreshFailed`:`pricing.override.outcomeUnknown`)}finally{i.clear(),p.current===i&&(p.current=null,m.current=!1)}},L=()=>{m.current||r()};return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`${a}-title`,onCancel:e=>{e.preventDefault(),L()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`pricing.override.close`),disabled:N,onClick:L}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog model-price-dialog`,role:`document`,noValidate:!0,"aria-busy":h===`loading`||N,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),p.current)return;if(h===`unknown`||h===`loadFailed`){g(`loading`),D(null),F(h===`unknown`);return}if(h===`refreshFailed`){I(void 0);return}if(P)return;let t=Object.entries(u.current).find(([,e])=>e.validity.badInput)?.[0],n=oD(_,y,S,t);`field`in n?(k(n.field),D(n.field===`threshold`||n.field.startsWith(`custom`)?`pricing.override.customInvalid`:`pricing.override.invalid`),u.current[n.field]?.focus()):I(n.cost)},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`${a}-title`,children:i(`pricing.override.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:N,onClick:L,children:i(`pricing.override.close`)})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:i(`pricing.override.modelId`)}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`div`,{className:`model-price-body`,children:[(0,Q.jsx)(`p`,{id:o,className:`muted small`,children:i(`pricing.override.help`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:i(`pricing.override.promptHelp`)}),h===`loading`&&(0,Q.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.loading`)}),(0,Q.jsx)(`div`,{className:`model-price-rates-grid`,children:WE.map(e=>(0,Q.jsxs)(`div`,{className:`model-price-rate-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-${e}`,children:i(sD[e])}),(0,Q.jsx)(`input`,{ref:t=>{t?u.current[e]=t:delete u.current[e],e===`input`&&(l.current=t)},id:`${a}-${e}`,className:`input`,type:`number`,min:0,max:1e6,step:`any`,inputMode:`decimal`,value:_[e],disabled:P,required:e===`input`||e===`output`,"aria-describedby":`${o}${E?` ${s}`:``}`,"aria-invalid":O===e||void 0,onChange:t=>{if(P||p.current)return;let n=t.target.value;v(t=>({...t,cacheRead:t.cacheRead||`0`,cacheWrite:t.cacheWrite||`0`,[e]:n})),D(null),k(null)}})]},e))}),(0,Q.jsxs)(`fieldset`,{className:`model-price-mode`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`pricing.override.promptTitle`)}),[`automatic`,`flat`,`custom`].map(e=>(0,Q.jsxs)(`label`,{className:`model-price-mode-option`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`${a}-mode`,value:e,checked:y===e,disabled:P,onChange:()=>{x(e),D(null),k(null)}}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:i(`pricing.override.mode${e[0].toUpperCase()}${e.slice(1)}`)}),(0,Q.jsx)(`small`,{className:`muted`,children:i(`pricing.override.mode${e[0].toUpperCase()}${e.slice(1)}Help`)})]})]},e))]}),y===`custom`&&(0,Q.jsxs)(`section`,{className:`model-price-band`,"aria-labelledby":`${a}-custom-title`,children:[(0,Q.jsx)(`h4`,{id:`${a}-custom-title`,className:`model-price-band-title`,children:i(`pricing.override.bandTitle`)}),(0,Q.jsxs)(`div`,{className:`model-price-custom-controls`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-threshold`,children:i(`pricing.override.threshold`)}),(0,Q.jsx)(`input`,{ref:e=>{e?u.current.threshold=e:delete u.current.threshold},id:`${a}-threshold`,className:`input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:S.threshold,disabled:P,"aria-describedby":`${o}${E?` ${s}`:``}`,"aria-invalid":O===`threshold`||void 0,onChange:e=>{C(t=>({...t,threshold:e.target.value})),D(null),k(null)}})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-comparison`,children:i(`pricing.override.comparison`)}),(0,Q.jsx)(Vn,{id:`${a}-comparison`,label:i(`pricing.override.comparison`),value:S.comparison,disabled:P,portal:!1,describedBy:o,options:[{value:`gt`,label:i(`pricing.override.comparisonGt`)},{value:`gte`,label:i(`pricing.override.comparisonGte`)}],onChange:e=>C(t=>({...t,comparison:e}))})]})]}),(0,Q.jsx)(`p`,{id:`${a}-custom-help`,className:`muted small`,children:i(`pricing.override.bandHelp`)}),(0,Q.jsx)(`div`,{className:`model-price-rates-grid`,children:WE.map(e=>(0,Q.jsxs)(`div`,{className:`model-price-rate-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-custom-${e}`,children:i(sD[e])}),(0,Q.jsx)(`input`,{ref:t=>{let n=JE[e];t?u.current[n]=t:delete u.current[n]},id:`${a}-custom-${e}`,className:`input`,type:`number`,min:0,max:1e6,step:`any`,inputMode:`decimal`,value:S[e],disabled:P,required:e===`input`||e===`output`,"aria-describedby":`${o}${E?` ${s}`:``}`,"aria-invalid":O===JE[e]||void 0,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),D(null),k(null)}})]},`custom-${e}`))})]})]}),A&&(0,Q.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.recovered`)}),E&&(0,Q.jsx)(`p`,{id:s,className:`model-display-name-error`,role:`alert`,children:i(E)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P||!w,onClick:()=>void I(null),children:i(`pricing.override.reset`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:N,onClick:L,children:i(`pricing.override.cancel`)}),(0,Q.jsx)(`button`,{ref:f,type:`submit`,className:`btn btn-primary btn-sm`,disabled:h===`loading`||N,children:i(N?`pricing.override.saving`:h===`unknown`||h===`loadFailed`?`pricing.override.reload`:h===`refreshFailed`?`pricing.override.refresh`:`pricing.override.save`)})]})]})]})}var uD=[`text`,`image`,`audio`],dD=[`100000`,`128000`,`200000`,`256000`,`352000`,`500000`,`1000000`],fD=6e4;function pD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mD(e){let t=e.reasoningOverridden===!0;return{contextWindow:e.contextWindowDeclared===void 0?``:String(e.contextWindowDeclared),modalities:Array.isArray(e.inputModalitiesDeclared)?[...e.inputModalitiesDeclared]:[],reasoning:t,ladder:t&&Array.isArray(e.reasoningEfforts)?[...e.reasoningEfforts]:[],defaultEffort:t?e.defaultReasoningEffort??``:``}}function hD(e){return e.toSorted().join(`,`)}function gD(e){let t=e.trim();if(!t)return null;let n=Number(t.replace(/[_,\s]/g,``));return Number.isSafeInteger(n)&&n>0?n:void 0}function _D({row:e,apiBase:t,onRefresh:n,onFeedback:r,onClose:i}){let a=b(),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u]=(0,Z.useState)(()=>mD(e)),[f,p]=(0,Z.useState)(`ready`),[m,h]=(0,Z.useState)(()=>u.contextWindow),[g,_]=(0,Z.useState)(()=>u.contextWindow!==``&&!dD.includes(u.contextWindow)),[v,y]=(0,Z.useState)(()=>[...u.modalities]),[x,S]=(0,Z.useState)(()=>u.reasoning),[C,w]=(0,Z.useState)(()=>[...u.ladder]),[T,E]=(0,Z.useState)(()=>u.defaultEffort),[D,O]=(0,Z.useState)(null),k=f===`saving`||f===`restoring`,A=f===`unknown`||f===`saved-stale`;(0,Z.useEffect)(()=>{let e=s.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&typeof t.focus==`function`&&t.focus()}},[]),(0,Z.useEffect)(()=>{A&&c.current?.focus()},[A]);let j=async()=>{let t=d(fD);l.current=t;try{if(!await n(t.signal)||(t.signal.throwIfAborted(),l.current!==t))return;r(!0,a(`models.settingsReloaded`,{model:e.namespaced})),i()}catch{}finally{t.clear(),l.current===t&&(l.current=null)}},M=t=>{if(S(t),!t||C.length>0)return;let n=Array.isArray(e.reasoningEfforts)?e.reasoningEfforts:void 0;w(n&&n.length>0?[...n]:[...hp])},N=(e,t)=>{w(n=>t?[...n,e]:n.filter(t=>t!==e)),!t&&T===e&&E(``)},P=()=>{k||i()},F=async(o,s)=>{let c=d(fD);l.current=c,p(s?`restoring`:`saving`),O(null);let u=!1,f=!1;try{let d=await fetch(t+`/api/model-settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:e.provider,modelId:e.id,...o}),signal:c.signal});if(d.status>=400&&d.status<500)throw f=!0,Error(`model settings rejected`);let p=await Yn(d);if(c.signal.throwIfAborted(),!pD(p)||p.ok!==!0||p.provider!==e.provider||p.modelId!==e.id||typeof p.changed!=`boolean`||typeof p.hasOverrides!=`boolean`||typeof p.saved!=`boolean`||p.saved!==p.changed||!pD(p.catalogRefresh)||![`committed`,`skipped`,`failed`].includes(String(p.catalogRefresh.status)))throw Error(`invalid model-settings receipt`);if(l.current!==c)return;if(u=!0,!p.changed){r(!0,a(s&&!p.hasOverrides?`models.settingsNothingToRestore`:`models.settingsNoChange`,{model:e.namespaced})),i();return}let m=p.catalogRefresh,h=m.status===`failed`||m.status===`skipped`&&m.retryable===!0;if(!await n(c.signal))throw Error(`catalog refresh failed`);if(c.signal.throwIfAborted(),l.current!==c)return;h?r(!1,a(`models.settingsSavedCodexStale`,{model:e.namespaced})):s?r(!0,a(`models.settingsRestored`,{model:e.namespaced})):r(!0,a(`models.settingsSaved`,{model:e.namespaced})),i()}catch{if(l.current!==c)return;if(f){p(`ready`),O(`models.settingsRejected`);return}p(u?`saved-stale`:`unknown`),O(u?`models.settingsRefreshFailed`:`models.settingsSaveFailed`)}finally{c.clear(),l.current===c&&(l.current=null)}},I=()=>{if(f!==`ready`)return;let e=gD(m);if(e===void 0){O(`models.contextInvalid`);return}let t=u,n={};m.trim()!==t.contextWindow&&(n.contextWindow=e),hD(v)!==hD(t.modalities)&&(n.inputModalities=v.length>0?[...v]:null);let r=x?hD(C):``;(x!==t.reasoning||r!==hD(t.ladder))&&(n.reasoningEfforts=x?[...C]:null);let a=x&&C.includes(T)?T:``;a!==t.defaultEffort&&(n.defaultReasoningEffort=a||null),Object.keys(n).length===0?i():F(n,!1)},L=async()=>{f===`ready`&&await Ju({message:a(`models.settingsRestoreConfirm`,{model:e.namespaced}),confirmLabel:a(`models.settingsRestore`),tone:`danger`})&&F({contextWindow:null,inputModalities:null,reasoningEfforts:null,defaultReasoningEffort:null},!0)},R=Array.isArray(e.inputModalities)?e.inputModalities.join(`, `):``,z=Array.isArray(e.inputModalities)?e.inputModalities.filter(e=>uD.includes(e)):[];return(0,Q.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":o+`-title`,onCancel:e=>{e.preventDefault(),P()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,disabled:k,onClick:P}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,noValidate:!0,"aria-busy":k,onClick:e=>e.stopPropagation(),onSubmit:e=>{e.preventDefault(),I()},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:o+`-title`,children:a(`models.settingsTitle`,{model:e.namespaced})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k,onClick:P,children:a(`common.close`)})]}),D&&(0,Q.jsx)($,{tone:f===`saved-stale`?`warn`:`err`,children:a(D)}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[a(`models.customFieldModelId`),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[a(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(Vn,{value:g?Sp:m,options:[{value:``,label:`—`},{value:`100000`,label:`100k`},{value:`128000`,label:`128k`},{value:`200000`,label:`200k`},{value:`256000`,label:`256k`},{value:`352000`,label:`352k`},{value:`500000`,label:`500k`},{value:`1000000`,label:`1M`},{value:Sp,label:a(`models.custom`)}],onChange:e=>{e===`custom`?_(!0):(_(!1),h(e))},disabled:k,label:a(`models.customFieldContext`),portal:!1}),g&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:m,onChange:e=>h(e.target.value),disabled:k,placeholder:a(`models.customPlaceholder`),"aria-label":a(`models.customFieldContext`)})]}),e.contextWindowDeclared===void 0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`models.settingsContextInherit`,{value:e.contextWindow?String(e.contextWindow):a(`models.settingsContextUnknown`)})})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[a(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:uD.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:v.includes(e),onChange:t=>{let n=t.target.checked;y(t=>{if(!n)return t.filter(t=>t!==e);let r=t.length>0?t:z;return[...new Set([...r,e])]})},disabled:k}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))}),v.length===0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`models.settingsModalitiesInherit`,{modalities:R||a(`models.settingsModalitiesUnknown`)})})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[a(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>M(e.target.checked),disabled:k}),(0,Q.jsx)(`span`,{className:`text-control`,children:a(`models.customFieldReasoningOverride`)})]})}),x&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:hp.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:C.includes(e),onChange:t=>N(e,t.target.checked),disabled:k}),(0,Q.jsx)(`span`,{className:`text-control`,children:a(`models.reasoningEffort.`+e)})]},e))})]}),x&&(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[a(`models.settingsDefaultEffort`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsx)(Vn,{value:T,options:[{value:``,label:`—`},...C.map(e=>({value:e,label:a(`models.reasoningEffort.`+e)}))],onChange:E,disabled:k,label:a(`models.settingsDefaultEffort`),portal:!1})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[A&&(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn btn-ghost`,onClick:()=>void j(),children:a(`models.settingsReload`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,title:a(`models.settingsRestoreHint`),disabled:k||A,onClick:()=>void L(),children:a(`models.settingsRestore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:P,disabled:k,children:a(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:k||A,children:a(k?`models.customSaving`:`models.customApply`)})]})]})]})}var vD=[`current`,`stale`,`unknown`,`not_running`],yD=[`fresh`,`stale`,`not_running`,`unknown`],bD=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function xD(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function SD(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&yD.includes(t.stateBefore)&&typeof t.code==`string`&&bD.includes(t.code)&&xD(t.requested)&&xD(t.stopped)&&xD(t.surviving)&&xD(t.failed)))return!1;let n=t.success,r=t.code,i=t.surviving,a=t.failed,o=t.stopped;if(n!==(r!==`partially_stopped`)||n&&(i.length>0||a.length>0)||!n&&i.length===0&&a.length===0||(r===`nothing_running`||r===`enumeration_unavailable`)&&o.length>0)return!1;if(`desktopApp`in t&&t.desktopApp!==void 0){let e=t.desktopApp;if(typeof e!=`object`||!e)return!1;let n=e;if(typeof n.attempted!=`boolean`||!xD(n.stopped)||!xD(n.surviving)||n.relaunch!==`started`&&n.relaunch!==`skipped`||n.reason!==void 0&&typeof n.reason!=`string`||n.pickerState!==void 0&&(typeof n.pickerState!=`string`||!vD.includes(n.pickerState))||n.relaunch===`started`&&n.surviving.length>0)return!1}return!0}function CD(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&yD.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var wD={state:null,runningCount:0};async function TD(e,t={}){let n=t.fetchFn??fetch;try{let r=await n(`${e}/api/system/codex-app-server`,{signal:t.signal});if(!r.ok)return wD;let i=await r.json().catch(()=>null);return CD(i)?{state:i.state,runningCount:i.runningCount}:wD}catch{return wD}}var ED=class extends Z.Component{getSnapshotBeforeUpdate(e){if(e.stale===this.props.stale)return null;let t=e.stale?e.bannerRef.current:e.headRef.current;return t?.ownerDocument.activeElement===t?t:null}componentDidUpdate(e,t,n){if(!n)return;let r=n.ownerDocument.activeElement;if(r!==n&&r!==n.ownerDocument.body)return;let i=this.props.stale?this.props.bannerRef.current:this.props.headRef.current;i&&!i.disabled&&i.focus()}render(){return this.props.children}},DD=3e4;function OD(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function kD(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=DD,formatFailure:i=e=>`Failed to restart Codex (HTTP ${e}).`,formatUnreachable:a=()=>`Could not reach the proxy.`,formatMalformed:o=()=>`The proxy returned an unexpected response.`,formatTimeout:s=()=>`The proxy did not answer in time. It may still be working.`}=t,c;try{c=await n(`${e}/api/system/codex-restart`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return{ok:!1,message:OD(e)?s():a()}}if(!c.ok)return{ok:!1,message:i(c.status)};let l;try{l=await c.json()}catch(e){return{ok:!1,message:OD(e)?s():o()}}return SD(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function AD(e){return e===`stopped`||e===`nothing_running`}function jD(e,t){let{t:n}=s(),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(!0),o=(0,Z.useRef)(t.onSettled),c=(0,Z.useRef)(t.restoreFocusFallback),l=(0,Z.useRef)(t.report),u=(0,Z.useRef)(e),d=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{o.current=t.onSettled,c.current=t.restoreFocusFallback,l.current=t.report},[t.onSettled,t.report,t.restoreFocusFallback]),(0,Z.useEffect)(()=>(u.current=e,()=>{d.current?.abort(),d.current=null}),[e]),(0,Z.useEffect)(()=>(a.current=!0,()=>{a.current=!1,d.current?.abort(),d.current=null}),[]),{restarting:r,restart:(0,Z.useCallback)(async()=>{let t=new AbortController;d.current?.abort(),d.current=t;let r=await Ju({message:n(`dash.codexRestartConfirm`),confirmLabel:n(`dash.codexRestart`),tone:`danger`,signal:t.signal,restoreFocusFallback:e=>c.current?.(e)??null});if(d.current===t&&(d.current=null),!r||!a.current||u.current!==e)return null;i(!0);let s=await kD(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(a.current&&i(!1),!s.ok)return l.current(s.message,`err`),null;let f=s.result;return f.code===`stopped`?l.current(n(`dash.codexRestartDone`,{count:String(f.stopped.length)}),`ok`):f.code===`nothing_running`?l.current(n(`dash.codexRestartNothing`),`ok`):f.code===`enumeration_unavailable`?l.current(n(`dash.codexRestartUnknown`),`warn`):l.current(n(`dash.codexRestartPartial`,{count:String(f.surviving.length)}),`warn`),a.current&&AD(f.code)&&o.current?.(f.code),f.code},[e,n])}}async function MD(e,t,{apiBase:n,t:r,reloadAliases:i,publishFeedback:a}){let o=await Yu({message:r(`models.aliasPrompt`),initialValue:t});o!==null&&((await fetch(`${n}/api/providers/${encodeURIComponent(e)}/alias`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:o.trim()||null})})).ok?(await i(),a(!0,r(`models.aliasSaved`))):a(!1,r(`models.aliasConflict`)))}async function ND(e,t,n,{apiBase:r,t:i,reloadAliases:a,publishFeedback:o}){let s=await Yu({message:i(`models.modelAliasPrompt`),initialValue:n});if(s===null)return;let c=s.trim()?{set:{[t]:s.trim()}}:{remove:[t]};(await fetch(`${r}/api/providers/${encodeURIComponent(e)}/model-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(c)})).ok?(await a(),o(!0,i(`models.aliasSaved`))):o(!1,i(`models.aliasConflict`))}var PD={"gpt-5.6-sol":Se,"gpt-5.6-terra":at,"gpt-5.6-luna":Ae,"gpt-daybreak-blue-latest":Se,"daybreak-blue-latest":Se,"daybreak-red-latest":_t},FD={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function ID(e){return e.slice(e.lastIndexOf(`/`)+1)}function LD(e){return PD[e]??PD[ID(e)]??null}function RD(e){let t=LD(e);return t?(0,Z.createElement)(`span`,{className:`model-label`},(0,Z.createElement)(t,{style:FD,"aria-hidden":!0}),e):e}function zD(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var BD=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),VD=new Set([`unparseable`,`not-regular-file`,`foreign-edit`,`unowned-key`,`blocked-container`,`unresolvable-path`]);function HD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UD(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function WD(e){if(!HD(e)||e.clientId!==`aside`||!UD(e.profileId)||typeof e.current!=`boolean`||typeof e.enabled!=`boolean`||!BD.has(e.state)||typeof e.installed!=`boolean`||typeof e.configPath!=`string`||!Number.isSafeInteger(e.snapshotCount)||e.snapshotCount<-1||typeof e.retentionDegraded!=`boolean`||e.reason!==void 0&&!VD.has(e.reason))return null;for(let t of[`name`,`error`,`appliedAt`,`lastOpId`])if(e[t]!==void 0&&typeof e[t]!=`string`)return null;return{clientId:`aside`,profileId:e.profileId,current:e.current,enabled:e.enabled,state:e.state,installed:e.installed,configPath:e.configPath,snapshotCount:e.snapshotCount,retentionDegraded:e.retentionDegraded,...typeof e.name==`string`?{name:e.name}:{},...typeof e.error==`string`?{error:e.error}:{},...typeof e.appliedAt==`string`?{appliedAt:e.appliedAt}:{},...typeof e.lastOpId==`string`?{lastOpId:e.lastOpId}:{},...e.reason===void 0?{}:{reason:e.reason}}}function GD(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!HD(n)||!UD(n.profileId)||typeof n.ok!=`boolean`||n.state!==void 0&&!BD.has(n.state)||n.residual!==void 0&&typeof n.residual!=`boolean`)return null;for(let e of[`reason`,`refusalReason`,`message`,`snapshotPath`])if(n[e]!==void 0&&typeof n[e]!=`string`)return null;t.push({profileId:n.profileId,ok:n.ok,...n.state===void 0?{}:{state:n.state},...typeof n.reason==`string`?{reason:n.reason}:{},...typeof n.refusalReason==`string`?{refusalReason:n.refusalReason}:{},...typeof n.message==`string`?{message:n.message}:{},...typeof n.snapshotPath==`string`?{snapshotPath:n.snapshotPath}:{},...typeof n.residual==`boolean`?{residual:n.residual}:{}})}return t}var KD=[`qoder`,`qoder-cn`,`workbuddy`,`workbuddy-ai`,`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`,`gentle-shell`,`t3code`];function qD(e){return e.clientId===`kilo`&&!!e.lastOpId&&(e.reason===`candidate-conflict`||e.state===`unsafe`&&!!e.candidateFailurePath&&e.candidateFailurePath!==e.configPath)}var JD=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`superseded_store`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),YD=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),XD=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),ZD=[`apply`,`overwrite`,`disable`,`restore`],QD=[`add`,`replace`,`remove`,`snapshot`,`ownership`,`journal`],$D=[`none`,`unowned`,`foreign-edit`,`drift`],eO=new Set([`version`,`clientId`,`operation`,`state`,`foreignEdit`,`changes`,`fingerprint`,`canApply`,`willChange`,`refusalReason`,`supersededReason`,`missingStoreDocument`,`profileId`]),tO=new Set([`owned-config-file`,`unestablished-schema`,`missing-store`]),nO=/^[\x20-\x7e]{1,64}$/,rO=new Set([`kind`,`path`]),iO=new Set([`$snapshot`,`$ownership`,`$journal`]),aO=new Set([`*`,`provider.opencodex`,`providers.opencodex`,`models.providers.opencodex`,`models.*`,`modelConfigs.customModels.*`,`providerInstances.opencodex`,`llm-pi-ai.providers.opencodex`,`custom_provider.opencodex`,`providers.[id=opencodex]`,`settings.providers.opencodex`,`catalog.providers.opencodex`,`customModels.*`,`config.providerConfigRules.providerRules.[providerId=opencodex]`,`config.modelConfigRules.providerModelRules.*`,`[id=llm-pi-ai].config.providers.opencodex`]),oO=256;function sO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cO(e,t){return Object.keys(e).every(e=>t.has(e))}function lO(e){return iO.has(e)||aO.has(e)}function uO(){return new pO(502,{code:`invalid_integration_preview_response`})}function dO(e){if(!sO(e)||!cO(e,eO)||e.version!==1||!KD.includes(e.clientId)||!ZD.includes(e.operation)||!XD.has(String(e.state))||!$D.includes(e.foreignEdit)||typeof e.fingerprint!=`string`||!/^p[0-9]+:(?:[0-9a-f]{32}|unbound)$/.test(e.fingerprint)||typeof e.canApply!=`boolean`||typeof e.willChange!=`boolean`||!Array.isArray(e.changes)||e.changes.length>oO||e.profileId!==void 0&&(typeof e.profileId!=`number`||!Number.isSafeInteger(e.profileId)||e.profileId<0)||e.profileId!==void 0&&e.clientId!==`aside`||e.refusalReason!==void 0&&!JD.has(String(e.refusalReason))||e.supersededReason!==void 0&&(e.refusalReason!==`superseded_store`||typeof e.supersededReason!=`string`||!tO.has(e.supersededReason))||e.missingStoreDocument!==void 0&&(e.supersededReason!==`missing-store`||typeof e.missingStoreDocument!=`string`||!nO.test(e.missingStoreDocument)))throw uO();let t=[],n=-1,r=``,i=new Map;for(let a of e.changes){if(!sO(a)||!cO(a,rO)||!QD.includes(a.kind)||typeof a.path!=`string`||!lO(a.path))throw uO();let e=QD.indexOf(a.kind);if(e<n||e===n&&a.path<=r)throw uO();let o=a.kind,s=i.get(o)??new Set;if(s.has(a.path))throw uO();s.add(a.path),i.set(o,s),n=e,r=a.path,t.push({kind:o,path:a.path})}if(e.willChange&&(!e.canApply||t.length===0)||!e.willChange&&t.length!==0||e.fingerprint.endsWith(`:unbound`)&&e.canApply||e.canApply===(e.refusalReason!==void 0))throw uO();return{version:1,clientId:e.clientId,operation:e.operation,state:e.state,foreignEdit:e.foreignEdit,changes:t,fingerprint:e.fingerprint,canApply:e.canApply,willChange:e.willChange,...e.refusalReason===void 0?{}:{refusalReason:e.refusalReason},...e.supersededReason===void 0?{}:{supersededReason:e.supersededReason},...e.missingStoreDocument===void 0?{}:{missingStoreDocument:e.missingStoreDocument},...e.profileId===void 0?{}:{profileId:Number(e.profileId)}}}function fO(e){return!sO(e)||!JD.has(String(e.reason))?!1:typeof e.error==`string`&&YD.has(String(e.code))&&KD.includes(e.clientId)&&XD.has(String(e.state))&&typeof e.message==`string`}var pO=class extends Error{refusal;status;body;stalePlan;constructor(e,t){let n=fO(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`IntegrationApiError`,this.status=e,this.body=t,this.refusal=n,this.stalePlan=t.code===`integration_preview_stale`&&`plan`in t&&t.plan?t.plan:null}};function mO(e){return e instanceof pO&&e.status===404&&e.body.code===`integration_operation_not_found`}async function hO(e){let t;try{t=await e.json()}catch{return{}}return sO(t)?t.code===`integration_preview_stale`?{code:t.code,plan:dO(t.plan)}:t:{}}async function gO(e){if(!e.ok)throw new pO(e.status,await hO(e));let t=await Xn(e);if(t==null)throw new pO(e.status,{});return t}function _O(e){return e instanceof pO&&e.body.code===`integration_preview_unavailable`}function vO(e){return{operation:e.operation,planFingerprint:e.fingerprint}}function yO(e){if(!Number.isSafeInteger(e)||e<0)throw new pO(400,{code:`invalid_aside_profile`});return`/api/client-integrations/aside/profiles/${e}`}function bO(e,t){if(t!==void 0){if(e!==`aside`)throw new pO(400,{code:`invalid_aside_profile`});return yO(t)}return e===`aside`?`/api/client-integrations/aside/profiles`:`/api/client-integrations/${encodeURIComponent(e)}`}function xO(e,t){if(e===void 0)return``;let n=`profile=${encodeURIComponent(e)}`;return t?`client=hermes&${n}`:n}function SO(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}${t}`:e}function CO(){return new pO(502,{code:`invalid_hermes_profile_response`})}async function wO(e,t){return gO(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function TO(e,t,n,r,i){let a=await gO(await fetch(`${e}${SO(bO(t,r),xO(i,!1))}`,{signal:n}));if(i!==void 0&&(t!==`hermes`||a.hermesProfile!==i))throw CO();if(r!==void 0){let e=WD(a);if(!e||e.profileId!==r)throw new pO(502,{code:`invalid_aside_profile_response`});return e}return a}async function EO(e,t,n,r,i){if(r!==void 0&&t!==`aside`)throw new pO(400,{code:`invalid_aside_profile`});if(i!==void 0&&t!==`hermes`)throw new pO(400,{code:`invalid_hermes_profile`});let a=t===`aside`?`${bO(t,r)}/journal`:SO(`/api/client-integrations/journal${t?`?client=${encodeURIComponent(t)}`:``}`,xO(i,!1)),o=await gO(await fetch(`${e}${a}`,{signal:n}));if(r!==void 0&&(!Array.isArray(o.operations)||o.operations.some(e=>e.clientId!==`aside`||e.profileId!==r)))throw new pO(502,{code:`invalid_aside_profile_response`});return o}async function DO(e,t,n,r,i,a,o){let s=i===void 0?SO(`/api/client-integrations/preview`,xO(o,!0)):`${yO(i)}/preview`,c={...i===void 0?{clientId:t}:{},operation:n,...t===`droid`&&a!==void 0?{droidReasoningDefaults:a}:{}},l=dO(await gO(await fetch(`${e}${s}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c),signal:r})));if(l.clientId!==t||l.operation!==n||l.profileId!==i)throw uO();return l}async function OO(e,t,n=!1,r,i,a){let o=i===void 0?SO(`/api/client-integrations/restore/preview`,xO(a,!0)):`${yO(i)}/preview`,s=i===void 0?{opId:t,confirmDrift:n}:{operation:`restore`,opId:t,confirmDrift:n},c=dO(await gO(await fetch(`${e}${o}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s),signal:r})));if(c.operation!==`restore`||c.profileId!==i)throw uO();return c}async function kO(e,t,n){let{enabled:r,signal:i,overwriteConflict:a,profileId:o,binding:s,droidReasoningDefaults:c,hermesProfile:l}=n;if(l!==void 0&&t!==`hermes`)throw new pO(400,{code:`invalid_hermes_profile`});let u=r?a?`overwrite`:`apply`:`disable`,d;try{d=await gO(await fetch(`${e}${SO(bO(t,o),xO(l,!1))}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:r,...a===!0?{overwriteConflict:!0}:{},...s,...t===`droid`&&c!==void 0?{droidReasoningDefaults:c}:{}}),signal:i}))}catch(e){throw e instanceof pO&&e.stalePlan&&(e.stalePlan.clientId!==t||e.stalePlan.operation!==u||e.stalePlan.profileId!==o)?uO():e}let f=d.results===void 0?void 0:GD(d.results);if(t===`aside`&&d.results!==void 0&&(!f||d.ok!==f.every(e=>e.ok)))throw new pO(502,{code:`invalid_aside_profile_response`});if(d.ok!==!0)throw new pO(207,{code:t===`aside`?`aside_profile_partial`:`integration_mutation_failed`,message:d.message,results:f??void 0});if(o!==void 0&&d.profileId!==o)throw new pO(502,{code:`invalid_aside_profile_response`});return{...d,...f?{results:f}:{}}}async function AO(e,t){let{opId:n,confirmDrift:r=!1,signal:i,profileId:a,binding:o,hermesProfile:s}=t,c;try{c=await gO(await fetch(`${e}${a===void 0?SO(`/api/client-integrations/restore`,xO(s,!0)):`${yO(a)}/restore`}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:n,confirmDrift:r,...o}),signal:i}))}catch(e){throw e instanceof pO&&e.stalePlan&&(e.stalePlan.operation!==`restore`||e.stalePlan.profileId!==a)?uO():e}if(a!==void 0&&c.profileId!==a)throw new pO(502,{code:`invalid_aside_profile_response`});return c}async function jO(e,t,n,r,i){let a=await gO(await fetch(`${e}${SO(r===void 0?`/api/client-integrations/journal`:`${yO(r)}/journal`,xO(i,!0))}${i===void 0?`?`:`&`}opId=${encodeURIComponent(t)}`,{method:`DELETE`,signal:n}));if(r!==void 0&&a.profileId!==r)throw new pO(502,{code:`invalid_aside_profile_response`});return a}async function MO(e){try{let t=await e;return t.ok?await Xn(t)??null:null}catch{return null}}async function NO(e,t){let n=await MO(fetch(`${e}/api/startup-health`,{signal:t}));return n?{routingInjected:n.routingInjected===!0,status:typeof n.status==`string`?n.status:void 0,recommendedCommand:typeof n.recommendedCommand==`string`?n.recommendedCommand:null}:null}async function PO(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await Xn(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function FO(e,t){let n=await MO(fetch(`${e}/api/claude-code`,{signal:t}));return n?{enabled:n.enabled===!0,authMode:typeof n.authMode==`string`?n.authMode:void 0}:null}async function IO(e,t){let n=await MO(fetch(`${e}/api/claude-desktop/status`,{signal:t}));return!n||typeof n.desiredEnabled!=`boolean`||typeof n.installed!=`boolean`||typeof n.observedKind!=`string`?null:{desiredEnabled:n.desiredEnabled,installed:n.installed,observedKind:n.observedKind,applied:n.applied===!0,stale:n.stale===!0,drift:n.drift===!0,driftReason:typeof n.driftReason==`string`?n.driftReason:null,activeProfile:typeof n.activeProfile==`boolean`?n.activeProfile:null,appliedAt:typeof n.appliedAt==`string`?n.appliedAt:null}}async function LO(e,t){let n=await MO(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var RO=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),zO=new Set([`native_integration_refused`,`native_integration_failed`]),BO=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function VO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function HO(e){return VO(e)?typeof e.error==`string`&&zO.has(String(e.code))&&RO.has(String(e.clientId))&&BO.has(String(e.reason))&&typeof e.message==`string`:!1}var UO=class extends Error{refusal;status;body;constructor(e,t){let n=HO(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`NativeApiError`,this.status=e,this.body=t,this.refusal=n}};async function WO(e){try{let t=await e;return t.ok?await Xn(t)??null:null}catch{return null}}async function GO(e){try{let t=await e.json();return VO(t)?t:{}}catch{return{}}}async function KO(e){if(!e.ok)throw new UO(e.status,await GO(e));let t=await Xn(e);if(t==null)throw new UO(e.status,{});return t}function qO(e,t){return WO(fetch(`${e}/api/native-integrations`,{signal:t}))}async function JO(e,t,n,r){return KO(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var YO={integration_mutation_busy:`integrations.error.busy`,integration_journal_newest_protected:`integrations.rollback.deleteNewest`,integration_operation_not_found:`integrations.rollback.deleteGone`,aside_profile_partial:`integrations.aside.partial`,invalid_aside_profile_response:`integrations.aside.loadError`};function XO(e){return e instanceof pO?e.refusal:null}function ZO(e){return e instanceof UO?e.refusal:null}function QO(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var $O=new Set([`non_loopback`]);function ek(e,t,n){return t.reason===`orphaned_marker`?e(`integrations.native.error.orphanedMarker`,{path:n??``}):t.reason===`home_mismatch`?`${e(`integrations.native.error.homeMismatch`)} ${t.message}`:t.reason===`not_installed`?e(`integrations.native.error.notInstalled`):t.reason===`config_busy`?e(`integrations.native.error.configBusy`):t.reason===`metadata_unreadable`?e(`integrations.native.error.desktopUnsafeMetadata`,{path:n??``}):t.reason===`cleanup_incomplete`?e(`integrations.native.error.desktopCleanupIncomplete`,{paths:(t.residualPaths??[]).join(`, `)}):t.message||e(`integrations.error.generic`)}function tk(e,t,n,r){let i=ZO(t);if(i)return ek(e,i,r);let a=XO(t);if(!a){if(t instanceof pO&&`results`in t.body&&t.body.results?.length){let n=t.body.results.filter(e=>!e.ok).map(t=>{let n=nk(e,t);return`${e(`integrations.aside.profile`,{id:String(t.profileId)})}: ${n}`});return[e(`integrations.aside.partial`),...n].join(`
8
- `)}let r=YO[t instanceof pO?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}return rk(e,a)}function nk(e,t){return rk(e,{clientId:`aside`,message:t.message??t.reason,reason:t.refusalReason??t.reason,snapshotPath:t.snapshotPath,residual:t.residual})}function rk(e,t){let n=$O.has(t.reason??``)?e(QO(t.reason),{client:t.clientId}):t.message||e(QO(t.reason));return t.snapshotPath?e(t.residual?`integrations.error.residual`:`integrations.error.recover`,{message:n,path:t.snapshotPath}):t.residual?e(`integrations.error.residualNoSnapshot`,{message:n}):t.reason===`conflict`||t.reason===`unsafe`?`${e(QO(t.reason))} ${n}`:n}var ik=(e,t,n)=>JSON.stringify([e,t,n]),ak=new Map;function ok(e,t){let[n,r]=(0,Z.useState)({apiBase:e,overrides:ak,pending:!1});n.apiBase!==e&&r({apiBase:e,overrides:ak,pending:!1});let i=n.apiBase===e?n.overrides:ak,a=n.apiBase===e&&n.pending,o=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{o.current=t});let s=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e={active:!0,running:!1,queue:[],readVersion:0,bounded:null};return s.current=e,o.current.onBusy(!1),()=>{e.active=!1,e.queue.length=0,e.bounded?.controller.abort(),e.bounded?.clear()}},[e]);let c=async t=>{let n=null;for(;t.active;){for(;t.active&&t.queue.length>0;){let r=t.queue.shift(),i=d(6e4);t.bounded=i;try{let a=await sp(e,r.scope,r.provider,r.targets,r.enabled,fetch,i.signal);if(t.active){if(!a.ok)n=`models.saveFailed`;else{let e=await a.json().catch(()=>void 0);t.active&&o.current.onResponse(e)}}}catch{if(!t.active)return;n=`models.networkError`}finally{i.clear(),t.bounded=null}}if(!t.active)return;let i=t.readVersion,a=!1,s=d(6e4);t.bounded=s;try{a=await o.current.refresh(s.signal)}catch{}finally{s.clear(),t.bounded=null}if(!t.active)return;if(!(t.queue.length||i!==t.readVersion)){t.running=!1,r({apiBase:e,overrides:ak,pending:!1}),o.current.onBusy(!1),o.current.onSettled(n??(a?null:`models.networkError`));return}}};return{pending:a,overrides:i,enqueue:(t,n,i,a)=>{let l=s.current;l?.active&&(l.queue.push({scope:t,provider:n,targets:i,enabled:a}),l.readVersion++,o.current.onQueued(),r(t=>{let r=new Map(t.apiBase===e?t.overrides:ak);for(let e of i)r.set(ik(n,e.id,e.native===!0),a);return{apiBase:e,overrides:r,pending:!0}}),l.running||(l.running=!0,o.current.onBusy(!0),c(l)))},isRunning:()=>s.current?.running===!0,visible:(e,t,n,r)=>i.get(ik(e,t,n))??r}}function sk({className:e,style:t}){return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function ck({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,Q.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,Q.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,Q.jsx)(sk,{})},t))]})}function lk({children:e,busy:t=!0,live:n=!0,className:r}){return(0,Q.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,Q.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:e})]})}var uk=class extends Z.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:Error(String(e))}}reload=()=>{this.setState({error:null})};render(){return this.state.error?(0,Q.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,Q.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,Q.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,Q.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}};function dk(e,t){let n=e.provider.trim(),r=e.model.trim();if(!n||!r)return`missing`;let i=t.find(e=>e.provider===n&&e.id===r);if(!i)return`missing`;if(i.visionSidecarConsumer===!0)return`sidecar`;let a=i.inputModalitiesDeclared??i.inputModalities;return!a||a.length===0?`blocked`:a.includes(`image`)?`vision`:a.includes(`text`)?`sidecar`:`blocked`}function fk(e,t){return e.length!==0&&e.every(e=>{let n=dk(e,t);return n===`vision`||n===`sidecar`})}function pk(e,t){if(!fk(e,t))return[];let n=new Set,r=[];for(let i of e){if(dk(i,t)!==`sidecar`)continue;let e=i.provider.trim(),a=i.model.trim(),o=`${e}/${a}`;n.has(o)||(n.add(o),r.push({provider:e,model:a}))}return r}function mk(e,t){return e.filter(e=>dk(e,t)===`blocked`).map(e=>({provider:e.provider.trim(),model:e.model.trim()}))}function hk(e,t,n,r){if(t===`invalidSessionPin`)return e(`cws.err.invalidSessionPin`,{min:vl,max:yl});if(t===`invalidDecisionTimeout`)return e(`cws.err.invalidDecisionTimeout`,{min:xl,max:Sl});if(t===`invalidDecisionProvider`){let t=Cu(n.decisionProvider,r)??`missing`;return e(`cws.err.invalidDecisionProvider`,{name:n.decisionProvider??``,reason:e(Ll[t])})}return e(`cws.err.${t}`)}function gk(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function _k(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function vk(e){if(!e)return!1;let t=e.name.toLowerCase();if(t!==`openai`&&t!==`chatgpt`||(e.authMode??``).toLowerCase()!==`forward`||(e.adapter??``).toLowerCase()!==`openai-responses`)return!1;let n=(e.baseUrl??``).replace(/\/+$/,``);return!n||n.includes(`chatgpt.com/backend-api/codex`)}function yk(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||vk(i))&&r.add(`openai`);let a=[],o=new Set;for(let t of e)r.has(t.provider)&&t.id&&(o.has(t.id)||(o.add(t.id),a.push(t.id)));return a.toSorted((e,t)=>e.localeCompare(t))}var bk=`max-[939px]:[grid-column:3/-1]`;function xk({value:e,onChange:t,disabled:n}){let r=b();return(0,Q.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:Ml.map(i=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(Nl[i])},i))})}function Sk({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=b(),o=i??jl,s=t!==null&&!o.includes(t);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Vn,{id:e,fullWidth:!0,value:t??``,disabled:r,label:a(`cws.field.defaultEffort`),onChange:e=>n(e===``?null:e),options:[{value:``,label:a(`cws.field.defaultEffortNone`)},...s&&t?[{value:t,label:`${t} (${a(`cws.field.defaultEffortUnsupportedOption`)})`}]:[],...o.map(e=>({value:e,label:e}))]}),s?(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function Ck({targets:e,models:t,imageInput:n,reasoningEffortMode:r,visionEnabled:i,disabled:a,onChange:o}){let s=b(),c=fk(e,t),l=mk(e,t),u=c&&n!==`disabled`,d=pk(e,t),f=c?d.length>0&&n!==`disabled`?s(`cws.capability.imageInputSidecarHint`,{models:d.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}):s(`cws.capability.imageInputHint`):l.length>0?s(`cws.capability.imageInputBlockedHint`,{models:l.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}):s(`cws.capability.imageInputUnavailable`);return(0,Q.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":s(`cws.capabilities`),children:[(0,Q.jsx)(`span`,{className:`field-label`,children:s(`cws.capabilities`)}),(0,Q.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`cwi-capability-label`,children:s(`cws.capability.imageInput`)}),(0,Q.jsx)(`p`,{className:`muted cwi-capability-hint`,children:f}),d.length>0&&u&&i===!1?(0,Q.jsxs)(`p`,{className:`cwi-capability-hint cwi-capability-hint--warn`,children:[s(`cws.capability.imageInputSidecarDisabled`,{models:d.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>En(`dashboard`),children:s(`nav.dashboard`)})]}):null]}),(0,Q.jsx)(Rn,{on:u,onClick:()=>{c&&o({imageInput:n===`auto`?`disabled`:`auto`})},disabled:a||!c,label:s(`cws.capability.imageInput`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`cwi-capability-label`,children:s(`cws.capability.adaptiveEffort`)}),(0,Q.jsx)(`p`,{className:`muted cwi-capability-hint`,children:s(`cws.capability.adaptiveEffortHint`)})]}),(0,Q.jsx)(Rn,{on:r===`adaptive`,onClick:()=>{o({reasoningEffortMode:r===`adaptive`?`strict`:`adaptive`})},disabled:a,label:s(`cws.capability.adaptiveEffort`)})]})]})}function wk({targets:e,strategy:t,providers:n,models:r,capabilityModels:i=r,providerQuotaStates:a,onChange:o}){let s=b(),c=gk(n),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=t===`jev`?e.findIndex(e=>{let t=n.find(t=>t.name===e.provider.trim());return!!e.provider.trim()&&!!e.model.trim()&&t!==void 0&&t.disabled!==!0&&t.adapter!==`jev-decision`&&a[e.provider.trim()]!==`exhausted`}):-1,m=(t,n)=>{o(e.map((e,r)=>r===t?{...e,...n}:e))},h=(t,n)=>{o(e.map((e,r)=>{if(r!==t)return e;let{reasoningEfforts:i,modelProfile:a,...o}=e;return{...o,...n}}))},g=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[i]=r.splice(t,1);r.splice(n,0,i),o(r)};return(0,Q.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((_,v)=>{let y=n.find(e=>e.name===_.provider),b=y&&!c.some(e=>e.name===_.provider)?[...c,y]:c,x=yk(r,_.provider,n),S=_.model&&!x.includes(_.model)?[_.model,...x]:x,C=!_.provider,w=l===v,T=d===v&&l!==null&&l!==v,E=a[_.provider.trim()]??`unknown`,D=i.find(e=>e.provider===_.provider&&e.id===_.model)?.reasoningEfforts,O=D===void 0?void 0:new Set(D),k=O===void 0?void 0:jl.filter(e=>O.has(e)),A=new Set(k??[]),j=k===void 0?[]:_.reasoningEfforts===void 0?k:_.reasoningEfforts.filter(e=>A.has(e)),M=new Set(j);return(0,Q.jsxs)(`div`,{className:`cwi-target-entry`,children:[(0,Q.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`||t===`jev`?`cwi-target-row--failover`:``,w?`cwi-target-row--dragging`:``,T?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{l!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,d!==v&&f(v))},onDrop:e=>{e.preventDefault(),l!==null&&g(l,v),u(null),f(null)},onDragEnd:()=>{u(null),f(null)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":s(`cws.target.drag`),title:s(`cws.target.drag`),onDragStart:e=>{u(v),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(v))},children:(0,Q.jsx)(Be,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===0,"aria-label":s(`cws.target.moveUp`),onClick:()=>g(v,v-1),children:(0,Q.jsx)(ot,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===e.length-1,"aria-label":s(`cws.target.moveDown`),onClick:()=>g(v,v+1),children:(0,Q.jsx)(Ot,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Q.jsx)(Vn,{fullWidth:!0,className:bk,value:_.provider,label:s(`cws.target.provider`),onChange:e=>{let t=yk(r,e,n)[0]??``;h(v,{provider:e,model:t})},options:[{value:``,label:s(`cws.target.pickProvider`)},...b.map(e=>({value:e.name,label:e.disabled?s(`cws.target.disabled`,{name:re(e.name,s)}):re(e.name,s)}))]}),(0,Q.jsx)(Vn,{fullWidth:!0,className:bk,value:_.model,disabled:C,label:s(`cws.target.model`),onChange:e=>h(v,{provider:_.provider,model:e}),options:[{value:``,label:C?s(`cws.target.pickProviderFirst`):S.length===0?s(`cws.target.noModels`):s(`cws.target.pickModel`)},...S.map(e=>({value:e,label:e}))]}),(t===`round-robin`||t===`random`)&&(0,Q.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:_.weight??1,"aria-label":s(`cws.target.weight`),onChange:e=>{let t=_k(e.target.value,1,1e4);t!==void 0&&m(v,{weight:t})}}),(0,Q.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${E}`,"aria-label":s(`cws.quota.${E}`),children:s(`cws.quota.${E}`)}),(0,Q.jsx)(`div`,{className:`cwi-target-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>o(e.filter((e,t)=>t!==v)),"aria-label":s(`common.remove`),children:(0,Q.jsx)(et,{width:14,height:14})})})]}),t===`jev`&&(0,Q.jsxs)(`div`,{className:`cwi-jev-target-meta`,children:[v===p&&(0,Q.jsx)(`span`,{className:`chip`,children:s(`cws.jev.failOpen`)}),k===void 0?(0,Q.jsx)(`span`,{className:`muted`,children:s(`cws.jev.effortsUnknown`)}):k.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:s(`cws.jev.effortsNone`)}):(0,Q.jsxs)(`fieldset`,{className:`cwi-jev-efforts`,children:[(0,Q.jsx)(`legend`,{children:s(`cws.jev.allowedEfforts`)}),k.map(e=>{let t=M.has(e);return(0,Q.jsxs)(`label`,{className:`cwi-jev-effort`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,"data-jev-effort":!0,value:e,checked:t,disabled:t&&j.length===1,onChange:t=>{let n=new Set(j);t.target.checked?n.add(e):n.delete(e),m(v,{reasoningEfforts:k.filter(e=>n.has(e))})}}),(0,Q.jsx)(`span`,{children:e})]},e)})]}),(0,Q.jsxs)(`label`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:s(`cws.jev.modelProfile`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:3,maxLength:512,value:_.modelProfile??``,placeholder:s(`cws.jev.modelProfilePlaceholder`),onChange:e=>m(v,{modelProfile:e.target.value})}),(0,Q.jsx)(`span`,{className:`muted`,children:s(`cws.jev.modelProfileHint`)})]})]})]},_.clientKey??`${_.provider}:${_.model}`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>o([...e,Vl()]),children:[(0,Q.jsx)(Vt,{width:14,height:14}),` `,s(`cws.target.add`)]})]})}var Tk=[`typesafe`,`systemone`,`model`],Ek={typesafe:`cws.jev.method.typesafe`,systemone:`cws.jev.method.systemone`,model:`cws.jev.method.model`};function Dk({idPrefix:e,apiBase:t,combo:n,combos:r,providers:i,models:a,decisionProvider:o,decisionModel:s,decisionTimeoutMs:c,sessionPin:l,disabled:u,onChange:d}){let f=b(),p=Ol({decisionProvider:o,decisionModel:s}),m=l!=null&&!bl(l),h=(0,Z.useMemo)(()=>wu(i,o).filter(e=>e.id!==null),[i,o]),g=h.find(e=>e.id===o?.trim()),{id:_,alias:v,model:y}=n,x=(0,Z.useMemo)(()=>Al(a,i,r,{id:_,alias:v,model:y}),[a,i,r,_,v,y]),[S,C]=(0,Z.useState)(null),w=(0,Z.useRef)(null),T=`${p}\0${o??``}\0${s??``}\0${c??``}`,E=S?.key===T?S.result:null,D=e+`-decision-model-options`;(0,Z.useEffect)(()=>()=>{w.current?.abort(),w.current=null},[T]);let O=e=>{e!==p&&d(e===`typesafe`?{decisionProvider:null,decisionModel:null}:e===`systemone`?{decisionProvider:h.find(e=>!e.issue)?.id??h[0]?.id??``,decisionModel:null}:{decisionProvider:null,decisionModel:x[0]??``})},k=p===`typesafe`||p===`systemone`&&!!g&&!g.issue||p===`model`&&!!s?.trim(),A=async()=>{w.current?.abort();let e=new AbortController;w.current=e;let r=T,i=e=>C({key:r,result:e});i({state:`running`});try{let r=await fetch(`${t??``}/api/combos/decision-test`,{method:`POST`,headers:{"content-type":`application/json`},signal:e.signal,body:JSON.stringify({...n.id.trim()?{comboId:n.id.trim()}:{},...p===`systemone`&&o?{decisionProvider:o.trim()}:{},...p===`model`&&s?{decisionModel:s.trim()}:{},...c===null?{}:{decisionTimeoutMs:c}})});if(!r.ok){let t=await r.json().catch(()=>null);if(e.signal.aborted)return;i({state:`error`,message:t&&typeof t.error==`string`?t.error:String(r.status)});return}let a=await r.json().catch(()=>null);if(e.signal.aborted)return;if(!a||typeof a.gate!=`string`){i({state:`error`,message:String(r.status)});return}i({state:`done`,ok:a.ok===!0,backend:typeof a.backend==`string`?a.backend:`unknown`,gate:a.gate,latencyMs:typeof a.latencyMs==`number`?Math.round(a.latencyMs):0})}catch(t){if(e.signal.aborted)return;i({state:`error`,message:t instanceof Error?t.message:String(t)})}finally{w.current===e&&(w.current=null)}};return(0,Q.jsxs)(`fieldset`,{className:`cwi-field cwi-jev-decision`,"aria-describedby":`${e}-decision-method-hint`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:f(`cws.jev.decisionMethod`)}),(0,Q.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":f(`cws.jev.decisionMethod`),children:Tk.map(t=>(0,Q.jsx)(`button`,{type:`button`,id:`${e}-decision-method-${t}`,className:`btn btn-sm ${p===t?`btn-primary`:`btn-ghost`}`,"aria-pressed":p===t,disabled:u,onClick:()=>O(t),children:f(Ek[t])},t))}),(0,Q.jsxs)(`p`,{id:`${e}-decision-method-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[p===`typesafe`&&f(`cws.jev.decisionServiceDefaultHint`),p===`systemone`&&h.length===0&&f(`cws.jev.method.systemoneEmpty`)]}),p===`systemone`&&h.length>0&&(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-provider`,children:f(`cws.jev.decisionService`)}),(0,Q.jsx)(Vn,{id:`${e}-decision-provider`,fullWidth:!0,value:o?.trim()??``,disabled:u,describedBy:g?.issue?e+`-decision-provider-hint `+e+`-decision-provider-issue`:e+`-decision-provider-hint`,invalid:g?.issue!==void 0,onChange:e=>d({decisionProvider:e,decisionModel:null}),options:[...g?[]:[{value:``,label:`—`,disabled:!0}],...h.map(e=>({value:e.id,label:e.issue?`${e.id} (${f(Ll[e.issue])})`:e.id,disabled:e.issue!==void 0&&e.id!==g?.id}))]}),(0,Q.jsxs)(`p`,{id:`${e}-decision-provider-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[f(`cws.jev.decisionServiceHint`),g?.baseUrl&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`code`,{children:g.baseUrl})]})]}),g?.issue&&(0,Q.jsx)(`p`,{id:`${e}-decision-provider-issue`,className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:f(`cws.err.invalidDecisionProvider`,{name:g.id??``,reason:f(Ll[g.issue])})})]}),p===`model`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-model`,children:f(`cws.jev.decisionModel`)}),(0,Q.jsx)(`input`,{id:`${e}-decision-model`,className:`input mono`,list:D,value:s??``,maxLength:512,spellCheck:!1,autoComplete:`off`,placeholder:`ollama/qwen3:4b`,disabled:u,"aria-describedby":`${e}-decision-model-hint`,onChange:e=>d({decisionModel:e.target.value,decisionProvider:null})}),(0,Q.jsx)(`datalist`,{id:D,children:x.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),(0,Q.jsx)(`p`,{id:`${e}-decision-model-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:f(`cws.jev.decisionModelHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-timeout`,children:f(`cws.jev.decisionTimeout`)}),(0,Q.jsx)(`input`,{id:`${e}-decision-timeout`,className:`input mono`,type:`number`,inputMode:`numeric`,min:xl,max:Sl,step:1,placeholder:String(Cl),value:c??``,disabled:u,"aria-describedby":`${e}-decision-timeout-hint`,onChange:e=>{if(e.target.value===``){d({decisionTimeoutMs:null});return}let t=Number(e.target.value);Number.isFinite(t)&&d({decisionTimeoutMs:t})}}),(0,Q.jsx)(`p`,{id:`${e}-decision-timeout-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.jev.decisionTimeoutHint`,{default:Cl,min:xl,max:Sl})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsxs)(`label`,{htmlFor:`${e}-session-pin`,children:[(0,Q.jsx)(`input`,{id:`${e}-session-pin`,type:`checkbox`,checked:l!=null,disabled:u,"aria-describedby":`${e}-session-pin-hint`,onChange:e=>d({sessionPin:e.target.checked?{ttlMs:vl}:null})}),` `,f(`cws.jev.sessionPin`)]}),(0,Q.jsx)(`p`,{id:`${e}-session-pin-hint`,className:`muted text-label`,children:f(`cws.jev.sessionPinHint`,{min:vl,max:yl})}),l!=null&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-session-pin-ttl`,children:f(`cws.jev.sessionPinTtl`)}),(0,Q.jsx)(`input`,{id:`${e}-session-pin-ttl`,className:`input mono`,type:`number`,inputMode:`numeric`,min:6e4,max:864e5,step:1,value:l.ttlMs||``,disabled:u,"aria-invalid":m||void 0,"aria-describedby":m?`${e}-session-pin-hint ${e}-session-pin-error`:`${e}-session-pin-hint`,onChange:e=>{if(e.target.value===``){d({sessionPin:{ttlMs:0}});return}let t=Number(e.target.value);d({sessionPin:{ttlMs:Number.isFinite(t)?t:0}})}}),m&&(0,Q.jsx)(`p`,{id:`${e}-session-pin-error`,className:`notice-err text-label`,role:`alert`,children:f(`cws.err.invalidSessionPin`,{min:6e4,max:864e5})})]})]}),(0,Q.jsxs)(`div`,{className:`cwi-jev-decision-test`,style:{display:`flex`,gap:8,alignItems:`center`,flexWrap:`wrap`,marginTop:8},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:u||!k||E?.state===`running`,onClick:()=>{A()},children:E?.state===`running`?f(`cws.jev.testing`):f(`cws.jev.test`)}),(0,Q.jsxs)(`span`,{className:`muted`,role:`status`,"aria-live":`polite`,style:{fontSize:12,overflowWrap:`anywhere`},children:[E===null&&f(`cws.jev.testHint`),E?.state===`done`&&(E.ok?f(`cws.jev.testOk`,{ms:E.latencyMs,backend:f(Dl[E.backend]??`cws.jev.backend.unknown`)}):f(`cws.jev.testFailOpen`,{gate:E.gate,ms:E.latencyMs})),E?.state===`error`&&f(`cws.jev.testError`,{error:E.message})]})]})]})}var Ok=[];function kk({apiBase:e,combos:t=Ok,existingIds:n,existingAliases:r,providerMap:i,providerQuotaStates:a,providers:o,models:s,capabilityModels:c=s,initialDraft:l,onClose:u,onSubmit:d}){let f=b(),p=(0,Z.useRef)(null),[m,h]=(0,Z.useState)(()=>l?{...l,targets:l.targets.map(e=>({...e}))}:bu()),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(``),x=(0,Z.useMemo)(()=>{let e=new Map;for(let t of c)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[c]),S=(0,Z.useMemo)(()=>Rl(m.targets,x,m.reasoningEffortMode??`strict`),[m.targets,x,m.reasoningEffortMode]),C=mu(m.targets,a,i)===`exhausted`,w=l?.strategy===`jev`,T=w&&(n.includes(m.id.trim())||!!m.alias?.trim()&&r.includes(m.alias.trim()));(0,Z.useEffect)(()=>{let e=p.current;e&&!e.open&&e.showModal()},[]);let E=(0,Z.useCallback)(()=>{g||u()},[g,u]),D=(0,Z.useCallback)(e=>{e.preventDefault(),E()},[E]),O=async()=>{let e=yu(m,{existingIds:n,existingAliases:r,combos:t,isCreate:!0,providers:i});if(e){y(hk(f,e,m,i));return}_(!0),y(``);let a=m.id.trim(),o=m.alias?.trim()||null;try{let e=await d({...m,id:a,alias:o,model:Yl(a,o)});if(!e.ok){y(e.error||f(`cws.saveFailed`));return}}finally{_(!1)}};return(0,Q.jsxs)(`dialog`,{ref:p,className:`modal-overlay`,"data-combo-preset":w?`jev-auto`:void 0,"aria-labelledby":`cwi-add-title`,onCancel:D,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":f(`common.close`),tabIndex:-1,onClick:E}),(0,Q.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,Q.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:f(`cws.addTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:E,disabled:g,"aria-label":f(`common.close`),children:(0,Q.jsx)(Ie,{width:16,height:16})})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:f(w?`cws.jev.setupHint`:`cws.addSubtitle`)}),v&&(0,Q.jsx)($,{tone:`err`,children:v}),T&&(0,Q.jsx)($,{tone:`err`,children:f(`cws.jev.exists`)}),C&&(0,Q.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:f(`cws.quota.allExhausted`)}),(0,Q.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-id`,children:f(`cws.field.id`)}),(0,Q.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:m.id,disabled:g,onChange:e=>h(t=>({...t,id:e.target.value,model:Yl(e.target.value,t.alias)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.idInternalHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:f(`cws.field.alias`)}),(0,Q.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:m.alias??``,placeholder:f(`cws.field.aliasPlaceholder`),disabled:g,onChange:e=>h(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:Yl(t.id,e.target.value)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.aliasHint`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.idHint`,{model:m.id.trim()?Yl(m.id,m.alias):`…`})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,Q.jsx)(xk,{value:m.strategy,disabled:g,onChange:e=>h(t=>({...t,strategy:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(Pl[m.strategy])})]}),m.strategy===`jev`&&(0,Q.jsx)(Dk,{idPrefix:`cwi-new`,apiBase:e,combo:m,combos:t,providers:o,models:s,decisionProvider:m.decisionProvider??null,decisionModel:m.decisionModel??null,decisionTimeoutMs:m.decisionTimeoutMs??null,sessionPin:m.sessionPin,disabled:g,onChange:e=>h(t=>({...t,...e}))}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:f(`cws.field.defaultEffort`)}),(0,Q.jsx)(Sk,{id:`cwi-new-effort`,value:m.defaultEffort,disabled:g,allowedEfforts:S,onChange:e=>h(t=>({...t,defaultEffort:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),m.strategy===`round-robin`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:f(`cws.field.stickyLimit`)}),(0,Q.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:m.stickyLimit,disabled:g,onChange:e=>{let t=_k(e.target.value,1,100);t!==void 0&&h(e=>({...e,stickyLimit:t}))}}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.stickyLimitHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,Q.jsx)(wk,{targets:m.targets,strategy:m.strategy,providers:o,models:s,capabilityModels:c,providerQuotaStates:a,onChange:e=>h(t=>({...t,targets:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(Fl[m.strategy])})]}),(0,Q.jsx)(Ck,{targets:m.targets,models:c,imageInput:m.imageInput??`auto`,reasoningEffortMode:m.reasoningEffortMode??`strict`,disabled:g,onChange:e=>h(t=>({...t,...e}))})]}),(0,Q.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:E,disabled:g,children:f(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{O()},disabled:g||C||T,children:f(g?`common.saving`:`cws.create`)})]})]})]})}function Ak(e){return e===null?`—`:`${Math.round(e*100)}%`}function jk(e,t){if(e===null)return`—`;let n=e>=1e3;return new Intl.NumberFormat(t,{style:`unit`,unit:n?`second`:`millisecond`,unitDisplay:`short`,maximumFractionDigits:n&&e<1e4?1:0}).format(n?e/1e3:e)}function Mk({apiBase:e,comboId:t,active:n}){let{t:r,locale:i}=s(),[a,o]=(0,Z.useState)(`30d`),c=(0,Z.useCallback)(async n=>{let r=new URLSearchParams({jev:`1`,comboId:t,range:a}),i=await fetch(`${e}/api/usage?${r}`,{signal:n});if(!i.ok)throw Error(String(i.status));return i.json()},[e,t,a]),l=mf(`ocx.jev-stats.v1:${e}:${t}:${a}`,[e,t,a],c,{isEmpty:e=>e.summary.decisions===0,enabled:n,pollMs:3e4,pauseWhenHidden:!0,deadlineMs:6e4}),{state:u}=l,d=u.data;return n?(0,Q.jsxs)(`section`,{className:`jev-stats`,"aria-busy":u.refreshing,children:[(0,Q.jsxs)(`div`,{className:`jev-stats-toolbar`,children:[(0,Q.jsx)(`div`,{className:`segmented jev-stats-ranges`,role:`group`,"aria-label":r(`cws.jev.stats.range`),children:[`7d`,`30d`,`all`].map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm ${a===e?`btn-primary`:`btn-ghost`}`,"aria-pressed":a===e,onClick:()=>o(e),children:r(e===`all`?`usage.range.available`:`usage.range.${e}`)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>l.refresh(),children:r(`cws.jev.stats.refresh`)})]}),u.showSkeleton&&(0,Q.jsx)(ck,{label:r(`cws.jev.stats.loading`),rows:4}),u.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`cws.jev.stats.loadFailed`)}),d&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ni,{data:d}),(d.historyTruncated||d.entriesTruncated)&&(0,Q.jsx)($,{tone:`warn`,children:r(`cws.jev.stats.historyIncomplete`)}),d.error&&(0,Q.jsx)($,{tone:`err`,children:r(`cws.jev.stats.loadFailed`)}),d.summary.decisions===0?(0,Q.jsxs)(`div`,{className:`jev-stats-empty`,children:[(0,Q.jsx)(`h3`,{children:r(`cws.jev.stats.emptyTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,children:r(`cws.jev.stats.emptyBody`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`jev-stats-cards`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`cws.jev.stats.decisions`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:d.summary.decisions.toLocaleString(i)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:r(`cws.jev.stats.appliedAndFailOpen`,{applied:d.summary.appliedDecisions,failOpen:d.summary.failOpenDecisions})})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`cws.jev.stats.modelTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:$e(d.summary.modelTotalTokens,i)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:r(`cws.jev.stats.measuredAttempts`,{measured:d.summary.measuredModelAttempts,total:d.summary.modelAttempts})})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`cws.jev.stats.decisionTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:$e(d.summary.decisionTotalTokens,i)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:r(`cws.jev.stats.measuredDecisions`,{measured:d.summary.decisionUsageReported,total:d.summary.decisions})})]})]}),(0,Q.jsxs)(`div`,{className:`jev-stats-facts`,children:[(0,Q.jsx)(`span`,{children:r(`cws.jev.stats.successful`,{count:d.summary.successfulRequests})}),(0,Q.jsx)(`span`,{children:r(d.summary.requestsWithModelFallback===1?`cws.jev.stats.fallbackOne`:`cws.jev.stats.fallbackMany`,{count:d.summary.requestsWithModelFallback})}),(0,Q.jsx)(`span`,{children:r(`cws.jev.stats.averageLatency`,{value:jk(d.summary.averageLatencyMs,i)})}),(0,Q.jsx)(`span`,{children:r(`cws.jev.stats.averageConfidence`,{value:Ak(d.summary.averageConfidence)})})]}),(0,Q.jsx)(`div`,{className:`jev-stats-gates`,"aria-label":r(`cws.jev.stats.gates`),children:d.gates.map(e=>(0,Q.jsxs)(`span`,{className:`chip`,children:[e.gate,`: `,e.decisions]},e.gate))}),d.backends&&d.backends.length>0&&(0,Q.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`jev-stats-table`,"aria-label":r(`cws.jev.stats.backends`),children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`cws.jev.stats.backend`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.decisions`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.applied`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.latency`)})]})}),(0,Q.jsx)(`tbody`,{children:d.backends.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:r(Dl[e.backend]??`cws.jev.backend.unknown`)}),(0,Q.jsx)(`td`,{className:`num mono`,children:e.decisions.toLocaleString(i)}),(0,Q.jsx)(`td`,{className:`num mono`,children:e.applied.toLocaleString(i)}),(0,Q.jsx)(`td`,{className:`num mono`,children:jk(e.averageLatencyMs,i)})]},e.backend))})]})}),(0,Q.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`jev-stats-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`cws.jev.stats.model`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.picks`)}),(0,Q.jsx)(`th`,{children:r(`cws.jev.stats.efforts`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.attempts`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.input`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.output`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.reasoning`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.cacheReadWrite`)}),(0,Q.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.total`)})]})}),(0,Q.jsx)(`tbody`,{children:d.models.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:e.overflow?(0,Q.jsx)(`div`,{children:r(`cws.jev.stats.otherModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mono`,children:e.model}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:re(e.provider,r)})]})}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.picks,(0,Q.jsx)(`span`,{className:`jev-stats-cell-note`,children:r(`cws.jev.stats.appliedAndFailOpen`,{applied:e.appliedPicks,failOpen:e.failOpenPicks})})]}),(0,Q.jsx)(`td`,{children:e.efforts.length>0?e.efforts.map(e=>`${e.effort??r(`cws.jev.stats.noEffort`)} × ${e.picks}`).join(`, `):`—`}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.attempts,(0,Q.jsxs)(`span`,{className:`jev-stats-cell-note`,children:[e.measuredAttempts,` `,r(`cws.jev.stats.measuredShort`)]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.inputTokens,i)}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.outputTokens,i)}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.reasoningTokens,i)}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[$e(e.cacheReadTokens,i),` / `,$e(e.cacheWriteTokens,i)]}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.totalTokens,i)})]},e.overflow?`__jev_stats_overflow__`:`${e.provider}\0${e.model}`))})]})}),(0,Q.jsx)(`p`,{className:`muted text-caption jev-stats-footnote`,children:r(`cws.jev.stats.tokenFootnote`)})]})]})]}):null}var Nk={passthrough:`api.plan.disposition.passthrough`,translated:`api.plan.disposition.translated`,degraded:`api.plan.disposition.degraded`,unsupported:`api.plan.disposition.unsupported`},Pk={passthrough:`badge-green`,translated:`badge-accent`,degraded:`badge-amber`,unsupported:`badge-muted`};function Fk({effects:e,unknownFeatures:t}){let n=b();return e.length===0&&t.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:n(`api.plan.noFeatures`)}):(0,Q.jsxs)(`ul`,{className:`protocol-feature-list`,children:[e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e.feature}),(0,Q.jsx)(`span`,{className:`badge ${Pk[e.disposition]}`,children:n(Nk[e.disposition])})]},e.feature)),t.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:n(`api.plan.disposition.unknown`)})]},e))]})}var Ik=[`responses`,`chat`,`messages`],Lk={native:`api.plan.mode.native`,translated:`api.plan.mode.translated`,"legacy-bridge":`api.plan.mode.legacyBridge`,blocked:`api.plan.mode.blocked`},Rk={native:`badge-green`,translated:`badge-accent`,"legacy-bridge":`badge-amber`,blocked:`badge-muted`},zk={preserved:`api.plan.fidelity.preserved`,degraded:`api.plan.fidelity.degraded`,unknown:`api.plan.fidelity.unknown`},Bk={direct:`api.plan.routeKind.direct`,combo:`api.plan.routeKind.combo`,policy:`api.plan.routeKind.policy`,unknown:`api.plan.routeKind.unknown`},Vk=` → `;function Hk({path:e}){let t=b();return e.length>0?(0,Q.jsx)(`code`,{children:e.join(Vk)}):(0,Q.jsx)(`span`,{className:`muted`,children:t(`api.plan.noPath`)})}function Uk({features:e}){let t=b();return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:t(`api.plan.none`)}):(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:e.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})}function Wk({plan:e}){let t=b();return(0,Q.jsxs)(`div`,{className:`protocol-plan-result`,"aria-live":`polite`,children:[(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.overallMode`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`badge ${Rk[e.mode]}`,children:t(Lk[e.mode])})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.routeKind`)}),(0,Q.jsx)(`dd`,{children:t(Bk[e.routeKind])})]}),e.reasonCodes.length>0&&(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:e.reasonCodes.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.guaranteed`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Uk,{features:e.guaranteedFeatures})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.partial`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Uk,{features:e.partialFeatures})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.policyRevision`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.policyRevision})})]})]}),e.candidates.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:t(`api.plan.noCandidates`)}):(0,Q.jsx)(`ol`,{className:`protocol-plan-candidates`,children:e.candidates.map(n=>(0,Q.jsxs)(`li`,{className:`protocol-plan-candidate`,children:[(0,Q.jsxs)(`div`,{className:`protocol-plan-candidate-head`,children:[(0,Q.jsxs)(`code`,{children:[n.provider,`/`,n.model]}),(0,Q.jsx)(`span`,{className:`badge ${Rk[n.mode]}`,children:t(Lk[n.mode])}),!n.eligible&&n.mode!==`blocked`&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:t(`api.plan.ineligible`)})]}),(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.requestPath`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Hk,{path:n.requestPath})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.responsePath`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Hk,{path:n.responsePath})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.fidelity`)}),(0,Q.jsx)(`dd`,{children:t(zk[n.fidelity])})]}),n.reasonCodes.length>0&&(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:n.reasonCodes.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})})]})]}),(0,Q.jsx)(Fk,{effects:n.featureEffects,unknownFeatures:n.unknownFeatures}),(0,Q.jsxs)(`div`,{className:`protocol-plan-links`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>fE(n.provider),children:t(`protocolLinks.providerSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>dE({inbound:e.inbound,upstream:tE(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]})]},`${n.provider}/${n.model}`))})]})}function Gk({apiBase:e,models:t,protocolLabel:n}){let r=b(),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(`chat`),[c,l]=(0,Z.useState)(()=>new Set),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>v.current?.abort(),[]);let y=i||t[0]?.id||``,x=(0,Z.useMemo)(()=>jC.filter(e=>PC[e].includes(o)),[o]),S=e=>{s(e),l(t=>new Set([...t].filter(t=>PC[t].includes(e))))},C=(e,t)=>{l(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},w=async()=>{if(!y||f)return;v.current?.abort();let t=new AbortController;v.current=t,p(!0),h(!1);try{let n=await sw(e,{model:y,inbound:o,features:[...c]},t.signal);if(t.signal.aborted)return;n.kind===`unavailable`?(_(!0),d(null)):n.kind===`error`?h(!0):d(n.plan)}catch{}finally{v.current===t&&p(!1)}};return(0,Q.jsxs)(`div`,{className:`panel api-panel protocol-plan-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:r(`api.plan.title`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.description`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.modeNote`)}),g?(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.unavailable`)}):t.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`protocol-plan-form`,children:[(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:r(`api.plan.model`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:r(`api.plan.model`),value:y,onChange:a,options:t.map(e=>({value:e.id,label:e.id}))})]}),(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:r(`api.plan.inbound`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:r(`api.plan.inbound`),value:o,onChange:e=>S(e),options:Ik.map(e=>({value:e,label:n(e)}))})]})]}),(0,Q.jsxs)(`fieldset`,{className:`protocol-plan-features`,children:[(0,Q.jsx)(`legend`,{className:`muted small`,children:r(`api.plan.features`)}),x.map(e=>(0,Q.jsxs)(`label`,{className:`protocol-plan-feature`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:c.has(e),onChange:t=>C(e,t.target.checked)}),(0,Q.jsx)(`code`,{children:e})]},e))]}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:!y||f,onClick:()=>{w()},children:r(f?`api.plan.previewing`:`api.plan.preview`)})}),m&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:r(`api.plan.failed`)}),u&&(0,Q.jsx)(Wk,{plan:u})]})]})}function Kk({apiBase:e,model:t,dirty:n}){let r=b(),[i,a]=(0,Z.useState)(`responses`),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),m=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>m.current?.abort(),[]);let h=(0,Z.useMemo)(()=>jC.filter(e=>PC[e].includes(i)),[i]),g=async()=>{if(c)return;m.current?.abort();let n=new AbortController;m.current=n,l(!0),d(!1);try{let r=await sw(e,{model:t,inbound:i,features:h},n.signal);if(n.signal.aborted)return;r.kind===`unavailable`?p(!0):r.kind===`error`?d(!0):s(r.plan)}catch{}finally{m.current===n&&l(!1)}};return f?null:(0,Q.jsxs)(`section`,{className:`pwi-section combo-protocol-plan`,"aria-labelledby":`cws-plan-title`,children:[(0,Q.jsx)(`h3`,{id:`cws-plan-title`,className:`pwi-section-title`,children:r(`cws.plan.title`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`cws.plan.description`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.modeNote`)}),n&&(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:r(`cws.plan.savedOnly`)}),(0,Q.jsx)(`div`,{className:`protocol-plan-form`,children:(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:r(`api.plan.inbound`)}),(0,Q.jsx)(Vn,{fullWidth:!0,label:r(`api.plan.inbound`),value:i,onChange:e=>{a(e),s(null)},options:dC.map(e=>({value:e,label:mw(e,r)}))})]})}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:c,onClick:()=>{g()},children:r(c?`api.plan.previewing`:`cws.plan.run`)})}),u&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:r(`api.plan.failed`)}),o&&o.inbound===i&&(0,Q.jsx)(Wk,{plan:o})]})}var qk=[`config`,`about`],Jk=[`config`,`stats`,`about`],Yk=e=>`cws-detail-tab-${e}`,Xk=e=>`cws-detail-panel-${e}`,Zk=[];function Qk({apiBase:e,baseline:t,combos:n=Zk,isCreate:r=!1,otherIds:i,otherAliases:a,providerMap:o,providerQuotaStates:s,providers:c,models:l,capabilityModels:u=l,visionEnabled:d,onBack:f,onSaved:p,onRequestRemove:m,onSave:h,onDirtyChange:g}){let _=b(),[v,y]=(0,Z.useState)(`config`),x=!r&&t.strategy===`jev`?Jk:qk,S=(0,Z.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%x.length;else if(e.key===`ArrowLeft`)n=(t-1+x.length)%x.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=x.length-1;else return;e.preventDefault(),y(x[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[x]),[C,w]=(0,Z.useState)(t),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(!1),j=!_u(C,t),M=mu(C.targets,s,o)===`exhausted`,N=JSON.stringify([t.id,t.alias,t.nativeAlias,t.displayName,t.strategy,t.stickyLimit,t.defaultEffort,t.imageInput,t.reasoningEffortMode,t.decisionProvider,t.decisionModel,t.decisionTimeoutMs,t.sessionPin===void 0,t.sessionPin,t.targets.map(e=>[e.provider,e.model,e.weight,e.reasoningEfforts,e.modelProfile])]),P=(0,Z.useMemo)(()=>{let e=new Map;for(let t of u)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[u]),F=(0,Z.useMemo)(()=>Rl(C.targets,P,C.reasoningEffortMode??`strict`),[C.targets,P,C.reasoningEffortMode]),I=(0,Z.useCallback)(e=>{let n=e(C);w(n),g(!_u(n,t))},[C,t,g]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{w(t),O(null),y(`config`),g(!1)},0);return()=>window.clearTimeout(e)},[N]);let L=async()=>{try{await navigator.clipboard.writeText(t.model),A(!0),window.setTimeout(()=>A(!1),1200)}catch{}},R=async()=>{let e=yu(C,{existingIds:i,existingAliases:a,combos:n,isCreate:r,providers:o});if(e){O({ok:!1,text:hk(_,e,C,o)});return}E(!0);let s=C.id.trim(),c=C.alias?.trim()||null,l=C.displayName?.trim()||null,u={...C,id:s,alias:c,displayName:l,model:Yl(s,c),...C.strategy===`jev`?{}:{decisionProvider:null,decisionModel:null,decisionTimeoutMs:null,sessionPin:void 0}},d=!r&&s!==t.id?t.id:void 0;try{let e=await h(u,r,d);if(!e.ok){O({ok:!1,text:e.error||_(`cws.saveFailed`)});return}O({ok:!0,text:r?_(`cws.created`,{model:u.model}):_(`cws.saved`)}),p(u)}finally{E(!1)}},z=r?C.id.trim()?Yl(C.id,C.alias):_(`cws.addTitle`):t.model;return(0,Q.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[f&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:f,"aria-label":_(`cws.backToAll`),children:[(0,Q.jsx)(lt,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),_(`cws.allCombos`)]}),(0,Q.jsx)(`h2`,{className:`combos-workspace-detail-title${r&&!C.id.trim()?` combos-workspace-detail-title--label`:``}`,children:z}),!r&&(0,Q.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{L()},title:_(`cws.copyModel`),children:_(k?`cws.copied`:`cws.copyModel`)}),(0,Q.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!r&&m&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:[(0,Q.jsx)(et,{width:14,height:14}),` `,_(`common.remove`)]}),(0,Q.jsx)(`button`,{id:r?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!r&&!j||T||M,onClick:()=>{R()},children:_(T?`common.saving`:r?`cws.create`:`common.save`)})]})]}),D&&(0,Q.jsx)($,{tone:D.ok?`ok`:`err`,children:D.text}),M&&(0,Q.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:_(`cws.quota.allExhausted`)}),(0,Q.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":_(`cws.tabsLabel`),children:x.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:Yk(e),"aria-selected":v===e,"aria-controls":Xk(e),tabIndex:v===e?0:-1,className:`btn btn-sm ${v===e?`btn-primary`:`btn-ghost`}`,onClick:()=>y(e),onKeyDown:e=>S(e,t),children:_(e===`config`?`cws.tab.config`:e===`stats`?`cws.jev.stats.tab`:`cws.tab.about`)},e))}),(0,Q.jsxs)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Xk(`config`),"aria-labelledby":Yk(`config`),hidden:v!==`config`,children:[(0,Q.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:_(`cws.field.id`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:C.id,disabled:T,onChange:e=>I(t=>({...t,id:e.target.value,model:Yl(e.target.value,t.alias)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:r?_(`cws.field.idInternalHint`):_(`cws.field.idHintEdit`,{model:Yl(C.id,C.alias)})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:_(`cws.field.alias`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:C.alias??``,placeholder:Jl(C.id.trim()||`…`),disabled:T,onChange:e=>I(t=>Xl(t,e.target.value))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:_(`cws.field.aliasHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(Rn,{on:C.nativeAlias,disabled:T,label:_(`cws.field.nativeAlias`),showLabel:!0,onClick:()=>I(e=>({...e,nativeAlias:!e.nativeAlias}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:_(`cws.field.nativeAliasHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:_(`cws.field.displayName`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:C.displayName??``,maxLength:128,disabled:T,onChange:e=>I(t=>({...t,displayName:e.target.value||null}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:_(`cws.field.displayNameHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:_(`cws.strategy`)}),(0,Q.jsx)(xk,{value:C.strategy,disabled:T,onChange:e=>I(t=>({...t,strategy:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:_(Pl[C.strategy])})]}),C.strategy===`jev`&&(0,Q.jsx)(Dk,{idPrefix:`cwi-edit`,apiBase:e,combo:C,combos:n,providers:c,models:l,decisionProvider:C.decisionProvider??null,decisionModel:C.decisionModel??null,decisionTimeoutMs:C.decisionTimeoutMs??null,sessionPin:C.sessionPin,disabled:T,onChange:e=>I(t=>({...t,...e}))}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-effort`,children:_(`cws.field.defaultEffort`)}),(0,Q.jsx)(Sk,{id:`cwi-effort`,value:C.defaultEffort,disabled:T,allowedEfforts:F,onChange:e=>I(t=>({...t,defaultEffort:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:_(`cws.field.defaultEffortHint`)})]}),C.strategy===`round-robin`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-sticky`,children:_(`cws.field.stickyLimit`)}),(0,Q.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:C.stickyLimit,disabled:T,onChange:e=>{let t=_k(e.target.value,1,100);t!==void 0&&I(e=>({...e,stickyLimit:t}))}})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:_(`cws.targets`)}),(0,Q.jsx)(wk,{targets:C.targets,strategy:C.strategy,providers:c,models:l,capabilityModels:u,providerQuotaStates:s,onChange:e=>I(t=>({...t,targets:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:_(Fl[C.strategy])})]}),(0,Q.jsx)(Ck,{targets:C.targets,models:u,imageInput:C.imageInput??`auto`,reasoningEffortMode:C.reasoningEffortMode??`strict`,visionEnabled:d,disabled:T,onChange:e=>I(t=>({...t,...e}))})]}),!r&&e!==void 0&&(0,Q.jsx)(Kk,{apiBase:e,model:t.model,dirty:j})]}),!r&&t.strategy===`jev`&&(0,Q.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Xk(`stats`),"aria-labelledby":Yk(`stats`),hidden:v!==`stats`,children:(0,Q.jsx)(Mk,{apiBase:e??``,comboId:t.id,active:v===`stats`})}),(0,Q.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Xk(`about`),"aria-labelledby":Yk(`about`),hidden:v!==`about`,tabIndex:0,children:(0,Q.jsxs)(`section`,{className:`pwi-section`,children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:_(`cws.aboutTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:_(`cws.aboutBody`)})]})})]})}function $k({model:e,onCancel:t,onConfirm:n}){let r=b(),i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,Z.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,Q.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,Q.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,Q.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,Q.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function eA({onKeep:e,onDiscard:t}){let n=b(),r=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]);let i=(0,Z.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,Q.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,Q.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,Q.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,Q.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function tA(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:e===`all-targets-exhausted`?`cws.attention.allTargetsExhausted`:`cws.attention.few`)}function nA({combos:e,cataloguedComboIds:t,providerMap:n,providerQuotaStates:r,providers:i,onSelect:a,onAdd:o}){let s=b(),c=ou(e),l=hu(e,{cataloguedComboIds:t,providers:n,providerQuotaStates:r}),u=e.flatMap(e=>{let t=Tu(e,i);return t?[{item:e,decision:t}]:[]});return(0,Q.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,Q.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:s(`cws.overviewTitle`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:o,children:[(0,Q.jsx)(Vt,{width:14,height:14}),` `,s(`cws.add`)]})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:s(`cws.overviewBlurb`)}),(0,Q.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:e.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.total`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:c.failover.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.failover`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:c.roundRobin.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.roundRobin`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:c.other.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.other`)})]})]}),(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.howTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.howTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:0},children:s(`cws.howBody`)})]}),u.length>0&&(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.jev.decisionServicesTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.jev.decisionServicesTitle`)}),(0,Q.jsx)(`div`,{className:`cwi-attention-list`,children:u.map(({item:e,decision:t})=>(0,Q.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,style:{flexWrap:`wrap`},"data-decision-provider":t.model?void 0:t.provider??`jev`,"data-decision-model":t.model??void 0,onClick:()=>a(e.id),children:[(0,Q.jsx)(`code`,{className:`chip`,children:e.model}),t.model?(0,Q.jsxs)(`span`,{children:[s(`cws.jev.method.model`),`: `,(0,Q.jsx)(`code`,{children:t.model})]}):(0,Q.jsx)(`span`,{children:t.provider??s(`cws.jev.decisionServiceDefault`)}),t.baseUrl&&(0,Q.jsx)(`code`,{className:`muted`,style:{overflowWrap:`anywhere`},children:t.baseUrl}),(0,Q.jsx)(`span`,{className:`muted`,children:t.timeoutMs===null?s(`cws.jev.decisionTimeoutDefaultShort`):s(`cws.jev.decisionTimeoutShort`,{ms:t.timeoutMs})}),(0,Q.jsx)(lt,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},e.id))})]}),l.length>0&&(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.attentionTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.attentionTitle`)}),(0,Q.jsx)(`div`,{className:`cwi-attention-list`,children:l.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>a(e.id),children:[(0,Q.jsx)(St,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`code`,{className:`chip`,children:e.model}),(0,Q.jsx)(`span`,{className:`muted`,children:tA(e.reason,s)}),(0,Q.jsx)(lt,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function rA({apiBase:e,combos:t,providerQuotaStates:n,providers:r,models:i,capabilityModels:a=i,cataloguedComboIds:o,visionEnabled:s,loading:c,onRefresh:l,onSave:u,onRemove:d,onAdd:f,adding:p,addIntent:m,addDecisionProvider:h,onCloseAdd:g,onCreated:_}){let v=b(),y=(0,Z.useMemo)(()=>Object.fromEntries(r.map(e=>[e.name,{disabled:e.disabled,adapter:e.adapter,baseUrl:e.baseUrl,defaultModel:e.defaultModel,models:e.models}])),[r]),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(void 0),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),j=(0,Z.useMemo)(()=>bu(),[]),M=(0,Z.useMemo)(()=>t.some(e=>e.id===`jev-auto`||e.alias===`jev-auto`),[t]),N=(0,Z.useMemo)(()=>new Set(r.filter(e=>!e.disabled&&!e.hiddenFromPicker&&e.adapter!==`jev-decision`).map(e=>e.name)),[r]),P=(0,Z.useMemo)(()=>{if(m!==`jev-auto`)return;let e=r.length===0||Cu(h,y)===null;return Su(i,N,e?h:null)},[h,m,N,i,y,r.length]),F=(0,Z.useMemo)(()=>su(t,x),[t,x]),I=(0,Z.useMemo)(()=>ou(F),[F]),L=(0,Z.useMemo)(()=>t.flatMap(e=>e.alias?[e.alias]:[]),[t]),R=C&&t.some(e=>e.id===C)?C:null,z=t.find(e=>e.id===R)??null,B=z&&k?.source===z?k.item:z,[V,H]=(0,Z.useState)(!1),U=[],W=[];if(B)for(let e of t)e.id!==B.id&&(U.push(e.id),e.alias&&W.push(e.alias));let ee=(0,Z.useCallback)(e=>{e!==R&&(V?E(e):(w(e),A(null)))},[R,V]),G=()=>{T!==void 0&&(w(T),A(null),H(!1),E(void 0))},te=()=>E(void 0),ne=T!==void 0&&V,K=!c&&t.length===0&&!p;return(0,Q.jsxs)(`div`,{className:`combos-workspace-root${K?` combos-workspace-root--empty`:``}`,children:[(0,Q.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":v(`cws.railAria`),children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-heading`,children:[(0,Q.jsx)(`div`,{className:`combos-workspace-rail-title`,children:v(`nav.combos`)}),(0,Q.jsx)(`div`,{className:`combos-workspace-rail-count`,children:t.length})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn ${K?`btn-ghost`:`btn-primary`} btn-sm`,onClick:()=>{K?document.getElementById(`cwi-edit-id`)?.focus():f()},"aria-label":v(`cws.add`),children:[(0,Q.jsx)(Vt,{width:14,height:14}),` `,v(`cws.add`)]})]}),(0,Q.jsxs)(`div`,{className:`cwi-jev-quick-action`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f(`jev-auto`),disabled:M,title:v(M?`cws.jev.exists`:`cws.jev.setupHint`),children:[(0,Q.jsx)(ge,{width:14,height:14}),` `,v(`cws.jev.create`)]}),M&&(0,Q.jsx)(`span`,{className:`muted`,children:v(`cws.jev.exists`)})]}),t.length>0&&(0,Q.jsx)(`div`,{className:`cwi-search-row`,children:(0,Q.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,Q.jsx)(We,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{className:`input cwi-search-input`,value:x,onChange:e=>S(e.target.value),placeholder:v(`cws.searchPlaceholder`),"aria-label":v(`cws.searchPlaceholder`)})]})}),(0,Q.jsx)(`div`,{className:`combos-workspace-rail-list`,children:K?(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-empty`,children:[(0,Q.jsx)(`strong`,{children:v(`cws.emptyTitle`)}),(0,Q.jsx)(`p`,{children:v(`cws.empty.createDesc`)})]}):F.length===0&&t.length>0?(0,Q.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:v(`cws.noSearchResults`)}):(0,Q.jsx)(Q.Fragment,{children:[[`failover`,I.failover,`cws.group.failover`],[`round-robin`,I.roundRobin,`cws.group.roundRobin`],[`other`,I.other,`cws.group.other`]].map(([e,t,n])=>t.length>0?(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,Q.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),v(n),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${R===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>ee(e.id),"aria-current":R===e.id?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ge,{width:16,height:16})}),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?v(`cws.targetCountOne`):v(`cws.targetCount`,{count:e.targets.length})}),(0,Q.jsx)(lt,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,Q.jsx)(`div`,{className:`combos-workspace-main`,children:B&&z?(0,Q.jsx)(Qk,{apiBase:e,baseline:B,combos:t.filter(e=>e.id!==B.id),otherIds:U,otherAliases:W,providerMap:y,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,visionEnabled:s,onBack:()=>ee(null),onSaved:e=>{H(!1),e.id===B.id?A({source:z,item:e}):(w(e.id),A(null)),l()},onRequestRemove:()=>O(B.id),onSave:u,onDirtyChange:H},B.id):K?(0,Q.jsx)(Qk,{apiBase:e,baseline:j,isCreate:!0,otherIds:[],otherAliases:[],providerMap:y,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,visionEnabled:s,onSaved:e=>{H(!1),w(e.id),A(null),_(e.id)},onSave:u,onDirtyChange:H},`first-combo`):(0,Q.jsx)(nA,{combos:t,cataloguedComboIds:o,providerMap:y,providerQuotaStates:n,providers:r,onSelect:e=>ee(e),onAdd:f})}),p&&(0,Q.jsx)(kk,{apiBase:e,combos:t,existingIds:t.map(e=>e.id),existingAliases:L,providerMap:y,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,initialDraft:P,onClose:g,onSubmit:async e=>{let t=await u(e,!0);return t.ok&&(g(),_(e.id),w(e.id),A(null)),t}},`${m??`blank`}:${P?.decisionProvider??``}`),D&&(0,Q.jsx)($k,{model:t.find(e=>e.id===D)?.model??Jl(D),onCancel:()=>O(null),onConfirm:()=>{(async()=>{let e=await d(D);O(null),e.ok&&(R===D&&(w(null),A(null)),l())})()}}),ne&&(0,Q.jsx)(eA,{onKeep:te,onDiscard:G})]})}function iA(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function aA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function oA(e){return lf(e)?.data??null}function sA(e){return lf(e)?.cachedAt??null}function cA({apiBase:e,active:t=!0,onCountChange:n}){let r=b(),i=`ocx.combos.workspace.v2:${e}`,a=(0,Z.useMemo)(()=>oA(i),[i]),[o,s]=(0,Z.useState)(a??null),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(()=>GT(window.location.hash)===void 0?null:`jev-auto`),[m,h]=(0,Z.useState)(()=>GT(window.location.hash)??null),g=(0,Z.useCallback)(()=>{p(null),h(null),GT(window.location.hash)!==void 0&&Tn(`models/combos`)},[]),_=(e,t)=>{l(e),d(t)};(0,Z.useEffect)(()=>{if(!c||!u)return;let e=window.setTimeout(()=>{l(``),d(!1)},5e3);return()=>window.clearTimeout(e)},[c,u]);let v=(0,Z.useCallback)(async t=>{let[n,r,a]=await Promise.all([fetch(`${e}/api/combos`,{signal:t}),fetch(`${e}/api/config`,{signal:t}),fetch(`${e}/api/models`,{signal:t})]);if(!n.ok||!r.ok||!a.ok)throw Error(`combo workspace load failed`);let o=await n.json(),c=await r.json(),l=await a.json(),u=Array.isArray(l)?l:Array.isArray(l?.models)?l.models:[],d=au(o),f=c.providers??{},p=Ge(f),m=Object.entries(f).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:t.adapter===`jev-decision`||!Object.hasOwn(p,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl,...typeof t.defaultModel==`string`?{defaultModel:t.defaultModel}:{},...Array.isArray(t.models)?{models:t.models.filter(e=>typeof e==`string`)}:{}})),h=[],g=[],_=new Set,v=e=>Array.isArray(e)?e.flatMap(e=>{let t=typeof e==`string`?e.trim():``;return t?[t]:[]}):void 0;for(let e of u){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.provider!=`string`||typeof t.id!=`string`)continue;let n=t.provider.trim(),r=t.id.trim();if(!n||!r)continue;if(n===`combo`){_.add(r);continue}let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0,a=v(t.inputModalities),o=v(t.inputModalitiesDeclared),s={provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{},...a&&a.length>0?{inputModalities:a}:{},...o&&o.length>0?{inputModalitiesDeclared:o}:{},visionSidecarConsumer:t.visionSidecarConsumer===!0};g.push(s),h.push(s)}for(let[e,t]of Object.entries(f)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;n&&!t.disabled&&(g.some(t=>t.provider===e&&t.id===n)||h.push({provider:e,id:n,namespaced:`${e}/${n}`}))}let y={combos:d,providers:m,models:h,capabilityModels:g,cataloguedComboIds:[..._]};return uf(i,y),s(y),y},[e,i]),y=mf(i,[e],v,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:sA(i),staleAfterMs:6e4,enabled:t}),{state:x}=y,[S,C]=(0,Z.useState)(void 0);(0,Z.useEffect)(()=>{if(!t)return;let n=!1;return fetch(`${e}/api/sidecar-settings`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e||typeof e!=`object`)return;let t=e.vision;t&&typeof t==`object`&&C(t.enabled!==!1)}).catch(()=>{}),()=>{n=!0}},[t,e]);let[w,T]=(0,Z.useState)(()=>Date.now()),E=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`combo quota load failed`);let r=await n.json();return t?.aborted||T(Date.now()),r&&typeof r==`object`&&!Array.isArray(r)?r:{}},[e]),D=mf(`ocx.combos.provider-quotas.v1:${e}`,[e],E,{isEmpty:()=>!1,pollMs:6e4,pauseWhenHidden:!0,enabled:t}),O=t&&D.lastAttemptOk?D.data?.reports:void 0,k=pu(O,w),A=fu(O,w);(0,Z.useEffect)(()=>{if(!t)return;let e=()=>T(Date.now()),n=window.setTimeout(e,A===void 0?0:Math.max(0,A-Date.now())),r=Ut(()=>{Ht()||e()});return()=>{window.clearTimeout(n),r()}},[t,e,D.data,D.lastAttemptOk,A]);let j=x.data??o??void 0,M=j?.combos??[];(0,Z.useEffect)(()=>{j&&n?.(M.length)},[M.length,j,n]);let N=j?.providers??[],P=j?.models??[],F=j?.capabilityModels??P,I=new Set(j?.cataloguedComboIds??[]),L=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(vu(t,{...i?{renameFrom:i}:{},...t.imageInput===`disabled`?{}:{visionSidecarTargets:pk(t.targets,F)}}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=iA(o);if(!a.ok||s||!aA(o)){let e=s||r(`cws.saveFailed`);return _(e,!1),{ok:!1,error:e}}return y.refresh(),_(i?r(`cws.renamed`,{from:Jl(i),to:t.model}):n?r(`cws.created`,{model:t.model}):r(`cws.saved`),!0),{ok:!0}}catch{let e=r(`cws.saveFailed`);return _(e,!1),{ok:!1,error:e}}},R=async t=>{try{let n=await fetch(`${e}/api/combos?id=${encodeURIComponent(t)}`,{method:`DELETE`}),i=n.ok?await n.json():await n.json().catch(()=>null),a=iA(i);if(!n.ok||a||!aA(i)){let e=a||r(`cws.removeFailed`);return _(e,!1),{ok:!1,error:e}}return y.refresh(),_(r(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=r(`cws.removeFailed`);return _(e,!1),{ok:!1,error:e}}};if(x.showSkeleton&&!j)return(0,Q.jsx)(ck,{label:r(`cws.loading`),rows:5});if(x.kind===`failed-cold`&&!j){let e=x.error instanceof Error?x.error.message:r(`cws.loadFailed`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>y.refresh(),children:r(`common.retry`)})]})}return(0,Q.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,Q.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Q.jsx)($,{tone:u?`ok`:`err`,children:c})}),x.showError&&(0,Q.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Q.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,Q.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":x.refreshing,children:[(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:x.refreshing?r(`common.loading`):``}),(0,Q.jsx)(rA,{apiBase:e,combos:M,providerQuotaStates:k,providers:N,models:P,capabilityModels:F,cataloguedComboIds:I,visionEnabled:S,loading:!1,onRefresh:()=>{y.refresh(),D.refresh()},onSave:L,onRemove:R,onAdd:(e=`blank`)=>p(e),adding:f!==null,addIntent:f??void 0,addDecisionProvider:m,onCloseAdd:g,onCreated:()=>y.refresh()})]})]})}var lA=0;function uA(){return lA+=1,`candidate-${lA}`}function dA(e,t){return{provider:e,model:t,key:uA()}}function fA(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))continue;let e=typeof n.suiteId==`string`?n.suiteId.trim():``,r=n.evidenceLayer;!e||r!==`protocol_conformance`&&r!==`live_route_compatibility`||t.push({suiteId:e,evidenceLayer:r})}return t}function pA(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:fA(t.requiredSuites)};return(t.minStatus===`PROBED`||t.minStatus===`VERIFIED`)&&(n.minStatus=t.minStatus),typeof t.maxEvidenceAgeMs==`number`&&Number.isFinite(t.maxEvidenceAgeMs)&&t.maxEvidenceAgeMs>=0&&(n.maxEvidenceAgeMs=t.maxEvidenceAgeMs),(t.unknownEvidence===`allow`||t.unknownEvidence===`penalize`||t.unknownEvidence===`exclude`)&&(n.unknownEvidence=t.unknownEvidence),(t.degradedEvidence===`allow`||t.degradedEvidence===`penalize`||t.degradedEvidence===`exclude`)&&(n.degradedEvidence=t.degradedEvidence),n}var mA={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},hA={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function gA(e){return e===!0?`true`:e===!1?`false`:``}function _A(e){return e===void 0?``:String(e)}function vA(e=``,t=``){return{id:``,alias:``,candidates:[dA(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...mA},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...hA},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function yA(e){let t=pA(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:uA()})),require:{minContextWindow:_A(e.require.minContextWindow),minQuotaHeadroom:_A(e.require.minQuotaHeadroom),tools:gA(e.require.tools),imageInput:gA(e.require.imageInput),structuredOutput:gA(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:gA(e.require.localOnly),remoteAllowed:gA(e.require.remoteAllowed),encryptedCodexTasks:gA(e.require.encryptedCodexTasks)},optimize:{latency:String(e.optimize.latency),health:String(e.optimize.health),cost:String(e.optimize.cost),quota:String(e.optimize.quota)},limits:{maxEstimatedCostUsd:_A(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:_A(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function bA(e){let t=e.trim();return t?Number(t):void 0}function xA(e){if(e===`true`)return!0;if(e===`false`)return!1}function SA(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function CA(e,t,n){let r=SA({minContextWindow:bA(e.require.minContextWindow),minQuotaHeadroom:bA(e.require.minQuotaHeadroom),tools:xA(e.require.tools),imageInput:xA(e.require.imageInput),structuredOutput:xA(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:xA(e.require.localOnly),remoteAllowed:xA(e.require.remoteAllowed),encryptedCodexTasks:xA(e.require.encryptedCodexTasks)}),i=bA(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?SA({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:bA(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=SA({maxEstimatedCostUsd:i,onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:void 0});return{mode:t,id:e.id.trim(),...t===`update`&&n?{expectedRevision:n}:{},profile:{...e.alias.trim()?{alias:e.alias.trim()}:{},candidates:e.candidates.map(e=>({provider:e.provider.trim(),model:e.model.trim()})),...Object.keys(r).length>0?{require:r}:{},optimize:{latency:Number(e.optimize.latency),health:Number(e.optimize.health),cost:Number(e.optimize.cost),quota:Number(e.optimize.quota)},...Object.keys(o).length>0?{limits:o}:{},unknownEvidence:{...e.unknownEvidence},...a&&Object.keys(a).length>0?{compatibility:a}:{}}}}function wA(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;if(typeof t==`string`&&t.trim())return t;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.message;if(typeof e==`string`&&e.trim())return e}}function TA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function EA(e,t){return e.filter(e=>e.provider===t)}var DA={en:{maxEvidenceAgeMs:`Maximum evidence age (ms)`,unknownEvidence:`Unknown evidence`,degradedEvidence:`Degraded evidence`},de:{maxEvidenceAgeMs:`Maximales Evidenzalter (ms)`,unknownEvidence:`Unbekannte Evidenz`,degradedEvidence:`Eingeschränkte Evidenz`},fr:{maxEvidenceAgeMs:`Âge maximal des preuves (ms)`,unknownEvidence:`Preuves inconnues`,degradedEvidence:`Preuves dégradées`},ko:{maxEvidenceAgeMs:`최대 증거 유효 기간 (ms)`,unknownEvidence:`알 수 없는 증거`,degradedEvidence:`저하된 증거`},zh:{maxEvidenceAgeMs:`证据最大有效期(毫秒)`,unknownEvidence:`未知证据`,degradedEvidence:`降级证据`},"zh-TW":{maxEvidenceAgeMs:`證據最大有效期限(毫秒)`,unknownEvidence:`未知證據`,degradedEvidence:`降級證據`},ru:{maxEvidenceAgeMs:`Максимальный возраст доказательств (мс)`,unknownEvidence:`Неизвестные доказательства`,degradedEvidence:`Ухудшенные доказательства`},ja:{maxEvidenceAgeMs:`エビデンスの最大有効期間 (ms)`,unknownEvidence:`不明なエビデンス`,degradedEvidence:`低下したエビデンス`},tr:{maxEvidenceAgeMs:`Maksimum kanıt yaşı (ms)`,unknownEvidence:`Bilinmeyen kanıt`,degradedEvidence:`Bozulmuş kanıt`},vi:{maxEvidenceAgeMs:`Tuổi bằng chứng tối đa (ms)`,unknownEvidence:`Bằng chứng không xác định`,degradedEvidence:`Bằng chứng bị suy giảm`},pt:{maxEvidenceAgeMs:`Idade máxima da evidência (ms)`,unknownEvidence:`Evidência desconhecida`,degradedEvidence:`Evidência degradada`}},OA=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],kA=[`reasoningEffort`,`serviceTier`],AA={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},jA=Object.keys(AA),MA=[`latency`,`health`,`cost`,`quota`],NA=[`capability`,`health`,`quota`,`cost`],PA=[`allow`,`penalize`,`exclude`],FA=[`allow`,`exclude`];function IA(e){return`${e.evidenceLayer}:${e.suiteId}`}function LA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function RA(e){let t=new Set,n=[];for(let r of e){if(!LA(r))continue;let e=typeof r.suiteId==`string`?r.suiteId.trim():``,i=r.evidenceLayer;if(!e||i!==`protocol_conformance`&&i!==`live_route_compatibility`)continue;let a={suiteId:e,evidenceLayer:i},o=IA(a);t.has(o)||(t.add(o),n.push({...a,key:o}))}return n.sort((e,t)=>{let n=e.evidenceLayer.localeCompare(t.evidenceLayer);return n===0?e.suiteId.localeCompare(t.suiteId):n})}function zA(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function BA(e,t){return e===void 0?t:`${Math.round(e)}ms`}function VA(e,t){return e==null?t:`${Math.round(e*100)}%`}function HA(e,t,n){switch(e){case`satisfied`:return t(`routing.capOutcome.satisfied`);case`exceeded`:return t(`routing.capOutcome.exceeded`);case`unknown-allowed`:return t(`routing.capOutcome.unknown-allowed`);case`unknown-excluded`:return t(`routing.capOutcome.unknown-excluded`);default:return n}}function UA(e,t){switch(e){case`capability-unsatisfied`:return t(`routing.exclusion.capability-unsatisfied`);case`unknown-capability`:return t(`routing.exclusion.unknown-capability`);case`cost-limit`:return t(`routing.exclusion.cost-limit`);case`cost-limit-unknown`:return t(`routing.exclusion.cost-limit-unknown`);case`cooldown`:return t(`routing.exclusion.cooldown`);case`unknown-health`:return t(`routing.exclusion.unknown-health`);case`unknown-quota`:return t(`routing.exclusion.unknown-quota`);case`unknown-price`:return t(`routing.exclusion.unknown-price`);default:return t(`routing.exclusion.other`,{code:e})}}function WA(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid-profiles-response`);let t=e.profiles;if(!Array.isArray(t))throw Error(`invalid-profiles-response`);let n=t.filter(e=>LA(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&LA(e.require)&&LA(e.optimize)&&LA(e.limits)&&LA(e.unknownEvidence):!1);if(t.length>0&&n.length===0)throw Error(`invalid-profiles-response`);return n.map(e=>{let t=pA(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}})}function GA(e){let t=Array.isArray(e)?e:e&&typeof e==`object`&&Array.isArray(e.models)?e.models:[],n=new Set,r=[];for(let e of t){if(!e||typeof e!=`object`||Array.isArray(e))continue;let t=typeof e.provider==`string`?e.provider.trim():``,i=typeof e.id==`string`?e.id.trim():``;if(!t||!i||t===`combo`||t===`policy`||e.disabled===!0)continue;let a=JSON.stringify([t,i]);n.has(a)||(n.add(a),r.push({provider:t,id:i}))}return r}function KA(e,t,n){let r=n??t;if(r){let t=e.find(e=>e.id===r);if(t)return t}return e[0]??null}function qA({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=s(),a=DA[r],o=i(`routing.unavailable`),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)({}),[v,y]=(0,Z.useState)([]),[b,x]=(0,Z.useState)(``),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(!1),[A,j]=(0,Z.useState)(``),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(!1),[R,z]=(0,Z.useState)(null),[B,V]=(0,Z.useState)(``),[H,U]=(0,Z.useState)(!1),[W,ee]=(0,Z.useState)([]),[G,te]=(0,Z.useState)(!1),ne=(0,Z.useRef)(null),K=(0,Z.useRef)(0),q=(0,Z.useRef)(null),J=(0,Z.useRef)(!0),re=(0,Z.useCallback)(()=>{J.current=!1,q.current?.abort(),K.current++},[]),Y=(0,Z.useRef)(0),ie=(0,Z.useCallback)((e,t)=>{D({message:e,ok:t})},[]);(0,Z.useEffect)(()=>{if(!E?.ok)return;let e=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(e)},[E]);let ae=(0,Z.useCallback)(()=>{Y.current+=1,z(null),V(``),U(!1)},[]),oe=(0,Z.useCallback)(e=>{ne.current=e,C(e),T(e?yA(e):null),D(null),ae()},[ae]),se=(0,Z.useCallback)(async t=>{if(!J.current)return;q.current?.abort();let n=new AbortController;q.current=n;let{signal:r}=n,i=++K.current;d(!1),x(``);try{let[n,a,o,s,c]=await Promise.all([fetch(`${e}/api/routing-profiles`,{signal:r}),fetch(`${e}/api/routing-analytics`,{signal:r}),fetch(`${e}/api/config`,{signal:r}),fetch(`${e}/api/models`,{signal:r}),fetch(`${e}/api/lab/catalog`,{signal:r})]);if(!n.ok)throw Error(`load-${n.status}`);let[u,f,m,g,v]=await Promise.all([n.json(),a.ok?a.json():Promise.resolve(null),o.ok?o.json():Promise.resolve({}),s.ok?s.json():Promise.resolve([]),c.ok?c.json().catch(()=>null):Promise.resolve(null)]);if(i!==K.current)return;let b=WA(u),x=ne.current,S=KA(b,x?.id??null,t),w=m.providers??{},E=Object.entries(w).filter(([,e])=>e.disabled!==!0).map(([e])=>e).sort((e,t)=>e<t?-1:+(e>t)),D=Object.fromEntries(Object.entries(w).filter(([,e])=>e.disabled!==!0&&typeof e.defaultModel==`string`).map(([e,t])=>[e,t.defaultModel.trim()]));ne.current=S,l(b),d(!0),C(S),T(S?yA(S):null),p(f),h(E),_(D),y(GA(g)),v&&Array.isArray(v.scenarios)?(ee(RA(v.scenarios)),te(!1)):(ee([]),te(!0)),(!x||!S||x.id!==S.id||x.revision!==S.revision)&&ae()}catch(e){if(i!==K.current||r.aborted)return;x(e instanceof Error?e.message:String(e))}finally{q.current===n&&(q.current=null)}},[e,ae]);(0,Z.useEffect)(()=>{if(!t){re();return}J.current=!0;let e=window.setTimeout(()=>void se(),0);return()=>{window.clearTimeout(e),re()}},[t,re,se]),(0,Z.useEffect)(()=>{n?.(c.length)},[n,c.length]);let ce=m[0]??``,le=g[ce]??EA(v,ce)[0]?.id??``,ue=()=>{ne.current=null,C(null),T(vA(ce,le)),D(null),ae()},de=()=>{S?(T(yA(S)),D(null)):oe(c[0]??null)},fe=async()=>{if(w&&!O){k(!0),D(null);try{let t=CA(w,S?`update`:`create`,S?.revision),n=await fetch(`${e}/api/routing-profiles`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await Xn(n);if(!n.ok){let e=await n.json().catch(()=>null);ie(wA(e)??i(`routing.loadFailed`),!1);return}if(!TA(r)){ie(wA(r)??i(`routing.loadFailed`),!1);return}await se(t.id),ie(i(`common.ok`),!0)}catch(e){ie(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{k(!1)}}},pe=async()=>{if(S&&!O&&await Ju({message:i(`routing.removeConfirm`,{id:S.id}),confirmLabel:i(`common.remove`),tone:`danger`})){k(!0),D(null);try{let t=await fetch(`${e}/api/routing-profiles?id=${encodeURIComponent(S.id)}`,{method:`DELETE`}),n=await Xn(t);if(!t.ok){let e=await t.json().catch(()=>null);ie(wA(e)??i(`routing.loadFailed`),!1);return}if(!TA(n)){ie(wA(n)??i(`routing.loadFailed`),!1);return}ne.current=null,await se(),ie(i(`common.ok`),!0)}catch(e){ie(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{k(!1)}}},me=(e,t,n)=>{T(r=>{if(!r)return r;let i=r.candidates.map((r,i)=>i===e?t===`provider`?{...r,provider:n,model:g[n]??EA(v,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},he=()=>{T(e=>e&&{...e,candidates:[...e.candidates,dA(ce,le)]})},ge=e=>{T(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},_e=async()=>{if(!S)return;let t=++Y.current;U(!0),z(null),V(``);try{let n={},r=A.trim()?Number(A.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),M&&(n.toolsRequired=!0),P&&(n.imageInputRequired=!0),I&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:S.id,evidence:n})});if(t!==Y.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==Y.current)return;V(wA(e)??i(`routing.dryRunError`,{status:a.status}));return}let o=await a.json();if(t!==Y.current)return;z(o)}catch(e){if(t!==Y.current)return;V(e instanceof Error?e.message:String(e))}finally{t===Y.current&&U(!1)}},ve=w?.candidates.map(e=>EA(v,e.provider))??[],ye=PA.map(e=>({value:e,label:i(`routing.unknownEvidence.${e}`)}));return(0,Q.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,Q.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:ue,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void se(),children:i(`common.retry`)})]}),b?(0,Q.jsxs)($,{tone:`err`,children:[i(`routing.loadFailed`),`: `,b]}):null,E?(0,Q.jsx)($,{tone:E.ok?`ok`:`err`,children:E.message}):null,u&&!b&&c.length===0&&!w?(0,Q.jsx)(`p`,{className:`muted`,children:i(`routing.empty`)}):null,c.length>0?(0,Q.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:c.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>oe(e),"aria-pressed":S?.id===e.id,children:(0,Q.jsxs)(`div`,{className:`card-badges`,children:[(0,Q.jsx)(`strong`,{children:e.id}),(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,w?(0,Q.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),fe()},children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,S?.model??(0,Q.jsx)(`code`,{children:`policy/…`})]}),S?(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,S.revision]}):null]}),(0,Q.jsxs)(`div`,{className:`model-grid`,children:[(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`id`}),(0,Q.jsx)(`input`,{className:`input`,required:!0,disabled:S!==null,value:w.id,onChange:e=>T(t=>t&&{...t,id:e.target.value})})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`alias`}),(0,Q.jsx)(`input`,{className:`input`,value:w.alias,onChange:e=>T(t=>t&&{...t,alias:e.target.value})})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[w.candidates.map((e,t)=>{let n=[...new Set([e.provider,...m])].filter(Boolean),r=`routing-model-options-${t}`;return(0,Q.jsxs)(`div`,{className:`model-card`,children:[(0,Q.jsxs)(`div`,{className:`model-grid`,children:[(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`provider`}),(0,Q.jsx)(Vn,{fullWidth:!0,required:!0,value:e.provider,onChange:e=>me(t,`provider`,e),options:[{value:``,label:i(`routing.none`),disabled:!0},...n.map(e=>({value:e,label:e}))]})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`model`}),(0,Q.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>me(t,`model`,e.target.value)}),(0,Q.jsx)(`datalist`,{id:r,children:ve[t]?.map(e=>(0,Q.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w.candidates.length===1,onClick:()=>ge(t),"aria-label":i(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:i(`common.remove`)})]},e.key)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:he,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,Q.jsxs)(`div`,{className:`model-grid`,children:[jA.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:AA[e].min,max:AA[e].max,step:AA[e].step,value:w.require[e],onChange:t=>T(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),kA.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,value:w.require[e],onChange:t=>T(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),OA.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(Vn,{fullWidth:!0,value:w.require[e],onChange:t=>T(n=>n&&{...n,require:{...n.require,[e]:t}}),options:[{value:``,label:i(`routing.none`)},{value:`true`,label:i(`routing.yes`)},{value:`false`,label:i(`routing.no`)}]})]},e))]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,Q.jsx)(`div`,{className:`model-grid`,children:MA.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,required:!0,value:w.optimize[e],onChange:t=>T(n=>n&&{...n,optimize:{...n.optimize,[e]:t.target.value}})})]},e))})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,value:w.limits.maxEstimatedCostUsd,onChange:e=>T(t=>t&&{...t,limits:{...t.limits,maxEstimatedCostUsd:e.target.value}})})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`onUnknownCost`}),(0,Q.jsx)(Vn,{fullWidth:!0,value:w.limits.onUnknownCost,onChange:e=>T(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e}}),options:FA.map(e=>({value:e,label:i(`routing.unknownEvidence.${e}`)}))})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,Q.jsx)(`div`,{className:`model-grid`,children:NA.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(Vn,{fullWidth:!0,value:w.unknownEvidence[e],onChange:t=>T(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t}}),options:ye})]},e))})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:w.compatibility.enabled,onChange:e=>T(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),i(`routing.compatibility.enabled`)]}),w.compatibility.enabled?(0,Q.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,Q.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),G?(0,Q.jsx)(`div`,{style:{marginTop:6},children:(0,Q.jsx)($,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,W.length>0?(0,Q.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:W.map(e=>(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:zA(w.compatibility.requiredSuites,e),onChange:t=>T(n=>{if(!n)return n;let r=t.target.checked?[...n.compatibility.requiredSuites,{suiteId:e.suiteId,evidenceLayer:e.evidenceLayer}]:n.compatibility.requiredSuites.filter(t=>t.suiteId!==e.suiteId||t.evidenceLayer!==e.evidenceLayer);return{...n,compatibility:{...n.compatibility,requiredSuites:r}}})}),(0,Q.jsxs)(`span`,{children:[e.suiteId,` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,Q.jsx)(Vn,{fullWidth:!0,value:w.compatibility.minStatus,onChange:e=>T(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e}}),options:[{value:``,label:i(`routing.none`)},{value:`PROBED`,label:i(`lab.verdict.PROBED`)},{value:`VERIFIED`,label:i(`lab.verdict.VERIFIED`)}]})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[a.maxEvidenceAgeMs,(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:0,value:w.compatibility.maxEvidenceAgeMs,onChange:e=>T(t=>t&&{...t,compatibility:{...t.compatibility,maxEvidenceAgeMs:e.target.value}})})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[a.unknownEvidence,(0,Q.jsx)(Vn,{fullWidth:!0,value:w.compatibility.unknownEvidence,onChange:e=>T(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e}}),options:ye})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[a.degradedEvidence,(0,Q.jsx)(Vn,{fullWidth:!0,value:w.compatibility.degradedEvidence,onChange:e=>T(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e}}),options:ye})]})]}):null]}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:O,children:i(O?`common.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:O,onClick:de,children:i(`common.cancel`)}),S?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:O,onClick:()=>void pe(),children:i(`common.remove`)}):null]})]}):null,S&&(0,Q.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Q.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,Q.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:A,onChange:e=>{j(e.target.value),ae()}})]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),ae()}}),i(`routing.dryRunTools`)]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),ae()}}),i(`routing.dryRunImage`)]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:I,onChange:e=>{L(e.target.checked),ae()}}),i(`routing.dryRunStructured`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!S||H,onClick:()=>void _e(),children:i(`routing.dryRunRun`)}),B?(0,Q.jsx)($,{tone:`err`,children:B}):null,R?(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`routing.candidate`)}),(0,Q.jsx)(`th`,{children:i(`routing.eligible`)}),(0,Q.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,Q.jsx)(`th`,{children:i(`routing.costCap`)}),(0,Q.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,Q.jsx)(`tbody`,{children:R.candidates.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===R.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,Q.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,Q.jsx)(`td`,{children:e.exclusions.map(e=>UA(e.code,i)).join(`, `)||i(`routing.none`)}),(0,Q.jsx)(`td`,{children:HA(e.cost?.capOutcome,i,o)}),(0,Q.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):o})]},`${e.provider}/${e.model}`))})]}):null]}),c.length>0&&(0,Q.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Q.jsx)(`h3`,{children:i(`routing.analytics`)}),f?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`card-badges`,children:[(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,f.totalRequests]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,VA(f.successRate,o)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,VA(f.fallbackRate,o)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,BA(f.durationMs.p50,o)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,BA(f.durationMs.p95,o)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,BA(f.durationMs.p99,o)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,f.cooldownTriggeringFailures]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,f.confidence??o]}),f.historyTruncated?(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`routing.candidate`)}),(0,Q.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,Q.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,Q.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,Q.jsx)(`tbody`,{children:f.breakdown.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,Q.jsx)(`td`,{children:e.requests}),(0,Q.jsx)(`td`,{children:VA(e.successRate,o)}),(0,Q.jsx)(`td`,{children:BA(e.p50DurationMs,o)})]},`${e.provider}/${e.model}`))})]})]}):(0,Q.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var JA=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],YA=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],XA=[`present`,`corrupt`,`purged_unavailable`];function ZA(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function QA(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function $A(e){return e===null||typeof e==`string`}function ej(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function tj(e){if(!ZA(e)||typeof e.projectionAvailable!=`boolean`||e.projectionIncompatible!==void 0&&typeof e.projectionIncompatible!=`boolean`)return null;for(let t of[`sqliteSchemaVersion`,`builtAtMs`,`eventCount`,`subjectCount`,`observationCount`,`claimCount`,`verdictCount`,`artifactCount`,`corruptionCount`])if(!ej(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function nj(e){return!ZA(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!JA.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||e.suiteId.length===0||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.projectionSpecVersion!=`string`||typeof e.verdict!=`string`||!YA.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!QA(e.scenarioManifestDigests)||!$A(e.claimSourceDigest)||!QA(e.contributingEventIds)||!QA(e.contradictingEventIds)||!QA(e.notes)?null:e}function rj(e){return!ZA(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(nj).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function ij(e){return!ZA(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>ZA(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function aj(e){return!ZA(e)||!ZA(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function oj(e){return!ZA(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!JA.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.scenarioId!=`string`||typeof e.scenarioVersion!=`string`||typeof e.scenarioManifestDigest!=`string`||typeof e.outcome!=`string`||typeof e.completedAt!=`number`||!Number.isFinite(e.completedAt)||typeof e.executionMode!=`string`||typeof e.excluded!=`boolean`||!$A(e.exclusionReason)?null:e}function sj(e){return!ZA(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(oj).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function cj(e){if(!ZA(e)||!ZA(e.event))return null;let t={...e.event};return delete t.payload_json,typeof t.eventKind!=`string`||typeof t.eventId!=`string`||typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt)||typeof t.producer!=`string`||typeof t.producerVersion!=`string`||typeof t.excluded!=`boolean`||!$A(t.exclusionReason)?null:t}function lj(e){if(!ZA(e)||!ZA(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!XA.includes(t.status)||!$A(t.artifactClass)||!$A(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!$A(t.lastError)?null:t}function uj(e){let t={},n=e.subjectQuery.trim();return e.layer&&(t.layer=e.layer),e.verdict&&(t.verdict=e.verdict),n&&(t.subjectId=n),e.suiteId.trim()&&(t.suiteId=e.suiteId.trim()),t}function dj(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function fj(e,t){let n=new Map(t.map(e=>[e.subjectId,e.subjectKind])),r=new Map;for(let t of e){let e=r.get(t.subjectId);e||(e={subjectId:t.subjectId,subjectKind:n.get(t.subjectId)??``,byLayer:dj()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function pj(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function mj(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function hj(e){let t=new Set;e.suiteManifestDigest&&t.add(e.suiteManifestDigest);for(let n of e.scenarioManifestDigests)n&&t.add(n);return e.claimSourceDigest&&t.add(e.claimSourceDigest),[...t]}function gj(e){if(!e)return{};let t=typeof e.inboundProtocol==`string`?kC(e.inboundProtocol):void 0,n=typeof e.upstreamProtocol==`string`?kC(e.upstreamProtocol):void 0;return{...t?{inbound:t}:{},...n?{upstream:n}:{}}}function _j(e){return e.inbound!==``||e.upstream!==``}function vj(e,t){return!_j(t)||!(!e||t.inbound&&e.inbound!==t.inbound||t.upstream&&e.upstream!==t.upstream)}function yj(e,t,n){return _j(n)?e.filter(e=>vj(t.get(e.subjectId),n)):e}function bj(e,t){return _j(e)?t.some(e=>JA.some(t=>e.byLayer[t].length>0))?`evidence`:`unverified`:`any`}function xj(){let e=b();return t=>t?mw(t,e):e(`compatProtocol.anyProtocol`)}function Sj({value:e,onChange:t}){let n=b(),r=xj(),i=[{value:``,label:n(`lab.filter.all`)},...dC.map(e=>({value:e,label:r(e)}))];return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-inbound`,children:n(`compatProtocol.filter.inbound`)}),(0,Q.jsx)(Vn,{id:`lab-filter-inbound`,value:e.inbound,options:i,onChange:n=>t({...e,inbound:n}),label:n(`compatProtocol.filter.inbound`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-upstream`,children:n(`compatProtocol.filter.upstream`)}),(0,Q.jsx)(Vn,{id:`lab-filter-upstream`,value:e.upstream,options:i,onChange:n=>t({...e,upstream:n}),label:n(`compatProtocol.filter.upstream`),portal:!1})]})]})}function Cj({filter:e,evidence:t,resolution:n}){let r=b(),i=xj();if(!_j(e))return null;let a=r(`compatProtocol.pair`,{inbound:i(e.inbound),upstream:i(e.upstream)});return(0,Q.jsxs)(`div`,{className:`lab-protocol-status`,"data-pair-evidence":n.loading?`loading`:t,children:[n.loading?(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:r(`compatProtocol.loading`)}):t===`unverified`?(0,Q.jsx)(`p`,{className:`lab-protocol-unverified`,role:`status`,children:r(`compatProtocol.unverified`,{pair:a})}):null,n.unresolved>0&&!n.loading&&(0,Q.jsx)(`p`,{className:`muted small`,children:r(`compatProtocol.unresolved`,{count:n.unresolved})}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`compatProtocol.axisNote`)})]})}var wj=50,Tj=200,Ej=6,Dj=200;async function Oj(e,t,n){return Yn(await fetch(`${e}${t}`,{signal:n}))}function kj(e,t){let n=new URLSearchParams({limit:String(wj)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Aj=class extends Error{};function jj(){return new Aj}function Mj(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw jj()}function Nj(e){if(!ZA(e)||!Array.isArray(e.verdicts))throw jj();let t=rj(e);if(t.verdicts.length!==e.verdicts.length)throw jj();return Mj(e,t.hasMore,t.nextCursor),t}function Pj(e){if(!ZA(e)||!Array.isArray(e.subjects))throw jj();let t=ij(e);if(t.subjects.length!==e.subjects.length)throw jj();return Mj(e,t.hasMore,t.nextCursor),t}function Fj(e){if(!ZA(e)||!Array.isArray(e.observations))throw jj();let t=sj(e);if(t.observations.length!==e.observations.length)throw jj();return Mj(e,t.hasMore,t.nextCursor),t}async function Ij(e,t){let n=tj(await Oj(e,`/api/lab/status`,t));if(!n)throw jj();return n}async function Lj(e,t,n,r){return Nj(await Oj(e,`/api/lab/verdicts?${kj({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Rj(e,t,n){return Pj(await Oj(e,`/api/lab/subjects?${kj({},t)}`,n))}async function zj(e){let t=[],n=new Set,r;for(let i=0;i<Tj;i++){let i=await e(r);if(t.push(...i.rows),!i.hasMore)return{rows:t,truncated:!1};let a=i.nextCursor;if(!a||n.has(a)||a===r)throw new Aj;n.add(a),r=a}return{rows:t,truncated:!0}}async function Bj(e,t){return zj(async n=>{let r=await Rj(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function Vj(e,t,n){let r=aj(await Oj(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw jj();return r}async function Hj(e,t,n,r){return Fj(await Oj(e,`/api/lab/observations?${kj({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Uj(e,t,n){return zj(async r=>{let i=await Hj(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Wj(e,t,n){let r=cj(await Oj(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw jj();return r}async function Gj(e,t,n){let r=lj(await Oj(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw jj();return r}function Kj(e){if(!ZA(e)||e.verificationStatus!==`not_verification`||!ZA(e.summary))throw jj();let t=e.summary;if(t.verificationStatus!==`not_verification`||typeof t.subjectId!=`string`||typeof t.recentProductionAttempts!=`number`||typeof t.recentSuccessfulAttempts!=`number`||typeof t.recentRouteErrorSignals!=`number`||t.lastObservedProductionAttempt!==void 0&&typeof t.lastObservedProductionAttempt!=`number`)throw jj();return{verificationStatus:`not_verification`,summary:t}}async function qj(e,t,n){return Kj(await Oj(e,`/api/lab/production-signals?${kj({subjectId:t})}`,n))}function Jj(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function Yj(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function Xj(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Zj(e){if(!ZA(e)||!Jj(e,[`evidence`,`trustClass`,`locallyVerified`])||e.trustClass!==`community_untrusted_v1`||e.locallyVerified!==!1||!Array.isArray(e.evidence)||e.evidence.length>4096)return null;let t=[];for(let n of e.evidence){if(!ZA(n)||!Jj(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!Yj(n.bundleId)||!Yj(n.publisherKeyId)||!Xj(n.activeRecordCount)||!Xj(n.revokedRecordCount))return null;t.push({trustClass:`community_untrusted_v1`,status:`cryptographically_valid`,bundleId:n.bundleId,publisherKeyId:n.publisherKeyId,activeRecordCount:n.activeRecordCount,revokedRecordCount:n.revokedRecordCount})}return{evidence:t,trustClass:`community_untrusted_v1`,locallyVerified:!1}}async function Qj(e,t){let n=Zj(await Oj(e,`/api/lab/public/community`,t));if(!n)throw jj();return n}async function $j(e,t,n){let[r,i]=await Promise.all([Ij(e,n),Qj(e,n).catch(e=>{if(n.aborted)throw e;return null})]);if(!r.projectionAvailable)return{status:r,verdicts:[],subjects:[],subjectsTruncated:!1,hasMore:!1,community:i};let[a,o]=await Promise.all([Lj(e,t,void 0,n),Bj(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function eM(e,t,n,r){return Lj(e,t,n,r)}async function tM(e,t,n,r){let i=e.slice(0,Dj),a=[],o=0,s=async()=>{for(;;){if(n.aborted)throw new DOMException(`Aborted`,`AbortError`);let e=o++;if(e>=i.length)return;try{a.push(await r(i[e]))}catch(e){if(n.aborted)throw e}}},c=Math.min(t,i.length);return await Promise.all(Array.from({length:c},()=>s())),a}async function nM(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=hj(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([Vj(e,t.subjectId,n),Uj(e,a,n),tM(r,Ej,n,t=>Wj(e,t,n)),tM(i,Ej,n,t=>Gj(e,t,n)),qj(e,t.subjectId,n).catch(e=>{if(n.aborted)throw e;return null})]);return{subject:o,observations:s.rows,observationsTruncated:s.truncated,events:c,artifacts:l,production:u}}var rM=6,iM=2e3,aM=`
9
- `,oM=new Map;function sM(e,t){return JSON.stringify([e,t])}function cM(e,t){for(oM.set(e,t);oM.size>iM;){let e=oM.keys().next().value;if(e===void 0)break;oM.delete(e)}}var lM={pairs:new Map,loading:!1,unresolved:0};function uM(e,t,n){let[,r]=(0,Z.useState)(0),i=n?t.slice(0,200):[],a=i.filter(t=>!oM.has(sM(e,t))).join(aM);if((0,Z.useEffect)(()=>{if(!a)return;let t=new AbortController,n=a.split(aM);return Promise.all(Array.from({length:Math.min(rM,n.length)},async()=>{for(let r=n.shift();r!==void 0;r=n.shift())try{let n=await Vj(e,r,t.signal);cM(sM(e,r),gj(n))}catch{if(t.signal.aborted)return;cM(sM(e,r),null)}})).then(()=>{t.signal.aborted||r(e=>e+1)}),()=>t.abort()},[e,a]),!n)return lM;let o=new Map,s=Math.max(0,t.length-200);for(let t of i){let n=oM.get(sM(e,t));n?o.set(t,n):n===null&&(s+=1)}return{pairs:o,loading:a.length>0,unresolved:s}}var dM={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},fM={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},pM={UNKNOWN:`lab.verdict.UNKNOWN`,CLAIMED:`lab.verdict.CLAIMED`,PROBED:`lab.verdict.PROBED`,VERIFIED:`lab.verdict.VERIFIED`,DEGRADED:`lab.verdict.DEGRADED`,BLOCKED:`lab.verdict.BLOCKED`,UNSUPPORTED:`lab.verdict.UNSUPPORTED`},mM={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function hM(e,t){if(!(e instanceof Error))return t;let n=e.message;return n===`Failed to fetch`||n.includes(`NetworkError`)||n.includes(`network error`)?t:n||t}function gM({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,Q.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]}):(0,Q.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]})}function _M({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:`-`}):(0,Q.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,Q.jsx)(gM,{verdict:e.verdict,caption:e.suiteId,label:t(pM[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function vM({data:e,t,locale:n}){let{status:r}=e,i=[{label:t(`lab.subjectCount`),value:String(r.subjectCount??0)},{label:t(`lab.verdictCount`),value:String(r.verdictCount??0)},{label:t(`lab.observationCount`),value:String(r.observationCount??0)},{label:t(`lab.eventCount`),value:String(r.eventCount??0)}];return r.builtAtMs&&i.push({label:t(`lab.builtAt`),value:mj(r.builtAtMs,n)}),(0,Q.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,Q.jsxs)(`div`,{className:`lab-status-card`,children:[(0,Q.jsx)(`span`,{className:`label`,children:e.label}),(0,Q.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function yM({community:e,locale:t}){if(!e||e.evidence.length===0)return null;let n=e.evidence.reduce((e,t)=>e+t.activeRecordCount,0),r=e.evidence.reduce((e,t)=>e+t.revokedRecordCount,0);return(0,Q.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:H(t,`community.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:H(t,`community.notLocalVerdict`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:H(t,`community.bundles`)}),(0,Q.jsx)(`dd`,{children:e.evidence.length})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:H(t,`community.activeRecords`)}),(0,Q.jsx)(`dd`,{children:n})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:H(t,`community.revokedRecords`)}),(0,Q.jsx)(`dd`,{children:r})]})]})]})}function bM({verdict:e,detail:t,loading:n,error:r,t:i,locale:a,onClose:o}){let s=new Set([...e.contributingEventIds,...e.contradictingEventIds]).size;return(0,Q.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,Q.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,Q.jsx)(`h3`,{children:pj(e.subjectId)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,Q.jsx)(`dd`,{children:i(dM[e.evidenceLayer])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,Q.jsx)(`dd`,{children:i(pM[e.verdict])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,Q.jsx)(`dd`,{children:mj(e.asOf,a)})]})]}),n&&(0,Q.jsx)(lk,{busy:!0,children:i(`common.loading`)}),r&&(0,Q.jsx)($,{tone:`err`,children:r}),t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,Q.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,Q.jsx)(`dd`,{children:mj(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,Q.jsx)(`span`,{children:e.outcome}),(0,Q.jsx)(`span`,{className:`muted`,children:mj(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,Q.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,title:e.digest,children:pj(e.digest)}),(0,Q.jsx)(`span`,{children:e.artifactClass??`-`}),(0,Q.jsx)(`span`,{children:H(a,mM[e.status])})]},e.digest))})]})]})]})}function xM({apiBase:e,active:t=!0,onCountChange:n}){let{t:r,locale:i}=s(),[a,o]=(0,Z.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[c,l]=(0,Z.useState)(()=>iE()??eE),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(null),w=(0,Z.useRef)(null),T=(0,Z.useRef)(null),E=(0,Z.useRef)(null),D=(0,Z.useMemo)(()=>uj(a),[a]),O=JSON.stringify(D),k=(0,Z.useCallback)(t=>$j(e,D,t),[e,D]),A=mf(`lab-matrix:${e}:${O}`,[e,O],k,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:t,pauseWhenHidden:!0}),j=(0,Z.useCallback)(()=>{w.current?.abort(),w.current=null,d(null),p(null),h(!1)},[]),M=(0,Z.useCallback)(()=>{E.current=null,T.current?.abort(),T.current=null,_(null),y(null),C(null),x(!1)},[]);(0,Z.useEffect)(()=>{w.current?.abort()},[A.data]),(0,Z.useEffect)(()=>()=>{w.current?.abort(),T.current?.abort()},[]);let N=(0,Z.useCallback)(e=>{M(),j(),o(e)},[M,j]),P=(0,Z.useCallback)(e=>{M(),l(e),t&&Tn(nE(e))},[t,M]);(0,Z.useEffect)(()=>{let e=()=>{let e=iE();e&&l(t=>t.inbound===e.inbound&&t.upstream===e.upstream?t:e)};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let F=u!==null&&u.baseData===A.data&&u.queryKey===O?u:null,I=f!==null&&f.baseData===A.data&&f.queryKey===O?f.message:null,L=(0,Z.useMemo)(()=>{if(!t||!A.data?.status.projectionAvailable)return null;let e=A.data.status.verdictCount;return typeof e==`number`?e:A.data.verdicts.length+(F?.verdicts.length??0)},[t,A.data,F]);(0,Z.useEffect)(()=>{n?.(L)},[n,L]);let R=(0,Z.useMemo)(()=>A.data?[...A.data.verdicts,...F?.verdicts??[]]:[],[A.data,F]),z=(0,Z.useMemo)(()=>A.data?fj(R,A.data.subjects):[],[R,A.data]),B=_j(c),V=uM(e,(0,Z.useMemo)(()=>z.map(e=>e.subjectId),[z]),t&&B),U=(0,Z.useMemo)(()=>yj(z,V.pairs,c),[c,V.pairs,z]),W=(0,Z.useMemo)(()=>{if(!B)return R;let e=new Set(U.map(e=>e.subjectId));return R.filter(t=>e.has(t.subjectId))},[R,U,B]),ee=bj(c,U),G=(0,Z.useCallback)(async()=>{let t=F?.nextCursor??A.data?.nextCursor,n=A.data;if(!t||!n||m)return;w.current?.abort();let i=new AbortController;w.current=i;let a=O;p(null),h(!0);try{let r=await eM(e,D,t,i.signal);if(i.signal.aborted)return;d(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...r.verdicts],nextCursor:r.nextCursor,hasMore:r.hasMore}})}catch(e){i.signal.aborted||p({baseData:n,queryKey:a,message:hM(e,r(`lab.loadFailed`))})}finally{w.current===i&&(w.current=null,h(!1))}},[e,m,D,O,A.data,r,F]),te=(0,Z.useCallback)(async n=>{if(!t)return;T.current?.abort();let i=new AbortController;T.current=i,E.current=n.projectionKey,_(n),y(null),C(null),x(!0);try{let t=await nM(e,n,i.signal);!i.signal.aborted&&E.current===n.projectionKey&&y(t)}catch(e){!i.signal.aborted&&E.current===n.projectionKey&&C(hM(e,r(`lab.detailLoadFailed`)))}finally{T.current===i&&(T.current=null,!i.signal.aborted&&E.current===n.projectionKey&&x(!1))}},[t,e,r]),ne=A.refresh,K=(0,Z.useCallback)(()=>{M(),j(),ne({forceLoading:!0})},[M,ne,j]),q=t?g:null,J=F?F.hasMore:A.data?.hasMore??!1,re=[{value:``,label:r(`lab.filter.all`)},...JA.map(e=>({value:e,label:r(dM[e])}))],Y=[{value:``,label:r(`lab.filter.all`)},...YA.map(e=>({value:e,label:r(pM[e])}))],ie=[{value:``,label:r(`lab.filter.all`)},...(A.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${pj(e.subjectId)} · ${e.subjectKind}`}))];if(A.state.showSkeleton)return(0,Q.jsx)(ck,{label:r(`lab.loading`),rows:5});let ae=A.state.showError?hM(A.error,r(`lab.loadFailed`)):null,oe=A.data?.status,se=oe&&!oe.projectionAvailable,ce=oe?.projectionIncompatible===!0;return(0,Q.jsxs)(`div`,{className:`lab-page`,children:[(0,Q.jsx)(`div`,{className:`lab-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:K,disabled:A.refreshing,children:[(0,Q.jsx)(Ke,{}),r(`lab.refresh`)]})}),A.refreshing&&!A.state.showSkeleton&&(0,Q.jsx)(lk,{busy:!0,live:!ae,children:r(`common.loading`)}),ae&&(0,Q.jsx)($,{tone:`err`,children:ae}),ce&&(0,Q.jsx)($,{tone:`err`,children:r(`lab.projectionIncompatible`)}),se&&!ce&&(0,Q.jsx)(Un,{title:r(`lab.projectionUnavailable`)}),se&&!ce&&(0,Q.jsx)(Cj,{filter:c,evidence:`unverified`,resolution:{loading:!1,unresolved:0}}),A.data&&(0,Q.jsx)(yM,{community:A.data.community,locale:i}),A.data&&oe?.projectionAvailable&&!ce&&(0,Q.jsxs)(`div`,{className:`lab-layout`,children:[(0,Q.jsxs)(`div`,{className:`lab-main`,children:[(0,Q.jsx)(vM,{data:A.data,t:r,locale:i}),(0,Q.jsxs)(`div`,{className:`lab-filters`,children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:r(`lab.filter.layer`)}),(0,Q.jsx)(Vn,{id:`lab-filter-layer`,value:a.layer,options:re,onChange:e=>N(t=>({...t,layer:e})),label:r(`lab.filter.layer`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:r(`lab.filter.verdict`)}),(0,Q.jsx)(Vn,{id:`lab-filter-verdict`,value:a.verdict,options:Y,onChange:e=>N(t=>({...t,verdict:e})),label:r(`lab.filter.verdict`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:r(`lab.filter.subject`)}),(0,Q.jsx)(Vn,{id:`lab-filter-subject`,value:a.subjectQuery,options:ie,onChange:e=>N(t=>({...t,subjectQuery:e})),label:r(`lab.filter.subject`),portal:!1})]}),(0,Q.jsx)(Sj,{value:c,onChange:P})]}),(0,Q.jsx)(Cj,{filter:c,evidence:ee,resolution:V}),U.length===0?(0,Q.jsx)(Un,{title:r(`lab.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.matrixTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-matrix`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:r(`lab.subjectKind`)}),JA.map(e=>(0,Q.jsx)(`th`,{children:r(fM[e])},e))]})}),(0,Q.jsx)(`tbody`,{children:U.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`subject`,title:e.subjectId,children:pj(e.subjectId)}),(0,Q.jsx)(`td`,{className:`kind`,children:e.subjectKind||H(i,`subjectKindUnknown`)}),JA.map(t=>(0,Q.jsx)(`td`,{children:(0,Q.jsx)(_M,{rows:e.byLayer[t],t:r,selectedKey:q?.projectionKey??null,onSelect:e=>{te(e)}})},t))]},e.subjectId))})]})})]}),(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.verdictsTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:r(`lab.col.layer`)}),(0,Q.jsx)(`th`,{children:r(`lab.col.suite`)}),(0,Q.jsx)(`th`,{children:r(`lab.col.verdict`)}),(0,Q.jsx)(`th`,{children:r(`lab.col.asOf`)})]})}),(0,Q.jsx)(`tbody`,{children:W.map(e=>{let t=q?.projectionKey===e.projectionKey;return(0,Q.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":H(i,`selectVerdict`,{subject:pj(e.subjectId)}),onClick:()=>{te(e)},children:pj(e.subjectId)})}),(0,Q.jsx)(`td`,{children:r(dM[e.evidenceLayer])}),(0,Q.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(gM,{verdict:e.verdict,caption:e.suiteId,label:r(pM[e.verdict])})}),(0,Q.jsx)(`td`,{children:mj(e.asOf,i)})]},e.projectionKey)})})]})})]}),I&&(0,Q.jsx)($,{tone:`err`,children:I}),J&&(0,Q.jsx)(`div`,{className:`lab-load-more`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:m,onClick:()=>{G()},children:r(m?`common.loading`:`lab.loadMore`)})})]})]}),q&&(0,Q.jsx)(bM,{verdict:q,detail:v,loading:b,error:S,t:r,locale:i,onClose:M})]})]})}var SM=[`catalog`,`combos`,`routing`,`compatibility`];function CM(e){return e===`catalog`?`models`:`models/${e}`}function wM(e=window.location.hash){let t=wn(Cn(e)).path;return t===`models/combos`||t===`models/combos/jev-auto`||t===`combos`||t.startsWith(`combos/`)?`combos`:t===`models/routing`||t===`routing`||t.startsWith(`routing/`)?`routing`:t===`models/compatibility`||t===`lab`||t.startsWith(`lab/`)?`compatibility`:`catalog`}function TM(e){En(CM(e))}function EM(e){return`models-tab-${e}`}function DM(e){return`models-panel-${e}`}var OM={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function kM({tab:e,onSelect:t,meta:n}){let r=b(),i=(0,Z.useRef)(null);i.current===null&&(i.current=new Map);let a=e=>{t(e),window.requestAnimationFrame(()=>{i.current.get(e)?.focus({preventScroll:!0})})},o=t=>{let n=SM.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+SM.length)%SM.length:t.key===`ArrowRight`?r=(n+1)%SM.length:t.key===`Home`?r=0:t.key===`End`&&(r=SM.length-1),r!==null&&(t.preventDefault(),a(SM[r]))};return(0,Q.jsx)(`div`,{className:`page-tabs models-page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:SM.map(t=>{let s=t===e,c=n?.[t];return(0,Q.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:EM(t),"aria-selected":s,"aria-controls":DM(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(OM[t]),c?(0,Q.jsx)(`span`,{className:`section-tab-meta tabular-nums`,children:c}):null]},t)})})}function AM({summary:e,apiBase:t,onSaved:n}){let r=b(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),c=e?.fastOptIn?.enabled;if(o&&c!==o.from&&s(null),!e?.fastOptIn)return null;let l=e.fastOptIn.enabled,u=o&&o.from===l?o.value:l,d=async o=>{if(!(i||o===u)){a(!0);try{await Yn(await fetch(`${t}/api/providers?name=${encodeURIComponent(e.name)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({fastEnabled:o})}),r(`models.fastSaveFailed`)),s({value:o,from:l}),n(!0,r(o?`models.fastEnabled`:`models.fastDisabled`))}catch(e){n(!1,e instanceof Error?e.message:r(`models.fastSaveFailed`))}finally{a(!1)}}};return(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:r(`models.fastProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":r(`models.fastProvider`),children:[!1,!0].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e,className:`btn btn-sm${u===e?` btn-primary`:` btn-ghost`}`,disabled:i,onClick:()=>void d(e),children:r(e?`models.newPolicy_on`:`models.newPolicy_off`)},String(e)))}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`models.fastProviderHint`)})]})}function jM(e,t){let n=new Map;for(let t of e){let e=n.get(t.provider);e?e.push(t):n.set(t.provider,[t])}let r=new Map(t.map(e=>[e.name,e]));for(let e of t)e.disabled===!0?n.delete(e.name):e.authMode!==`forward`&&(n.has(e.name)||n.set(e.name,[]));return[...n.entries()].map(([e,t])=>{let n=r.get(e);return{provider:e,rows:t,native:t.length>0&&t.every(e=>e.native===!0),nativeProviderGroup:t.some(e=>e.native===!0)||e===`openai`&&n?.authMode===`forward`,liveModels:n?.liveModels!==!1,configuredModels:n?.models??[],contextWindow:n?.contextWindow,modelContextWindows:n?.modelContextWindows,discovery:n?.discovery,entitlement:n?.entitlement}}).sort((e,t)=>e.nativeProviderGroup===t.nativeProviderGroup?e.provider.localeCompare(t.provider):e.nativeProviderGroup?-1:1)}function MM({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=b(),i=e&&t?.status===`failed`?t:void 0;return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(He,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[i&&n&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${lp(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>En(`providers`),children:r(`models.openProviderSettings`)})]})]})}function NM(){let e=b();return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(He,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[`${e(`models.discoveryFailedDependency`,{control:e(`pws.liveModels`)})} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>En(`providers`),children:e(`models.openProviderSettings`)})]})]})}var PM=`ocx.models.settingsOpen.v1`;function FM(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function IM(e){try{return FM(e)?.getItem(PM)===`1`}catch{return!1}}function LM(e,t){try{FM(t)?.setItem(PM,e?`1`:`0`)}catch{}}var RM={default:`models.pickerOrder.default`,alphabetical:`models.pickerOrder.alphabetical`,provider:`models.pickerOrder.provider`,"most-used":`models.pickerOrder.mostUsed`,custom:`models.pickerOrder.custom`};function zM(e,t){let n=e(`models.settingsPanel.off`),r=[];t.multiAgentMode&&r.push({id:`subagent`,label:e(`models.v2Label`),value:e(`models.v2Mode_${t.multiAgentMode}`)}),typeof t.v2Threads==`number`&&r.push({id:`threads`,label:e(`models.v2ThreadsLabel`),value:String(t.v2Threads)}),t.multiAgentMode===`v2`&&t.keepNativeOnV1&&r.push({id:`keep-native`,label:e(`models.keepNativeOnV1`),value:``}),r.push({id:`shadow`,label:e(`models.shadowCallIntercept`),value:t.shadowEnabled&&t.shadowModel?t.shadowModel:n}),t.autoReviewEnabled&&r.push({id:`auto-review`,label:e(`models.autoReviewOverride`),value:t.autoReviewModel||e(`models.autoReviewPending`)}),r.push({id:`window`,label:e(`models.contextCapLabel`),value:t.windowOn?Op(t.windowValue):n});let i=RM[t.pickerMode];return r.push({id:`order`,label:e(`models.pickerOrder.label`),value:i?e(i):t.pickerMode}),t.newModelsOff&&r.push({id:`new-models`,label:e(`models.newPolicyGlobal`),value:``}),t.aliasesOn&&r.push({id:`aliases`,label:e(`models.useDefaultAliasesGlobal`),value:``}),r}function BM({title:e,attentionLabel:t,summary:n,warn:r,children:i,storage:a}){let[o,s]=(0,Z.useState)(()=>IM(a)),[c,l]=(0,Z.useState)(!1),u=o||r&&!c;return(0,Q.jsxs)(`details`,{className:`models-settings`,open:u,onToggle:e=>{let t=e.currentTarget.open;t!==u&&(s(t),!t&&r&&l(!0),LM(t,a))},children:[(0,Q.jsxs)(`summary`,{className:`models-settings-summary`,children:[(0,Q.jsx)(`span`,{className:`models-settings-title`,children:e}),r&&(0,Q.jsx)(`span`,{className:`models-settings-warn`,role:`img`,"aria-label":t,title:t}),(0,Q.jsx)(`span`,{className:`models-settings-state`,children:n.map(e=>(0,Q.jsxs)(`span`,{className:`models-settings-kv`,"data-item":e.id,children:[(0,Q.jsx)(`span`,{className:`models-settings-k`,children:e.label}),e.value&&(0,Q.jsx)(`span`,{className:`models-settings-v`,children:e.value})]},e.id))})]}),(0,Q.jsx)(`div`,{className:`models-settings-body`,children:i})]})}function VM({count:e,label:t}){return e===0?null:(0,Q.jsx)(`span`,{className:`models-chip mono text-caption models-custom-summary`,children:t})}function HM({text:e}){return(0,Q.jsx)(Wn,{content:e,side:`top`,maxWidth:360,children:(0,Q.jsxs)(`span`,{className:`models-info-hint`,children:[(0,Q.jsx)(He,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})})}function UM({label:e,hint:t,busy:n,muted:r=!0,caption:i,children:a}){let o=[`models-row-label`,r?`muted`:``,i?`text-caption`:`text-control`].filter(Boolean).join(` `);return(0,Q.jsxs)(`div`,{className:`models-control-row`,"aria-busy":n||void 0,children:[(0,Q.jsxs)(`span`,{className:o,children:[e,t?(0,Q.jsxs)(Q.Fragment,{children:[` `,t]}):null]}),(0,Q.jsx)(`div`,{className:`models-row-actions`,children:a})]})}function WM({shadowCall:e,saving:t,modelOptions:n,onSave:r}){let i=b(),a=i(`models.shadowCallInterceptHint`,{models:$n(e?.sourceModels)});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(UM,{label:i(`models.shadowCallIntercept`),hint:(0,Q.jsx)(Wn,{content:a,side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":a,children:(0,Q.jsx)(He,{width:13,height:13,"aria-hidden":`true`})})}),busy:!e,children:[(0,Q.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:i(`models.shadowCallOriginal`,{models:rr(e?.sourceModels,i(`shadowCall.memoryLabel`))})}),(0,Q.jsx)(Rn,{on:e?.enabled??!1,onClick:()=>r({enabled:!e?.enabled}),disabled:!e||t,label:i(`models.shadowCallIntercept`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(Vn,{value:e?.model??``,options:n,onChange:e=>r({model:e}),disabled:!e||t||!e.enabled,label:i(`models.shadowCallIntercept`)})})]}),(0,Q.jsx)(Wd,{className:`models-shadow-sources`,options:e?.sourceModelOptions,sourceModels:e?.sourceModels,disabled:!e?.enabled,saving:t,onChange:e=>r({sourceModels:e})})]})}function GM(e,t){if(!e)return null;let n=new Date(e);return Number.isNaN(n.getTime())?null:new Intl.DateTimeFormat(t,{dateStyle:`medium`,timeStyle:`short`}).format(n)}function KM({connected:e,catalogSyncedAt:t}){let{locale:n,t:r}=s(),i=GM(t,n),a=e?[{id:`saved`,chip:r(`models.delivery.chip.savedHub`),title:r(`models.delivery.savedHub.title`),body:r(`models.delivery.savedHub.body`)},{id:`synced`,chip:i?r(`models.delivery.chip.synced`,{time:i}):r(`models.delivery.chip.syncedUnknown`),title:r(`models.delivery.synced.title`),body:i?r(`models.delivery.synced.bodyAt`,{time:i}):r(`models.delivery.synced.bodyUnknown`)}]:[{id:`saved`,chip:r(`models.delivery.chip.saved`),title:r(`models.delivery.saved.title`),body:r(`models.delivery.saved.body`)}];return a.push({id:`loaded`,chip:r(`models.delivery.chip.loaded`),title:r(`models.delivery.loaded.title`),body:r(`models.delivery.loaded.body`)}),(0,Q.jsxs)(`details`,{className:`models-delivery`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`models-delivery-title`,children:r(`models.delivery.title`)}),(0,Q.jsx)(`span`,{className:`models-delivery-flow`,children:a.map(e=>e.chip).join(` → `)})]}),(0,Q.jsx)(`ol`,{className:`models-delivery-steps`,children:a.map(e=>(0,Q.jsxs)(`li`,{"data-step":e.id,children:[(0,Q.jsx)(`strong`,{children:e.title}),(0,Q.jsx)(`p`,{children:e.body})]},e.id))}),(0,Q.jsx)(`p`,{className:`models-delivery-hint`,children:r(`models.delivery.hint`)})]})}function qM(e,t,n){let[r,i]=(0,Z.useState)({apiBase:e,data:null,saving:!1}),a=r.apiBase===e?r.data:null,o=r.apiBase===e&&r.saving,s=(0,Z.useRef)({read:null,write:null,generation:0,apiBase:e});(0,Z.useLayoutEffect)(()=>{let t=s.current;return t.apiBase=e,t.generation++,()=>{t.generation++,t.read?.controller.abort(),t.read?.clear(),t.read=null,t.write?.controller.abort(),t.write?.clear(),t.write=null}},[e]);let c=(0,Z.useCallback)(async({reconcile:t=!1}={})=>{let n=s.current;if(n.write&&!t)return null;n.read?.controller.abort(),n.read?.clear();let r=d(15e3),a=n.generation;n.read=r;try{let o=await Xn(await fetch(`${e}/api/auto-review-settings`,{signal:r.signal}));return!o||typeof o.enabled!=`boolean`||typeof o.model!=`string`?null:!r.signal.aborted&&n.apiBase===e&&n.generation===a&&n.read===r&&(!n.write||t)?(i({apiBase:e,data:o,saving:n.write!==null}),o):null}catch{return null}finally{r.clear(),n.read===r&&(n.read=null)}},[e]);return{data:a,saving:o,load:c,save:(0,Z.useCallback)(async r=>{let l=s.current;if(!a||o||l.apiBase!==e||l.write)return;let u=a,f=d(15e3);l.write=f;let p=++l.generation;l.read?.controller.abort(),l.read?.clear(),l.read=null,i({apiBase:e,data:{...u,...r},saving:!0});try{let a=await Yn(await fetch(`${e}/api/auto-review-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:f.signal,body:JSON.stringify(r)}),t(`models.saveFailed`));if(!a||a.ok!==!0||typeof a.enabled!=`boolean`||typeof a.model!=`string`)throw Error(t(`models.saveFailed`));if(l.apiBase!==e||l.generation!==p)return;i({apiBase:e,data:{enabled:a.enabled,model:a.model},saving:!0}),(!a.catalogRefresh||a.catalogRefresh.status!==`committed`)&&n(!1,t(`codexAuth.catalogRefreshPending`))}catch(r){if(l.apiBase===e&&l.generation===p){let a=await c({reconcile:!0});if(l.apiBase!==e||l.generation!==p)return;i({apiBase:e,data:a??u,saving:!0}),n(!1,r instanceof Error&&r.message?r.message:t(`models.saveFailed`))}}finally{f.clear(),l.write===f&&(l.write=null),l.apiBase===e&&l.generation===p&&i(t=>t.apiBase===e?{...t,saving:!1}:t)}},[e,a,o,t,n,c])}}function JM({apiBase:e,publishFeedback:t,t:n}){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(!1);return{shadowCall:r,shadowCallSaving:a,loadShadowCall:(0,Z.useCallback)(async()=>{let t=d(15e3);try{let n=await Xn(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&i(n)}catch{}finally{t.clear()}},[e]),saveShadowCall:async s=>{if(!r||a)return;let c=r;o(!0),i({...r,...s});try{let r=await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s)});if(!r.ok){i(c),t(!1,n(_p((await r.json().catch(()=>null))?.code)));return}let a=await r.json().catch(()=>null);a&&typeof a.enabled==`boolean`&&i(a)}catch{i(c),t(!1,n(`models.networkError`))}finally{o(!1)}}}}function YM({text:e,children:t}){let n=b(),[r,i]=(0,Z.useState)(!1),a=(0,Z.useId)(),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{if(!r)return;let e=o.current?.ownerDocument,t=e=>{o.current?.contains(e.target)||i(!1)},n=e=>{e.key===`Escape`&&(i(!1),s.current?.focus({preventScroll:!0}))};return e?.addEventListener(`pointerdown`,t),e?.addEventListener(`keydown`,n),()=>{e?.removeEventListener(`pointerdown`,t),e?.removeEventListener(`keydown`,n)}},[r]),(0,Q.jsxs)(`div`,{ref:o,className:`ui-v2 relative`,children:[(0,Q.jsx)(`button`,{ref:s,type:`button`,"aria-expanded":r,"aria-controls":a,"aria-label":n(`modelsV2.about`),title:n(`modelsV2.about`),onClick:()=>i(e=>!e),className:X(`grid size-8 cursor-pointer place-items-center rounded-[10px] text-fg-muted transition-colors duration-200`,`hover:bg-surface hover:text-fg aria-expanded:bg-surface aria-expanded:text-fg`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`grid size-[18px] place-items-center rounded-full text-[11px] leading-none font-semibold ring-[1.5px] ring-current`,children:`?`})}),(0,Q.jsxs)(`div`,{id:a,role:`region`,"aria-label":n(`modelsV2.about`),hidden:!r,className:X(`models-about absolute top-10 right-0 z-30 w-[min(460px,calc(100vw-48px))] flex-col gap-3 rounded-[12px] bg-raised p-4 text-[13px] leading-5 text-fg-muted shadow-lg ring-1 ring-line`,r?`flex`:`hidden`),children:[(0,Q.jsx)(`p`,{className:`m-0`,children:e}),t]})]})}function XM({name:e,className:t}){let n=Dt(e),r=xt(n);return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`inline-grid size-5 shrink-0 place-items-center overflow-hidden rounded-[6px] bg-raised text-fg ring-1 ring-line`,r===`plate`&&`bg-[#f4f4f4]`,r===`dark-plate`&&`bg-[#1c1c1c]`,t),children:n&&r===`mask`?(0,Q.jsx)(`span`,{className:`block size-3.5 bg-current [mask-position:center] [mask-repeat:no-repeat] [mask-size:contain]`,style:{maskImage:`url(${n})`,WebkitMaskImage:`url(${n})`}}):n?(0,Q.jsx)(`img`,{src:n,alt:``,className:`block size-3.5 object-contain`}):(0,Q.jsx)(`span`,{className:`text-[11px] leading-none font-semibold uppercase`,children:e.slice(0,1)})})}function ZM({items:e,all:t,selected:n,onSelect:r}){let i=b();return(0,Q.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":i(`nav.models`),children:[(0,Q.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-title`,children:i(`models.workspace.providers`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-count`,children:e.length})]}),(0,Q.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,Q.jsx)(QM,{label:i(`models.workspace.allProviders`),meta:i(`models.active`,t),ratio:t.total?t.active/t.total:0,current:n===null,onClick:()=>r(null)}),e.map(e=>(0,Q.jsx)(QM,{provider:e.provider,label:re(e.provider,i),meta:i(`models.active`,{active:e.active,total:e.total}),ratio:e.total?e.active/e.total:0,current:n===e.provider,onClick:()=>r(e.provider)},e.provider))]})]})}function QM({provider:e,label:t,meta:n,ratio:r,current:i,onClick:a}){return(0,Q.jsxs)(`button`,{type:`button`,className:X(`models-workspace-rail-row`,i&&`models-workspace-rail-row--selected`),onClick:a,"aria-current":i?`true`:void 0,children:[e?(0,Q.jsx)(XM,{name:e}):(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`models-rail-all-mark`}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:t}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:n}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`models-rail-meter`,children:(0,Q.jsx)(`span`,{style:{width:`${Math.round(r*100)}%`}})})]})}var $M={catalog:[`modelsV2.ledeCatalog`,`models.subtitle`],combos:[`modelsV2.ledeCombos`,`models.subtitle.combos`],routing:[`models.subtitle.routing`],compatibility:[`models.subtitle.compatibility`]};function eN({apiBase:e,restartEpoch:t=0,connected:n=!1,catalogSyncedAt:r,reportRestart:i}){let[a,o]=(0,Z.useState)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(l.current=!0,()=>{l.current=!1}),[]);let u=(0,Z.useRef)(null),f=(0,Z.useRef)(0),p=(0,Z.useRef)(e),m=(0,Z.useCallback)(()=>{f.current++,u.current?.controller.abort(),u.current?.clear(),u.current=null},[]),h=(0,Z.useCallback)(async()=>{if(!l.current||p.current!==e)return;m();let t=f.current,n=d(15e3);u.current=n;try{let r=await TD(e,{signal:n.signal});if(n.signal.aborted||!l.current||p.current!==e||t!==f.current||u.current!==n)return;o(r.state)}finally{n.clear(),u.current===n&&(u.current=null)}},[e,m]),{restarting:g,restart:_}=jD(e,{onSettled:()=>{h()},restoreFocusFallback:e=>e?.hasAttribute(`data-models-reload-action`)?c.current??s.current:null,report:i});(0,Z.useEffect)(()=>(p.current=e,o(null),h(),m),[e,m,h,t]);let[v,y]=(0,Z.useState)(wM),[x,S]=(0,Z.useState)(()=>new Set([wM()])),C=(0,Z.useCallback)(e=>{y(e),S(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,Z.useEffect)(()=>{let e=()=>C(wM());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[C]);let w=(0,Z.useCallback)(e=>{TM(e),C(e)},[C]),T=v===`catalog`,[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),M=b(),N=`ocx.models.catalog.v1:${e}`,P=(0,Z.useMemo)(()=>sf(N),[N]),[F,I]=(0,Z.useState)(()=>P?.models??[]),[L,R]=(0,Z.useState)(()=>P?.providers??[]),[z,B]=(0,Z.useState)(()=>new Set(P?.disabled??[])),[V,H]=(0,Z.useState)(()=>P?.selectedModels??null),[U,W]=(0,Z.useState)({}),[ee,G]=(0,Z.useState)({}),[te,ne]=(0,Z.useState)({}),[K,q]=(0,Z.useState)(()=>P?.contextCaps??{}),[J,Y]=(0,Z.useState)(()=>P?.contextCapValues??{}),[ie,ae]=(0,Z.useState)(()=>P?.contextCapValue??35e4),oe=`${N}:picker-order`,se=(0,Z.useMemo)(()=>{let e=sf(oe);return CE(e)?e:void 0},[oe]),[ce,le]=(0,Z.useState)(null),[ue,de]=(0,Z.useState)(!1),fe=(0,Z.useRef)(null),pe=(0,Z.useRef)(0),me=mf(oe,[e],(0,Z.useCallback)(async t=>{let n=await Yn(await fetch(`${e}/api/subagent-models`,{signal:t}));if(!CE(n))throw Error(`picker settings payload missing`);if(t.aborted)throw Error(`picker settings request aborted`);return df(oe,n),n},[e,oe]),{isEmpty:()=>!1,enabled:T,deadlineMs:15e3,initialData:se}),he=me.state.data,ge=ce??kE(he?.pickerAvailable??[],he?.pickerOrder??[],he?.pickerOrderMode);(0,Z.useLayoutEffect)(()=>(pe.current++,le(null),de(!1),()=>{pe.current++,fe.current?.controller.abort(),fe.current?.clear(),fe.current=null}),[e,T]),(0,Z.useLayoutEffect)(()=>{T&&ce===null&&ge===`custom`&&le(`custom`)},[T,ce,ge]);let[_e,ve]=(0,Z.useState)(``),[ye,xe]=(0,Z.useState)(!1),[Se,Ce]=(0,Z.useState)({}),[we,Te]=(0,Z.useState)({}),Ee=Mp(),[De,Oe]=(0,Z.useState)(()=>Ee??new Set),ke=(0,Z.useRef)(Ee===null),[Ae,je]=(0,Z.useState)(``),[Me,Ne]=(0,Z.useState)([]),[Pe,Fe]=(0,Z.useState)(!1),[Ie,Le]=(0,Z.useState)(0),Re=(0,Z.useCallback)((e,t)=>{Fe(e),je(t),Le(e=>e+1)},[]),{data:ze,saving:Be,load:Ve,save:Ue}=qM(e,M,Re);(0,Z.useEffect)(()=>{T||Ve()},[e,T,Ve]),(0,Z.useEffect)(()=>{if(!Ae)return;let e=setTimeout(()=>je(``),Pe?6e3:8e3);return()=>clearTimeout(e)},[Ae,Pe,Ie]);let[We,Ge]=(0,Z.useState)(!1),qe=(0,Z.useRef)(!1),Je=(0,Z.useRef)(!1),Ye=(0,Z.useRef)(0),Xe=(0,Z.useRef)(!1),Ze=ok(e,{onQueued:()=>{++Ye.current,je(``)},onBusy:e=>{++Ye.current,Xe.current=!1,Je.current=e,qe.current=e,Ge(e)},onResponse:e=>{let t=ep(e);t!==void 0&&Ne(t)},refresh:e=>xr(!0,e),onSettled:e=>{Fe(!e),je(M(e??`models.applied`))}}),Qe=(e,t,n,r,i)=>Ze.visible(t,n,r,op(e,t,n,r,i)),[$e,et]=(0,Z.useState)(null),[tt,nt]=(0,Z.useState)({}),[rt,it]=(0,Z.useState)(null),[at,ot]=(0,Z.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[ct,ut]=(0,Z.useState)(!1),[dt,ft]=(0,Z.useState)(null),[pt,X]=(0,Z.useState)(!0),[mt,ht]=(0,Z.useState)(!1),[gt,_t]=(0,Z.useState)(``),vt=(0,Z.useRef)(!1),yt=(0,Z.useRef)(0),bt=(0,Z.useRef)(0),[xt,Ct]=(0,Z.useState)(``),[wt,Tt]=(0,Z.useState)(!1),[Et,Dt]=(0,Z.useState)(!1),[Ot,kt]=(0,Z.useState)(null),[Mt,Nt]=(0,Z.useState)(null),[Pt,Ft]=(0,Z.useState)(!1),[It,Lt]=(0,Z.useState)(null),[Rt,zt]=(0,Z.useState)(null),Bt=(0,Z.useRef)(null),[Vt,Ht]=(0,Z.useState)(null),[Ut,Wt]=(0,Z.useState)(!1),[Gt,Kt]=(0,Z.useState)(null),[qt,Jt]=(0,Z.useState)(null),[Yt,Xt]=(0,Z.useState)(!1),Zt=(0,Z.useRef)(null),Qt=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>()=>{Zt.current?.controller.abort(),Zt.current?.clear(),Zt.current=null},[]);let $t=(0,Z.useRef)(null),en=(0,Z.useCallback)(async t=>{let n=await Xn(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&ot(n)},[e]);(0,Z.useEffect)(()=>{let e=new AbortController;return en(e.signal),()=>e.abort()},[en]);let tn={apiBase:e,t:M,reloadAliases:en,publishFeedback:Re},nn=e=>MD(e,at.providers[e]??``,tn),rn=(e,t)=>ND(e,t,at.models[e]?.[t]?.alias??``,tn),an=async(t,n)=>{(await fetch(`${e}/api/default-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:t,...n?{provider:n}:{}})})).ok&&await en()},[on,sn]=(0,Z.useState)(`add`),[cn,ln]=(0,Z.useState)(``),[un,dn]=(0,Z.useState)(``),[fn,pn]=(0,Z.useState)(``),[mn,hn]=(0,Z.useState)(``),[gn,_n]=(0,Z.useState)(``),[vn,yn]=(0,Z.useState)(!1),[bn,xn]=(0,Z.useState)([`text`]),[Cn,wn]=(0,Z.useState)(!1),[Tn,En]=(0,Z.useState)([]),Dn=(0,Z.useRef)(!1),[On,kn]=(0,Z.useState)(!1),[An,jn]=(0,Z.useState)(``),[Mn,Nn]=(0,Z.useState)(null),[Pn,Fn]=(0,Z.useState)([]),[In,Ln]=(0,Z.useState)(``),[zn,Bn]=(0,Z.useState)(``),[Hn,Gn]=(0,Z.useState)({}),[Kn,qn]=(0,Z.useState)({contextWindow:null,modelContextWindows:{}}),[Jn,Zn]=(0,Z.useState)(new Set),[Qn,$n]=(0,Z.useState)(!1),[er,tr]=(0,Z.useState)(!1),[nr,rr]=(0,Z.useState)(``),[ir,ar]=(0,Z.useState)(null),or=(0,Z.useRef)(null),{shadowCall:sr,shadowCallSaving:cr,loadShadowCall:lr,saveShadowCall:ur}=JM({apiBase:e,publishFeedback:Re,t:M}),[dr,fr]=(0,Z.useState)(null);(0,Z.useEffect)(()=>()=>{or.current&&clearTimeout(or.current)},[]);let pr=(0,Z.useMemo)(()=>Ap(F,z,V??{},M),[F,z,V,M]),mr=(0,Z.useMemo)(()=>{let e=new Set(pr.map(e=>e.value));return Nr(F.filter(t=>e.has(t.namespaced)),sr?.model,sr?.sourceModels)},[F,sr?.model,sr?.sourceModels,pr]),hr=(0,Z.useMemo)(()=>[{value:``,label:`—`},...jp(pr,F,ze?.model)],[F,pr,ze?.model]),gr=(0,Z.useCallback)(async()=>{if(vt.current)return;let t=++yt.current,n=bt.current,r=()=>t===yt.current&&n===bt.current,i=d(15e3);try{let t=await fetch(`${e}/api/v2`,{signal:i.signal});if(!r())return;if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){et(null);return}let n=await Xn(t);if(!r())return;if(!n||typeof n.enabled!=`boolean`){et(null);return}et(gp(n))}catch{r()&&et(null)}finally{i.clear(),X(!1)}},[e]),_r=(0,Z.useCallback)(async t=>{let n=Ye.current,[r,i,a,o]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),ip(e,fetch,t)]),[s,c,l]=await Promise.all([Yn(r),Yn(i),Yn(a)]);if(s===void 0||c===void 0||l===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let u=kp(s),d=typeof c.value==`number`&&Number.isFinite(c.value)&&c.value>0?c.value:typeof c.cap==`number`&&Number.isFinite(c.cap)&&c.cap>0?c.cap:void 0,f=d===void 0?35e4:d,p={models:s,providers:l,selectedModels:o,disabled:[...u],contextCaps:c.caps??{},contextCapValues:c.values??c.caps??{},contextCapValue:f};return n===Ye.current&&df(N,p),p},[e,N]),vr=(0,Z.useCallback)(e=>{let t=jM(e.models,e.providers);fr(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),I(e.models),R(e.providers),B(new Set(e.disabled)),H(e.selectedModels),ae(e.contextCapValue),q(e.contextCaps),Y(e.contextCapValues??e.contextCaps)},[]),yr=mf(N,[e],async e=>{let t=Ye.current,n=await _r(e);if(e.aborted)throw Error(`models request aborted`);return!Je.current&&t===Ye.current&&vr(n),n},{isEmpty:()=>!1,pollMs:1e4,initialData:P??void 0,enabled:T,deadlineMs:6e4}),br=yr.state,xr=(0,Z.useCallback)(async(e=!1,t)=>{if(Xe.current&&!e)return!1;Xe.current=!0;let n=++Ye.current;try{let e=await _r(t??new AbortController().signal);return cp(n,Ye.current)?(vr(e),Sn(N,e),me.refresh(),!0):!1}catch{return!1}finally{cp(n,Ye.current)&&(Xe.current=!1)}},[vr,N,_r,me.refresh]),Sr=(0,Z.useCallback)(()=>{let e=$t.current;Lt(null),Kt(null),Jt(null),Xt(!1),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)},[]),Cr=(0,Z.useCallback)(()=>{Qt.current||Sr()},[Sr]),wr=(0,Z.useCallback)(async t=>{let n=It;if(!n||Qt.current)return;let r=d(6e4);Zt.current=r,Qt.current=!0,Wt(!0),Kt(null);let i=qt?.confirmed===!0&&(t===void 0||t===qt.value),a=t===void 0,o=t===void 0;try{if(t!==void 0){let s=await fetch(`${e}/api/providers/${encodeURIComponent(n.provider)}/model-display-names`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:n.id,displayName:t}),signal:r.signal}),c=s.ok?await Yn(s,M(`models.displayNameSaveFailed`)):await s.json();if(r.signal.throwIfAborted(),!c||typeof c!=`object`||Array.isArray(c)||!s.ok&&c.saved!==!0&&typeof c.error!=`string`)throw Error(M(`models.displayNameSaveFailed`));a=!0;let l=s.ok||c.saved===!0;if(i||=l,l){let e=c.displayNameOverride===null?void 0:c.displayNameOverride??t??void 0,r={displayName:c.displayName??e,displayNameOverride:e,displayNameSource:c.displayNameSource??(e?`operator`:void 0)};I(e=>e.map(e=>e.namespaced===n.namespaced?{...e,...r}:e)),Lt({...n,...r}),Xt(r.displayName===void 0)}if(!s.ok)throw Error(c.error||M(`models.displayNameSaveFailed`));o=!0}if(!await xr(!0,r.signal))throw Error(M(`models.loadFail`));r.signal.throwIfAborted(),Re(!0,M(i?t===null||t===void 0&&qt?.value===null?`models.displayNameResetDone`:`models.displayNameSaved`:`models.displayNameReloaded`)),Sr()}catch(e){if(Zt.current!==r)return;let n=!a||r.signal.aborted;n&&!i&&Xt(!0),Jt(i||n||o?{value:o||n?void 0:t,confirmed:i}:null),Kt(i?M(`models.displayNameSavedRefreshFailed`):n||o?M(`models.displayNameOutcomeUnknown`):e instanceof Error&&e.message?e.message:M(`models.displayNameSaveFailed`))}finally{r.clear(),Zt.current===r&&(Zt.current=null,Qt.current=!1,Wt(!1))}},[e,It,qt,Sr,xr,Re,M]);(0,Z.useEffect)(()=>{if(!T)return;let e=window.setTimeout(()=>{lr(),Ve(),gr(),Qr(),$r()},0),t=$u(()=>{vt.current||gr()},1e4);return()=>{window.clearTimeout(e),t()}},[T,lr,Ve,gr]);let Tr=(0,Z.useMemo)(()=>jM(F,L),[F,L]),Er=F.length>0||br.data!==void 0,Dr=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;Nn(e.provider),Fn(t),Ln(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));Bn(r),Gn(i),qn({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Zn(new Set),$n(!1),rr(``)},Or=e=>{Ln(e)},kr=async()=>{if(!Mn)return;let t=Pp(zn);if(!Tr.find(e=>e.provider===Mn)){rr(M(`models.contextSaveFailed`));return}if(Qn&&t===void 0){rr(M(`models.contextInvalid`));return}let n=Object.create(null);for(let e of Jn){let t=Pp(zD(Hn,e)??``);if(t===void 0){rr(M(`models.contextInvalid`));return}t!==(zD(Kn.modelContextWindows,e)??null)&&(n[e]=t)}let r=Qn&&t!==Kn.contextWindow;if(!r&&Object.keys(n).length===0)Nn(null),Re(!0,M(`models.contextUnchanged`));else{tr(!0),rr(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await Yn(await fetch(`${e}/api/providers?name=${encodeURIComponent(Mn)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),M(`models.contextSaveFailed`))}catch(e){rr(e instanceof Error?e.message:M(`models.contextSaveFailed`));return}finally{tr(!1)}Nn(null),Re(!0,M(`models.contextSaved`)),await xr(!0)}};(0,Z.useEffect)(()=>{if(!ke.current||Tr.length===0)return;ke.current=!1;let e=new Set(Tr.map(e=>e.provider));Oe(e),Np(e)},[Tr]);let Ar=(0,Z.useMemo)(()=>V?F.filter(e=>Qe(V,e.provider,e.id,e.native===!0,z.has(e.namespaced))).length:0,[z,F,V,Ze.overrides]),jr=(0,Z.useMemo)(()=>({catalog:Er?M(`models.active`,{active:Ar,total:F.length}):void 0,combos:E===null?void 0:String(E),routing:O===null?void 0:String(O),compatibility:A===null?void 0:String(A)}),[Er,E,A,Ar,F.length,O,M]),Mr=async(e,t,n,r)=>{(!qe.current||Ze.isRunning())&&Ze.enqueue(e,t,n,r)},Pr=async t=>{Ge(!0),qe.current=!0,je(``);let n=K[t]===void 0;try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,enabled:n})});try{let e=await Yn(r,M(`models.capSaveFailed`));q(e?.caps??{}),Y(e?.values??e?.caps??{}),Fe(!0),je(M(`models.capApplied`)),await xr(!0)}catch(e){Fe(!1),je(e instanceof Error?e.message:M(`models.capSaveFailed`))}}catch{Fe(!1),je(M(`models.networkError`))}finally{Ge(!1),qe.current=!1}},Fr=e=>{Oe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Np(n),n})},Ir=e=>{Oe(()=>{let t=e?new Set(Tr.map(e=>e.provider)):new Set;return Np(t),t})},Lr=async t=>{Ge(!0),qe.current=!0,je(``);try{let n=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await Yn(n,M(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&ae(e.value),q(e?.caps??{}),Y(e?.values??e?.caps??{}),Fe(!0),je(M(`models.capApplied`)),await xr(!0)}catch(e){Fe(!1),je(e instanceof Error?e.message:M(`models.capSaveFailed`))}}catch{Fe(!1),je(M(`models.networkError`))}finally{Ge(!1),qe.current=!1}},Rr=(0,Z.useMemo)(()=>{let e=Tr.filter(e=>!e.native);return e.length>0&&e.every(e=>K[e.provider]===ie)&&Object.keys(K).every(e=>K[e]===ie)},[Tr,K,ie]),zr=e=>{!Number.isSafeInteger(e)||e<=0||Lr(Rr?{value:e,setAll:!0}:{value:e})},Br=(e,t)=>{if(t===`custom`){Ce(t=>({...t,[e]:!0})),Te(t=>({...t,[e]:String(K[e]??J[e]??ie)}));return}Ce(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==K[e]&&Lr({provider:e,enabled:!0,value:n})},Vr=e=>{let t=Number((we[e]??``).replace(/[_,\s]/g,``));!Number.isSafeInteger(t)||t<=0?Re(!1,M(`models.capSaveFailed`)):(Ce(t=>({...t,[e]:!1})),Lr({provider:e,enabled:!0,value:t}))},Ur=e=>{if(e===`custom`){xe(!0),ve(String(ie));return}xe(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==ie&&zr(t)},Jr=()=>{let e=Number(_e.replace(/[_,\s]/g,``));!Number.isSafeInteger(e)||e<=0?Re(!1,M(`models.capSaveFailed`)):(xe(!1),zr(e))},Yr=()=>{Lr({setAll:!Rr})},Xr=async t=>{if($e&&!vt.current){ht(!0),vt.current=!0,bt.current++,_t(``),je(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await Yn(n,M(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`||t.multiAgentMode===`v2-plaintext`&&!Gr(e)){Fe(!1),je(M(`models.saveFailed`));return}et(gp(e)),Fe(!0),je(M(`models.v2Applied`)),_t((e.warnings??[]).join(` `))}catch(e){Fe(!1),je(e instanceof Error?e.message:M(`models.saveFailed`))}}catch{Fe(!1),je(M(`models.networkError`))}finally{ht(!1),vt.current=!1}}},Zr=async t=>{$e&&$e.multiAgentMode!==t&&(t===`v1`?await Xr({multiAgentMode:`v1`}):t===`v2-plaintext`?Nt(e):kt(t))},Qr=async()=>{try{let t=d(15e3),n=await Xn(await fetch(`${e}/api/model-presets`,{signal:t.signal}));nt(n?.providers??{})}catch{nt({})}},$r=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);it(await Xn(t)??null)}catch{it(null)}},ei=async(t,n)=>{await Xn(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([$r(),xr()])},ti=async(t,n,r)=>{if((!r||await Ju({message:M(`models.presetConfirmReplace`,{count:String(r.presetCount)}),tone:`danger`}))&&!Je.current){Je.current=!0,ft(t),Ge(!0),qe.current=!0;try{let r=d(3e4),i=await Yn(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}),M(`models.saveFailed`));if(!i)throw Error(M(`models.saveFailed`));if(i.fallback===`preset-empty`)Re(!1,M(`models.presetEmpty`,{provider:t}));else{let e=ep(i);e!==void 0&&Ne(e),Re(!0,n===`all`?M(`models.presetClearedToast`,{provider:t}):M(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)}))}await Promise.all([Qr(),xr()])}catch(e){Re(!1,e instanceof Error?e.message:String(e))}finally{ft(null),Ge(!1),qe.current=!1,Je.current=!1}}},ni=async e=>{$e&&$e.keepNativeChatGptOnV1!==e&&await Xr({keepNativeChatGptOnV1:e})},ri=$e?.maxConcurrentThreadsPerSession==null?null:Tp($e.maxConcurrentThreadsPerSession,$e.enabled),ii=async t=>{if(!$e||vt.current)return;let n=Ep(t,$e.enabled);if(!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n))Re(!1,M(`models.v2ThreadsInvalid`));else if(ri!==t){ht(!0),vt.current=!0,bt.current++,_t(``),je(``);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await Yn(t,M(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Fe(!1),je(M(`models.saveFailed`));return}et(gp(e)),Fe(!0),je(M(`models.v2ThreadsApplied`)),Tt(!1)}catch(e){Fe(!1),je(e instanceof Error?e.message:M(`models.saveFailed`))}}catch{Fe(!1),je(M(`models.networkError`))}finally{ht(!1),vt.current=!1}}},ai=e=>{e===`custom`?(Tt(!0),Ct(String(ri??``))):(Tt(!1),ii(Number(e)))},oi=(e,t)=>{or.current&&clearTimeout(or.current),or.current=setTimeout(()=>{ar({namespaced:e,rect:t.getBoundingClientRect()})},300)},si=(e,t)=>{or.current&&clearTimeout(or.current),ar({namespaced:e,rect:t.getBoundingClientRect()})},ci=()=>{or.current&&clearTimeout(or.current),or.current=setTimeout(()=>ar(null),120)},li=()=>{or.current&&clearTimeout(or.current)},ui=async(t,n,r,i,a,o)=>{kn(!0),jn(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,modelId:n,displayName:r,contextWindow:i,inputModalities:a,reasoningEfforts:o})});try{await Yn(s,M(`models.customSaveFailed`)),Ft(!1),Re(!0,M(`models.customAdded`)),await xr(!0)}catch(e){jn(e instanceof Error?e.message:M(`models.customSaveFailed`))}}catch{jn(M(`models.networkError`))}finally{kn(!1)}},di=async(t,n)=>{kn(!0),jn(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await Yn(r,M(`models.customSaveFailed`)),Ft(!1),Re(!0,M(`models.customUpdated`)),await xr(!0)}catch(e){jn(e instanceof Error?e.message:M(`models.customSaveFailed`))}}catch{jn(M(`models.networkError`))}finally{kn(!1)}},fi=async(t,n)=>{if(await Ju({message:M(`models.customDeleteConfirm`,{name:n}),confirmLabel:M(`common.delete`),tone:`danger`}))try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(Re(!0,M(`models.customDeleted`)),await xr(!0)):Re(!1,M(`models.customSaveFailed`))}catch{Re(!1,M(`models.networkError`))}},pi=br.data??P,mi=br.kind===`failed-cold`?br.error instanceof Error?br.error.message:M(`models.loadFail`):null,hi=br.showSkeleton&&!pi,gi=V??{},_i=t=>{let{provider:n,rows:r,nativeProviderGroup:i,liveModels:a,discovery:o}=t,s=De.has(n),c=e=>Qe(gi,n,e.id,e.native===!0,z.has(e.namespaced)),l=ee[n]===!0,u=up(r),d=fp(l,r),f=dp(r,d),p=f.filter(c).length,m=rt?.recentArrivals[n]??[],h=new Set(m.map(e=>e.id)),g=K[n]!==void 0,_=K[n]??J[n]??ie,v=t.nativeProviderGroup?bp:vp,y=t.nativeProviderGroup?xp:yp,b=a&&o?.status===`failed`?o:void 0,x=(U[n]??``).trim().toLowerCase(),S=x?f.filter(e=>e.id.toLowerCase().includes(x)):f,C=S.toSorted((e,t)=>Number(!c(e))-Number(!c(t))),w=te[n]??60,T=C.slice(0,w),E=S.length-T.length,D=f.length>0,O=r.some(e=>e.initialSelectionPending),k=!D||f.every(c),A=!D||f.every(e=>!c(e)),j=e=>{D&&!O&&Mr(`provider`,n,f.map(e=>({id:e.id,native:e.native===!0})),e)},N=(()=>{let e=tt[n];if(!e)return null;let t=We||dt!==null,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":M(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.mode===r,className:`btn btn-sm${e.mode===r?` btn-primary`:` btn-ghost`}`,style:{background:e.mode===r?void 0:`transparent`,color:e.mode===r?void 0:`var(--muted)`},disabled:We||t||O,onClick:t=>{t.stopPropagation(),ti(n,r,r===`preset`&&e.mode===`custom`?e:void 0)},children:M(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:M(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:M(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:M(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})();return(0,Q.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,Q.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>Fr(n),"aria-expanded":!s,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,Q.jsx)(lt,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,Q.jsx)(XM,{name:n}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:At(n)}),at.providers[n]&&(0,Q.jsx)(`span`,{className:`models-chip models-chip--identifier mono text-caption`,children:at.providers[n]}),i&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:M(`models.nativeGroupLabel`)}),b&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:lp(M,b),children:M(`models.discoveryFailedBadge`)}),(0,Q.jsx)(`span`,{className:`muted mono text-label models-provider-count`,children:M(`models.active`,{active:p,total:f.length})}),m.length>0&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:M(`models.newCount`,{count:m.length})}),s&&g&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:M(`models.contextCappedValue`,{value:Op(_)})})]}),(0,Q.jsxs)(`div`,{className:`row models-provider-actions`,children:[N,(0,Q.jsxs)(`div`,{className:`models-bulk`,role:`group`,"aria-label":M(`modelsV2.bulkLabel`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:We&&!Ze.pending||k||O,onClick:()=>j(!0),children:M(`models.allOn`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:We&&!Ze.pending||A||O,onClick:()=>j(!1),children:M(`models.allOff`)})]})]}),!s&&(0,Q.jsxs)(`div`,{className:`row models-provider-actions models-provider-tools`,role:`group`,"aria-label":M(`modelsV2.providerTools`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm models-alias-edit`,"aria-label":M(`models.editProviderAlias`),title:M(`models.editProviderAlias`),onClick:()=>void nn(n),children:(0,Q.jsx)(be,{style:{width:14,height:14}})}),(0,Q.jsx)(Rn,{on:at.defaults.providers[n]??at.defaults.global,onClick:()=>void an(!(at.defaults.providers[n]??at.defaults.global),n),label:M(`models.useDefaultAliases`),showLabel:!0}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),sn(`add`),ln(n),dn(``),pn(``),hn(``),_n(``),yn(!1),xn([`text`]),wn(!1),En([]),Dn.current=!1,jn(``),Ft(!0)},"aria-haspopup":`dialog`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,M(`models.customAdd`)]}),(0,Q.jsxs)(`div`,{className:`models-cap-cluster`,children:[(0,Q.jsx)(Rn,{on:g,onClick:()=>Pr(n),disabled:We,label:M(`models.contextCapLabel`),showLabel:!0}),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Vn,{value:Se[n]?`custom`:String(_),options:[...!y.has(_)&&!Se[n]?[{value:String(_),label:Op(_)}]:[],...v.map(e=>({value:String(e),label:Op(e)})),{value:`custom`,label:M(`models.custom`)}],onChange:e=>Br(n,e),disabled:We||!g,label:M(`models.capValue`,{value:Op(_)}),title:M(`models.contextCapLabel`)}),g&&Se[n]&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:M(`models.customPlaceholder`),value:we[n]??``,onChange:e=>Te(t=>({...t,[n]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&Vr(n)},disabled:We,"aria-label":M(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>Vr(n),disabled:We,className:`btn btn-ghost btn-sm`,children:M(`models.customApply`)})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Dr(t),"aria-haspopup":`dialog`,children:M(`models.contextSettings`)})]})]})]}),!s&&(0,Q.jsxs)(`div`,{className:`models-provider-body`,children:[i&&(0,Q.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:M(`models.nativeHint`)}),r.length===0&&(0,Q.jsx)(MM,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>0&&b&&(0,Q.jsx)(NM,{}),(r.length>30||u||!i&&rt)&&(0,Q.jsxs)(`div`,{className:`row models-provider-filters`,children:[r.length>30&&(0,Q.jsx)(`input`,{className:`input`,placeholder:M(`models.search`),value:U[n]??``,onChange:e=>W(t=>({...t,[n]:e.target.value})),"aria-label":M(`models.search`)}),u&&(0,Q.jsx)(Rn,{on:l,onClick:()=>G(e=>({...e,[n]:!l})),label:M(`models.freeOnly`),showLabel:!0}),!i&&rt&&(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:M(`models.newPolicyProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":M(`models.newPolicyProvider`),children:[`off`,`on`,`admit`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(rt.providers[n]??`inherit`)===e,className:`btn btn-sm${(rt.providers[n]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void ei(e,n),children:M(`models.newPolicy_${e}`)},e))})]})]}),!i&&(0,Q.jsx)(AM,{summary:L.find(e=>e.name===n),apiBase:e,onSaved:(e,t)=>{Re(e,t),e&&xr(!0)}}),d&&f.length===0&&r.length>0&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:M(`models.noFreeMatch`)}),T.map(e=>{let t=!c(e);return(0,Q.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>oi(e.namespaced,t.currentTarget),onMouseLeave:ci,onFocus:t=>si(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||ar(null)},children:[(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsx)(Rn,{on:!t,onClick:()=>void Mr(`models`,n,[{id:e.id,native:e.native===!0}],t),disabled:We&&!Ze.pending||e.initialSelectionPending,label:e.native?e.id:e.namespaced}),(0,Q.jsxs)(`span`,{className:`models-model-main`,children:[at.models[n]?.[e.id]&&(0,Q.jsx)(`strong`,{className:`mono text-control`,children:at.models[n][e.id].alias}),(0,Q.jsxs)(`span`,{className:`models-model-identity`,children:[(0,Q.jsx)(`code`,{className:`mono text-control`,style:{color:t?`var(--faint)`:`var(--text)`,textDecoration:t?`line-through`:`none`},children:e.native?RD(e.id):e.namespaced}),!e.native&&e.displayName?.trim()&&e.displayName.trim()!==e.namespaced&&(0,Q.jsx)(`span`,{className:`models-model-friendly text-caption`,children:e.displayName.trim()})]}),e.initialSelectionPending&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,children:M(`models.initialSelectionPending`)}),e.quotaInactiveReason===`no_credit`&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,title:M(`models.inactiveNoCreditHint`),children:M(`models.inactiveNoCredit`)}),at.models[n]?.[e.id]?.source===`builtin`&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:M(`models.aliasAuto`)}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:M(`models.customBadge`)}),!e.native&&e.provider!==`combo`&&e.manualPricing===!0&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:M(`pricing.override.badge`)}),!e.custom&&h.has(e.id)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:M(`models.newBadge`)}),e.contextCapped&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:M(`models.contextCappedValue`,{value:Op(e.contextCap??ie)})})]}),(0,Q.jsxs)(`span`,{className:`models-model-actions`,role:`group`,"aria-label":M(`modelsV2.modelActions`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":M(`models.editModelAlias`),title:M(`models.editModelAlias`),onClick:()=>void rn(n,e.id),children:(0,Q.jsx)(be,{style:{width:13,height:13}})}),!e.native&&!e.custom&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":M(`models.displayNameActionLabel`,{model:e.namespaced}),onClick:t=>{$t.current=t.currentTarget,Kt(null),Jt(null),Xt(!1),Lt(e)},children:M(`models.displayNameAction`)}),!e.native&&e.provider!==`combo`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":M(`pricing.override.actionLabel`,{model:e.namespaced}),onClick:t=>{Bt.current=t.currentTarget,zt(e)},children:M(`pricing.override.action`)}),!e.native&&!e.custom&&e.provider!==`combo`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":M(`models.settingsTitle`,{model:e.namespaced}),onClick:()=>Ht(e),children:M(`models.customEdit`)})]})]}),ir?.namespaced===e.namespaced&&(()=>{let n=ir.rect,r=n.bottom+4,i=r+360>window.innerHeight;return(0,Q.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:n.left+24,...i?{bottom:window.innerHeight-n.top+4}:{top:r}},onMouseEnter:li,onMouseLeave:ci,children:[(0,Q.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,Q.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:M(`models.customBadge`)}),(0,Q.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:M(`models.tipProvider`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:re(e.provider,M)}),(e.contextWindow||e.contextCap)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:M(`models.tipContext`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:Op(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:M(`models.tipModalities`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,Q.jsx)(`span`,{className:`model-tip-key`,children:M(`models.tipStatus`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:M(t?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,Q.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{sn(`edit`),ln(e.provider),dn(e.customId),pn(e.id),hn(e.displayName??``),_n(e.contextWindow?String(e.contextWindow):``),yn(!1),xn(e.inputModalities??[`text`]),wn(Array.isArray(e.reasoningEfforts)),En(e.reasoningEfforts??[]),Dn.current=Array.isArray(e.reasoningEfforts),jn(``),Ft(!0),ar(null)},children:M(`models.customEdit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{fi(e.customId,e.displayName??e.id).finally(()=>ar(null))},children:M(`models.customDelete`)})]})]})})()]},e.namespaced)}),E>0&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>ne(e=>({...e,[n]:w+60})),className:`btn btn-ghost btn-sm models-show-more`,children:M(`models.showMore`,{n:E})})]})]},n)},vi=dr?Tr.filter(e=>e.provider===dr):Tr,yi=(e,t=!1)=>{let n={pickerOrder:e.pickerOrder,pickerOrderMode:e.pickerOrderMode,pickerAvailable:[]};Sn(oe,n),df(oe,n),t&&le(`custom`),me.refresh();let r=e.catalogRefresh,i=typeof r==`object`&&!!r&&`status`in r&&r.status===`committed`&&`degraded`in r&&r.degraded===!1;Re(i,M(i?`models.pickerOrder.saved`:`models.pickerOrder.pending`)),h()},bi=async()=>{if(fe.current||!he||me.state.showError||ge===`custom`)return;let t=pe.current,n=ge,r=he.pickerAvailable,i=d(15e3);fe.current=i,de(!0);let a=()=>pe.current===t&&fe.current===i,o=()=>a()&&!i.signal.aborted;try{let t=[];if(n===`most-used`){let n=await fetch(`${e}/api/usage?range=all&surface=all`,{signal:i.signal});if(!o())return;let r=await Yn(n,M(`models.pickerOrder.usageFailed`));if(!o())return;if(r?.usageIncomplete===!0)throw Error(M(`models.pickerOrder.usageIncomplete`));if(!wE(r?.models))throw Error(M(`models.pickerOrder.usageFailed`));t=r.models}if(!o())return;let a=OE(n,r,t,F),s=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:i.signal,body:JSON.stringify({pickerOrder:a,pickerOrderMode:n==="default"?null:n})});if(!o())return;let c=await Yn(s,M(`models.saveFailed`));if(!SE(c)||!(`ok`in c)||c.ok!==!0)throw Error(M(`models.saveFailed`));if(!o())return;yi({pickerOrder:c.pickerOrder,pickerOrderMode:c.pickerOrderMode,catalogRefresh:`catalogRefresh`in c?c.catalogRefresh:void 0}),le(null)}catch(e){a()&&Re(!1,e instanceof Error?e.message:M(`models.networkError`))}finally{i.clear(),a()&&(fe.current=null,de(!1))}},xi=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`models-control-top-row`,children:[rt&&(0,Q.jsx)(UM,{label:M(`models.newPolicyGlobal`),children:(0,Q.jsx)(Rn,{on:rt.policy===`off`,onClick:()=>void ei(rt.policy===`off`?`on`:`off`),label:M(`models.newPolicyGlobal`)})}),(0,Q.jsxs)(UM,{label:M(`models.useDefaultAliasesGlobal`),children:[(0,Q.jsx)(Rn,{on:at.defaults.global,onClick:()=>void an(!at.defaults.global),label:M(`models.useDefaultAliasesGlobal`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ut(e=>!e),children:M(`models.aliases`)})]}),(0,Q.jsx)(WM,{shadowCall:sr,saving:cr,modelOptions:mr,onSave:e=>void ur(e)}),(0,Q.jsxs)(UM,{label:M(`models.autoReviewOverride`),hint:(0,Q.jsx)(Wn,{content:M(`models.autoReviewOverrideHint`),side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":M(`models.autoReviewOverrideHint`),children:`ⓘ`})}),busy:!ze,children:[(0,Q.jsx)(Rn,{on:ze?.enabled??!1,onClick:()=>void Ue({enabled:!ze?.enabled}),disabled:!ze||Be,label:M(`models.autoReviewOverride`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(Vn,{value:ze?.model??``,options:hr,onChange:e=>void Ue({model:e}),disabled:!ze||Be||!ze.enabled,label:M(`models.autoReviewOverride`)})})]}),(pt||$e)&&(0,Q.jsxs)(UM,{label:M(`models.v2Label`),children:[(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":M(`models.v2Label`),children:Wr($e?.supportsPlaintextV2Mode===!0).map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":($e?.multiAgentMode??`default`)===e,className:`btn btn-sm${($e?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:($e?.multiAgentMode??`default`)===e?void 0:`transparent`,color:($e?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!$e||mt,onClick:()=>void Zr(e),children:M(`models.v2Mode_${e}`)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!$e,onClick:()=>Dt(!0),"aria-label":M(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,Q.jsx)(He,{width:14,height:14,"aria-hidden":`true`})})]}),$e&&$e.multiAgentMode===`v2`&&(0,Q.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,Q.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,Q.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:M(`models.keepNativeOnV1`)}),(0,Q.jsx)(Rn,{on:$e.keepNativeChatGptOnV1===!0,onClick:()=>void ni(!$e.keepNativeChatGptOnV1),disabled:mt,label:M(`models.keepNativeOnV1`)}),(0,Q.jsx)(Wn,{content:M(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,Q.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":M(`models.keepNativeOnV1Hint`),children:(0,Q.jsx)(He,{width:13,height:13,"aria-hidden":`true`})})})]})}),Ot&&(0,Q.jsx)(Kr,{reason:`selection`,mode:Ot,docsUrl:Hr($e?.multiAgentSurfaceAdvisory)?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:mt,onContinue:()=>{let e=Ot;kt(null),Xr({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{kt(null),$e?.multiAgentMode!==`v1`&&Xr({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>kt(null)}),Mt===e&&(0,Q.jsx)(qr,{busy:mt,onConfirm:()=>void Xr({multiAgentMode:`v2-plaintext`,plaintextAgentMessagesAcknowledged:!0}).finally(()=>Nt(null)),onDismiss:()=>Nt(null)})]}),$e&&(0,Q.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:M(`models.v2ThreadsLabel`)}),(0,Q.jsx)(Vn,{value:wt?`custom`:ri===null?``:wp.has(ri)?String(ri):`custom`,options:[...ri===null?[{value:``,label:M(`models.v2ThreadsDefault`)}]:[],...ri!==null&&!wp.has(ri)&&!wt?[{value:`custom`,label:String(ri)}]:[],...Cp.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:M(`models.custom`)}],onChange:e=>ai(e),disabled:mt,label:M(`models.v2ThreadsLabel`)}),wt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:xt,onChange:e=>Ct(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ii(Number(xt.replace(/[_,\s]/g,``)))},disabled:mt,"aria-label":M(`models.v2ThreadsLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:mt,onClick:()=>{ii(Number(xt.replace(/[_,\s]/g,``)))},children:M(`models.v2ThreadsApply`)})]}),$e.enabled&&$e.agentsMaxThreadsConflict&&(0,Q.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:M(`models.v2Conflict`)}),gt&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:gt}),$e.plaintextAgentMessagesEnabled===!0&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:M(`models.v2PlaintextOn`)})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:M(`models.contextCapLabel`)}),(0,Q.jsx)(Vn,{value:ye?Sp:String(ie),options:[...!yp.has(ie)&&!ye?[{value:String(ie),label:Op(ie)}]:[],...vp.map(e=>({value:String(e),label:Op(e)})),{value:Sp,label:M(`models.custom`)}],onChange:e=>Ur(e),disabled:We,label:M(`models.contextCapLabel`)}),ye&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:M(`models.customPlaceholder`),value:_e,onChange:e=>ve(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Jr()},disabled:We,"aria-label":M(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:Jr,disabled:We,className:`btn btn-ghost btn-sm`,children:M(`models.customApply`)})]}),(0,Q.jsx)(Rn,{on:Rr,onClick:Yr,disabled:We,label:M(`models.setAll`)}),(0,Q.jsx)(HM,{text:M(`models.setAllHint`,{value:Op(ie)})})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,"aria-busy":ue||me.state.refreshing,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:M(`models.pickerOrder.label`)}),(0,Q.jsx)(Vn,{value:ge,options:[{value:`default`,label:M(`models.pickerOrder.default`)},{value:`alphabetical`,label:M(`models.pickerOrder.alphabetical`)},{value:`provider`,label:M(`models.pickerOrder.provider`)},{value:`most-used`,label:M(`models.pickerOrder.mostUsed`)},{value:`custom`,label:M(`models.pickerOrder.custom`)}],onChange:e=>le(e),disabled:ue||!he||me.state.showError,label:M(`models.pickerOrder.label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void bi(),disabled:ue||!he||me.state.showError||ge===`custom`||ge!=="default"&&he.pickerAvailable.length===0,children:M(ue?`models.pickerOrder.applying`:`models.pickerOrder.apply`)}),me.state.showError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{role:`alert`,children:M(`models.pickerOrder.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>me.refresh(),children:M(`models.pickerOrder.retry`)})]}),(0,Q.jsx)(HM,{text:M(`models.pickerOrder.hint`)})]}),(0,Q.jsx)(VE,{showOrderEditor:ge===`custom`,apiBase:e,active:T,identities:F,onBusyChange:de,onAccepted:e=>yi(e,!0),onSaved:()=>yr.refresh()}),ct&&(0,Q.jsxs)(`div`,{className:`card models-aliases-card`,"aria-label":M(`models.aliasesTable`),children:[(0,Q.jsx)(`div`,{className:`row group-head`,children:(0,Q.jsx)(`strong`,{children:M(`models.aliases`)})}),Object.entries(at.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,Q.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?M(`models.aliasAuto`):M(`models.aliasUser`)}),n.stale&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:M(`models.aliasStale`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":M(`models.editModelAlias`),onClick:()=>void rn(e,t),children:(0,Q.jsx)(be,{style:{width:13,height:13}})})]},`${e}/${t}`)))]})]}),Si=F.filter(e=>e.custom).length,Ci=(0,Q.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Ir(!0),disabled:We,children:[(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`}),` `,M(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Ir(!1),disabled:We,children:[(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,M(`models.expandAll`)]}),(0,Q.jsx)(HM,{text:M(`models.orderHint`)}),(0,Q.jsx)(VM,{count:Si,label:M(`models.customSummary`,{count:Si})})]}),wi=(0,Q.jsx)(Q.Fragment,{children:Tr.length===0&&(0,Q.jsx)(Un,{icon:(0,Q.jsx)(jt,{}),title:M(`models.noRouted`),children:M(`models.noRoutedHint`)})}),Ti=(0,Q.jsxs)(Q.Fragment,{children:[Et&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":M(`models.v2Label`),onClick:()=>Dt(!1),onKeyDown:e=>{e.key===`Escape`&&Dt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:M(`models.v2Label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Dt(!1),"aria-label":M(`common.close`),children:`×`})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:M(`models.v2Help`)}),(0,Q.jsx)(`div`,{className:`models-help-link`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:M(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Dt(!1),children:M(`common.ok`)})})]})}),Mn&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":M(`models.contextSettings`),onClick:()=>{er||Nn(null)},onKeyDown:e=>{e.key===`Escape`&&!er&&Nn(null)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:M(`models.contextSettingsTitle`,{provider:re(Mn,M)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Nn(null),disabled:er,"aria-label":M(`common.close`),children:`×`})]}),nr&&(0,Q.jsx)($,{tone:`err`,children:nr}),(0,Q.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:M(`models.contextHint`)}),(0,Q.jsxs)(`div`,{className:`models-context-fields`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[M(`models.contextDefault`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:zn,onChange:e=>{Bn(e.target.value),$n(!0)},disabled:er,placeholder:M(`models.contextAutomatic`),autoFocus:!0})]}),Pn.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[M(`models.contextModel`),(0,Q.jsx)(Vn,{value:In,options:Pn.map(e=>({value:e,label:e})),onChange:Or,disabled:er,label:M(`models.contextModel`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[M(`models.contextModelOverride`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:zD(Hn,In)??``,onChange:e=>{Gn(t=>({...t,[In]:e.target.value})),Zn(e=>new Set(e).add(In))},disabled:er,placeholder:M(`models.contextAutomatic`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Nn(null),disabled:er,children:M(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void kr(),disabled:er,children:M(er?`models.customSaving`:`models.customApply`)})]})]})}),Pt&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":M(`models.customAdd`),onClick:()=>{On||Ft(!1)},onKeyDown:e=>{e.key===`Escape`&&!On&&Ft(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:M(on===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:re(cn,M)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ft(!1),disabled:On,"aria-label":M(`common.close`),children:`×`})]}),An&&(0,Q.jsx)($,{tone:`err`,children:An}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[M(`models.customFieldModelId`),(0,Q.jsx)(`input`,{className:`input`,value:fn,onChange:e=>pn(e.target.value),disabled:On,placeholder:M(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[M(`models.customFieldDisplayName`),(0,Q.jsx)(`input`,{className:`input`,value:mn,onChange:e=>hn(e.target.value),disabled:On,placeholder:M(`models.customFieldDisplayNamePlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[M(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(Vn,{value:vn?`custom`:gn,options:[{value:``,label:`—`},{value:`100000`,label:`100k`},{value:`128000`,label:`128k`},{value:`200000`,label:`200k`},{value:`256000`,label:`256k`},{value:`352000`,label:`352k`},{value:`500000`,label:`500k`},{value:`1000000`,label:`1M`},{value:`custom`,label:M(`models.custom`)}],onChange:e=>{e===`custom`?yn(!0):(yn(!1),_n(e))},disabled:On,label:M(`models.customFieldContext`)}),vn&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:gn,onChange:e=>_n(e.target.value),disabled:On,placeholder:M(`models.customPlaceholder`),"aria-label":M(`models.customFieldContext`)})]})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[M(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:bn.includes(e),onChange:t=>{xn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:On}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[M(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Cn,onChange:e=>{if(wn(e.target.checked),e.target.checked&&!Dn.current){Dn.current=!0;let e=F.find(e=>e.provider===cn&&e.id===fn),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;En(t??[...hp])}},disabled:On}),(0,Q.jsx)(`span`,{className:`text-control`,children:M(`models.customFieldReasoningOverride`)})]})}),Cn&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:hp.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Tn.includes(e),onChange:t=>{En(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:On}),(0,Q.jsx)(`span`,{className:`text-control`,children:M(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Ft(!1),disabled:On,children:M(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:On||!fn.trim(),onClick:()=>{let e=fn.trim(),t=mn.trim(),n=Pp(gn);if(n===void 0)jn(M(`models.contextInvalid`));else if(on===`add`){let r=Cn?Tn:void 0;ui(cn,e,t||void 0,n??void 0,bn.length>0?bn:void 0,r)}else di(un,{modelId:e,displayName:t,contextWindow:n,inputModalities:bn,reasoningEfforts:Cn?Tn:null})},children:M(On?`models.customSaving`:on===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),Ei=(0,Q.jsxs)(`div`,{className:`models-workspace-shell`,children:[Ae&&(0,Q.jsxs)(`div`,{className:`action-toast notice ${Pe?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[Pe?(0,Q.jsx)(st,{}):(0,Q.jsx)(St,{}),(0,Q.jsx)(`span`,{children:Ae})]}),br.showError&&(0,Q.jsx)($,{tone:`err`,children:M(`models.loadFail`)}),Me.length>0&&(0,Q.jsx)(`div`,{className:`models-integration-warning`,children:(0,Q.jsxs)($,{tone:`warn`,children:[M(`models.integrationRefreshWarning`),(0,Q.jsx)(`ul`,{children:Me.map(e=>(0,Q.jsxs)(`li`,{children:[e.client,e.profileId===void 0?``:`:${e.profileId}`,`: `,rk(M,{clientId:e.client,message:e.reason===`integration_mutation_busy`?M(`integrations.error.busy`):e.reason,reason:e.refusalReason,snapshotPath:e.snapshotPath,residual:e.residual})]},`${e.client}:${e.profileId??`all`}`))})]})}),(0,Q.jsx)(BM,{title:M(`models.settingsPanel.title`),attentionLabel:M(`models.settingsPanel.attention`),warn:!!($e?.enabled&&$e.agentsMaxThreadsConflict)||gt!==``||me.state.showError,summary:zM(M,{multiAgentMode:$e?.multiAgentMode,v2Threads:ri,keepNativeOnV1:$e?.keepNativeChatGptOnV1===!0,shadowEnabled:sr?.enabled===!0,shadowModel:sr?.model,windowOn:Rr,windowValue:ie,newModelsOff:rt?.policy===`off`,aliasesOn:at.defaults.global,autoReviewEnabled:ze?.enabled===!0,autoReviewModel:ze?.model,pickerMode:kE(he?.pickerAvailable??[],he?.pickerOrder??[],he?.pickerOrderMode)}),children:xi}),(0,Q.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":Ze.pending||br.refreshing||void 0,children:[(0,Q.jsx)(ZM,{selected:dr,onSelect:fr,all:{active:Ar,total:F.length},items:Tr.map(({provider:e,rows:t})=>({provider:e,total:t.length,active:t.filter(t=>Qe(gi,e,t.id,t.native===!0,z.has(t.namespaced))).length}))}),(0,Q.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":M(`models.workspace.mainAria`),children:[Ci,(0,Q.jsx)(`div`,{className:`models-provider-list`,children:vi.map(e=>_i(e))}),Tr.length===0&&wi]})]}),Ti]});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(ED,{stale:a===`stale`,headRef:s,bannerRef:c,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`div`,{className:`ui-v2 flex min-w-0 flex-col gap-1`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:M(`nav.models`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[14px] leading-5 text-fg-muted`,children:M($M[v][0])})]}),(0,Q.jsxs)(`div`,{className:`page-head-actions`,children:[$M[v][1]&&(0,Q.jsx)(YM,{text:M($M[v][1]),children:v===`catalog`&&(0,Q.jsx)(KM,{connected:n,catalogSyncedAt:r})},v),a!==`stale`&&(0,Q.jsxs)(Jp,{"data-models-reload-action":!0,ref:s,variant:`outline`,size:`sm`,onClick:()=>{_()},disabled:g,children:[(0,Q.jsx)(`span`,{className:g?`inline-flex animate-spin`:`inline-flex`,children:(0,Q.jsx)(Ke,{"aria-hidden":`true`})}),M(g?`dash.codexRestarting`:`dash.codexRestart`)]})]})]}),(0,Q.jsx)(yE,{state:a,actionRef:c,controller:{restarting:g,restart:_}})]}),(0,Q.jsx)(kM,{tab:v,onSelect:w,meta:jr}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DM(`catalog`),"aria-labelledby":EM(`catalog`),hidden:v!==`catalog`,children:(0,Q.jsx)(uk,{pageName:M(`models.tab.catalog`),title:M(`errorBoundary.title`),message:M(`errorBoundary.message`),detailsLabel:M(`errorBoundary.details`),reloadLabel:M(`errorBoundary.reload`),children:hi?(0,Q.jsx)(ck,{label:M(`models.loading`),rows:5}):mi===null?Ei:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:mi}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>yr.refresh(),children:M(`common.retry`)})]})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:DM(`combos`),"aria-labelledby":EM(`combos`),hidden:v!==`combos`,children:x.has(`combos`)&&(0,Q.jsx)(uk,{pageName:M(`models.tab.combos`),title:M(`errorBoundary.title`),message:M(`errorBoundary.message`),detailsLabel:M(`errorBoundary.details`),reloadLabel:M(`errorBoundary.reload`),children:(0,Q.jsx)(cA,{apiBase:e,active:v===`combos`,onCountChange:D})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DM(`routing`),"aria-labelledby":EM(`routing`),hidden:v!==`routing`,children:x.has(`routing`)&&(0,Q.jsx)(uk,{pageName:M(`models.tab.routing`),title:M(`errorBoundary.title`),message:M(`errorBoundary.message`),detailsLabel:M(`errorBoundary.details`),reloadLabel:M(`errorBoundary.reload`),children:(0,Q.jsx)(qA,{apiBase:e,active:v===`routing`,onCountChange:k})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DM(`compatibility`),"aria-labelledby":EM(`compatibility`),hidden:v!==`compatibility`,children:x.has(`compatibility`)&&(0,Q.jsx)(uk,{pageName:M(`models.tab.compatibility`),title:M(`errorBoundary.title`),message:M(`errorBoundary.message`),detailsLabel:M(`errorBoundary.details`),reloadLabel:M(`errorBoundary.reload`),children:(0,Q.jsx)(xM,{apiBase:e,active:v===`compatibility`,onCountChange:j})})}),It&&(0,Q.jsx)(UE,{model:It,saving:Ut,requestError:Gt,currentNamePending:Yt,mutationOutcomeUnknown:qt?.confirmed===!1,onRetry:qt?()=>void wr(qt.value):void 0,onEdit:()=>Jt(null),onSave:e=>void wr(e),onReset:()=>void wr(null),onClose:Cr}),Rt&&(0,Q.jsx)(lD,{model:Rt,apiBase:e,onRefresh:e=>xr(!0,e),onClose:()=>{let e=Bt.current;zt(null),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)}},`${e}/${Rt.namespaced}`),Vt&&(0,Q.jsx)(_D,{row:Vt,apiBase:e,onRefresh:e=>xr(!0,e),onFeedback:Re,onClose:()=>Ht(null)},`${e}/${Vt.namespaced}`)]})}function tN(e){return[...new Set(e.filter(e=>!e.disabled&&!e.initialSelectionPending).map(e=>e.namespaced))]}function nN({apiBase:e,value:t,disabled:n,onChange:r}){let i=b(),a=mf(`advisor-models:${e}`,[e],async t=>{let n=await fetch(`${e}/api/models`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();if(!Array.isArray(r)||!r.every(e=>e&&typeof e.namespaced==`string`&&e.namespaced.length>0))throw Error(`Invalid model catalog`);return r},{isEmpty:e=>e.length===0}),{state:o}=a,s=tN(o.data??[]),c=t!==``&&!s.includes(t),l=[{value:``,label:i(`advisor.modelClear`)},...c?[{value:t,label:t}]:[],...s.map(e=>({value:e,label:e}))];return(0,Q.jsxs)(`div`,{"aria-busy":o.showSkeleton||o.refreshing,children:[(0,Q.jsx)(Vn,{id:`advisor-model`,value:t,options:l,label:i(`advisor.model`),describedBy:`advisor-model-hint`,disabled:n||o.showSkeleton,onChange:r}),(0,Q.jsx)(`p`,{id:`advisor-model-hint`,className:`muted setting-hint`,children:i(`advisor.modelHint`)}),o.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:i(`common.loading`)}),o.showError&&!o.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[i(`advisor.modelsLoadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:()=>a.refresh(),children:i(`common.retry`)})]}),!o.showSkeleton&&!o.showError&&s.length===0&&(0,Q.jsxs)($,{tone:`warn`,children:[i(`advisor.modelsEmpty`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:()=>a.refresh(),children:i(`common.retry`)})]}),!o.showSkeleton&&!o.showError&&c&&(0,Q.jsx)($,{tone:`warn`,children:i(`advisor.modelUnavailable`)})]})}var rN={ok:`bg-success-soft text-success`,failed:`bg-danger-soft text-danger`,blocked:`bg-warning-soft text-warning`,running:`bg-surface-2 text-fg-muted`,cancelled:`bg-surface-2 text-fg-muted`};function iN({entries:e}){let t=b();if(!e.length)return(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1.5 px-6 py-10 text-center`,children:[(0,Q.jsx)(`span`,{className:`mb-1 grid size-9 place-items-center rounded-[10px] bg-surface text-fg-muted`,"aria-hidden":`true`,children:(0,Q.jsx)(Pc,{icon:Hc,size:18,strokeWidth:1.8})}),(0,Q.jsx)(`p`,{className:`m-0 text-[14px] font-medium text-fg`,children:t(`advisor.activity.empty`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:t(`proxyV2.activityEmptyHint`)})]});let n=`px-4 py-2.5 text-left text-xs font-medium whitespace-nowrap text-fg-subtle`,r=`px-4 py-3 align-top whitespace-nowrap`;return(0,Q.jsx)(`div`,{className:`max-h-[480px] overflow-auto rounded-[12px]`,children:(0,Q.jsxs)(`table`,{className:`pv2-table advisor-activity-table w-full border-collapse text-[13px] text-fg`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-line`,children:[(0,Q.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.activity.started`)}),(0,Q.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.activity.trigger`)}),(0,Q.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.model`)}),(0,Q.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.effort`)}),(0,Q.jsx)(`th`,{scope:`col`,className:X(n,`text-right`),children:t(`advisor.activity.tokens`)}),(0,Q.jsx)(`th`,{scope:`col`,className:X(n,`text-right`),children:t(`advisor.activity.duration`)})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-line`,children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:X(r,`font-mono text-xs text-fg-muted tabular-nums`),children:(0,Q.jsx)(`time`,{dateTime:new Date(e.startedAt).toISOString(),children:new Date(e.startedAt).toLocaleTimeString()})}),(0,Q.jsx)(`td`,{className:r,children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-start gap-1`,children:[(0,Q.jsx)(`span`,{children:t(`advisor.activity.trigger.${e.trigger}`)}),(0,Q.jsx)(`span`,{className:X(`rounded-full px-2 py-0.5 text-[11px] font-semibold`,rN[e.status]),children:t(`advisor.activity.status.${e.status}`)})]})}),(0,Q.jsxs)(`td`,{className:r,children:[(0,Q.jsx)(`code`,{className:`font-mono text-xs text-fg`,children:e.advisorModel}),(0,Q.jsx)(`div`,{className:`mt-0.5`,children:(0,Q.jsx)(`code`,{className:`font-mono text-xs text-fg-subtle`,children:e.workerModel})})]}),(0,Q.jsx)(`td`,{className:r,children:(0,Q.jsxs)(`code`,{className:`font-mono text-xs`,children:[e.requestedEffort,` → `,e.effectiveEffort??t(`logs.tokens.unreported`)]})}),(0,Q.jsx)(`td`,{className:X(r,`num text-right font-mono text-xs tabular-nums`),children:e.usage?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{title:t(`logs.tokens.input`),children:e.usage.inputTokens??`—`}),` / `,(0,Q.jsx)(`span`,{title:t(`logs.tokens.output`),children:e.usage.outputTokens??`—`})]}):(0,Q.jsx)(`span`,{className:`font-sans text-fg-subtle`,children:t(`logs.tokens.unreported`)})}),(0,Q.jsx)(`td`,{className:X(r,`num text-right font-mono text-xs tabular-nums`),children:e.durationMs===null?`—`:(0,Q.jsxs)(Q.Fragment,{children:[e.durationMs,` ms`]})})]},e.id))})]})})}function aN({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(!1),i=mf(`advisor-activity:${e}`,[e],async t=>{let n=await fetch(`${e}/api/advisor/activity`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{isEmpty:e=>e.entries.length===0,pollMs:5e3,pauseWhenHidden:!0}),{state:a}=i;return(0,Q.jsxs)(`section`,{"aria-labelledby":`advisor-activity-title`,className:`min-w-0 rounded-card bg-surface p-1`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-col gap-0.5 px-4 pt-3 pb-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{id:`advisor-activity-title`,className:`m-0 text-[15px] leading-5 font-semibold text-fg`,children:t(`advisor.activity.title`)}),(0,Q.jsx)(Yc,{label:t(`proxyV2.detailsFor`,{name:t(`advisor.activity.title`)}),expanded:n,controls:`advisor-activity-note`,onClick:()=>r(e=>!e)})]}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-[18px] text-fg-muted`,children:t(`proxyV2.activityLede`)}),(0,Q.jsx)(`p`,{id:`advisor-activity-note`,hidden:!n,className:`m-0 mt-1 max-w-[72ch] text-[13px] leading-[19px] text-fg-muted`,children:t(`advisor.activity.note`)})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col rounded-[12px] bg-raised ring-1 ring-line`,children:[a.showSkeleton&&(0,Q.jsx)(`p`,{className:`m-0 px-4 py-6 text-[13px] text-fg-muted`,children:t(`common.loading`)}),a.showError&&(0,Q.jsx)(`div`,{className:`p-3`,children:(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.activity.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i.refresh(),children:t(`common.retry`)})]})}),a.data&&(0,Q.jsx)(iN,{entries:a.data.entries})]})]})}function oN({agreed:e,disabled:t,onChange:n}){let r=b();return(0,Q.jsxs)(`section`,{"aria-labelledby":`advisor-consent-title`,className:X(`advisor-consent flex flex-col gap-3 rounded-card p-4 ring-1 ring-inset`,e?`bg-surface ring-line`:`bg-warning-soft ring-warning/25`),children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:X(`grid size-7 shrink-0 place-items-center rounded-[8px]`,e?`bg-raised text-fg`:`bg-raised text-warning`),"aria-hidden":`true`,children:(0,Q.jsx)(Pc,{icon:Gc,size:16,strokeWidth:1.8})}),(0,Q.jsx)(`h3`,{id:`advisor-consent-title`,className:`m-0 text-[15px] leading-5 font-semibold text-fg`,children:r(`proxyV2.consentTitle`)}),(0,Q.jsx)(`span`,{className:X(`ml-auto rounded-full px-2 py-0.5 text-[11px] font-semibold`,e?`bg-success-soft text-success`:`bg-raised text-warning`),children:r(e?`proxyV2.consentGiven`:`proxyV2.consentNeeded`)})]}),(0,Q.jsxs)(`label`,{className:`flex cursor-pointer items-start gap-3 rounded-control bg-raised p-3 ring-1 ring-line`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`advisor-consent-check mt-0.5 size-4 shrink-0 cursor-pointer`,checked:e,disabled:t,"aria-label":r(`advisor.consent.label`),onChange:e=>n(e.target.checked)}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-[19px] text-fg`,children:r(`advisor.consent.label`)})]}),(0,Q.jsxs)(`details`,{className:`advisor-notices pv2-more`,children:[(0,Q.jsx)(`summary`,{children:r(`advisor.notices`)}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.costNote`)}),(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.privacyNote`)}),(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.disclosure`)})]})]})]})}var sN=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],cN=`w-[16rem] max-w-full max-[640px]:w-full`;function lN({apiBase:e,initial:t}){let n=b(),[r,i]=(0,Z.useState)(t),[a,o]=(0,Z.useState)(t),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(``),p=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]);let m=(0,Z.useCallback)(async()=>{p.current!==null&&(clearTimeout(p.current),p.current=null),u(!1),c(!0),f(``);let t=a;try{let n=await fetch(`${e}/api/advisor/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t.enabled,model:t.model,effort:t.effort,policy:t.policy,contextMode:t.contextMode??`context`,...t.maxConsultationsPerTask===void 0?{}:{maxConsultationsPerTask:t.maxConsultationsPerTask},timeoutMs:t.timeoutMs,contextSharingConsent:t.contextSharingConsent})});if(!n.ok){let e=await n.json().catch(()=>null);f(e?.error?.message??String(n.status));return}let r=await n.json();i(r.settings),o(e=>JSON.stringify(e)===JSON.stringify(t)?r.settings:e),u(!0),p.current=setTimeout(()=>{p.current=null,u(!1)},2500)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},[e,a]),h=(0,Z.useCallback)(e=>{f(``),o(t=>({...t,...e}))},[]),g=JSON.stringify(a)!==JSON.stringify(r),_=a.enabled&&a.model.trim()===``,v=a.enabled&&a.model.trim()!==``&&a.contextSharingConsent!==`v1`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(Jc,{id:`advisor-settings`,title:n(`proxyV2.advisorSettings`),children:[(0,Q.jsx)(Xc,{label:n(`advisor.enabled`),hint:n(`proxyV2.enabledHint`),inline:!0,control:(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.enabled,disabled:s,"aria-label":n(`advisor.enabled`),onChange:e=>h({enabled:e.target.checked})}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}),(0,Q.jsx)(Xc,{className:`advisor-model-row`,label:n(`advisor.model`),labelFor:`advisor-model`,control:(0,Q.jsx)(`div`,{className:cN,children:(0,Q.jsx)(nN,{apiBase:e,value:a.model,disabled:s,onChange:e=>h({model:e})})})}),(0,Q.jsx)(Xc,{label:n(`advisor.effort`),labelFor:`advisor-effort`,hint:n(`proxyV2.effortHint`),control:(0,Q.jsx)(Vn,{id:`advisor-effort`,value:a.effort,disabled:s,fullWidth:!0,className:cN,options:sN.map(e=>({value:e,label:n(`models.reasoningEffort.${e}`)})),onChange:e=>h({effort:e})})}),(0,Q.jsx)(Xc,{label:n(`advisor.questionOnly`),labelFor:`advisor-question-only`,inline:!0,hint:a.contextMode===`question-only`?n(`advisor.questionOnlyNote`):void 0,control:(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{id:`advisor-question-only`,type:`checkbox`,checked:a.contextMode===`question-only`,disabled:s,"aria-label":n(`advisor.questionOnly`),onChange:e=>h({contextMode:e.target.checked?`question-only`:`context`})}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}),(0,Q.jsx)(Xc,{label:n(`advisor.policy`),labelFor:`advisor-policy`,hint:n(`proxyV2.policyHint`),control:(0,Q.jsx)(Vn,{id:`advisor-policy`,value:a.policy,disabled:s||a.contextMode===`question-only`,fullWidth:!0,className:cN,options:[{value:`manual`,label:n(`advisor.policy.manual`)},{value:`preflight`,label:n(`advisor.policy.preflight`)},{value:`adaptive`,label:n(`advisor.policy.adaptive`)}],onChange:e=>h({policy:e})})}),a.policy===`adaptive`&&(0,Q.jsx)(Xc,{label:n(`advisor.taskLimit`),labelFor:`advisor-task-limit`,hint:n(`proxyV2.taskLimitHint`),details:a.contextMode===`question-only`?void 0:n(`advisor.adaptiveNote`),control:(0,Q.jsx)(Vn,{id:`advisor-task-limit`,value:String(a.maxConsultationsPerTask??3),disabled:s,fullWidth:!0,className:cN,options:[1,2,3].map(e=>({value:String(e),label:String(e)})),onChange:e=>h({maxConsultationsPerTask:Number(e)})})}),(0,Q.jsx)(Xc,{label:n(`advisor.timeout`),labelFor:`advisor-timeout`,hint:n(`proxyV2.timeoutHint`),control:(0,Q.jsx)(`input`,{id:`advisor-timeout`,className:X(`input mono`,cN),type:`number`,min:1e3,max:6e5,value:a.timeoutMs,disabled:s,onChange:e=>{let t=e.target.value.trim();if(t===``)return;let n=Number(t);Number.isFinite(n)&&h({timeoutMs:n})}})})]}),(0,Q.jsx)(oN,{agreed:a.contextSharingConsent===`v1`,disabled:s,onChange:e=>h({contextSharingConsent:e?`v1`:null})}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[_&&(0,Q.jsx)($,{tone:`warn`,children:n(`advisor.warning.noModel`)}),v&&(0,Q.jsx)($,{tone:`warn`,children:n(`advisor.consent.required`)}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),l&&(0,Q.jsx)($,{tone:`ok`,children:n(`advisor.saved`)}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-3`,children:[g&&!s&&(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted`,role:`status`,children:n(`proxyV2.unsaved`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!g||s,onClick:()=>void m(),children:n(s?`common.loading`:`advisor.save`)})]})]})]})}function uN({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(!1),i=mf(`advisor-settings:${e}`,[e],async t=>{let n=await fetch(`${e}/api/advisor/settings`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{isEmpty:()=>!1}),{state:a}=i;return(0,Q.jsxs)(`div`,{className:`pv2-page flex max-w-[60rem] flex-col gap-5`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-col gap-1.5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:t(`nav.advisor`)}),(0,Q.jsx)(Yc,{label:t(`proxyV2.detailsFor`,{name:t(`nav.advisor`)}),expanded:n,controls:`advisor-about`,onClick:()=>r(e=>!e)})]}),(0,Q.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[14px] leading-[1.55] text-fg-muted`,children:t(`proxyV2.advisorLede`)}),(0,Q.jsx)(`p`,{id:`advisor-about`,hidden:!n,className:`m-0 mt-1 max-w-[72ch] rounded-control bg-surface px-4 py-3 text-[13px] leading-[19px] text-fg-muted`,children:t(`advisor.description`)})]}),a.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:t(`common.loading`)}),a.showError&&!a.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i.refresh(),children:t(`common.retry`)})]}),a.data!==void 0&&(0,Q.jsx)(lN,{apiBase:e,initial:a.data.settings},i.hasSucceeded?`ready`:`cold`),(0,Q.jsx)(aN,{apiBase:e})]})}function dN(e){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...e,children:[(0,Q.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9.5`}),(0,Q.jsx)(`path`,{d:`M9.6 9.3a2.5 2.5 0 0 1 4.85.85c0 1.65-2.45 2.2-2.45 3.6`}),(0,Q.jsx)(`path`,{d:`M12 17h.01`})]})}function fN({label:e,children:t}){let n=b();return(0,Q.jsx)(`span`,{className:`inline-flex shrink-0 items-center text-fg-subtle transition-colors hover:text-fg-muted`,children:(0,Q.jsxs)(Wn,{content:t,side:`bottom`,maxWidth:380,children:[(0,Q.jsx)(dN,{width:15,height:15,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:n(`subagentsV2.moreAbout`,{label:e})})]})})}function pN({id:e,title:t,lede:n,meta:r,actions:i,below:a,children:o,className:s,headClassName:c,busy:l}){let u=(0,Z.useId)();return(0,Q.jsxs)(`section`,{id:e,"aria-labelledby":u,"aria-busy":l,className:X(`flex min-w-0 scroll-mt-[72px] flex-col rounded-[12px] bg-surface ring-1 ring-inset ring-line`,s),children:[(0,Q.jsxs)(`div`,{className:X(`flex min-w-0 flex-wrap items-start gap-x-3 gap-y-2 px-4 pt-3.5 pb-3`,c),children:[(0,Q.jsxs)(`div`,{className:`flex min-w-[min(100%,15rem)] flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Q.jsx)(`h3`,{id:u,className:`m-0 truncate text-[14px] leading-5 font-semibold text-fg`,children:t}),r]}),n&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:n})]}),i&&(0,Q.jsx)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 max-sm:w-full`,children:i})]}),a&&(0,Q.jsx)(`div`,{className:`px-4 pb-3`,children:a}),o]})}function mN({children:e,className:t,as:n=`div`}){return(0,Q.jsx)(n,{className:X(`m-1 mt-0 flex min-w-0 list-none flex-col divide-y divide-line overflow-hidden rounded-[8px] bg-raised p-0 shadow-sm ring-1 ring-line`,`[&:has(+*)]:mb-0`,t),children:e})}function hN({children:e,className:t}){return(0,Q.jsx)(`div`,{className:X(`flex min-h-12 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-2.5 text-[13px] text-fg-muted`,t),children:e})}function gN({label:e,hint:t,help:n,control:r,children:i,className:a}){return(0,Q.jsxs)(`div`,{className:X(`flex min-w-0 flex-col gap-2 px-4 py-3.5`,a),children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-[min(100%,12rem)] flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-[14px] leading-5 font-medium text-fg`,children:[e,n]}),t&&(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:t})]}),r&&(0,Q.jsx)(`div`,{className:`flex max-w-full min-w-0 flex-wrap items-center justify-end gap-2`,children:r})]}),i]})}function _N({children:e}){return(0,Q.jsx)(`span`,{className:`rounded-full bg-surface-2 px-2 py-0.5 font-mono text-[11px] font-medium text-fg-muted tabular-nums`,children:e})}var vN=X(`ui-v2 inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-[8px] text-fg-muted`,`transition-colors duration-150 hover:bg-surface-2 hover:text-fg`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-35 [&_svg]:size-4`),yN=`grid size-6 shrink-0 place-items-center rounded-[7px] text-[12px] font-medium tabular-nums ring-1 ring-inset`;function bN(e){let t=b(),[n,r]=(0,Z.useState)(!1),i=(0,Z.useId)();return{open:n,button:(0,Q.jsx)(`button`,{type:`button`,className:X(vN,`size-6 text-fg-subtle`,n&&`bg-surface-2 text-fg`),"aria-expanded":n,"aria-controls":i,"aria-label":t(`subagentsV2.moreAbout`,{label:e}),onClick:()=>r(e=>!e),children:(0,Q.jsx)(dN,{"aria-hidden":`true`})}),panel:(e,t)=>(0,Q.jsx)(`div`,{id:i,hidden:!n,className:X(`rounded-[8px] bg-surface-2/60 px-3 py-2.5 text-[13px] leading-5 text-fg-muted [&_p]:m-0 [&_p+p]:mt-2`,t),children:e})}}function xN(e,t){let n=new Set(t);return[...new Set([...e.filter(e=>n.has(e)),...t])]}function SN({apiBase:e,roster:t,id:n,onForceChange:r}){let i=b(),a=bN(i(`sub.forceTitle`)),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(0),[v,y]=(0,Z.useState)(null),x=u||v?.retry!==g||v.t!==i,S=(0,Z.useRef)(!1),C=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{C.current=!0,S.current=!0;let t=new AbortController,n=!1;return(async()=>{try{let r=await Yn(await fetch(`${e}/api/subagent-models`,{signal:t.signal}),i(`sub.loadFail`));if(n)return;let a={force:r?.force??null,forceAvailable:r?.forceAvailable??[],forceStatus:r?.forceStatus??null};s(a),l(a.force??``),p(``)}catch{n||p(i(`sub.loadFail`))}finally{n||(S.current=!1,y({retry:g,t:i}))}})(),()=>{n=!0,C.current=!1,t.abort()}},[e,g,i]);async function w(t){if(!(!o||x||S.current)){S.current=!0,d(!0),p(``),h(!1);try{let n=await Yn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({force:t})}),i(`sub.saveFailed`));if(!C.current)return;s(e=>e&&{...e,force:n?.force??null,forceStatus:null}),l(n?.force??c),h(!0),_(e=>e+1)}catch{C.current&&p(i(`sub.saveFailed`))}finally{S.current=!1,C.current&&d(!1)}}}let T=xN(t,o?.forceAvailable??[]),E=o?.force??c,D=T.includes(E),O=o?.forceStatus,k=o?o.force:void 0;(0,Z.useEffect)(()=>{r?.(k)},[k,r]);let A=[o?.force&&(!D||O?.targetValid===!1)&&(0,Q.jsx)($,{tone:`warn`,children:i(`sub.forceInvalid`)},`invalid`),o?.force&&O?.support===`unsupported`&&(0,Q.jsx)($,{tone:`warn`,children:i(`sub.forceOld`)},`old`),o?.force&&(!O||O.support===`unknown`)&&(0,Q.jsx)($,{tone:`warn`,children:i(`sub.forceUnknown`)},`unknown`),o?.force&&O?.settingsOverride&&(0,Q.jsx)($,{tone:`warn`,children:i(`sub.forceOverride`)},`override`),o?.force&&O?.settingsReadable===!1&&(0,Q.jsx)($,{tone:`warn`,children:i(`sub.forceSettingsUnknown`)},`settings`),m&&(0,Q.jsx)($,{tone:`ok`,children:i(`sub.forceSaved`)},`saved`),f&&(0,Q.jsxs)($,{tone:`err`,children:[f,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:x,onClick:()=>_(e=>e+1),children:i(`common.retry`)})]},`error`)].filter(Boolean);return(0,Q.jsxs)(pN,{id:n,title:i(`sub.forceTitle`),lede:i(`subagentsV2.forceLede`),meta:a.button,actions:(0,Q.jsx)(Rn,{on:!!o?.force,disabled:!o||x||!o.force&&!D,label:i(`sub.forceTitle`),onClick:()=>{w(o?.force?null:c)}}),below:a.panel((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:i(`sub.forceHelp`)}),(0,Q.jsx)(`p`,{children:i(`sub.forceScope`)})]})),children:[(0,Q.jsx)(mN,{children:(0,Q.jsxs)(`label`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3`,children:[(0,Q.jsx)(`span`,{className:`min-w-[min(100%,12rem)] flex-1 text-[14px] leading-5 font-medium text-fg`,children:i(`sub.forceModel`)}),(0,Q.jsx)(Vn,{fullWidth:!0,className:`max-w-[22rem] sm:w-auto sm:min-w-[16rem]`,triggerClassName:`text-[13px]`,label:i(`sub.forceModel`),value:E,disabled:!o||x,onChange:e=>{o?.force?e!==o.force&&w(e):l(e)},options:[{value:``,label:i(`sub.forceChoose`),disabled:!0},...E&&!D?[{value:E,label:E,disabled:!0}]:[],...T.map(e=>({value:e,label:e}))]})]})}),A.length>0&&(0,Q.jsx)(`div`,{className:`flex flex-col gap-2 px-4 py-3`,children:A})]})}var CN=X(`inline-flex h-full w-8 shrink-0 cursor-pointer items-center justify-center text-fg-muted transition-colors`,`hover:bg-surface-2 hover:text-fg focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-35 [&_svg]:size-3.5`);function wN({decrementLabel:e,incrementLabel:t,onDecrement:n,onIncrement:r,stepDisabled:i,unit:a,className:o,inputClassName:s,...c}){return(0,Q.jsxs)(`span`,{className:X(`ui-v2 inline-flex h-[var(--ocx-control-h)] items-stretch overflow-hidden rounded-control bg-raised shadow-sm ring-1 ring-inset ring-line-strong`,`transition-shadow focus-within:ring-2 focus-within:ring-highlight`,`has-[input[aria-invalid=true]]:ring-danger`,`has-[input:disabled]:opacity-60 has-[input[readonly]]:bg-surface`,o),children:[(0,Q.jsx)(`button`,{type:`button`,className:X(CN,`border-r border-line`),disabled:i,"aria-label":e,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Q.jsx)(ht,{"aria-hidden":`true`})}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-center`,children:[(0,Q.jsx)(`input`,{type:`number`,...c,className:X(`h-full w-20 min-w-0 border-0 bg-transparent px-2 text-center font-mono text-[13px] text-fg tabular-nums outline-none`,`[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none`,s)}),a&&(0,Q.jsx)(`span`,{className:`pr-2 font-mono text-[12px] text-fg-subtle select-none`,children:a})]}),(0,Q.jsx)(`button`,{type:`button`,className:X(CN,`border-l border-line`),disabled:i,"aria-label":t,onMouseDown:e=>e.preventDefault(),onClick:r,children:(0,Q.jsx)(Vt,{"aria-hidden":`true`})})]})}var TN=[`maxConcurrentChildren`,`maxPhysicalSends`,`maxDistinctChildren`],EN={maxConcurrentChildren:[`workflowBudget.maxConcurrentChildren`,`workflowBudget.maxConcurrentChildrenHint`],maxPhysicalSends:[`workflowBudget.maxPhysicalSends`,`workflowBudget.maxPhysicalSendsHint`],maxDistinctChildren:[`workflowBudget.maxDistinctChildren`,`workflowBudget.maxDistinctChildrenHint`]},DN=e=>typeof e==`number`&&Number.isInteger(e);function ON(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid workflow budget settings`);let t=e,n=t.defaults,r=t.bounds;if(!n||!r||!DN(t.windowMs))throw Error(`Missing workflow budget settings`);let i={values:{},defaults:{},bounds:{},windowMinutes:Math.round(t.windowMs/6e4)};for(let e of TN){let a=r[e];if(!DN(t[e])||!DN(n[e])||!a||!DN(a.min)||!DN(a.max))throw Error(`Missing workflow budget settings`);i.values[e]=t[e],i.defaults[e]=n[e],i.bounds[e]={min:a.min,max:a.max}}return i}var kN=e=>({maxConcurrentChildren:String(e.maxConcurrentChildren),maxPhysicalSends:String(e.maxPhysicalSends),maxDistinctChildren:String(e.maxDistinctChildren)});function AN(e,t){if(!/^\d+$/.test(e.trim()))return;let n=Number(e.trim());return n>=t.min&&n<=t.max?n:void 0}function jN({apiBase:e,id:t}){return(0,Q.jsx)(MN,{apiBase:e,id:t},e)}function MN({apiBase:e,id:t}){let n=b(),r=bN(n(`workflowBudget.title`)),[i,a]=(0,Z.useState)(),[o,s]=(0,Z.useState)({maxConcurrentChildren:``,maxPhysicalSends:``,maxDistinctChildren:``}),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(null),_=(0,Z.useCallback)(e=>{a(e),s(kN(e.values))},[]),v=(0,Z.useCallback)(async()=>{if(g.current)return;let t=d(15e3);g.current=t,f(!1);try{let n=ON(await cr(await fetch(e+`/api/workflow-budget/settings`,{signal:t.signal})));h.current&&g.current===t&&_(n)}catch{h.current&&g.current===t&&f(!0)}finally{t.clear(),g.current===t&&(g.current=null)}},[e,_]);(0,Z.useEffect)(()=>{h.current=!0;let e=window.setTimeout(()=>{v()},0);return()=>{window.clearTimeout(e),h.current=!1,g.current?.controller.abort(),g.current?.clear(),g.current=null}},[v]);let y=i?Object.fromEntries(TN.map(e=>[e,AN(o[e],i.bounds[e])])):void 0,x=y!==void 0&&TN.every(e=>y[e]!==void 0),S=i!==void 0&&y!==void 0&&TN.some(e=>y[e]!==i.values[e]),C=i!==void 0&&TN.every(e=>i.values[e]===i.defaults[e]),w=async(t=!1)=>{if(g.current||i===void 0||!t&&(!x||y===void 0))return;let n=t||TN.every(e=>y?.[e]===i.defaults[e])?null:Object.fromEntries(TN.map(e=>[e,y?.[e]])),r=d(15e3);g.current=r,l(!0),m(null);try{let t=ON(await cr(await fetch(e+`/api/workflow-budget/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:r.signal,body:JSON.stringify(n)})));h.current&&g.current===r&&(_(t),m(`saved`))}catch{h.current&&g.current===r&&m(`failed`)}finally{r.clear(),h.current&&g.current===r&&l(!1),g.current===r&&(g.current=null)}},T=c||i===void 0||u,E=(e,t)=>{s(n=>({...n,[e]:t})),m(null)};return(0,Q.jsxs)(pN,{id:t,title:n(`workflowBudget.title`),lede:n(`subagentsV2.budgetLede`),meta:r.button,busy:c||i===void 0&&!u,below:r.panel((0,Q.jsx)(`p`,{children:n(`workflowBudget.description`,{minutes:i?.windowMinutes??10})})),children:[u&&(0,Q.jsxs)(`div`,{className:`mx-4 mb-3 flex flex-wrap items-center gap-2 rounded-[8px] bg-danger-soft px-3 py-2 text-[13px] text-danger`,role:`alert`,children:[(0,Q.jsx)(`span`,{className:`flex-1`,children:n(`workflowBudget.loadFailed`)}),(0,Q.jsx)(Jp,{size:`sm`,variant:`outline`,onClick:()=>{v()},children:n(`common.retry`)})]}),(0,Q.jsx)(mN,{children:TN.map(e=>{let[t,r]=EN[e],a=n(t),s=i?.bounds[e]??{min:0,max:0},c=i!==void 0&&y?.[e]===void 0,l=`workflow-budget-`+e+`-hint`;return(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-[min(100%,12rem)] flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-[14px] leading-5 font-medium text-fg`,children:[a,(0,Q.jsx)(fN,{label:a,children:n(r)})]}),(0,Q.jsx)(`span`,{className:`text-[12px] leading-4 text-fg-subtle tabular-nums`,id:l,children:i&&n(`workflowBudget.range`,{default:i.defaults[e],min:s.min,max:s.max})}),c&&(0,Q.jsx)(`span`,{className:`text-[12px] leading-4 text-danger`,role:`alert`,children:n(`workflowBudget.invalid`,{min:s.min,max:s.max})})]}),(0,Q.jsx)(wN,{min:s.min,max:s.max,step:1,inputMode:`numeric`,value:o[e],readOnly:T,"aria-disabled":T,"aria-label":a,"aria-describedby":l,"aria-invalid":c,onChange:t=>E(e,t.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&!T&&S&&x&&(e.preventDefault(),w())},stepDisabled:T,incrementLabel:n(`workflowBudget.increase`,{label:a}),decrementLabel:n(`workflowBudget.decrease`,{label:a}),onIncrement:()=>E(e,f_(o[e],1,s.min,s.max)),onDecrement:()=>E(e,f_(o[e],-1,s.min,s.max))})]},e)})}),(0,Q.jsxs)(hN,{className:`sticky bottom-0 z-[1] rounded-b-[12px] bg-surface`,children:[(0,Q.jsx)(`span`,{className:`mr-auto min-w-0`,"aria-live":`polite`,children:p===`failed`?(0,Q.jsx)(`span`,{className:`text-danger`,role:`alert`,children:n(`workflowBudget.saveFailed`)}):p===`saved`?(0,Q.jsx)(`span`,{className:`text-success`,role:`status`,children:n(`workflowBudget.saved`)}):(0,Q.jsx)(`span`,{className:S?`text-fg`:void 0,children:n(S?`subagentsV2.unsaved`:`subagentsV2.noChanges`)})}),(0,Q.jsx)(Jp,{size:`sm`,variant:`ghost`,disabled:T||!S&&C,onClick:()=>{w(!0)},children:n(`workflowBudget.reset`)}),(0,Q.jsx)(Jp,{size:`sm`,variant:`primary`,disabled:T||!S||!x,onClick:()=>{w()},children:n(`common.save`)})]})]})}var NN=`section`;function PN(e,t){return[e,NN,t].join(`-`)}function FN(e){return[e,NN,``].join(`-`)}var IN=1200;function LN({scope:e,items:t,ariaLabel:n,mobileReadingLine:r}){let[i,a]=(0,Z.useState)(()=>r&&window.matchMedia(`(max-width: 760px)`).matches?r:72);(0,Z.useEffect)(()=>{if(!r)return;let e=window.matchMedia(`(max-width: 760px)`),t=()=>a(e.matches?r:72);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let[o,s]=(0,Z.useState)(t[0]?.id??``),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useCallback)(()=>{c.current=null,l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=(0,Z.useCallback)(()=>{u();let n=null,r=1/0;for(let a of t){let t=document.getElementById(PN(e,a.id));if(!t)continue;let o=Math.abs(t.getBoundingClientRect().top-i);o<r&&(r=o,n=a.id)}n&&s(n)},[u,t,e,i]);(0,Z.useEffect)(()=>()=>u(),[u]),(0,Z.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(PN(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=c.current;if(n){let r=document.getElementById(PN(e,n));t.some(e=>e.isIntersecting&&e.target===r)&&(u(),s(n));return}let r=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!r)return;let i=r.target.id.slice(FN(e).length);s(e=>e===i?e:i)},{rootMargin:[String(-i)+`px`,`0px`,`-60%`,`0px`].join(` `),threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[u,t,e,i]);let f=t=>{let n=document.getElementById(PN(e,t));n&&(c.current=t,l.current!==null&&clearTimeout(l.current),l.current=setTimeout(d,IN),s(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,Q.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===t.id,"aria-controls":PN(e,t.id),tabIndex:o===t.id?0:-1,className:`page-tab${o===t.id?` page-tab--active`:``}`,onClick:()=>f(t.id),children:[t.label,t.meta?(0,Q.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}var RN=1500,zN={fast:`integrations.lazycodexRoles.auto.tierFast`,standard:`integrations.lazycodexRoles.auto.tierStandard`,frontier:`integrations.lazycodexRoles.auto.tierFrontier`},BN={glance:`integrations.lazycodexRoles.auto.effortGlance`,measured:`integrations.lazycodexRoles.auto.effortMeasured`,thorough:`integrations.lazycodexRoles.auto.effortThorough`,exhaustive:`integrations.lazycodexRoles.auto.effortExhaustive`};function VN({apiBase:e,model:t,effort:n,available:r,saving:i,onAccept:a}){let o=b(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),h=e=>{let t=r.find(t=>t.namespaced===e);return t?Fe(`${t.provider}/${t.model}`,o):e},g=async()=>{u(!0),f(null);try{let t=await fetch(`${e}/api/injection-model/suggest`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({work:s.trim()})});m(await Yn(t,o(`sub.suggest.failed`))??null)}catch(e){m(null),f(e instanceof Error&&e.message?e.message:o(`sub.suggest.failed`))}finally{u(!1)}},_=p?.proposal,v=!!_?.proposedModel&&_.proposedModel===t&&(_.proposedEffort??``)===n,y=l?o(`sub.suggest.running`):p?o(`sub.suggest.title`):``;return(0,Q.jsxs)(`div`,{className:`swi-suggest`,children:[(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:y}),(0,Q.jsx)(`label`,{className:`swi-suggest-label`,htmlFor:`swi-suggest-work`,children:o(`sub.suggest.label`)}),(0,Q.jsxs)(`div`,{className:`swi-suggest-input`,children:[(0,Q.jsx)(`textarea`,{id:`swi-suggest-work`,className:`input`,rows:2,maxLength:RN,value:s,placeholder:o(`sub.suggest.placeholder`),onChange:e=>c(e.target.value),disabled:l}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:l||i||s.trim()===``,onClick:()=>void g(),children:o(l?`sub.suggest.running`:`sub.suggest.submit`)})]}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),p&&_&&(0,Q.jsxs)(`section`,{className:`swi-suggest-result`,"aria-label":o(`sub.suggest.title`),children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-head`,children:[_.tier&&_.effortIntent&&(0,Q.jsx)(`span`,{className:`font-semibold`,children:o(`integrations.lazycodexRoles.auto.tierEffort`,{tier:o(zN[_.tier]),effort:o(BN[_.effortIntent])})}),(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.sizedWith`,{model:p.sizingModel})})]}),p.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:o(`integrations.lazycodexRoles.auto.sizingFailed`,{error:p.sizingError})}),_.status===`unsized`?(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.unsized`,{reason:_.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-change`,children:[(0,Q.jsxs)(`span`,{children:[_.model?h(_.model):o(`dash.injectionNone`),_.effort?` · ${_.effort}`:``]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),_.proposedModel?(0,Q.jsxs)(`strong`,{children:[h(_.proposedModel),_.proposedEffort?` · ${_.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`muted`,children:o(`integrations.lazycodexRoles.auto.unassigned`,{reason:_.reason??``})})]}),_.rationale&&(0,Q.jsx)(`p`,{children:_.rationale}),_.moveUpIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.moveUp`,{text:_.moveUpIf})}),_.moveDownIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.moveDown`,{text:_.moveDownIf})})]}),(0,Q.jsxs)(`div`,{className:`swi-suggest-actions`,children:[v?(0,Q.jsx)(`span`,{className:`swi-suggest-done`,children:o(`integrations.lazycodexRoles.auto.alreadySet`)}):_.status===`proposed`&&_.proposedModel&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:i,onClick:()=>a({model:_.proposedModel,effort:_.proposedEffort??null}),children:o(`sub.suggest.accept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:i,onClick:()=>m(null),children:o(`integrations.lazycodexRoles.auto.discard`)})]})]})]})}function HN({apiBase:e,model:t,effort:n,efforts:r,available:i,guidanceEnabled:a,syncCodexDefaults:o,saving:s,onSave:c,ultraMode:l,ultraSaving:u,onUltraModeSave:d,ultraLoadFailed:f,onUltraModeRetry:p,fallback:m,fallbackPollMs:h,fallbackBusy:g,availableModels:_,onFallbackChange:v,onFallbackPollMsChange:y,onFallbackSave:x,id:S}){let C=b(),w=(l.hintText??``).trim().length>0,T=i.some(e=>e.namespaced===t&&(e.provider!==`openai`||e.namespaced!==e.model)),E=l.enabled||l.multiAgentMode!==`v1`&&!(l.multiAgentMode===`v2`&&l.keepNativeChatGptOnV1),D=!f&&l.loaded===!0&&T&&E,O=new Set(_),k=new Set(m),[A,j]=(0,Z.useState)(()=>({pollMs:h,text:String(h)}));Object.is(A.pollMs,h)||j({pollMs:h,text:Number.isFinite(h)?String(h):``});let M=(0,Z.useRef)(null),[N,P]=(0,Z.useState)(!1),[F,I]=(0,Z.useState)(()=>({models:m,rows:m.map((e,t)=>({model:e,id:t})),nextId:m.length})),L=F.rows;if(F.models!==m){let e=[...F.rows],t=F.nextId;L=m.map(n=>{let r=e.findIndex(e=>e.model===n);return r>=0?e.splice(r,1)[0]:{model:n,id:t++}}),I({models:m,rows:L,nextId:t})}let R=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e=R.current;if(!e)return;R.current=null;let t=M.current?.querySelectorAll(`.swi-fallback-row`)[e.row],n=t?.querySelectorAll(`button[data-action]:not(:disabled)`);(Array.from(n??[]).find(t=>t.dataset.action===e.action)??t?.querySelector(`button:not(:disabled)`)??M.current?.querySelector(`button[role="combobox"]`))?.focus()},[m]);let z=Number.isInteger(h)&&h>=5e3&&h<=6e5,B=(e,t)=>{let n=[...m],r=e+t;if(g||r<0||r>=n.length)return;[n[e],n[r]]=[n[r],n[e]];let i=[...L];[i[e],i[r]]=[i[r],i[e]],I({...F,models:n,rows:i}),R.current={row:r,action:t===-1?`up`:`down`},v(n)},V=e=>{let t=Number(e),n=e.trim()!==``&&Number.isFinite(t)?t:NaN;j({pollMs:n,text:e}),y(n)},H=C(`sub.fallbackPoll`);return(0,Q.jsx)(pN,{id:S,className:`swi-delegation`,title:C(`subagentsV2.delegationTitle`),children:(0,Q.jsxs)(mN,{children:[f&&(0,Q.jsx)(gN,{className:`swi-delegation-row`,label:C(`sub.ultraMode`),hint:(0,Q.jsx)(`span`,{className:`text-danger`,children:C(`sub.ultraModeLoadFail`)}),control:(0,Q.jsx)(Jp,{size:`sm`,variant:`outline`,onClick:p,children:C(`common.retry`)})}),(0,Q.jsx)(gN,{className:`swi-delegation-row swi-delegation-model-row`,label:C(`sub.delegation.model`),hint:C(`subagentsV2.delegationShort`),help:(0,Q.jsx)(fN,{label:C(`sub.delegation.model`),children:C(`sub.delegation.modelHint`)}),control:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Vn,{value:t,options:[{value:``,label:C(`dash.injectionNone`)},...i.map(e=>({value:e.namespaced,label:Fe(`${e.provider}/${e.model}`,C)}))],onChange:e=>c({model:e||null,effort:n||null}),disabled:s,label:C(`dash.injectionLabel`),align:`right`}),t&&r.length>0&&(0,Q.jsx)(Vn,{value:n,options:[{value:``,label:C(`dash.injectionEffortNone`)},...r.map(e=>({value:e,label:e}))],onChange:e=>c({model:t||null,effort:e||null}),disabled:s,label:C(`dash.injectionEffortLabel`),align:`right`}),(0,Q.jsx)(Jp,{size:`sm`,variant:N?`outline`:`ghost`,"aria-expanded":N,onClick:()=>P(e=>!e),children:C(`sub.suggest.button`)})]}),children:N&&(0,Q.jsx)(VN,{apiBase:e,model:t,effort:n,available:i,saving:s,onAccept:c})}),D&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-v2-compatibility px-4 py-3`,role:`note`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1 rounded-[8px] bg-warning-soft px-3 py-2.5 text-[13px] leading-5`,children:[(0,Q.jsx)(`div`,{className:`font-semibold text-warning`,children:C(`sub.v2Compatibility.title`)}),(0,Q.jsx)(`p`,{className:`m-0 text-fg-muted`,children:C(`sub.v2Compatibility.risk`)}),(0,Q.jsx)(`p`,{className:`m-0 text-fg-muted`,children:C(`sub.v2Compatibility.recoveryUnknown`)}),(0,Q.jsx)(`a`,{className:`w-fit text-highlight hover:underline`,href:`https://github.com/lidge-jun/opencodex/issues/92`,target:`_blank`,rel:`noreferrer`,children:C(`sub.v2Compatibility.details`)})]})}),(0,Q.jsx)(gN,{className:`swi-delegation-row swi-fallback-editor`,label:C(`sub.fallbackLabel`),hint:C(`sub.fallbackHint`),children:(0,Q.jsxs)(`div`,{className:`swi-fallback-controls flex min-w-0 flex-col gap-2`,ref:M,children:[m.length>0&&(0,Q.jsx)(`ol`,{className:`m-0 flex list-none flex-col divide-y divide-line overflow-hidden rounded-[8px] p-0 ring-1 ring-line`,children:m.map((e,t)=>(0,Q.jsxs)(`li`,{className:`swi-fallback-row flex min-h-10 min-w-0 items-center gap-3 py-1 pr-1.5 pl-2.5`,children:[(0,Q.jsx)(`span`,{className:X(`grid size-6 shrink-0 place-items-center rounded-[7px] text-[12px] font-medium tabular-nums ring-1 ring-inset`,`swi-fallback-pos bg-surface text-fg ring-line-strong`),children:t+1}),(0,Q.jsxs)(`span`,{className:`swi-fallback-model flex min-w-0 flex-1 flex-col`,children:[(0,Q.jsx)(`span`,{className:`swi-fallback-name truncate font-mono text-[13px] text-fg`,children:e}),!O.has(e)&&(0,Q.jsx)(`span`,{className:`text-[12px] text-warning`,children:C(`sub.fallbackUnavailable`)})]}),(0,Q.jsxs)(`span`,{className:`swi-fallback-actions flex shrink-0 items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,className:vN,"data-action":`up`,onClick:()=>B(t,-1),disabled:g||t===0,"aria-label":C(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(ot,{})}),(0,Q.jsx)(`button`,{type:`button`,className:vN,"data-action":`down`,onClick:()=>B(t,1),disabled:g||t===m.length-1,"aria-label":C(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(Ot,{})}),(0,Q.jsx)(`button`,{type:`button`,className:X(vN,`hover:bg-danger-soft hover:text-danger`),"data-action":`remove`,onClick:()=>{let e=m.filter((e,n)=>n!==t);I({...F,models:e,rows:L.filter((e,n)=>n!==t)}),R.current={row:Math.max(0,Math.min(t,m.length-2)),action:`remove`},v(e)},disabled:g,"aria-label":C(`sub.removeAria`,{m:e}),children:(0,Q.jsx)(Ie,{})})]})]},L[t].id))}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Q.jsx)(Vn,{value:``,label:C(`sub.fallbackAdd`),options:[{value:``,label:C(`sub.fallbackAdd`)},..._.filter(e=>!k.has(e)).map(e=>({value:e,label:e}))],onChange:e=>{e&&!k.has(e)&&v([...m,e])},disabled:g}),(0,Q.jsxs)(`div`,{className:`ml-auto flex items-center gap-2 text-[13px] text-fg-muted`,children:[(0,Q.jsx)(`label`,{htmlFor:`subagent-fallback-poll-ms`,children:H}),(0,Q.jsx)(wN,{id:`subagent-fallback-poll-ms`,min:5e3,max:6e5,step:1e3,value:A.text,onChange:e=>V(e.currentTarget.value),disabled:g,"aria-invalid":!z,stepDisabled:g,unit:`ms`,inputClassName:`w-24`,decrementLabel:C(`workflowBudget.decrease`,{label:H}),incrementLabel:C(`workflowBudget.increase`,{label:H}),onDecrement:()=>V(f_(A.text,-1e3,5e3,6e5)),onIncrement:()=>V(f_(A.text,1e3,5e3,6e5))})]}),(0,Q.jsx)(Jp,{size:`sm`,variant:`primary`,onClick:x,disabled:g||!z,children:C(`common.save`)})]}),!z&&(0,Q.jsx)(`div`,{className:`text-[12px] text-danger`,role:`alert`,children:C(`sub.fallbackPollInvalid`)})]})}),(0,Q.jsx)(gN,{className:`swi-delegation-row`,label:C(`dash.syncCodexSubagentDefaults`),hint:C(`subagentsV2.syncShort`),help:(0,Q.jsx)(fN,{label:C(`dash.syncCodexSubagentDefaults`),children:C(`dash.syncCodexSubagentDefaultsHint`)}),control:(0,Q.jsx)(`button`,{type:`button`,className:`switch ${o?`on`:``}`,onClick:()=>c({syncCodexSubagentDefaults:!o}),disabled:s||!t,"aria-label":C(`dash.syncCodexSubagentDefaults`),"aria-pressed":o,children:(0,Q.jsx)(`span`,{className:`knob`})})}),(0,Q.jsxs)(`details`,{className:`swi-advanced`,children:[(0,Q.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center gap-3 px-4 py-3 transition-colors hover:bg-surface/60 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(lt,{className:`size-4 shrink-0 text-fg-subtle transition-transform duration-200 [details[open]>summary>&]:rotate-90`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`text-[14px] font-medium text-fg`,children:C(`sub.advanced`)}),(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-[13px] text-fg-subtle`,children:C(`subagentsV2.advancedHint`)})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col divide-y divide-line border-t border-line`,children:[(0,Q.jsx)(gN,{className:`swi-delegation-row`,label:C(`models.v2Label`),hint:(0,Q.jsxs)(Q.Fragment,{children:[C(`subagentsV2.surfaceShort`),` `,(0,Q.jsx)(`a`,{className:`text-highlight hover:underline`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,children:C(`models.v2DocsLink`)}),l.plaintextAgentMessagesEnabled===!0&&(0,Q.jsx)(`span`,{className:`block`,children:C(`models.v2PlaintextOn`)})]}),help:(0,Q.jsx)(fN,{label:C(`models.v2Label`),children:(0,Q.jsx)(`span`,{className:`whitespace-pre-line`,children:C(`models.v2Help`)})}),control:(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":C(`models.v2Label`),children:Wr(l.supportsPlaintextV2Mode===!0).map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l.multiAgentMode===e,className:`btn btn-sm${l.multiAgentMode===e?` btn-primary`:` btn-ghost`}`,disabled:u||f,onClick:()=>{l.multiAgentMode!==e&&d({multiAgentMode:e})},children:C(`models.v2Mode_${e}`)},e))})}),(0,Q.jsx)(gN,{className:`swi-delegation-row`,label:C(`dash.multiAgentGuidance`),hint:C(`subagentsV2.guidanceShort`),help:(0,Q.jsx)(fN,{label:C(`dash.multiAgentGuidance`),children:C(`dash.multiAgentGuidanceHint`)}),control:(0,Q.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>c({multiAgentGuidanceEnabled:!a}),disabled:s,"aria-label":C(`dash.multiAgentGuidance`),"aria-pressed":a,children:(0,Q.jsx)(`span`,{className:`knob`})})}),(0,Q.jsx)(gN,{className:`swi-delegation-row`,label:C(`sub.ultraMode`),hint:l.multiAgentV2Enabled?C(`subagentsV2.ultraShort`):(0,Q.jsx)(`span`,{className:`text-warning`,children:C(`sub.ultraModeV2Required`)}),help:(0,Q.jsx)(fN,{label:C(`sub.ultraMode`),children:C(`sub.ultraModeHint`)}),control:(0,Q.jsx)(`button`,{type:`button`,className:`switch ${w?`on`:``}`,onClick:()=>{w?d({multiAgentModeHintText:null}):l.recommendation&&d({multiAgentModeHintText:l.recommendation.text})},disabled:s||u||!w&&(!l.multiAgentV2Enabled||!l.recommendation),"aria-label":C(`sub.ultraMode`),"aria-pressed":w,children:(0,Q.jsx)(`span`,{className:`knob`})})}),w&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor flex flex-col gap-2 px-4 py-3.5`,children:(0,Q.jsx)(UN,{initialHint:l.hintText??``,disabled:s||u,onSave:d,preset:l.recommendation?.text??null,labels:{text:C(`sub.ultraModeText`),preset:C(`sub.ultraModePreset`),save:C(`common.save`)}},l.hintText)})]})]})]})})}function UN({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,Z.useState)(e);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`textarea`,{className:`input swi-ultra-mode-textarea min-h-24 w-full font-mono text-[12px] leading-5`,value:a,onChange:e=>o(e.target.value),disabled:t,rows:4,"aria-label":i.text}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(Jp,{size:`sm`,variant:`ghost`,onClick:()=>{r!==null&&o(r)},disabled:t||r===null,children:i.preset}),(0,Q.jsx)(Jp,{size:`sm`,variant:`primary`,onClick:()=>{a.trim().length!==0&&n({multiAgentModeHintText:a})},disabled:t||a.trim().length===0,children:i.save})]})]})}function WN({available:e,fallbackAvailable:t,chosen:n,onToggle:r,onMove:i,fallback:a,fallbackPollMs:o,fallbackBusy:s,onFallbackChange:c,onFallbackPollMsChange:l,onFallbackSave:u,delegation:d,settingsExtra:f}){let p=b(),[m,h]=(0,Z.useState)(``),g=(0,Z.useMemo)(()=>new Set(n),[n]),_=n.length>=5,v=Math.max(0,5-n.length),y=(0,Z.useMemo)(()=>{let t=m.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,m]),x=(0,Z.useMemo)(()=>[{id:`featured`,label:p(`sub.featured`),meta:`${n.length}/5`},{id:`models`,label:p(`sub.models`),meta:String(y.length)},{id:`settings`,label:p(`sub.settings`)}],[p,n.length,y.length]);return(0,Q.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,Q.jsx)(LN,{scope:`subagents`,items:x,ariaLabel:p(`sub.sections`)}),(0,Q.jsxs)(`div`,{className:`subagents-workspace-root flex flex-col gap-4`,children:[(0,Q.jsx)(pN,{id:PN(`subagents`,`featured`),className:`subagents-workspace-section`,headClassName:`swi-featured-head`,title:(0,Q.jsx)(`span`,{className:`swi-featured-title`,children:p(`sub.featured`)}),meta:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(_N,{children:(0,Q.jsxs)(`span`,{className:`swi-featured-count`,children:[n.length,`/`,5]})}),(0,Q.jsx)(fN,{label:p(`sub.orderHintAria`),children:(0,Q.jsx)(z,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),lede:p(`subagentsV2.featuredLede`),children:(0,Q.jsxs)(mN,{as:`ol`,children:[n.map((e,t)=>(0,Q.jsxs)(`li`,{className:`swi-featured-row flex min-h-11 min-w-0 items-center gap-3 py-1.5 pr-2 pl-3 transition-colors hover:bg-surface/60`,children:[(0,Q.jsx)(`span`,{className:X(yN,`bg-surface text-fg ring-line-strong`),children:t+1}),(0,Q.jsx)(`span`,{className:`swi-featured-name min-w-0 flex-1 truncate font-mono text-[13px] text-fg`,children:RD(e)}),(0,Q.jsxs)(`span`,{className:`swi-featured-actions flex shrink-0 items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,className:vN,onClick:()=>i(t,-1),disabled:t===0,"aria-label":p(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(ot,{})}),(0,Q.jsx)(`button`,{type:`button`,className:vN,onClick:()=>i(t,1),disabled:t===n.length-1,"aria-label":p(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(Ot,{})}),(0,Q.jsx)(`button`,{type:`button`,className:X(vN,`hover:bg-danger-soft hover:text-danger`),onClick:()=>r(e),"aria-label":p(`sub.removeAria`,{m:e}),children:(0,Q.jsx)(Ie,{})})]})]},e)),Array.from({length:v},(e,t)=>(0,Q.jsxs)(`li`,{className:`flex min-h-11 min-w-0 items-center gap-3 py-1.5 pr-2 pl-3 text-[13px] text-fg-subtle`,children:[(0,Q.jsx)(`span`,{className:X(yN,`border border-dashed border-line-strong text-fg-subtle ring-0`),"aria-hidden":`true`,children:n.length+t+1}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n.length===0&&t===0?p(`sub.noneSelected`):p(`subagentsV2.emptySlot`)})]},`free-${t}`))]})}),(0,Q.jsx)(pN,{id:PN(`subagents`,`models`),className:`subagents-workspace-section`,title:p(`sub.workspace.allModels`),meta:(0,Q.jsx)(_N,{children:y.length}),lede:_?p(`sub.workspace.featuredFull`):p(`subagentsV2.modelsLede`,{max:5}),actions:(0,Q.jsxs)(`label`,{className:`relative flex w-full items-center sm:w-72`,children:[(0,Q.jsx)(We,{className:`pointer-events-none absolute left-2.5 size-4 text-fg-subtle`,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{className:`input w-full pl-8`,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:p(`sub.search`),"aria-label":p(`sub.search`)})]}),children:(0,Q.jsx)(mN,{as:`ul`,className:`max-h-[min(30rem,60vh)] overflow-y-auto`,children:y.length===0?(0,Q.jsx)(`li`,{className:`px-4 py-6 text-center text-[13px] text-fg-muted`,children:p(`sub.noModels`)}):y.map(e=>{let t=g.has(e),i=t?n.indexOf(e)+1:null,a=!t&&_;return(0,Q.jsxs)(`li`,{className:`flex min-h-11 min-w-0 items-center gap-3 py-1.5 pr-2 pl-3.5`,children:[(0,Q.jsx)(vt,{className:`size-4 shrink-0 text-fg-subtle`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:X(`min-w-0 flex-1 truncate font-mono text-[13px]`,t?`text-fg`:`text-fg-muted`),children:RD(e)}),i!==null&&(0,Q.jsx)(`span`,{className:`shrink-0 rounded-full bg-surface-2 px-2 py-0.5 text-[11px] font-medium text-fg-muted tabular-nums`,children:p(`subagentsV2.rank`,{n:i})}),(0,Q.jsxs)(`button`,{type:`button`,className:X(`ui-v2 inline-flex h-[var(--ocx-control-h-sm)] shrink-0 cursor-pointer items-center gap-1 rounded-[8px] px-2.5 text-[12px] font-medium transition-colors`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight [&_svg]:size-3.5`,`disabled:cursor-not-allowed disabled:opacity-40`,t?`bg-accent text-on-accent hover:opacity-85`:`text-fg-muted ring-1 ring-inset ring-line-strong hover:bg-surface-2 hover:text-fg`),onClick:()=>{a||r(e)},disabled:a,"aria-pressed":t,"aria-label":p(t?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:t?p(`sub.workspace.removeFromFeatured`,{m:e}):_?p(`sub.workspace.featuredFull`):p(`sub.workspace.addToFeatured`,{m:e}),children:[t?(0,Q.jsx)(st,{"aria-hidden":`true`}):(0,Q.jsx)(Vt,{"aria-hidden":`true`}),p(t?`subagentsV2.added`:`subagentsV2.add`)]})]},e)})})}),(0,Q.jsxs)(`section`,{id:PN(`subagents`,`settings`),className:`subagents-workspace-section flex flex-col gap-4`,"aria-label":p(`sub.settings`),children:[(0,Q.jsx)(HN,{id:PN(`subagents`,`delegation`),apiBase:d.apiBase,model:d.model,effort:d.effort,efforts:d.efforts,available:d.available,guidanceEnabled:d.guidanceEnabled,syncCodexDefaults:d.syncCodexDefaults,saving:d.saving,onSave:d.onSave,ultraMode:d.ultraMode,ultraSaving:d.ultraSaving,onUltraModeSave:d.onUltraModeSave,ultraLoadFailed:d.ultraLoadFailed,onUltraModeRetry:d.onUltraModeRetry,fallback:a,fallbackPollMs:o,fallbackBusy:s,availableModels:t??e,onFallbackChange:c,onFallbackPollMsChange:l,onFallbackSave:u}),f]})]})]})}function GN(e){let[t,n]=(0,Z.useState)(!1),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(!0),[h,g]=(0,Z.useState)(!1),_=(0,Z.useCallback)(e=>{let t=Uf(e);m(t.multiAgentGuidanceEnabled),g(t.syncCodexSubagentDefaults),o(t.injectionModel),c(t.injectionEffort),Array.isArray(e.efforts)&&u(e.efforts),Array.isArray(e.available)&&f(e.available)},[]);return(0,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await cr(await fetch(`${e}/api/injection-model`));if(t)return;_(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,_]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,Z.useCallback)(async t=>{if(!r){i(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await fetch(`${e}/api/injection-model`);_(await cr(n))}catch{}finally{i(!1)}}},[e,_,r])}}function KN({chosen:e,max:t,firstModel:n,firstEffort:r,pin:i,onJump:a}){let o=b(),s=e[0];return(0,Q.jsxs)(`section`,{"aria-label":o(`subagentsV2.nowTitle`),className:`flex flex-col gap-2`,children:[(0,Q.jsx)(`h3`,{className:`m-0 text-[12px] font-medium text-fg-subtle`,children:o(`subagentsV2.nowTitle`)}),(0,Q.jsxs)(`div`,{className:`grid gap-3 md:grid-cols-3`,children:[(0,Q.jsx)(qN,{label:o(`subagentsV2.nowOrder`),value:s?RD(s):o(`subagentsV2.nowOrderNone`),mono:!!s,muted:!s,caption:o(`subagentsV2.nowOrderCaption`,{n:e.length,max:t}),onClick:()=>a(`featured`)}),(0,Q.jsx)(qN,{label:o(`sub.delegation.model`),value:n||o(`dash.injectionNone`),mono:!!n,muted:!n,caption:n?`${o(`dash.injectionEffortLabel`)} · ${r||o(`dash.injectionEffortNone`)}`:o(`subagentsV2.firstNoneCaption`),onClick:()=>a(`delegation`)}),(0,Q.jsx)(qN,{label:o(`subagentsV2.nowPin`),value:i===void 0?`—`:i??o(`subagentsV2.off`),mono:!!i,muted:!i,on:!!i,caption:o(i?`subagentsV2.pinOnCaption`:`subagentsV2.pinOffCaption`),onClick:()=>a(`pin`)})]})]})}function qN({label:e,value:t,caption:n,mono:r,muted:i,on:a,onClick:o}){let s=b();return(0,Q.jsxs)(`button`,{type:`button`,onClick:o,className:X(`ui-v2 group flex min-w-0 cursor-pointer flex-col gap-1 rounded-[12px] bg-surface px-4 py-3.5 text-left ring-1 ring-inset ring-line`,`transition-colors duration-200 hover:bg-raised hover:ring-line-strong`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`),children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-2 text-[12px] font-medium text-fg-subtle`,children:[a!==void 0&&(0,Q.jsx)(`span`,{className:X(`size-1.5 shrink-0 rounded-full`,a?`bg-success`:`bg-fg-subtle`),"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e}),(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-fg-subtle opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100`,children:[s(`subagentsV2.change`),(0,Q.jsx)(lt,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,Q.jsx)(`span`,{className:X(`truncate text-[16px] leading-6 font-semibold tracking-[-0.01em]`,r&&`font-mono text-[15px]`,i?`text-fg-muted`:`text-fg`),children:t}),(0,Q.jsx)(`span`,{className:`truncate text-[12px] text-fg-muted`,children:n})]})}var JN={enabled:!1,hintText:null,recommendation:null,multiAgentV2Enabled:!1,multiAgentMode:`default`};function YN(e){return sf(e)}function XN(e){document.getElementById(PN(`subagents`,e))?.scrollIntoView({behavior:`smooth`,block:`start`})}function ZN({apiBase:e}){let t=b(),n=`ocx.subagents.v1:${e}`,r=YN(n),[i,a]=(0,Z.useState)(()=>r?.chosen??[]),[o,s]=(0,Z.useState)(()=>r?.fallback??[]),[c,l]=(0,Z.useState)(()=>r?.pollMs??6e4),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(()=>Array.isArray(r?.fallback)&&Number.isInteger(r?.pollMs)),[m,h]=(0,Z.useState)(()=>r?.fallbackAvailable),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(!0),x=(0,Z.useRef)(null),S=(0,Z.useRef)({fallback:r?.fallback,pollMs:r?.pollMs,fallbackAvailable:r?.fallbackAvailable}),C=(0,Z.useRef)(0),w=(0,Z.useRef)(0),T=(0,Z.useRef)(!1),E=(0,Z.useRef)(r),[D,O]=(0,Z.useState)(``),[k,A]=(0,Z.useState)(!1),j=(0,Z.useRef)(!1),M=(0,Z.useRef)(null),N=(0,Z.useRef)(i),P=(0,Z.useCallback)(e=>{N.current=e,a(e)},[]),F=GN(e),[I,L]=(0,Z.useState)(void 0),[R,z]=(0,Z.useState)(null),B=R?.apiBase===e,V=B?R.mode:JN,[H,U]=(0,Z.useState)(!1),[W,ee]=(0,Z.useState)(null),[G,te]=(0,Z.useState)(!1),ne=(0,Z.useRef)(0),K=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{K.current=e,ne.current++},[e]);let q=(0,Z.useCallback)(async n=>{if(K.current!==e)return!1;let r=++ne.current,i=await Yn(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));if(!i||n?.aborted||r!==ne.current||K.current!==e)return!1;te(!1);let a=i.multiAgentModeHintRecommendation,o=a&&typeof a.text==`string`&&a.text.trim().length>0&&typeof a.revision==`string`&&a.revision.trim().length>0?{text:a.text,revision:a.revision}:null;return z({apiBase:e,mode:{enabled:i.enabled??!1,loaded:!0,keepNativeChatGptOnV1:i.keepNativeChatGptOnV1===!0,hintText:i.multiAgentModeHintText??null,recommendation:o,multiAgentV2Enabled:i.enabled===!0&&i.multiAgentMode===`v2`||i.multiAgentMode===`v2-plaintext`,multiAgentMode:i.multiAgentMode===`v1`||i.multiAgentMode===`v2`||i.multiAgentMode===`v2-plaintext`?i.multiAgentMode:`default`,supportsPlaintextV2Mode:i.supportsPlaintextV2Mode===!0,plaintextAgentMessagesEnabled:i.plaintextAgentMessagesEnabled===!0}}),!0},[e,t]);(0,Z.useEffect)(()=>{let e=new AbortController;return(async()=>{await q(e.signal)})().catch(()=>{e.signal.aborted||(A(!1),te(!0),O(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[q,t]);let J=async n=>{if(H||!B||K.current!==e)return;let r=e;U(!0),O(``);try{let i=await Yn(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`));if(n.multiAgentMode===`v2-plaintext`&&!Gr(i))throw Error(t(`sub.ultraModeSaveFail`));if(K.current!==r||!await q())return;A(!0),O(t(`sub.ultraModeSaved`))}catch(e){if(K.current!==r)return;if(n.multiAgentMode===`v2-plaintext`){try{await q()}catch{}if(K.current!==r)return}A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{U(!1)}},re=(0,Z.useCallback)(async()=>{try{if(!await q())return;A(!1),O(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{A(!1),te(!0),O(t(`sub.ultraModeLoadFail`))}},[q,t]),Y=(0,Z.useCallback)(async()=>{x.current?.abort();let r=new AbortController;x.current=r;let{signal:i}=r,a=C.current;try{let r=await Yn(await fetch(`${e}/api/subagent-model-fallback`,{signal:i}));if(!r||!Array.isArray(r.models)||!r.models.every(e=>typeof e==`string`&&e.trim())||typeof r.pollMs!=`number`||!Number.isInteger(r.pollMs)||r.pollMs<5e3||r.pollMs>6e5||!Array.isArray(r.available)||!r.available.every(e=>typeof e==`string`&&e.trim()))throw Error(t(`sub.loadFail`));if(i.aborted||a!==C.current||T.current)return;let o={fallback:r.models,pollMs:r.pollMs,fallbackAvailable:r.available};S.current=o,s(o.fallback),l(o.pollMs),h(o.fallbackAvailable),p(!0),_(``),E.current&&(E.current={...E.current,...o},df(n,E.current))}catch(e){if(i.aborted||a!==C.current||T.current)return;p(!1),_(e instanceof Error&&!(e instanceof SyntaxError)?e.message:t(`sub.loadFail`))}finally{i.aborted||y(!1)}},[e,n,t]);(0,Z.useEffect)(()=>((async()=>{await Y()})(),()=>{x.current?.abort()}),[Y]);let ie=(0,Z.useCallback)(async r=>{let i=w.current,a=await Yn(await fetch(`${e}/api/subagent-models`,{signal:r}),t(`sub.loadFail`));if(!a)throw Error(t(`sub.loadFail`));let o=a.available??[],s=new Set(o),c=i===w.current&&!j.current,l={...S.current,available:o,chosen:c?(a.chosen??[]).filter(e=>s.has(e)):E.current?.chosen??[]};if(r?.aborted)throw r.reason;return E.current=l,c&&P(l.chosen),df(n,l),l},[e,n,P,t]),ae=mf(n,[e],ie,{isEmpty:()=>!1,initialData:r??void 0}),{state:oe}=ae,se=ae.refresh,ce=oe.data??r,le=ce?.available??[],ue=async r=>{if(M.current=r,j.current)return;j.current=!0,O(``);let i=null,a=r;for(;M.current;){let r=M.current;M.current=null;try{a=(await Yn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:r})}),t(`sub.saveFailed`)))?.applied??r,E.current={...E.current,available:le,chosen:a},df(n,E.current),i=null}catch(e){i=e}}w.current+=1,j.current=!1,i?(P(E.current?.chosen??[]),A(!1),O(i instanceof Error&&i.message?i.message:t(`sub.networkError`))):(P(a),A(!0),O(t(`sub.saved`,{n:a.length,cmd:`ocx sync`})))},de=e=>{w.current+=1,P(e),ue(e)},fe=e=>{let t=N.current;!t.includes(e)&&t.length>=5||de(t.includes(e)?t.filter(t=>t!==e):[...t,e])},pe=(e,t)=>{let n=e+t,r=[...N.current];n<0||n>=r.length||([r[e],r[n]]=[r[n],r[e]],de(r))},me=async()=>{if(!f||T.current||!Number.isInteger(c)||c<5e3||c>6e5)return;T.current=!0,C.current+=1;let r=e;d(!0),O(``);try{let i=await Yn(await fetch(`${e}/api/subagent-model-fallback`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:o,pollMs:c})}),t(`sub.fallbackSaveFailed`));if(K.current!==r)return;if(!i||!Array.isArray(i.models)||typeof i.pollMs!=`number`)throw Error(t(`sub.fallbackSaveFailed`));C.current+=1,s(i.models),l(i.pollMs),S.current={...S.current,fallback:i.models,pollMs:i.pollMs};let a={available:le,chosen:E.current?.chosen??[],...S.current};E.current=a,df(n,a),A(!0),O(t(`sub.fallbackSaved`))}catch(e){A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{T.current=!1,d(!1)}};if(oe.showSkeleton&&!ce)return(0,Q.jsx)(ck,{label:t(`sub.loading`),rows:4});if(oe.kind===`failed-cold`){let e=oe.error instanceof Error?oe.error.message:t(`sub.loadFail`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>se(),children:t(`common.retry`)})]})}let he=F.available.find(e=>e.namespaced===F.model),ge=F.model?he?Fe(`${he.provider}/${he.model}`,t):F.model:``;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head flex-col items-start gap-1.5`,children:[(0,Q.jsx)(`h2`,{children:t(`nav.subagents`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:t(`subagentsV2.lede`)})]}),(0,Q.jsx)(`div`,{className:`mt-5 mb-6`,children:(0,Q.jsx)(KN,{chosen:i,max:5,firstModel:ge,firstEffort:F.effort,pin:I,onJump:XN})}),D&&(0,Q.jsx)($,{tone:k?`ok`:`err`,children:D}),oe.showError&&(0,Q.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),g&&(0,Q.jsxs)($,{tone:`err`,children:[t(`sub.fallbackLabel`),`: `,t(`sub.loadFail`),g!==t(`sub.loadFail`)&&(0,Q.jsxs)(Q.Fragment,{children:[` `,g]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v,onClick:()=>{y(!0),Y()},children:t(`common.retry`)})]}),(0,Q.jsx)(WN,{available:le,fallbackAvailable:m??[],chosen:i,onToggle:fe,onMove:pe,fallback:o,fallbackPollMs:c,fallbackBusy:u||!f,onFallbackChange:e=>{C.current+=1,s(e)},onFallbackPollMsChange:e=>{C.current+=1,l(e)},onFallbackSave:()=>{me()},settingsExtra:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(SN,{apiBase:e,roster:i,id:PN(`subagents`,`pin`),onForceChange:L},e),(0,Q.jsx)(jN,{apiBase:e,id:PN(`subagents`,`budget`)})]}),delegation:{apiBase:e,model:F.model,effort:F.effort,efforts:F.efforts,available:F.available,guidanceEnabled:F.guidanceEnabled,syncCodexDefaults:F.syncCodexDefaults,saving:F.saving,onSave:e=>{F.save(e)},ultraMode:V,ultraSaving:H||!B,onUltraModeSave:t=>{t.multiAgentMode==="default"||t.multiAgentMode===`v2`||t.multiAgentMode===`v2-plaintext`?ee({mode:t.multiAgentMode,apiBase:e}):J(t)},ultraLoadFailed:G,onUltraModeRetry:()=>{re()}}}),W&&W.apiBase===e&&W.mode===`v2-plaintext`&&(0,Q.jsx)(qr,{busy:H,onConfirm:()=>{ee(null),J({multiAgentMode:`v2-plaintext`,plaintextAgentMessagesAcknowledged:!0})},onDismiss:()=>ee(null)}),W&&W.apiBase===e&&W.mode!==`v2-plaintext`&&(0,Q.jsx)(Kr,{reason:`selection`,mode:W.mode,docsUrl:`https://opencodex.me/guides/subagent-v1-default/`,busy:H,onContinue:()=>{let e=W.mode;ee(null),J({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{ee(null),V.multiAgentMode!==`v1`&&J({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>ee(null)})]})}function QN(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function $N(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return(o.length!==r.length||o.some((e,t)=>r[t]!==e))&&(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1),i}return o.updateDeps=e=>{r=e},o}function eP(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var tP=(e,t)=>Math.abs(e-t)<1.01,nP=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},rP,iP=()=>{if(rP!==void 0)return rP;if(typeof navigator>`u`)return rP=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return rP=!0;let e=navigator.maxTouchPoints;return rP=navigator.platform===`MacIntel`&&e!==void 0&&e>0},aP=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},oP=e=>e,sP=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},cP=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(aP(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(aP(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},lP={passive:!0},uP=typeof window>`u`||`onscrollend`in window,dP=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&uP,o=0,s=a?null:nP(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,lP),a&&r.addEventListener(`scrollend`,u,lP),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},fP=(e,t)=>dP(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),pP=(e,t,n)=>{if(n.options.useCachedMeasurements){let t=n.indexFromElement(e),r=n.options.getItemKey(t);return n.itemSizeCache.get(r)??n.options.estimateSize(t)}if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}if(!t){let t=n.indexFromElement(e),r=n.options.getItemKey(t),i=n.itemSizeCache.get(r);if(i!==void 0)return i}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},mP=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},hP=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(t.isConnected)this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this));else{this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}}};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:oP,rangeExtractor:sP,onChange:()=>{},measureElement:pP,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=e>0?s[0]?.key??n.getItemKey(0):null,l=e>0?s[e-1]?.key??n.getItemKey(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==c||t.getItemKey(o-1)!==l)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>e&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==l)&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=!1,s=0;if(r&&this.scrollOffset!==null){let[e,t]=r,n=this.getMeasurements(),{count:i,getItemKey:a}=this.options,c=0;for(;c<i&&a(c)!==e;)c++;if(c<i){let e=n[c];if(e){let n=Math.max(0,e.start+t);n!==this.scrollOffset&&(s=n-this.scrollOffset,this.scrollOffset=n,o=!0)}}}(o||i)&&(this.pendingScrollAnchor=[o?r[0]:null,o?r[1]:0,i,s])},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=$N(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.targetWindow=this.scrollElement&&`ownerDocument`in this.scrollElement?this.scrollElement.ownerDocument.defaultView:this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{if(t&&this._intendedScrollOffset===null&&e===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;let n=this.getScrollOffset();this.scrollDirection=t?n===e?this.scrollDirection:n<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,iP()&&this.targetWindow!=null&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,lP),e.addEventListener(`touchend`,n,lP),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}let t=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,t&&this.scrollElement&&this.options.enabled){let[e,n,r,i]=t;e!==null&&!r&&(iP()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?i!==0&&(this._iosDeferredAdjustment+=i):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),r&&this.scrollToEnd({behavior:r})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;if(this._iosDeferredAdjustment<0&&e>=t-1){this._iosDeferredAdjustment=0;return}let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=$N(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(e,t,n,r,i,a,o,s)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s}),{key:!1}),this.getMeasurements=$N(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s},c)=>{let l=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let u=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=e*2,a=this._flatMeasurements;if(!a||a.length<i){let e=new Float64Array(i);a&&u>0&&e.set(a.subarray(0,u*2)),a=e,this._flatMeasurements=a}let o;if(u===0)o=t+n;else{let e=u-1;o=a[e*2]+a[e*2+1]+s}for(let t=u;t<e;t++){let e=r(t),n=l.get(e),i=typeof n==`number`?n:this.options.estimateSize(t);a[t*2]=o,a[t*2+1]=i,o+=i+s}let c=QN(e,a,r);return this.measurementsCache=c,c}let d=this.measurementsCache.slice(0,u),f=Array(a).fill(void 0),p=new Float64Array(a),m=0;for(let e=0;e<u;e++){let t=d[e];t&&(f[t.lane]===void 0&&m++,f[t.lane]=e,p[t.lane]=t.end)}for(let i=u;i<e;i++){let e=r(i),c=this.laneAssignments.get(i),u,h,g=o===`estimate`||l.has(e);if(c!==void 0&&this.options.lanes>1){u=c;let e=f[u],r=e===void 0?void 0:d[e];h=r?r.end+s:t+n}else if(m===a){let e=0,t=p[0],n=f[0];for(let r=1;r<a;r++){let i=p[r];(i<t||i===t&&f[r]<n)&&(e=r,t=i,n=f[r])}u=e,h=t+s,g&&this.laneAssignments.set(i,u)}else u=i%this.options.lanes,h=t+n,g&&this.laneAssignments.set(i,u);let _=l.get(e),v=typeof _==`number`?_:this.options.estimateSize(i),y=h+v;d[i]={index:i,start:h,size:v,end:y,key:e,lane:u},f[u]===void 0&&m++,f[u]=i,p[u]=y}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=$N(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=vP(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=$N(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=this.itemSizeCache.get(i)??n,s=t-o;if(s!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,c=a?this.getTotalSize():0,l=this.getScrollOffset()+this.scrollAdjustments,u=this.itemSizeCache.has(i)?r+o<=l&&this.scrollDirection!==`backward`:r<l,d=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?u:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},s,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++;let f=!1;a?f=this.applyScrollAdjustment(this.getTotalSize()-c):d&&(f=this.applyScrollAdjustment(s)),this.notify(f)}},this.getVirtualItems=$N(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return eP(t[gP(0,t.length-1,r?e=>n[e*2]:e=>eP(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`){if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t]}if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0;let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0,e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:e=`auto`}={})=>{this.options.count>0?this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e}):this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}applyScrollAdjustment(e,t){return e===0?!1:iP()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=e,!1):(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0)}scheduleScrollReconcile(){this.targetWindow?this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}):this.scrollState=null}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&tP(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},gP=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function _P(e,t,n){let r=0;for(;r<=t;){let i=(r+t)/2|0,a=e[i*2];if(a<n)r=i+1;else if(a>n)t=i-1;else return i}return r>0?r-1:0}function vP(e,t,n,r,i){let a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&i!==null){let e=_P(i,a,n),r=e,o=n+t;for(;r<a&&i[r*2]+i[r*2+1]<o;)r++;return{startIndex:e,endIndex:r}}let o=gP(0,a,t=>e[t].start,n),s=o;if(r===1)for(;s<a&&e[s].end<n+t;)s++;else if(r>1){let i=Array(r).fill(0);for(;s<a&&i.some(e=>e<n+t);){let t=e[s];i[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(a,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var yP=typeof document<`u`?Z.useLayoutEffect:Z.useEffect;function bP({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=Z.useReducer(e=>e+1,0)[1],a=Z.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;let o=e=>{let t=a.current;if(!t.enabled||!t.container)return;let n=e.getTotalSize();if(n!==t.lastSize){t.lastSize=n;let r=e.options.horizontal?`width`:`height`;t.container.style[r]=`${n}px`}},s=e=>{let t=a.current;if(!t.enabled||!t.container)return;o(e);let n=!!e.options.horizontal,r=t.mode===`transform`,i=n?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let a of c){let o=a.start-s,c=e.elementsCache.get(a.key);c&&t.lastPositions.get(c)!==o&&(t.lastPositions.set(c,o),r?c.style.transform=n?`translate3d(${o}px, 0, 0)`:`translate3d(0, ${o}px, 0)`:c.style[i]=`${o}px`)}},c={...r,onChange:(t,n)=>{var o;let c=a.current,l=!0;if(c.enabled){s(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,Dn.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=Z.useState(()=>{let e=new hP(c);return Object.assign(e,{containerRef:t=>{let n=a.current;if(n.container=t,n.lastSize=null,t&&n.enabled){let r=e.getTotalSize();n.lastSize=r;let i=e.options.horizontal?`width`:`height`;t.style[i]=`${r}px`}}})});return l.setOptions(c),yP(()=>l._didMount(),[]),yP(()=>(o(l),l._willUpdate())),yP(()=>{s(l)}),l}function xP(e){return bP({observeElementRect:cP,observeElementOffset:fP,scrollToFn:mP,...e})}var SP=32;function CP(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function wP(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}var TP=`codex://threads/`,EP=512;function DP(e){let t=e.trim();if(t.length>EP||t.length<=16||!t.toLowerCase().startsWith(TP))return t;let n=t.slice(16),r=n.search(/[?#]/),i=(r===-1?n:n.slice(0,r)).replace(/\/+$/,``);return i!==``&&!/[/\s]/.test(i)?i:t}function OP(e){let t=e.trim(),n=DP(t),r=t.length>4096?t:kP(t);return[...new Set([n,t,r])]}function kP(e){if(!e.trimStart().startsWith(`{`))return e;try{let t=JSON.parse(e);if(typeof t==`object`&&t&&!Array.isArray(t)&&`tk`in t){let{tk:e,...n}=t;if(Object.keys(n).length>0)return JSON.stringify(n)}}catch{}return e}async function AP(e){let t=OP(e).filter(e=>e!==``&&!wP(e)&&e.length<=4096);return(await Promise.all(t.map(e=>crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))).map(e=>CP(e).slice(0,SP))}function jP(e,t,n){if(!e)return!1;let r=OP(t);return r.some(Boolean)?r.includes(e)?!0:n!==void 0&&n.includes(e):!1}var MP={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},fr:{label:`Requête incorrecte`,description:`Le proxy n’a pas pu comprendre la requête. Vérifiez le modèle, la structure des messages, les en-têtes et le corps JSON avant de réessayer.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{label:`错误请求`,description:`代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。`},"zh-TW":{label:`錯誤請求`,description:`代理無法理解該請求。重試前請檢查模型、訊息結構、標頭和 JSON 本文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`},ru:{label:`Некорректный запрос`,description:`Прокси не смог интерпретировать запрос. Перед повторной попыткой проверьте модель, формат сообщений, заголовки и тело JSON.`},ja:{label:`不正なリクエスト`,description:`プロキシがリクエストを解釈できませんでした。再試行前にモデル、メッセージ形式、ヘッダー、JSON 本文を確認してください。`},tr:{label:`Hatalı istek`,description:`Proxy isteği anlayamadı. Yeniden denemeden önce modeli, mesaj yapısını, başlıkları ve JSON gövdesini kontrol edin.`},vi:{label:`Yêu cầu không hợp lệ`,description:`Proxy không thể hiểu yêu cầu. Hãy kiểm tra model, cấu trúc tin nhắn, header và nội dung JSON trước khi thử lại.`},pt:{label:`Requisição inválida`,description:`O proxy não conseguiu entender a requisição. Verifique o modelo, a estrutura das mensagens, os cabeçalhos e o corpo JSON antes de tentar novamente.`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},fr:{label:`Non autorisé`,description:`Les identifiants sont absents, expirés ou non valides. Reconnectez-vous ou actualisez les identifiants du compte ou du fournisseur utilisés par opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{label:`未授权`,description:`凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。`},"zh-TW":{label:`未授權`,description:`憑證缺失、已過期或無效。請重新登入,或重新整理 opencodex 使用的帳號/供應商憑證。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`},ru:{label:`Не авторизован`,description:`Учётные данные отсутствуют, истекли или недействительны. Войдите заново или обновите учётные данные аккаунта или провайдера, которые использует opencodex.`},ja:{label:`認証が必要`,description:`認証情報が不在・期限切れ・無効です。opencodex が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`},tr:{label:`Yetkisiz erişim`,description:`Kimlik bilgileri eksik, süresi dolmuş veya geçersiz. opencodex tarafından kullanılan hesap veya sağlayıcı kimlik bilgilerini yeniden doğrulayın.`},vi:{label:`Chưa xác thực`,description:`Thông tin xác thực bị thiếu, đã hết hạn hoặc không hợp lệ. Hãy đăng nhập lại hoặc làm mới thông tin xác thực của tài khoản hay nhà cung cấp mà opencodex sử dụng.`},pt:{label:`Não autorizado`,description:`As credenciais estão ausentes, expiradas ou inválidas. Faça login novamente ou atualize as credenciais da conta/provedor usadas pelo opencodex.`}},402:{en:{label:`Payment required`,description:`The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider.`},fr:{label:`Paiement requis`,description:`Le fournisseur en amont a rejeté la requête, car la facturation, les crédits ou l’accès à l’offre ne sont pas disponibles. Ajoutez des crédits, mettez à jour la facturation ou changez de fournisseur.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{label:`需要付款`,description:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},"zh-TW":{label:`需要付款`,description:`上游供應商因帳單、額度或方案許可權不可用而拒絕了請求。請儲值、更新帳單資訊或切換供應商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`},ru:{label:`Требуется оплата`,description:`Вышестоящий провайдер отклонил запрос из-за проблем с оплатой, кредитами или доступом по тарифному плану. Пополните баланс, обновите платёжные данные или переключитесь на другого провайдера.`},ja:{label:`支払いが必要`,description:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`},tr:{label:`Ödeme gerekli`,description:`Yukarı akış sağlayıcısı faturalandırma, kredi veya plan erişimi bulunmadığından isteği reddetti. Kredi ekleyin, ödeme bilgilerini güncelleyin veya sağlayıcı değiştirin.`},vi:{label:`Yêu cầu thanh toán`,description:`Nhà cung cấp upstream đã từ chối yêu cầu vì không có quyền truy cập thanh toán, tín dụng hoặc gói dịch vụ. Hãy thêm tín dụng, cập nhật thanh toán hoặc đổi nhà cung cấp.`},pt:{label:`Pagamento necessário`,description:`O provedor upstream rejeitou a requisição porque faturamento, créditos ou acesso ao plano não estão disponíveis. Adicione créditos, atualize o faturamento ou troque de provedor.`}},403:{en:{label:`Forbidden`,description:`The account is authenticated but not allowed to use this model or operation. Often a plan/subscription gate (e.g. Ollama Cloud Pro), org policy, or model permission — not necessarily a bad API key.`},fr:{label:`Accès interdit`,description:`Le compte est authentifié, mais n’est pas autorisé à utiliser ce modèle ou cette opération. Il s’agit souvent d’une restriction liée à l’offre ou à l’abonnement (p. ex. Ollama Cloud Pro), à la politique de l’organisation ou aux autorisations du modèle — pas nécessairement d’une clé API incorrecte.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다.`},zh:{label:`禁止访问`,description:`账号已认证,但无权使用此模型或操作。常见原因是套餐/订阅限制(例如 Ollama Cloud Pro)、组织策略或模型权限——不一定是 API 密钥无效。`},"zh-TW":{label:`禁止存取`,description:`帳號已認證,但無權使用此模型或操作。常見原因是方案/訂閱限制(例如 Ollama Cloud Pro)、組織策略或模型許可權——不一定是 API 金鑰無效。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key.`},ru:{label:`Доступ запрещён`,description:`Аккаунт аутентифицирован, но не имеет права использовать эту модель или операцию. Часто причина — ограничение тарифа или подписки (например, Ollama Cloud Pro), политика организации или права доступа к модели, а не обязательно неверный API-ключ.`},ja:{label:`アクセス禁止`,description:`アカウントは認証済みですがこのモデルや操作の使用が許可されていません。多くはプラン/サブスクリプション制限(例: Ollama Cloud Pro)、組織ポリシー、モデル権限であり、API キーが不正とは限りません。`},tr:{label:`Erişim yasaklandı`,description:`Hesabın kimliği doğrulandı ancak bu modeli veya işlemi kullanma izni yok. Genellikle plan/abonelik sınırı (örn. Ollama Cloud Pro), organizasyon politikası veya model izni kaynaklıdır.`},vi:{label:`Bị cấm`,description:`Tài khoản đã được xác thực nhưng không được phép dùng model hoặc thao tác này. Nguyên nhân thường là giới hạn gói hoặc thuê bao (ví dụ Ollama Cloud Pro), chính sách tổ chức hay quyền model — không nhất thiết do API key sai.`},pt:{label:`Acesso negado`,description:`A conta está autenticada, mas não tem permissão para usar este modelo ou esta operação. Costuma ser limite de plano/assinatura (ex.: Ollama Cloud Pro), política da organização ou permissão do modelo — não necessariamente uma API key inválida.`}},404:{en:{label:`Not found`,description:`The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration.`},fr:{label:`Introuvable`,description:`La route, le modèle, le compte ou la ressource en amont demandés sont introuvables. Vérifiez le nom du modèle et la configuration du fournisseur opencodex.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{label:`未找到`,description:`找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。`},"zh-TW":{label:`未找到`,description:`找不到請求的路由、模型、帳號或上游資源。請確認模型名稱和 opencodex 供應商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`},ru:{label:`Не найдено`,description:`Запрошенный маршрут, модель, аккаунт или вышестоящий ресурс не найден. Проверьте имя модели и конфигурацию провайдера в opencodex.`},ja:{label:`見つかりません`,description:`要求されたルート、モデル、アカウント、上流リソースが見つかりませんでした。モデル名と opencodex プロバイダー設定を確認してください。`},tr:{label:`Bulunamadı`,description:`İstenen rota, model, hesap veya yukarı akış kaynağı bulunamadı. Model adını ve opencodex sağlayıcı yapılandırmasını doğrulayın.`},vi:{label:`Không tìm thấy`,description:`Không tìm thấy endpoint, model hoặc tài nguyên được yêu cầu. Hãy kiểm tra base URL, tên model và đường dẫn yêu cầu.`},pt:{label:`Não encontrado`,description:`A rota, o modelo, a conta ou o recurso upstream solicitado não foi encontrado. Verifique o nome do modelo e a configuração do provedor no opencodex.`}},408:{en:{label:`Request timeout`,description:`The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider.`},fr:{label:`Délai d’attente de la requête dépassé`,description:`La requête a pris trop de temps pour que le proxy ou le fournisseur en amont puisse la traiter. Réessayez avec une requête plus petite ou un autre fournisseur.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{label:`请求超时`,description:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},"zh-TW":{label:`請求逾時`,description:`代理或上游供應商未能在限定時間內完成請求。請縮小請求後重試,或切換供應商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`},ru:{label:`Тайм-аут запроса`,description:`Обработка запроса заняла слишком много времени, и прокси или вышестоящий провайдер не успел её завершить. Повторите попытку с меньшим запросом или через другого провайдера.`},ja:{label:`リクエストタイムアウト`,description:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`},tr:{label:`İstek zaman aşımı`,description:`Proxy veya yukarı akış sağlayıcısı isteği tamamlayamadan zaman aşımına uğradı. Daha küçük bir istek veya farklı bir sağlayıcı ile tekrar deneyin.`},vi:{label:`Yêu cầu hết thời gian chờ`,description:`Yêu cầu không hoàn tất trước thời hạn. Hãy thử lại với yêu cầu nhỏ hơn hoặc kiểm tra kết nối mạng.`},pt:{label:`Tempo limite da requisição`,description:`A requisição demorou demais para o proxy ou o provedor upstream concluí-la. Tente novamente com uma requisição menor ou outro provedor.`}},409:{en:{label:`Conflict`,description:`The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes.`},fr:{label:`Conflit`,description:`La requête entre en conflit avec l’état actuel du compte, de la session ou du fournisseur. Actualisez la session ou réessayez une fois l’opération en cours terminée.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{label:`状态冲突`,description:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},"zh-TW":{label:`狀態衝突`,description:`請求與當前帳號、會話或供應商狀態衝突。請重新整理會話,或等待當前操作完成後重試。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`},ru:{label:`Конфликт`,description:`Запрос конфликтует с текущим состоянием аккаунта, сессии или провайдера. Обновите сессию или повторите попытку после завершения текущей операции.`},ja:{label:`状態の衝突`,description:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`},tr:{label:`Durum çakışması`,description:`İstek mevcut hesap, oturum veya sağlayıcı durumuyla çakışıyor. Oturumu yenileyin veya aktif işlem bittikten sonra tekrar deneyin.`},vi:{label:`Xung đột`,description:`Yêu cầu xung đột với trạng thái hiện tại của tài nguyên hoặc tài khoản. Hãy làm mới trạng thái rồi thử lại.`},pt:{label:`Conflito`,description:`A requisição conflita com o estado atual da conta, da sessão ou do provedor. Atualize a sessão ou tente novamente quando a operação ativa terminar.`}},413:{en:{label:`Request too large`,description:`The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history.`},fr:{label:`Requête trop volumineuse`,description:`L’invite, les pièces jointes ou la charge utile générée dépassent une limite du proxy ou du fournisseur en amont. Réduisez le nombre de jetons, la taille des fichiers ou l’historique de la conversation.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{label:`请求过大`,description:`提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。`},"zh-TW":{label:`請求過大`,description:`提示、附件或生成的負載超過了代理或上游限制。請減少 token、檔案大小或對話歷史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`},ru:{label:`Слишком большой запрос`,description:`Промпт, вложения или сформированная полезная нагрузка превышают лимит прокси или вышестоящего провайдера. Сократите количество токенов, размер файлов или историю диалога.`},ja:{label:`リクエストが大きすぎます`,description:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`},tr:{label:`İstek çok büyük`,description:`İstemi, ekler veya oluşturulan veri proxy ya da yukarı akış sınırını aşıyor. Jeton sayısını, dosya boyutunu veya sohbet geçmişini azaltın.`},vi:{label:`Nội dung quá lớn`,description:`Nội dung yêu cầu vượt quá giới hạn của proxy hoặc nhà cung cấp. Hãy giảm kích thước tin nhắn, tệp hoặc ngữ cảnh rồi thử lại.`},pt:{label:`Requisição grande demais`,description:`O prompt, os anexos ou o conteúdo gerado excedem um limite do proxy ou do upstream. Reduza tokens, tamanho de arquivos ou histórico da conversa.`}},422:{en:{label:`Invalid content`,description:`The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields.`},fr:{label:`Contenu non valide`,description:`Le fournisseur a accepté le format de la requête, mais en a rejeté le contenu. Vérifiez les options du modèle, les définitions des outils, les rôles des messages et les champs non pris en charge.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{label:`内容无效`,description:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},"zh-TW":{label:`內容無效`,description:`供應商接受了請求格式,但拒絕了其中的內容。請檢查模型選項、工具定義、訊息角色和不支援的欄位。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`},ru:{label:`Недопустимое содержимое`,description:`Провайдер принял формат запроса, но отклонил его содержимое. Проверьте параметры модели, определения инструментов, роли сообщений и неподдерживаемые поля.`},ja:{label:`内容の検証失敗`,description:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`},tr:{label:`Geçersiz içerik`,description:`Sağlayıcı istek formatını kabul etti ancak içeriğini reddetti. Model seçeneklerini, araç tanımlarını, mesaj rollerini ve desteklenmeyen alanları kontrol edin.`},vi:{label:`Yêu cầu không thể xử lý`,description:`Yêu cầu có cú pháp hợp lệ nhưng chứa giá trị hoặc tổ hợp tùy chọn mà model hay nhà cung cấp không hỗ trợ.`},pt:{label:`Conteúdo inválido`,description:`O provedor aceitou o formato da requisição, mas rejeitou o conteúdo. Verifique as opções do modelo, as definições de ferramentas, os papéis das mensagens e campos não suportados.`}},424:{en:{label:`Provider dependency failed`,description:`A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider.`},fr:{label:`Échec d’une dépendance du fournisseur`,description:`Une dépendance en amont requise a échoué pendant le routage de la requête par opencodex. Réessayez plus tard ou sélectionnez un autre fournisseur configuré.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{label:`提供商依赖失败`,description:`opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},"zh-TW":{label:`供應商依賴失敗`,description:`opencodex 路由請求時,必需的上游依賴失敗。請稍後重試,或切換到另一個已配置的供應商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`},ru:{label:`Сбой зависимости провайдера`,description:`Необходимая вышестоящая зависимость дала сбой, пока opencodex маршрутизировал запрос. Повторите попытку позже или переключитесь на другого настроенного провайдера.`},ja:{label:`プロバイダー依存の失敗`,description:`opencodex がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı bağımlılığı başarısız`,description:`opencodex isteği yönlendirirken gerekli bir yukarı akış bağımlılığı başarısız oldu. Daha sonra tekrar deneyin veya başka bir sağlayıcıya geçin.`},vi:{label:`Phụ thuộc thất bại`,description:`Không thể hoàn tất yêu cầu vì một dịch vụ phụ thuộc hoặc thao tác upstream đã thất bại. Hãy kiểm tra lỗi liên quan rồi thử lại.`},pt:{label:`Falha em dependência do provedor`,description:`Uma dependência upstream necessária falhou enquanto o opencodex roteava a requisição. Tente novamente mais tarde ou troque para outro provedor configurado.`}},429:{en:{label:`Rate limited`,description:`The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider.`},fr:{label:`Limite de débit atteinte`,description:`La limite de débit ou de quota du fournisseur en amont a été atteinte. Attendez la réinitialisation de la fenêtre de quota ou changez de compte ou de fournisseur.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{label:`限流`,description:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},"zh-TW":{label:`限流`,description:`已達到上游供應商的速率或額度限制。請等待額度視窗重設,或切換帳號/供應商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`},ru:{label:`Превышен лимит запросов`,description:`Достигнут лимит скорости или квота вышестоящего провайдера. Дождитесь сброса окна квоты или переключитесь на другой аккаунт или провайдера.`},ja:{label:`レート制限`,description:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`},tr:{label:`Oran sınırı aşıldı`,description:`Yukarı akış sağlayıcısının hız veya kota sınırına ulaşıldı. Kota penceresinin sıfırlanmasını bekleyin ya da hesap/sağlayıcı değiştirin.`},vi:{label:`Quá nhiều yêu cầu`,description:`Tài khoản hoặc nhà cung cấp đã đạt giới hạn tốc độ hay hạn ngạch. Hãy chờ thời gian Retry-After, đổi tài khoản hoặc đổi nhà cung cấp.`},pt:{label:`Limite de requisições excedido`,description:`O limite de taxa ou de cota do provedor upstream foi atingido. Aguarde a janela de cota reiniciar ou troque de conta/provedor.`}},499:{en:{label:`Client closed request`,description:`The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental.`},fr:{label:`Requête fermée par le client`,description:`Le client s’est déconnecté ou a annulé la requête avant la fin de son routage par opencodex. Réessayez si l’annulation était involontaire.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{label:`客户端已取消`,description:`opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},"zh-TW":{label:`客戶端已取消`,description:`opencodex 完成路由前,客戶端已斷開連線或取消請求。如果不是有意取消,請重試。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`},ru:{label:`Запрос закрыт клиентом`,description:`Клиент отключился или отменил запрос до того, как opencodex завершил его маршрутизацию. Если отмена была случайной, повторите попытку.`},ja:{label:`クライアントがリクエストをクローズ`,description:`opencodex がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`},tr:{label:`İstemci isteği kapattı`,description:`opencodex yönlendirmeyi bitirmeden önce istemci bağlantıyı kesti veya isteği iptal etti. İptal kazara yapıldıysa tekrar deneyin.`},vi:{label:`Máy khách đã đóng yêu cầu`,description:`Máy khách đã ngắt kết nối hoặc hủy yêu cầu trước khi opencodex định tuyến xong. Nếu không chủ ý hủy, hãy thử lại.`},pt:{label:`Requisição encerrada pelo cliente`,description:`O cliente desconectou ou cancelou a requisição antes de o opencodex terminar de rotear. Tente novamente se o cancelamento foi acidental.`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},fr:{label:`Erreur du proxy`,description:`opencodex a rencontré une erreur interne lors du traitement de la requête. Réessayez une fois, puis consultez les journaux du proxy si l’erreur se reproduit.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{label:`代理错误`,description:`opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},"zh-TW":{label:`代理錯誤`,description:`opencodex 處理請求時發生內部錯誤。請先重試一次;如果重複出現,請檢查代理日誌。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`},ru:{label:`Ошибка прокси`,description:`В opencodex произошла внутренняя ошибка при обработке запроса. Повторите попытку один раз; если ошибка повторяется, проверьте логи прокси.`},ja:{label:`プロキシエラー`,description:`opencodex がリクエスト処理中に内部エラーに遭遇しました。1 回再試行し、繰り返す場合はプロキシログを確認してください。`},tr:{label:`Proxy hatası`,description:`opencodex isteği işlerken dahili bir hatayla karşılaştı. Bir kez tekrar deneyin, tekrarlarsa proxy günlüklerini kontrol edin.`},vi:{label:`Lỗi proxy`,description:`opencodex gặp lỗi nội bộ khi xử lý yêu cầu. Hãy thử lại một lần, rồi kiểm tra log proxy nếu lỗi lặp lại.`},pt:{label:`Erro do proxy`,description:`O opencodex encontrou um erro interno ao tratar a requisição. Tente novamente uma vez; se repetir, verifique os logs do proxy.`}},502:{en:{label:`Bad upstream response`,description:`The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider.`},fr:{label:`Réponse incorrecte du fournisseur en amont`,description:`Le fournisseur en amont a renvoyé une réponse non valide ou en échec par l’intermédiaire du proxy. Réessayez ou acheminez la requête vers un autre fournisseur.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`上游响应错误`,description:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},"zh-TW":{label:`上游回應錯誤`,description:`上游供應商透過代理返回了無效或失敗的回應。請重試,或將請求路由到其他供應商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Некорректный ответ провайдера`,description:`Вышестоящий провайдер вернул через прокси недействительный или ошибочный ответ. Повторите попытку или направьте запрос другому провайдеру.`},ja:{label:`上流レスポンス不良`,description:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Kötü yukarı akış yanıtı`,description:`Yukarı akış sağlayıcısı proxy üzerinden geçersiz veya başarısız bir yanıt döndürdü. Tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`},vi:{label:`Phản hồi upstream không hợp lệ`,description:`Nhà cung cấp upstream trả về phản hồi không hợp lệ hoặc thất bại qua proxy. Hãy thử lại hoặc định tuyến yêu cầu sang nhà cung cấp khác.`},pt:{label:`Resposta upstream inválida`,description:`O provedor upstream retornou uma resposta inválida ou com falha através do proxy. Tente novamente ou roteie a requisição para outro provedor.`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},fr:{label:`Fournisseur indisponible`,description:`Le proxy ou le fournisseur en amont est temporairement indisponible ou surchargé. Patientez un instant, puis réessayez ou changez de fournisseur.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{label:`提供商不可用`,description:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},"zh-TW":{label:`供應商不可用`,description:`代理或上游供應商暫時不可用或過載。請稍後重試,或切換供應商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`},ru:{label:`Провайдер недоступен`,description:`Прокси или вышестоящий провайдер временно недоступен или перегружен. Немного подождите, затем повторите попытку или смените провайдера.`},ja:{label:`プロバイダー利用不可`,description:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`},tr:{label:`Sağlayıcı kullanılamıyor`,description:`Proxy veya yukarı akış sağlayıcısı geçici olarak kullanılamıyor veya aşırı yüklü. Kısa bir süre bekleyip tekrar deneyin ya da sağlayıcı değiştirin.`},vi:{label:`Nhà cung cấp không khả dụng`,description:`Proxy hoặc nhà cung cấp upstream tạm thời không khả dụng hay đang quá tải. Hãy chờ một lát rồi thử lại hoặc đổi nhà cung cấp.`},pt:{label:`Provedor indisponível`,description:`O proxy ou o provedor upstream está temporariamente indisponível ou sobrecarregado. Aguarde um instante e tente novamente, ou troque de provedor.`}},504:{en:{label:`Upstream timeout`,description:`The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider.`},fr:{label:`Délai d’attente du fournisseur en amont dépassé`,description:`Le fournisseur en amont n’a pas répondu avant l’expiration du délai du proxy. Réessayez avec une requête plus petite ou choisissez un fournisseur plus rapide.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{label:`上游超时`,description:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},"zh-TW":{label:`上游逾時`,description:`上游供應商未在代理逾時前回應。請縮小請求後重試,或選擇回應更快的供應商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`},ru:{label:`Тайм-аут вышестоящего провайдера`,description:`Вышестоящий провайдер не ответил до истечения тайм-аута прокси. Повторите попытку с меньшим запросом или выберите более быстрого провайдера.`},ja:{label:`上流タイムアウト`,description:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`},tr:{label:`Yukarı akış zaman aşımı`,description:`Yukarı akış sağlayıcısı proxy zaman aşımı süresinden önce yanıt vermedi. Daha küçük bir istekle tekrar deneyin veya daha hızlı bir sağlayıcı seçin.`},vi:{label:`Upstream hết thời gian chờ`,description:`Nhà cung cấp upstream không phản hồi trước thời hạn của proxy. Hãy thử lại với yêu cầu nhỏ hơn hoặc chọn nhà cung cấp nhanh hơn.`},pt:{label:`Tempo limite do upstream`,description:`O provedor upstream não respondeu antes do tempo limite do proxy. Tente novamente com uma requisição menor ou escolha um provedor mais rápido.`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},fr:{label:`Fournisseur surchargé`,description:`Le fournisseur en amont est surchargé ou sa capacité est limitée. Patientez et réessayez, ou changez de compte ou de fournisseur.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{label:`提供商过载`,description:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},"zh-TW":{label:`供應商過載`,description:`上游供應商過載或容量受限。請等待後重試,或切換到其他帳號/供應商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`},ru:{label:`Провайдер перегружен`,description:`Вышестоящий провайдер перегружен или ограничен по мощности. Подождите и повторите попытку либо переключитесь на другой аккаунт или провайдера.`},ja:{label:`プロバイダー過負荷`,description:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı aşırı yüklü`,description:`Yukarı akış sağlayıcısı aşırı yüklü veya kapasitesi sınırlı. Bekleyip tekrar deneyin veya başka bir hesap/sağlayıcıya geçin.`},vi:{label:`Nhà cung cấp quá tải`,description:`Nhà cung cấp upstream đang quá tải hoặc bị giới hạn công suất. Hãy chờ rồi thử lại, hoặc đổi sang tài khoản hay nhà cung cấp khác.`},pt:{label:`Provedor sobrecarregado`,description:`O provedor upstream está sobrecarregado ou com capacidade limitada. Aguarde e tente novamente, ou troque para outra conta/provedor.`}}},NP={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},fr:{label:`Erreur de requête`,description:`Le proxy ou le fournisseur en amont a rejeté la requête. Vérifiez sa structure, les identifiants, le nom du modèle et la configuration du fournisseur.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{label:`请求错误`,description:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},"zh-TW":{label:`請求錯誤`,description:`代理或上游供應商拒絕了該請求。請檢查請求結構、憑證、模型名稱和供應商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`},ru:{label:`Ошибка запроса`,description:`Прокси или вышестоящий провайдер отклонил запрос. Проверьте структуру запроса, учётные данные, имя модели и конфигурацию провайдера.`},ja:{label:`リクエストエラー`,description:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`},tr:{label:`İstek hatası`,description:`Proxy veya yukarı akış sağlayıcısı isteği reddetti. İstek yapısını, kimlik bilgilerini, model adını ve sağlayıcı yapılandırmasını kontrol edin.`},vi:{label:`Lỗi yêu cầu`,description:`Proxy hoặc nhà cung cấp upstream đã từ chối yêu cầu. Hãy kiểm tra cấu trúc yêu cầu, thông tin xác thực, tên model và cấu hình nhà cung cấp.`},pt:{label:`Erro na requisição`,description:`O proxy ou o provedor upstream rejeitou a requisição. Verifique a estrutura da requisição, as credenciais, o nome do modelo e a configuração do provedor.`}},server:{en:{label:`Server or upstream error`,description:`opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider.`},fr:{label:`Erreur du serveur ou du fournisseur en amont`,description:`opencodex ou un fournisseur en amont a échoué lors du traitement de la requête. Réessayez plus tard ou acheminez la requête vers un autre fournisseur.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`服务器或上游错误`,description:`opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},"zh-TW":{label:`伺服器或上游錯誤`,description:`opencodex 或上游供應商處理請求時失敗。請稍後重試,或將請求路由到其他供應商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Ошибка сервера или провайдера`,description:`opencodex или вышестоящий провайдер завершил обработку запроса с ошибкой. Повторите попытку позже или направьте запрос другому провайдеру.`},ja:{label:`サーバーまたは上流エラー`,description:`opencodex または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Sunucu veya yukarı akış hatası`,description:`opencodex veya bir yukarı akış sağlayıcısı isteği işlerken başarısız oldu. Daha sonra tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`},vi:{label:`Lỗi máy chủ hoặc upstream`,description:`opencodex hoặc một nhà cung cấp upstream đã thất bại khi xử lý yêu cầu. Hãy thử lại sau hoặc định tuyến yêu cầu sang nhà cung cấp khác.`},pt:{label:`Erro do servidor ou do upstream`,description:`O opencodex ou um provedor upstream falhou ao processar a requisição. Tente novamente mais tarde ou roteie a requisição para outro provedor.`}}};function PP(e){return e.toLowerCase().startsWith(`fr`)?`fr`:e.toLowerCase().startsWith(`vi`)?`vi`:e.toLowerCase().startsWith(`pt`)?`pt`:e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function FP(e,t){if(e<400)return null;let n=PP(t);return(MP[Math.trunc(e)]??(e<500?NP.client:NP.server))[n]}var IP=`flex min-w-0 flex-col rounded-[12px] bg-surface ring-1 ring-inset ring-line`,LP=`mx-1 mb-1 min-w-0 overflow-hidden rounded-[8px] bg-bg ring-1 ring-line`,RP=`flex min-w-0 flex-col gap-4 rounded-[12px] bg-surface p-5 ring-1 ring-inset ring-line`,zP=`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em] text-fg`,BP=`m-0 text-[13px] leading-5 text-fg-muted`,VP=`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,HP=X(`ui-v2 inline-flex h-[var(--ocx-control-h)] shrink-0 cursor-pointer items-center gap-1.5 rounded-control px-2.5 text-[13px] font-medium text-fg-muted`,`transition-colors hover:bg-accent-soft hover:text-fg aria-expanded:bg-accent-soft aria-expanded:text-fg`,VP,`[&_svg]:size-4 [&_svg]:shrink-0`),UP=X(`ui-v2 inline-grid size-8 shrink-0 cursor-pointer place-items-center rounded-control text-fg-muted transition-colors`,`hover:bg-accent-soft hover:text-fg disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent`,VP,`[&_svg]:size-4`),WP=X(`ui-v2 inline-flex h-[var(--ocx-control-h-sm)] max-w-full min-w-0 shrink-0 cursor-pointer items-center gap-1.5 rounded-[8px] bg-raised px-2.5 text-[12.5px] font-medium text-fg`,`shadow-sm ring-1 ring-inset ring-line-strong transition-colors hover:bg-surface-2 dark:bg-surface-2 dark:hover:bg-raised`,VP,`[&_svg]:size-3 [&_svg]:shrink-0 [&_svg]:text-fg-subtle`),GP=`flex min-w-0 flex-col gap-1.5 text-[12px] font-medium text-fg-muted`,KP=`input select-sm h-[var(--ocx-control-h)] w-full min-w-0 max-w-none px-2.5 text-[13px] text-fg`;function qP({options:e,visible:t,onToggle:n,label:r,menuLabel:i}){let[a,o]=(0,Z.useState)(!1),s=(0,Z.useId)(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)([]);(0,Z.useEffect)(()=>{if(!a)return;let e=c.current?.ownerDocument,t=e=>{let t=e.target;l.current?.contains(t)||c.current?.contains(t)||o(!1)},n=e=>{e.key===`Escape`&&(e.preventDefault(),o(!1),c.current?.focus({preventScroll:!0}))};return e?.addEventListener(`pointerdown`,t),e?.addEventListener(`keydown`,n),u.current[0]?.focus({preventScroll:!0}),()=>{e?.removeEventListener(`pointerdown`,t),e?.removeEventListener(`keydown`,n)}},[a]);let d=t=>{let n=e.length;u.current[(t+n)%n]?.focus({preventScroll:!0})};return(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsxs)(`button`,{ref:c,type:`button`,"aria-haspopup":`menu`,"aria-expanded":a,"aria-controls":a?s:void 0,title:i,onClick:()=>o(e=>!e),className:HP,children:[(0,Q.jsx)(Pc,{icon:Wc,size:16,strokeWidth:1.8,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`max-sm:sr-only`,children:r}),(0,Q.jsx)(lt,{"aria-hidden":!0,className:X(`size-3.5 text-fg-subtle transition-transform`,a?`-rotate-90`:`rotate-90`)})]}),a&&(0,Q.jsx)(`div`,{ref:l,id:s,role:`menu`,"aria-label":i,onKeyDown:t=>{let n=u.current.findIndex(e=>e===t.currentTarget.ownerDocument.activeElement);t.key===`Tab`?o(!1):t.key===`ArrowDown`?(t.preventDefault(),d(n+1)):t.key===`ArrowUp`?(t.preventDefault(),d(n<0?e.length-1:n-1)):t.key===`Home`?(t.preventDefault(),d(0)):t.key===`End`&&(t.preventDefault(),d(e.length-1))},className:`absolute right-0 top-[calc(100%+6px)] z-30 flex w-52 flex-col gap-0.5 rounded-[10px] bg-raised p-1 shadow-md ring-1 ring-line dark:bg-surface-2`,children:e.map((e,r)=>(0,Q.jsxs)(`button`,{ref:e=>{u.current[r]=e},type:`button`,role:`menuitemcheckbox`,"aria-checked":t[e.key],tabIndex:-1,onClick:()=>n(e.key),className:`ui-v2 flex h-[var(--ocx-control-h)] w-full cursor-pointer items-center gap-2 rounded-[6px] px-2 text-left text-[13px] text-fg hover:bg-accent-soft focus-visible:bg-accent-soft focus-visible:outline-none`,children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`grid size-4 shrink-0 place-items-center text-fg`,children:t[e.key]&&(0,Q.jsx)(st,{className:`size-3.5`})}),e.label]},e.key))})]})}function JP({checked:e,onChange:t,label:n,title:r,className:i}){return(0,Q.jsxs)(`label`,{title:r,className:X(`inline-flex h-[var(--ocx-control-h)] shrink-0 cursor-pointer items-center gap-2 rounded-control px-2 text-[13px] font-medium text-fg-muted transition-colors select-none hover:bg-accent-soft hover:text-fg`,i),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e,onChange:e=>t(e.target.checked),className:`peer sr-only`}),(0,Q.jsx)(`span`,{"aria-hidden":!0,className:X(`relative inline-flex h-4 w-7 shrink-0 items-center rounded-full p-0.5 ring-1 ring-inset transition-colors duration-200`,`peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-highlight`,e?`bg-accent ring-transparent`:`bg-surface-2 ring-line-strong`),children:(0,Q.jsx)(`span`,{className:X(`size-3 rounded-full shadow-sm transition-transform duration-200 ease-soft`,e?`translate-x-3 bg-on-accent`:`translate-x-0 bg-fg-subtle`)})}),n]})}var YP={completed:`bg-success-soft text-success`,failed:`bg-danger-soft text-danger`,incomplete:`bg-warning-soft text-warning`,aborted:`bg-surface-2 text-fg-muted`};function XP({status:e,outcome:t,label:n,announce:r=!0,className:i}){return(0,Q.jsxs)(`span`,{title:n,className:X(`inline-flex h-[22px] shrink-0 items-center gap-1.5 rounded-full px-2 font-mono text-[12px] font-semibold tabular-nums`,YP[t],i),children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`size-1.5 rounded-full bg-current`}),e,r&&(0,Q.jsx)(`span`,{className:`sr-only`,children:n})]})}var ZP=[{key:`effort`,label:`logs.col.effort`},{key:`tokens`,label:`logs.col.tokens`},{key:`rate`,label:`logs.col.tokPerSec`},{key:`cost`,label:`logs.col.estimatedCost`},{key:`duration`,label:`logs.col.duration`}],QP=`ocx.logs.columns.v1`,$P={effort:!0,tokens:!0,rate:!0,cost:!0,duration:!0};function eF(){try{let e=window.localStorage.getItem(QP);if(!e)return $P;let t=JSON.parse(e);if(!t||typeof t!=`object`)return $P;let n={...$P};for(let{key:e}of ZP){let r=t[e];typeof r==`boolean`&&(n[e]=r)}return n}catch{return $P}}function tF(){let[e,t]=(0,Z.useState)(eF);return{columns:e,toggle:(0,Z.useCallback)(n=>{let r={...e,[n]:!e[n]};t(r);try{window.localStorage.setItem(QP,JSON.stringify(r))}catch{}},[e])}}var nF=[`provider`,`usage`,`injection`];function rF(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function iF(e){return new Date(e).toLocaleTimeString()}function aF(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function oF(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function sF({entries:e}){let{t}=s();return(0,Q.jsxs)(`section`,{className:RP,"aria-labelledby":`debug-claude-inbound-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Q.jsx)(`h3`,{id:`debug-claude-inbound-title`,className:zP,children:t(`debug.claudeInbound.title`)}),(0,Q.jsx)(`p`,{className:BP,children:t(`debug.claudeInbound.sub`)})]}),e.length===0?(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-subtle`,children:t(`debug.claudeInbound.empty`)}):(0,Q.jsx)(`div`,{className:`overflow-x-auto rounded-[8px] bg-bg ring-1 ring-inset ring-line`,children:(0,Q.jsxs)(`table`,{className:`debug-inbound-table w-full border-collapse`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,Q.jsx)(`th`,{children:`thinking`}),(0,Q.jsx)(`th`,{children:`effort`}),(0,Q.jsx)(`th`,{children:`beta`}),(0,Q.jsx)(`th`,{children:`metadata`}),(0,Q.jsx)(`th`,{children:`system`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted mono`,children:iF(e.at)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,Q.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,Q.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,Q.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,Q.jsx)(`td`,{className:`mono max-w-40 truncate`,title:e.anthropicBeta,children:e.anthropicBeta??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}var cF={provider:`debug.streamProvider`,usage:`debug.streamUsage`,injection:`debug.streamInjection`};function lF({debug:e,stream:t,streamEnabled:n,entries:r,refreshing:i,follow:a,scrollContainerRef:o,lineVirtualizer:c,onStreamChange:l,onRefresh:u,onFollowChange:d}){let{t:f}=s();if(!e)return null;let p=[e.enabled?`provider`:null,e.usage?`usage`:null,e.injection?`injection`:null].filter(e=>e!==null);return(0,Q.jsxs)(`section`,{className:IP,"aria-labelledby":`debug-tail-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-4 pt-3.5 pb-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2`,children:[(0,Q.jsx)(`h3`,{id:`debug-tail-title`,className:`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em] text-fg`,children:f(`logsV2.debugTail`)}),p.length>1&&(0,Q.jsx)(Mc,{size:`sm`,"aria-label":f(`logsV2.debugStream`),value:t,onChange:l,items:p.map(e=>({value:e,label:f(cF[e])}))}),p.length===1&&(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted`,children:f(cF[p[0]])})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`button`,{type:`button`,className:UP,disabled:i||!n,onClick:u,"aria-label":f(`debug.refresh`),title:f(`debug.refresh`),children:(0,Q.jsx)(`span`,{className:X(`inline-flex`,i&&`animate-spin`),children:(0,Q.jsx)(Ke,{"aria-hidden":!0})})}),(0,Q.jsx)(JP,{checked:a,onChange:d,label:f(`debug.follow`)})]})]}),(0,Q.jsx)(`div`,{className:LP,children:n?r.length===0?(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`title`,children:f(`debug.noLinesTitle`)}),(0,Q.jsx)(`div`,{className:`mx-auto mt-1.5 max-w-[560px] text-[13px] text-fg-muted`,children:f(`debug.noLines.${t}`)})]}):(0,Q.jsx)(`div`,{ref:o,className:`debug-tail-lines max-h-[calc(100dvh-320px)] min-h-48 overflow-auto px-4 py-2`,children:(0,Q.jsx)(`div`,{className:`relative w-full`,style:{height:c.getTotalSize()},children:c.getVirtualItems().map(e=>{let t=r[e.index];return(0,Q.jsxs)(`div`,{ref:c.measureElement,"data-index":e.index,className:`absolute top-0 left-0 w-full`,style:{transform:`translateY(${e.start}px)`},children:[(0,Q.jsx)(`span`,{className:`text-fg-subtle`,children:rF(t.at)}),(0,Q.jsx)(`span`,{className:`text-fg`,children:t.line})]},e.key)})})}):(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`title`,children:f(`debug.emptyTitle`)}),(0,Q.jsx)(`div`,{className:`mx-auto mt-1.5 max-w-[560px] text-[13px] text-fg-muted`,children:f(`debug.empty`)})]})}),n&&r.length>0&&(0,Q.jsx)(`p`,{className:`m-0 flex min-h-10 items-center px-4 text-[12.5px] text-fg-subtle tabular-nums`,children:f(`logsV2.debugLines`,{count:r.length})})]})}var uF=[`debug`,`usage`,`injection`,`claude`];function dF({debug:e,debugBusy:t,onSetFlag:n,onReset:r}){let{t:i}=s();return(0,Q.jsxs)(`section`,{className:RP,"aria-labelledby":`debug-logging-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 basis-80 flex-col gap-1`,children:[(0,Q.jsx)(`h3`,{id:`debug-logging-title`,className:zP,children:i(`logsV2.debugLogging`)}),(0,Q.jsx)(`p`,{className:BP,children:i(`debug.subtitle`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:HP,disabled:t,onClick:r,children:i(`debug.reset`)})]}),(0,Q.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:uF.map(r=>{let a=oF(e,r);return(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 rounded-[10px] bg-bg px-3 py-2.5 ring-1 ring-inset ring-line`,children:[(0,Q.jsx)(Rn,{on:a,disabled:t,label:i(`debug.${r}`),onClick:()=>n(r,!a)}),(0,Q.jsx)(`span`,{className:`min-w-0 text-[13px] font-medium text-fg`,children:i(`debug.${r}`)})]},r)})})]})}function fF({embedded:e}){let{t}=s();return e?null:(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:t(`debug.title`)})})}function pF(e){return`debug-settings:${e}`}function mF({apiBase:e,embedded:t,active:n=!0}){let{t:r}=s(),i=`ocx.debug.settings.v1:${e}`,a=sf(i),o=pF(e),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(`provider`),[p,m]=(0,Z.useState)([]),[h,g]=(0,Z.useState)(!0),[_,v]=(0,Z.useState)(!1),y=(0,Z.useRef)(0),b=(0,Z.useRef)(0),x=(0,Z.useRef)(0),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(null),T=mf(o,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return df(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),E=T.state,D=T.data??a??null,O=bn(`debug-claude-inbound:${e}`,[e,D?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:n&&!!D?.claude}).data??[],k=xP({count:p.length,getScrollElement:()=>C.current,estimateSize:()=>20,overscan:30,getItemKey:e=>p[e].seq}),A=(0,Z.useCallback)(e=>aF(D,e),[D]);(0,Z.useEffect)(()=>{if(!D||A(u))return;let e=nF.find(A);if(!e)return;let t=window.setTimeout(()=>f(e),0);return()=>window.clearTimeout(t)},[D,u,A]);let j=A(u),M=u===`provider`?`${e}/api/debug/logs`:u===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,N=(0,Z.useCallback)(async(e,t)=>{let n=++x.current;if(!j)n===x.current&&(m([]),y.current=0);else{v(!0);try{let r=new URLSearchParams({limit:`500`});!e&&y.current>0&&r.set(`after`,String(y.current));let i=await fetch(`${M}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==x.current)return;let a=await i.json();if(t?.aborted||n!==x.current||a.length===0)return;m(t=>(e?a:[...t,...a]).slice(-2e3)),y.current=a[a.length-1].seq}catch{}finally{n===x.current&&v(!1)}}},[M,j]);(0,Z.useEffect)(()=>{if(!n)return;let t=`${e}:${u}:${j}`,r=w.current!==t;if(w.current=t,!r&&p.length>0)return;y.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&m([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),x.current+=1,i.abort()}},[n,e,u,j]);let P=(0,Z.useRef)(!1),F=(0,Z.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let e=d(1e4);N(!1,e.signal).finally(()=>{e.clear(),P.current=!1})});(0,Z.useEffect)(()=>{if(n&&h&&j)return $u(()=>F(),1e3)},[n,h,j]),(0,Z.useEffect)(()=>{h&&p.length>0&&k.scrollToIndex(p.length-1,{align:`end`})},[p,h,k]);let I=async t=>{let n=++b.current;l(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let a=await r.json();if(n!==b.current)return;df(i,a),Sn(o,a)}catch{}},a=(S.current??Promise.resolve()).then(r,r);S.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===b.current&&l(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,Q.jsxs)(`div`,{className:`debug-v2 flex min-w-0 flex-col gap-4 font-sans text-fg`,children:[(0,Q.jsx)(fF,{embedded:t}),!D&&E.showError?(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>T.refresh(),children:r(`common.retry`)})]}):E.showSkeleton&&!D?(0,Q.jsx)(ck,{label:r(`debug.loading`),rows:3}):D?(0,Q.jsx)(dF,{debug:D,debugBusy:c,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()}}):null,D&&E.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`debug.loadFailed`)}),D?.claude&&(0,Q.jsx)(sF,{entries:O}),(0,Q.jsx)(lF,{debug:D,stream:u,streamEnabled:j,entries:p,refreshing:_,follow:h,scrollContainerRef:C,lineVirtualizer:k,onStreamChange:f,onRefresh:()=>void N(!0),onFollowChange:g})]})}var hF=[`all`,`native`,`translated`,`legacy-bridge`,`blocked`,`none`],gF={model:``,provider:``,status:`all`,timeWindow:`all`,interceptedOnly:!1,conversationId:``};function _F(e){return e.model.trim()!==``||e.provider.trim()!==``||e.status!==`all`||e.timeWindow!==`all`||e.minTokPerSec!==void 0||e.maxTokPerSec!==void 0||e.interceptedOnly||e.conversationId.trim()!==``||(e.protocolMode??`all`)!==`all`}function vF(e){return Array.isArray(e.attempts)?e.attempts.filter(e=>typeof e==`object`&&!!e):[]}function yF(e){if(typeof e!=`string`)return;let t=e.trim();return t?t.toLowerCase():void 0}function bF(e,t){if(e===`15m`)return t-9e5;if(e===`1h`)return t-36e5;if(e===`24h`)return t-864e5}function xF(e,t,n=Date.now()){let r=t.model.trim().toLowerCase(),i=t.provider.trim().toLowerCase(),a=t.conversationId.trim(),o=bF(t.timeWindow,n),s=t.protocolMode??`all`;return e.filter(e=>{if(t.interceptedOnly&&typeof e.shadowCallRewrittenFrom!=`string`)return!1;if(s!==`all`){let t=YC(e.protocolTrace)?.mode;if(s===`none`?t!==void 0:t!==s)return!1}if(a&&!jP(e.conversationId,a,t.conversationQueryHash)||t.status===`success`&&(typeof e.status!=`number`||!Number.isInteger(e.status)||e.status<200||e.status>=300)||t.status===`errors`&&(typeof e.status!=`number`||!Number.isInteger(e.status)||e.status<400||e.status>599))return!1;let n=vF(e);if(r&&![yF(e.model),yF(e.resolvedModel),yF(e.servedModel),...n.map(e=>yF(e.model))].some(e=>e===r)||i&&![yF(e.provider),...n.map(e=>yF(e.provider))].some(e=>e===i)||o!==void 0&&(typeof e.timestamp!=`number`||!Number.isFinite(e.timestamp)||e.timestamp<o))return!1;let c=e.displayMetrics?.tokPerSecond?.kind===`value`&&Number.isFinite(e.displayMetrics.tokPerSecond.value)?e.displayMetrics.tokPerSecond.value:void 0;return!(t.minTokPerSec!==void 0&&(c===void 0||c<t.minTokPerSec)||t.maxTokPerSec!==void 0&&(c===void 0||c>=t.maxTokPerSec))})}function SF(e,t){if(typeof t!=`string`)return;let n=t.trim(),r=yF(n);if(!r)return;let i=e.get(r);(i===void 0||n<i)&&e.set(r,n)}function CF(e){let t=new Map,n=new Map;for(let r of e){for(let e of[r.model,r.resolvedModel,r.servedModel,...vF(r).map(e=>e.model)])SF(t,e);for(let e of[r.provider,...vF(r).map(e=>e.provider)])SF(n,e)}return{models:[...t.values()].sort(),providers:[...n.values()].sort()}}var wF={fullWidth:!0,size:`sm`,triggerClassName:`px-2.5 text-fg`};function TF(e){return e.maxTokPerSec===15?`slow`:e.minTokPerSec===15&&e.maxTokPerSec===50?`medium`:e.minTokPerSec===50?`fast`:`all`}function EF(e){return e===`slow`?{minTokPerSec:void 0,maxTokPerSec:15}:e===`medium`?{minTokPerSec:15,maxTokPerSec:50}:e===`fast`?{minTokPerSec:50,maxTokPerSec:void 0}:{minTokPerSec:void 0,maxTokPerSec:void 0}}function DF({filters:e,options:t,hasActiveFilters:n,filteredCount:r,totalCount:i,t:a,onFilterChange:o,onResetFilters:s,trailing:c}){let l=(0,Z.useId)(),[u,d]=(0,Z.useState)(!1),f=(0,Z.useRef)(null),p=()=>{s(),f.current?.focus({preventScroll:!0})},m=t=>o({...e,...t}),h=TF(e),g=e.protocolMode??`all`,_=[];return e.interceptedOnly&&_.push({key:`intercepted`,label:a(`logs.filter.interceptedHelpersOnly`),clear:()=>m({interceptedOnly:!1})}),e.provider&&_.push({key:`provider`,label:`${a(`logs.filter.provider.label`)}: ${re(e.provider,a)}`,clear:()=>m({provider:``})}),e.model&&_.push({key:`model`,label:`${a(`logs.filter.model.label`)}: ${e.model}`,clear:()=>m({model:``})}),e.timeWindow!==`all`&&_.push({key:`time`,label:`${a(`logs.filter.time.label`)}: ${a(`logs.filter.time.${e.timeWindow}`)}`,clear:()=>m({timeWindow:`all`})}),h!==`all`&&_.push({key:`speed`,label:`${a(`logs.filter.speed.label`)}: ${a(`logs.filter.speed.${h}`)}`,clear:()=>m(EF(`all`))}),e.status!==`all`&&_.push({key:`status`,label:`${a(`logs.filter.status.label`)}: ${a(`logs.filter.status.${e.status}`)}`,clear:()=>m({status:`all`})}),g!==`all`&&_.push({key:`protocol`,label:`${a(`logs.filter.protocol.label`)}: ${a(OF(g))}`,clear:()=>m({protocolMode:`all`})}),(0,Q.jsxs)(`div`,{className:`logs-filter-container flex min-w-0 flex-col gap-2`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Q.jsxs)(`div`,{className:`relative min-w-0 flex-1 basis-56 sm:max-w-72`,children:[(0,Q.jsx)(We,{"aria-hidden":!0,className:`pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-fg-subtle`}),(0,Q.jsx)(`input`,{ref:f,type:`search`,className:X(KP,`mono pl-8`),value:e.conversationId,onChange:e=>m({conversationId:e.target.value}),placeholder:a(`logs.filter.conversation.placeholder`),"aria-label":a(`logs.filter.conversation.label`)})]}),(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":u,"aria-controls":l,onClick:()=>d(e=>!e),className:HP,children:[(0,Q.jsx)(Nt,{"aria-hidden":!0}),a(`logsV2.filters`),_.length>0&&(0,Q.jsx)(`span`,{className:`grid h-[18px] min-w-[18px] place-items-center rounded-full bg-accent px-1 text-[11px] font-semibold text-on-accent tabular-nums`,children:_.length})]}),c&&(0,Q.jsx)(`div`,{className:`ml-auto flex items-center gap-1`,children:c})]}),(0,Q.jsxs)(`div`,{id:l,hidden:!u,className:X(`grid-cols-2 gap-3 rounded-[10px] bg-bg p-3 ring-1 ring-inset ring-line sm:grid-cols-3 lg:grid-cols-6`,u?`grid`:`hidden`),children:[(0,Q.jsxs)(`label`,{className:GP,children:[a(`logs.filter.provider.label`),(0,Q.jsx)(Vn,{...wF,value:e.provider,label:a(`logs.filter.provider.label`),onChange:e=>m({provider:e}),options:[{value:``,label:a(`logs.filter.provider.all`)},...t.providers.map(e=>({value:e,label:re(e,a)}))]})]}),(0,Q.jsxs)(`label`,{className:GP,children:[a(`logs.filter.model.label`),(0,Q.jsx)(Vn,{...wF,value:e.model,label:a(`logs.filter.model.label`),onChange:e=>m({model:e}),options:[{value:``,label:a(`logs.filter.model.all`)},...t.models.map(e=>({value:e,label:e}))]})]}),(0,Q.jsxs)(`label`,{className:GP,children:[a(`logs.filter.time.label`),(0,Q.jsx)(Vn,{...wF,value:e.timeWindow,label:a(`logs.filter.time.label`),onChange:e=>m({timeWindow:e}),options:[{value:`all`,label:a(`logs.filter.time.all`)},{value:`15m`,label:a(`logs.filter.time.15m`)},{value:`1h`,label:a(`logs.filter.time.1h`)},{value:`24h`,label:a(`logs.filter.time.24h`)}]})]}),(0,Q.jsxs)(`label`,{className:GP,children:[a(`logs.filter.speed.label`),(0,Q.jsx)(Vn,{...wF,value:h,label:a(`logs.filter.speed.label`),onChange:e=>m(EF(e)),options:[{value:`all`,label:a(`logs.filter.speed.all`)},{value:`slow`,label:a(`logs.filter.speed.slow`)},{value:`medium`,label:a(`logs.filter.speed.medium`)},{value:`fast`,label:a(`logs.filter.speed.fast`)}]})]}),(0,Q.jsxs)(`label`,{className:GP,children:[a(`logs.filter.status.label`),(0,Q.jsx)(Vn,{...wF,value:e.status,label:a(`logs.filter.status.label`),onChange:e=>m({status:e}),options:[{value:`all`,label:a(`logs.filter.status.all`)},{value:`success`,label:a(`logs.filter.status.success`)},{value:`errors`,label:a(`logs.filter.status.errors`)}]})]}),(0,Q.jsxs)(`label`,{className:GP,children:[a(`logs.filter.protocol.label`),(0,Q.jsx)(Vn,{...wF,value:g,label:a(`logs.filter.protocol.label`),onChange:e=>m({protocolMode:e}),options:hF.map(e=>({value:e,label:a(OF(e))}))})]}),(0,Q.jsxs)(`label`,{className:`col-span-full inline-flex w-fit cursor-pointer items-center gap-2 text-[13px] text-fg-muted hover:text-fg`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 cursor-pointer accent-[var(--ocx-accent)]`,checked:e.interceptedOnly,onChange:e=>m({interceptedOnly:e.target.checked})}),a(`logs.filter.interceptedHelpersOnly`)]})]}),n&&(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1.5`,children:[_.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:WP,onClick:e.clear,"aria-label":a(`logsV2.removeFilter`,{name:e.label}),children:[(0,Q.jsx)(`span`,{className:`truncate`,children:e.label}),(0,Q.jsx)(Ie,{"aria-hidden":!0})]},e.key)),(0,Q.jsxs)(`div`,{className:`logs-filter-status ml-auto inline-flex flex-wrap items-center gap-1`,children:[(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:a(`logs.filter.showingCount`,{count:r,total:i})}),(0,Q.jsxs)(`button`,{type:`button`,className:HP,onClick:p,children:[(0,Q.jsx)(Ie,{"aria-hidden":!0}),` `,a(`logs.filter.reset`)]})]})]})]})}function OF(e){return e===`all`?`logs.filter.protocol.all`:e===`none`?`logs.filter.protocol.none`:uw[e]}var kF=new Set([`codex_cli`,`codex_desktop`,`codex_ide`,`claude_code`,`claude_desktop`,`grok`,`opencode`,`aside`,`other`,`unknown`]);function AF(e){if(e!==void 0)return typeof e==`string`&&kF.has(e)?e:`unknown`}var jF=new Set([`grok.svg`,`opencode.svg`,`aside.svg`]);function MF(e){return`usage-source-mark${jF.has(e)?` usage-source-mark--mono`:``}`}var NF={codex_cli:`Codex`,codex_desktop:`Codex`,codex_ide:`Codex`,claude_code:`Claude Code`,claude_desktop:`Claude Desktop`,grok:`Grok`,opencode:`OpenCode`,aside:`Aside`,other:`logsV2.clientOther`,unknown:`logsV2.clientUnknown`},PF={codex_cli:`openai.svg`,codex_desktop:`openai.svg`,codex_ide:`openai.svg`,claude_code:`claude-color.svg`,claude_desktop:`claude-color.svg`,grok:`grok.svg`,opencode:`opencode.svg`,aside:`aside.svg`,other:null,unknown:null};function FF({client:e,t}){let n=AF(e)??`unknown`,r=n===`other`||n===`unknown`?t(NF[n]):NF[n],i=PF[n];return(0,Q.jsx)(`span`,{className:`inline-flex h-6 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-fg-muted`,"data-log-client":n,role:`img`,"aria-label":r,children:i?(0,Q.jsx)(`img`,{src:`/provider-icons/${i}`,alt:``,"aria-hidden":`true`,className:MF(i)}):(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,focusable:`false`,viewBox:`0 0 16 16`,className:`size-4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,Q.jsx)(`path`,{d:`M5.5 5.5a2.5 2.5 0 1 1 4.15 1.88C8.65 8.2 8 8.65 8 10`}),(0,Q.jsx)(`path`,{d:`M8 12.5h.01`})]})})}function IF({trace:e,t}){let n=YC(e);if(!n)return null;let r=gw(n,t),i=t(uw[n.mode]);return(0,Q.jsxs)(`span`,{className:`badge badge-muted protocol-path-badge`,title:t(`logs.protocol.badgeTitle`,{path:r,mode:i}),"data-protocol-mode":n.mode,children:[r,` · `,i]})}function LF({trace:e,t}){let n=YC(e);return(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-protocol`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-protocol`,className:`log-detail-section-title`,children:t(`logs.detail.protocol.section`)}),n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,"data-protocol-mode":n.mode,children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.inbound`)}),(0,Q.jsx)(`span`,{children:mw(n.inbound,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.mode`)}),(0,Q.jsx)(`span`,{children:t(uw[n.mode])}),n.upstream&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.upstream`)}),(0,Q.jsx)(`span`,{children:mw(n.upstream,t)})]}),n.requestPath.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.requestPath`)}),(0,Q.jsx)(`span`,{children:hw(n.requestPath,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.responsePath`)}),(0,Q.jsx)(`span`,{children:hw(n.responsePath,t)})]}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.reasons`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:n.reasonCodes.join(`, `)||`–`}),n.featureEffects&&n.featureEffects.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.features`)}),(0,Q.jsx)(`span`,{children:n.featureEffects.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[(0,Q.jsx)(`code`,{children:e.feature}),`: `,t(dw[e.disposition])]},e.feature))})]}),n.attempts&&n.attempts.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.attempts`)}),(0,Q.jsx)(`span`,{children:n.attempts.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[t(`logs.detail.protocol.attempt`,{ordinal:e.ordinal}),`:`,` `,hw(e.requestPath,t),` · `,t(uw[e.mode])]},e.ordinal))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm protocol-deep-link`,onClick:()=>dE({inbound:n.inbound,upstream:tE(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]}):(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:t(`logs.detail.protocol.none`)})]})}function RF(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?{generatedAt:e,receivedAt:t}:void 0}function zF(e,t,n){return e?e.generatedAt+Math.max(0,t-e.receivedAt):n}function BF(){return BT(window.location.hash)===`logs/debug`?`debug`:`logs`}function VF(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function HF(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),VF(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),VF(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function UF(e){return e.servedModel!==void 0&&e.servedModel!==(e.wireModel??e.model)}function WF(e,t){let n=e?.confirmation;if(!n)return``;let r=n===`downgraded`&&e?.fastDowngradeReason?`: ${e.fastDowngradeReason}`:``;return` (${t(`logs.modelTooltip.tierOutcome.${n}`)}${r})`}function GF(e,t){return[UF(e)?t(`logs.modelRerouteTitle`):void 0,`${t(`logs.modelTooltip.model`)}=${e.model}`,e.resolvedModel?`${t(`logs.modelTooltip.resolvedModel`)}=${e.resolvedModel}`:void 0,e.servedModel?`${t(`logs.modelTooltip.servedModel`)}=${e.servedModel}`:void 0,e.wireModel?`${t(`logs.modelTooltip.wireModel`)}=${e.wireModel}`:void 0,e.requestedServiceTier?`${t(`logs.modelTooltip.requestedTier`)}=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`${t(`logs.modelTooltip.configuredTier`)}=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`${t(`logs.modelTooltip.responseTier`)}=${e.responseServiceTier}${WF(e.tierOutcome,t)}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function KF(e){return e.requestedSpeedLabel||void 0}function qF(e){switch(e.timingBasis){case`generation-window`:return{short:`logs.decodeBasis.generation`,detail:`logs.detail.decodeGeneration`,hint:`logs.detail.decodeBasisHint.generation`};case`legacy-post-visible-output`:return{short:`logs.decodeBasis.legacy`,detail:`logs.detail.decodeLegacy`,hint:`logs.detail.decodeBasisHint.legacy`};default:return{short:`logs.decodeBasis.unknown`,detail:`logs.detail.decodeUnknown`,hint:`logs.detail.decodeBasisHint.unknown`}}}var JF=[`max_completion_tokens`,`max_tokens`,`user`,`store`,`thinking`,`include_reasoning`,`reasoning`,`reasoning_effort`,`top_k`,`messages`,`tools`,`response_format`,`temperature`,`top_p`,`stream_options`,`parallel_tool_calls`,`metadata`,`service_tier`,`prompt_cache_key`],YF=[`messages.role`,`messages.content`,`tools.function`,`tools.function.strict`,`stream_options.include_usage`,`reasoning.effort`,`reasoning.enabled`,`thinking.type`],XF=[...JF,...YF,...JF.map(e=>`${e}.*`)],ZF=[`extra_forbidden`,`union_tag_invalid`,`literal_error`,`enum`,`value_error`],QF=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function $F(e){if(!Array.isArray(e))return;let t=[];for(let n of e.slice(0,64)){if(!QF(n))continue;let e=XF.find(e=>e===n.field),r=ZF.find(e=>e===n.type);if(e&&r&&!t.some(t=>t.field===e&&t.type===r)&&(t.push({field:e,type:r}),t.length===8))break}if(t.length)return t.length===e.length&&e.every((e,n)=>QF(e)&&Object.keys(e).length===2&&e.field===t[n].field&&e.type===t[n].type)?e:t}var eI=[`provider_error`,`header_timeout`,`connect_timeout`,`connect_failed`,`client_closed`,`body_stall`,`body_overflow`,`stream_error_stop`,`stream_ended_early`,`stream_failed`,`output_limit`,`stall_timeout`,`adapter_eof`,`generation_timeout`,`turn_inactivity`],tI=[`invalid_request_error`,`authentication_error`,`permission_error`,`not_found_error`,`rate_limit_error`,`api_error`,`overloaded_error`,`request_too_large`,`CANCELLED`,`UNKNOWN`,`INVALID_ARGUMENT`,`DEADLINE_EXCEEDED`,`NOT_FOUND`,`ALREADY_EXISTS`,`PERMISSION_DENIED`,`RESOURCE_EXHAUSTED`,`FAILED_PRECONDITION`,`ABORTED`,`OUT_OF_RANGE`,`UNIMPLEMENTED`,`INTERNAL`,`UNAVAILABLE`,`DATA_LOSS`,`UNAUTHENTICATED`],nI=[`FINISH_REASON_UNSPECIFIED`,`STOP`,`MAX_TOKENS`,`SAFETY`,`RECITATION`,`LANGUAGE`,`OTHER`,`BLOCKLIST`,`PROHIBITED_CONTENT`,`SPII`,`MALFORMED_FUNCTION_CALL`,`IMAGE_SAFETY`,`IMAGE_PROHIBITED_CONTENT`,`IMAGE_RECITATION`,`IMAGE_OTHER`,`NO_IMAGE`,`UNEXPECTED_TOOL_CALL`,`TOO_MANY_TOOL_CALLS`],rI=new Set(eI),iI=new Set(tI),aI=new Set(nI),oI=0xe8d4a51000,sI=new Set([`header_timeout`,`connect_timeout`,`body_stall`,`body_overflow`,`generation_timeout`,`turn_inactivity`]);function cI(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.code!=`string`||!rI.has(t.code))return;let n=t.code,r=t.value,i=typeof r==`number`&&Number.isSafeInteger(r)&&r>=0&&r<=oI&&sI.has(n),a=n===`provider_error`&&typeof t.type==`string`&&iI.has(t.type)?t.type:void 0,o=n===`provider_error`&&typeof t.finishReason==`string`&&aI.has(t.finishReason)?t.finishReason:void 0,s=n===`provider_error`?$F(t.validation):void 0;return Object.keys(t).every(e=>e===`code`||e===`value`&&i||e===`type`&&a!==void 0||e===`finishReason`&&o!==void 0||e===`validation`&&s!==void 0&&s===t.validation)?t:{code:n,...i?{value:r}:{},...a?{type:a}:{},...o?{finishReason:o}:{},...s?{validation:s}:{}}}var lI={"transport-unsent":`logs.detail.cause.transportUnsent`,"transport-ambiguous":`logs.detail.cause.transportAmbiguous`,"upstream-declined":`logs.detail.cause.upstreamDeclined`,"rate-limit":`logs.detail.cause.rateLimit`,"quota-exhausted":`logs.detail.cause.quotaExhausted`,"credential-rejected":`logs.detail.cause.credentialRejected`,"policy-refusal":`logs.detail.cause.policyRefusal`,"parameter-rejected":`logs.detail.cause.parameterRejected`,"ciphertext-refusal":`logs.detail.cause.ciphertextRefusal`,"payload-too-large":`logs.detail.cause.payloadTooLarge`,"payload-rejected":`logs.detail.cause.payloadRejected`,"upstream-fault":`logs.detail.cause.upstreamFault`,"empty-output":`logs.detail.cause.emptyOutput`,"client-cancelled":`logs.detail.cause.clientCancelled`,"local-refusal":`logs.detail.cause.localRefusal`},uI={"pre-header":`logs.detail.stage.preHeader`,"headers-only":`logs.detail.stage.headersOnly`,"protocol-prelude":`logs.detail.stage.protocolPrelude`,"semantic-output":`logs.detail.stage.semanticOutput`,"side-effect":`logs.detail.stage.sideEffect`,terminal:`logs.detail.stage.terminal`},dI={permitted:`logs.detail.resend.permitted`,"permitted-after-repair":`logs.detail.resend.permittedAfterRepair`,"refused-ambiguous":`logs.detail.resend.refusedAmbiguous`,"refused-committed":`logs.detail.resend.refusedCommitted`,"refused-futile":`logs.detail.resend.refusedFutile`};function fI(e,t){let n=e.failureCause===void 0?void 0:Object.hasOwn(lI,e.failureCause)?lI[e.failureCause]:void 0,r=e.failureStage===void 0?void 0:Object.hasOwn(uI,e.failureStage)?uI[e.failureStage]:void 0,i=e.resendPermission===void 0?void 0:Object.hasOwn(dI,e.resendPermission)?dI[e.resendPermission]:void 0;return{...e.failureCause?{cause:n?t(n):e.failureCause}:{},...e.failureStage?{stage:r?t(r):e.failureStage}:{},...e.resendPermission?{resend:i?t(i):e.resendPermission}:{}}}var pI=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0;function mI(e,t,n){let r=e.failureCause,i=r&&Object.hasOwn(lI,r)?lI[r]:void 0,a=i?{label:n(i)}:{label:t?.label,description:t?.description},o=e.spend;return!o||!pI(o.sends)||!pI(o.settled)||!pI(o.unresolved)||o.settled>o.sends||o.reserved!==void 0&&!pI(o.reserved)||(a.sends=o.sends,a.unresolved=o.unresolved,o.unresolved===0&&o.settled===o.sends&&(o.reserved===void 0||o.reserved<=o.settled)&&e.attemptNormalizationDropped!==!0&&Array.isArray(e.attempts)&&e.attempts.length===1&&pI(e.attempts[0]?.sendCount)&&e.attempts[0].sendCount===o.sends&&(a.retries=Math.max(0,o.sends-1))),a}var hI={auth_failed:`logs.detail.condition.authFailed`,access_denied:`logs.detail.condition.accessDenied`,context_overflow:`logs.detail.condition.contextOverflow`,location_unsupported:`logs.detail.condition.locationUnsupported`,account_verification_required:`logs.detail.condition.accountVerificationRequired`,billing_exhausted:`logs.detail.condition.billingExhausted`,model_unavailable:`logs.detail.condition.modelUnavailable`,rate_limited:`logs.detail.condition.rateLimited`,upstream_unavailable:`logs.detail.condition.upstreamUnavailable`,upstream_failed:`logs.detail.condition.upstreamFailed`,request_rejected:`logs.detail.condition.requestRejected`};function gI(e,t){return typeof e==`string`&&Object.hasOwn(hI,e)?t(hI[e]):void 0}var _I={provider_error:`logs.failureDetail.providerError`,header_timeout:`logs.failureDetail.headerTimeout`,connect_timeout:`logs.failureDetail.connectTimeout`,connect_failed:`logs.failureDetail.connectFailed`,client_closed:`logs.failureDetail.clientClosed`,body_stall:`logs.failureDetail.bodyStall`,body_overflow:`logs.failureDetail.bodyOverflow`,stream_error_stop:`logs.failureDetail.streamErrorStop`,stream_ended_early:`logs.failureDetail.streamEndedEarly`,stream_failed:`logs.failureDetail.streamFailed`,output_limit:`logs.failureDetail.outputLimit`,stall_timeout:`logs.failureDetail.stallTimeout`,adapter_eof:`logs.failureDetail.adapterEof`,generation_timeout:`logs.failureDetail.generationTimeout`,turn_inactivity:`logs.failureDetail.turnInactivity`},vI=new Set([`connect_timeout`,`body_stall`,`body_overflow`,`generation_timeout`,`turn_inactivity`]);function yI(e,t){let n=cI(e);if(n){if(n.code===`provider_error`){let e=n.type?t(`logs.failureDetail.providerErrorTyped`,{type:n.type}):t(_I.provider_error),r=n.finishReason?`${e} [finishReason: ${n.finishReason}]`:e;return n.validation?`${r}: ${n.validation.map(e=>`${e.field} [${e.type}]`).join(`; `)}`:r}return n.code===`header_timeout`&&n.value!==void 0?t(`logs.failureDetail.headerTimeoutAfter`,{value:n.value}):vI.has(n.code)?n.value===void 0?void 0:t(_I[n.code],{value:n.value}):t(_I[n.code])}}var bI=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function xI(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=bI.format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function SI(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):xI(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function CI(e){let t=0,n=!0,r=0,i=0,a=0;for(let o of e){if(o.usageStatus===`unsupported`){a+=1;continue}let e=o.displayMetrics?.cost;if(e?.kind===`value`){let i=e.estimate.cost.total;if(Number.isFinite(i)&&i>=0){t+=i,r+=1,n&&=e.estimate.priorityLowerBound===!0;continue}}i+=1}return{estimatedCostUsd:t,priorityLowerBound:r>0&&n,unpricedRequests:i,unmeteredRequests:a}}function wI(e){return e===`cursor`||e.startsWith(`cursor-`)}function TI(e){let t=e.usage;if(!t)return{};let n=typeof t.cacheCreationInputTokens==`number`?t.cacheCreationInputTokens:void 0;return{read:typeof t.cacheReadInputTokens==`number`?t.cacheReadInputTokens:typeof t.cachedInputTokens==`number`&&n!==void 0?Math.max(0,t.cachedInputTokens-n):t.cachedInputTokens,write:n}}function EI(e,t){if(!e.usage)return;let n=TI(e),r=[`${t(`logs.tokens.input`)}=${e.usage.inputTokens}`,`${t(`logs.tokens.output`)}=${e.usage.outputTokens}`];return n.read!==void 0&&r.push(`${t(`logs.tokens.cacheRead`)}=${n.read}`),n.write!==void 0&&r.push(`${t(`logs.tokens.cacheWrite`)}=${n.write}`),typeof e.usage.contextTotalTokens==`number`&&r.push(`${t(`logs.tokens.contextTotal`)}=${e.usage.contextTotalTokens}`),typeof e.usage.reasoningOutputTokens==`number`&&r.push(`${t(`logs.tokens.reasoning`)}=${e.usage.reasoningOutputTokens}`),e.usageStatus===`estimated`&&r.push(t(`logs.tokens.estimatedNote`)),e.usageStatus===`estimated`&&n.read===void 0&&n.write===void 0&&r.push(t(wI(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function DI(e){return e===void 0||typeof e==`string`}function OI(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!DI(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!DI(e.profile.id)||!DI(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!DI(e.selected.provider)||!DI(e.selected.model)||!DI(e.selected.reason)))return!1;if(e.candidates===void 0)return!0;if(!Array.isArray(e.candidates))return!1;for(let t of e.candidates){if(!t||typeof t!=`object`||!DI(t.provider)||!DI(t.model)||t.eligible!==void 0&&typeof t.eligible!=`boolean`)return!1;if(t.exclusions!==void 0){if(!Array.isArray(t.exclusions))return!1;for(let e of t.exclusions)if(!e||typeof e!=`object`||!DI(e.code))return!1}}return!0}function kI(e){if(e.routeDecision===void 0||OI(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function AI(e){if(Array.isArray(e))return{rows:e,cursor:null,reset:!1};if(!e||typeof e!=`object`)throw Error(`Invalid log response`);let t=e,n=Object.hasOwn(t,`cursor`)||Object.hasOwn(t,`reset`);if(t.logs!==void 0&&!Array.isArray(t.logs)||n&&(!Array.isArray(t.logs)||typeof t.cursor!=`string`||t.cursor.length===0||t.cursor.length>512||!/^[A-Za-z0-9_-]+$/.test(t.cursor)||typeof t.reset!=`boolean`))throw Error(`Invalid log response`);return{rows:t.logs??[],cursor:n?t.cursor:null,reset:t.reset===!0,generatedAt:t.generatedAt,...typeof t.timeZone==`string`?{timeZone:t.timeZone}:{},...typeof t.total==`number`&&Number.isFinite(t.total)&&t.total>=0?{total:t.total}:{}}}function jI(e,t,n=2e3){if(t.length===0&&e.length<=n)return e;let r=[...e,...t];return r.length>n?r.slice(r.length-n):r}function MI(e){return`ocx.logs.list.v1:${e}`}var NI=[];function PI(e){if(!Array.isArray(e))return null;for(let t of e)if(!t||typeof t!=`object`||typeof t.timestamp!=`number`||typeof t.model!=`string`||typeof t.provider!=`string`||typeof t.status!=`number`||typeof t.durationMs!=`number`||t.shadowCallRewrittenFrom!==void 0&&typeof t.shadowCallRewrittenFrom!=`string`||!OI(t.routeDecision))return null;return e}function FI(e){if(!e.usage)return typeof e.totalTokens==`number`?e.totalTokens:void 0;let t=e.usage.inputTokens+e.usage.outputTokens,n=e.usage.totalTokens??e.totalTokens;return typeof n==`number`?Math.max(n,t):t}function II(e){let t=FI(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function LI(e){let t=e.requestedEffort?.replace(/\s*->\s*/g,` → `),n=e.effectiveEffort;return t?!n||t===n||t.split(` → `).at(-1)===n?t:`${t} → ${n}`:n??`-`}function RI(e){if(e.reasoningWireField&&e.reasoningWireValue!==void 0)return`${e.reasoningWireField}=${e.reasoningWireValue}`}function zI(e){return UF(e)?(0,Q.jsxs)(Q.Fragment,{children:[RD(e.wireModel??e.model),` → `,RD(e.servedModel)]}):RD(e.servedModel??e.resolvedModel??e.model)}function BI(e,t){if(!e||e.kind===`unavailable`||!Number.isFinite(e.value)||e.value<=0)return`—`;let n=e.value>=100?0:1,r=new Intl.NumberFormat(t,{minimumFractionDigits:n,maximumFractionDigits:n}).format(e.value);return`${e.estimated?`~`:``}${r}`}var VI=2e3,HI=3e4,UI=4,WI=3,GI={usage_missing:`logs.detail.reason.usage_missing`,usage_unsupported:`logs.detail.reason.usage_unsupported`,output_missing:`logs.detail.reason.output_missing`,invalid_duration:`logs.detail.reason.invalid_duration`,price_unmatched:`logs.detail.reason.price_unmatched`,invalid_cache_breakdown:`logs.detail.reason.invalid_cache_breakdown`,invalid_usage:`logs.detail.reason.invalid_usage`,combo_attempt_unavailable:`logs.detail.reason.combo_attempt_unavailable`,ttft_missing:`logs.detail.reason.ttft_missing`,decode_window_too_short:`logs.detail.reason.decode_window_too_short`},KI={usage_estimated:`logs.detail.estimate.usage_estimated`,cache_detail_missing:`logs.detail.estimate.cache_detail_missing`,expected_price_overlay:`logs.detail.estimate.expected_price_overlay`,provider_cost_overlay:`logs.detail.estimate.provider_cost_overlay`,priority_lower_bound:`logs.detail.estimate.priority_lower_bound`},qI={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"offline-resend":`logs.detail.attempt.recovery.offlineResend`,"oauth-401":`logs.detail.attempt.recovery.oauth401`,"oauth-account-403":`logs.detail.attempt.recovery.oauthAccount403`,"key-401":`logs.detail.attempt.recovery.key401`,"key-429":`logs.detail.attempt.recovery.key429`,"rate-limit-429":`logs.detail.attempt.recovery.rateLimit429`,"anthropic-oauth-429":`logs.detail.attempt.recovery.anthropicOauth429`,"oauth-account-429":`logs.detail.attempt.recovery.oauthAccount429`,"oauth-account-402":`logs.detail.attempt.recovery.oauthAccount402`,"image-413":`logs.detail.attempt.recovery.image413`,"empty-completion":`logs.detail.attempt.recovery.emptyCompletion`,"console-go-upload-retry":`logs.detail.attempt.recovery.consoleGoUpload`,"opaque-blob-rejection":`logs.detail.attempt.recovery.opaqueBlobRejection`,"reasoning-effort-downgrade":`logs.detail.attempt.recovery.reasoningEffortDowngrade`,"anthropic-fast-downgrade":`logs.detail.attempt.recovery.anthropicFastDowngrade`};function JI(e){return GI[e]}function YI(e){return KI[e]}function XI(e){return qI[e]??`logs.detail.attempt.recovery.unknown`}function ZI(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}var QI={completed:`logs.detail.outcome.completed`,failed:`logs.detail.outcome.failed`,incomplete:`logs.detail.outcome.incomplete`,aborted:`logs.detail.outcome.aborted`};function $I(e){return QI[Xp(e)]}function eL(e,t,n){let r=n?{timeZone:n}:void 0;try{return{date:new Date(e).toLocaleDateString(t,r),time:new Date(e).toLocaleTimeString(t,r)}}catch{return{date:new Date(e).toLocaleDateString(t),time:new Date(e).toLocaleTimeString(t)}}}function tL(e,t,n){let{date:r,time:i}=eL(e,t,n);return`${r} ${i}`}function nL(e){let t=0;for(let n of e){let e=FI(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...CI(e)}}function rL(e){return X(`ui-v2 inline-flex h-7 cursor-pointer items-center rounded-[8px] px-3 text-[13px] font-medium transition-colors duration-200`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,e?`bg-raised text-fg shadow-sm ring-1 ring-line dark:bg-surface-2`:`text-fg-subtle hover:text-fg-muted`)}function iL({apiBase:e}){let{t:n,locale:r}=s(),i=MI(e),a=PI(sf(i)),[o,c]=(0,Z.useState)(!0),[l,u]=(0,Z.useState)({error:null,count:0}),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(gF),[h,g]=(0,Z.useState)(()=>Date.now()),_=(0,Z.useRef)({key:i,active:!1,request:0}),v=(0,Z.useRef)({key:i,cursor:null,rows:[]});(0,Z.useLayoutEffect)(()=>{let e={key:i,active:!0,request:0};return _.current=e,v.current={key:i,cursor:null,rows:[]},g(Date.now()),()=>{e.active=!1}},[i]);let y=(0,Z.useCallback)(()=>{let e=_.current;return zF(e.key===i?e.anchor:void 0,performance.now(),Date.now())},[i]),b=(0,Z.useRef)(null),x=(0,Z.useRef)({key:i,failures:0,nextAttemptAt:0,error:null}),S=t.find(e=>e.code===r)?.htmlLang,[C,w]=(0,Z.useState)();(0,Z.useEffect)(()=>{let t=new AbortController,n=!1;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{!n&&e&&typeof e.timeZone==`string`&&e.timeZone.trim()&&w(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[T,E]=(0,Z.useState)(BF),[D,O]=(0,Z.useState)(()=>BF()===`debug`);(0,Z.useEffect)(()=>{let e=()=>E(BF());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>{T===`debug`&&O(!0)},[T]);let k=VF,A=(0,Z.useCallback)(async t=>{let n=_.current;if(t.aborted||!n.active||n.key!==i)throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);let r=++n.request,a=()=>!t.aborted&&n.active&&_.current===n&&n.request===r,o=x.current;if(o.key!==i&&(o={key:i,failures:0,nextAttemptAt:0,error:null},x.current=o),o.failures>0&&Date.now()<o.nextAttemptAt)throw o.error;let s=v.current,c=s.key===i?s.cursor:null,l=`${e}/api/logs?limit=2000${c?`&cursor=${encodeURIComponent(c)}`:``}`;try{let e=await fetch(l,{signal:t});if(!e.ok)throw Error(`${e.status} ${e.statusText}`.trim());let r=await e.json(),o=performance.now(),u=AI(r),d=u.rows.map(kI),f=c&&u.cursor&&!u.reset?jI(s.rows,d):d;if(!a())throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);v.current={key:i,cursor:u.cursor,rows:f};let p=CF(f);m(e=>{let t=e.model.trim().toLowerCase(),n=e.provider.trim().toLowerCase(),r=t?p.models.find(e=>e.trim().toLowerCase()===t)??``:``,i=n?p.providers.find(e=>e.trim().toLowerCase()===n)??``:``;return e.model===r&&e.provider===i?e:{...e,model:r,provider:i}});let h=RF(u.generatedAt,o);return h&&(n.anchor=h),g(zF(n.anchor,o,Date.now())),x.current={key:i,failures:0,nextAttemptAt:0,error:null},df(i,f),f}catch(e){if(!a())throw e;let t=e??Error(`log request failed`),n=o.failures+1,r=VI*2**Math.min(n,UI);throw x.current={key:i,failures:n,nextAttemptAt:Date.now()+r,error:t},t}},[e,i]),j=mf(i,[e],A,{isEmpty:e=>e.length===0,enabled:T===`logs`,pollMs:o?VI:void 0,initialData:a??void 0}),M=j.state,N=M.data??a??NI,P=j.refresh,F=(0,Z.useCallback)(()=>{x.current={key:i,failures:0,nextAttemptAt:0,error:null},v.current={key:i,cursor:null,rows:[]},P({forceLoading:!0})},[P,i]),I=!j.refreshing&&M.showError;!j.refreshing&&!M.showError&&M.data!==void 0&&l.count!==0?u({error:null,count:0}):I&&l.error!==M.error&&u(e=>({error:M.error,count:e.count+1}));let L=l.count>=WI||!o&&I,R=d?FP(d.status,r):null,z=p.conversationId.trim();(0,Z.useEffect)(()=>{if(p.timeWindow===`all`||T!==`logs`)return;g(y());let e=window.setInterval(()=>g(y()),HI);return()=>window.clearInterval(e)},[p.timeWindow,T,y]),(0,Z.useEffect)(()=>{let e=!1;if(!z)m(e=>e.conversationQueryHash===void 0?e:{...e,conversationQueryHash:void 0});else return AP(z).then(t=>{e||m(e=>e.conversationQueryHash?.join(` `)===t.join(` `)?e:{...e,conversationQueryHash:t})}),()=>{e=!0}},[z]);let B=(0,Z.useMemo)(()=>CF(N),[N]),V=_F(p),H=(0,Z.useMemo)(()=>xF(N,p,h),[N,p,h]),U=z?nL(H):null,W=(0,Z.useMemo)(()=>H.reduce((e,t)=>e+ +(Xp(t)===`failed`),0),[H]),{columns:ee,toggle:G}=tF(),te=5+ZP.filter(e=>ee[e.key]).length,ne=xP({count:H.length,getScrollElement:()=>b.current,estimateSize:()=>60,overscan:15,getItemKey:e=>{let t=H[H.length-1-e];return t.requestId??`${t.timestamp}:${t.model}:${t.provider}`}}),K=ne.getVirtualItems(),q=K.length>0?K[0].start:0,J=K.length>0?ne.getTotalSize()-K[K.length-1].end:0;return(0,Q.jsxs)(`div`,{className:`logs-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:n(`nav.logs`)}),(0,Q.jsxs)(`div`,{className:`inline-flex items-center gap-0.5 rounded-control bg-surface p-0.5 ring-1 ring-inset ring-line`,role:`tablist`,"aria-label":n(`nav.logs`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":T===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:T===`logs`?0:-1,className:rL(T===`logs`),onClick:()=>k(`logs`),onKeyDown:HF,children:n(`logs.tabLogs`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":T===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:T===`debug`?0:-1,className:rL(T===`debug`),onClick:()=>k(`debug`),onKeyDown:HF,children:n(`logs.tabDebug`)})]})]}),D&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:T!==`debug`,children:(0,Q.jsx)(mF,{apiBase:e,embedded:!0,active:T===`debug`})}),(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:T!==`logs`,children:[(0,Q.jsxs)(`section`,{className:IP,"aria-labelledby":`logs-requests-title`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 px-4 pt-3.5 pb-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 gap-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`h3`,{id:`logs-requests-title`,className:`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em]`,children:n(`logsV2.requests`)}),(0,Q.jsxs)(`span`,{className:X(`inline-flex items-center gap-1.5 text-[13px] font-medium`,o?`text-fg`:`text-fg-subtle`),children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,className:X(`size-1.5 rounded-full`,o?`bg-success`:`ring-1 ring-current`)}),n(o?`logsV2.live`:`logsV2.paused`)]}),N.length>0&&(0,Q.jsxs)(`span`,{className:`text-[13px] text-fg-subtle tabular-nums`,children:[n(`logsV2.countLine`,{shown:H.length,total:N.length}),W>0&&(0,Q.jsxs)(`span`,{className:`text-danger`,children:[` · `,n(`logsV2.failedCount`,{count:W})]})]})]}),(0,Q.jsx)(JP,{className:`logs-auto-refresh`,checked:o,onChange:c,label:n(`logs.autoRefresh`),title:n(`logsV2.liveHint`)})]}),(0,Q.jsx)(DF,{filters:p,options:B,hasActiveFilters:V,filteredCount:H.length,totalCount:N.length,t:n,onFilterChange:m,onResetFilters:()=>m(gF),trailing:(0,Q.jsx)(qP,{options:ZP.map(e=>({key:e.key,label:n(e.label)})),visible:ee,onToggle:G,label:n(`logsV2.columns`),menuLabel:n(`logsV2.columnsMenu`)})}),U&&(0,Q.jsx)(`div`,{className:`logs-conversation-totals m-0`,children:(0,Q.jsxs)($,{tone:`ok`,children:[n(`logs.conversation.totals`,{requests:U.requests,tokens:$e(U.totalTokens,S??r),cost:xI(U.estimatedCostUsd,n,S,U.priorityLowerBound)}),` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[n(`logs.conversation.scope`),U.unpricedRequests+U.unmeteredRequests>0?` ${n(`logs.conversation.excluded`,{unpriced:U.unpricedRequests,unmetered:U.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,Q.jsxs)($,{tone:`err`,children:[M.error instanceof Error?`${n(`logs.loadError`)} ${M.error.message}`:n(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:n(`common.retry`)})]}),L&&N.length>0&&(0,Q.jsxs)($,{tone:`err`,children:[n(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:j.refreshing,children:n(`common.retry`)})]})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,Q.jsx)(`div`,{className:X(LP,`p-3`),children:(0,Q.jsx)(ck,{label:n(`common.loading`),rows:6})}):H.length===0?(0,Q.jsx)(`div`,{className:LP,children:(0,Q.jsx)(Un,{title:N.length>0&&V?n(`logs.noMatchingRequests`):n(`logs.noRequests`)})}):(0,Q.jsx)(`div`,{className:LP,children:(0,Q.jsx)(`div`,{ref:b,className:`logs-table-wrap max-h-[calc(100dvh-300px)] overflow-auto [overflow-anchor:none]`,children:(0,Q.jsxs)(`table`,{className:X(`logs-table ui-v2 w-full min-w-[1020px] table-fixed border-collapse text-[13px] font-normal text-fg`,`[&_th]:h-9 [&_th]:px-3 [&_th]:text-left [&_th]:text-[12px] [&_th]:font-medium [&_th]:whitespace-nowrap [&_th]:text-fg-subtle`,`[&_td]:px-3 [&_td]:py-2.5 [&_td]:align-middle`),children:[(0,Q.jsxs)(`colgroup`,{children:[(0,Q.jsx)(`col`,{className:`logs-col-client w-[48px]`}),(0,Q.jsx)(`col`,{className:`logs-col-time w-[120px]`}),(0,Q.jsx)(`col`,{className:`logs-col-status w-[80px]`}),(0,Q.jsx)(`col`,{className:`logs-col-model`,style:{width:280}}),ee.effort&&(0,Q.jsx)(`col`,{className:`logs-col-effort w-[104px]`}),ee.tokens&&(0,Q.jsx)(`col`,{className:`logs-col-tokens w-[84px]`}),ee.rate&&(0,Q.jsx)(`col`,{className:`logs-col-rate w-[84px]`}),ee.cost&&(0,Q.jsx)(`col`,{className:`logs-col-cost w-[84px]`}),ee.duration&&(0,Q.jsx)(`col`,{className:`logs-col-duration w-[84px]`}),(0,Q.jsx)(`col`,{className:`logs-col-actions w-[40px]`})]}),(0,Q.jsx)(`thead`,{className:`sticky top-0 z-10 bg-bg shadow-[inset_0_-1px_0_var(--ocx-line)]`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:n(`logsV2.client`)})}),(0,Q.jsx)(`th`,{scope:`col`,children:n(`logs.col.time`)}),(0,Q.jsx)(`th`,{scope:`col`,children:n(`logs.col.status`)}),(0,Q.jsxs)(`th`,{scope:`col`,children:[n(`logs.col.provider`),` · `,n(`logs.col.model`)]}),ee.effort&&(0,Q.jsx)(`th`,{scope:`col`,children:n(`logs.col.effort`)}),ee.tokens&&(0,Q.jsx)(`th`,{scope:`col`,className:`text-right!`,children:n(`logs.col.tokens`)}),ee.rate&&(0,Q.jsx)(`th`,{scope:`col`,className:`text-right!`,title:n(`logs.metric.tokPerSecTitle`),children:n(`logs.col.tokPerSec`)}),ee.cost&&(0,Q.jsx)(`th`,{scope:`col`,className:`text-right!`,title:n(`logs.metric.estimatedCostTitle`),children:n(`logs.col.estimatedCost`)}),ee.duration&&(0,Q.jsx)(`th`,{scope:`col`,className:`text-right!`,children:n(`logs.col.duration`)}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:n(`logs.details`)})})]})}),(0,Q.jsxs)(`tbody`,{children:[q>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:te,className:`logs-virtual-spacer p-0!`,style:{height:q}})}),K.map(e=>{let t=H[H.length-1-e.index],i=RI(t),a=t.displayMetrics?.decodeTokPerSecond,o=qF(a?.kind===`value`?a:{}),s=eL(t.timestamp,S,C),c=`${n(`logs.details`)}: ${t.requestId??t.status}`;return(0,Q.jsxs)(`tr`,{"data-index":e.index,ref:ne.measureElement,className:`group cursor-pointer border-b border-line transition-colors last:border-b-0 hover:bg-accent-soft`,onClick:e=>{e.target.closest(`button`)||window.getSelection?.()?.toString()||f(t)},children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(FF,{client:t.client,t:n})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`span`,{className:`flex flex-col leading-tight`,children:[(0,Q.jsx)(`span`,{className:`font-mono text-[12.5px] whitespace-nowrap text-fg tabular-nums`,children:s.time}),(0,Q.jsx)(`span`,{className:`mt-0.5 text-[11.5px] whitespace-nowrap text-fg-subtle tabular-nums`,children:s.date})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(XP,{status:t.status,outcome:Xp(t),label:n($I(t))})}),(0,Q.jsx)(`td`,{title:GF(t,n),children:(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1`,children:[(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:re(t.provider,n)}),(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`text-fg-subtle`,children:`·`}),(0,Q.jsx)(`span`,{className:`min-w-0 font-mono text-[12.5px] break-words text-fg`,children:zI(t)}),t.shadowCallRewrittenFrom&&(0,Q.jsx)(`span`,{className:`badge badge-muted whitespace-nowrap`,title:n(`logs.badge.interceptedHelperTitle`),children:n(`logs.badge.interceptedHelper`,{model:t.shadowCallRewrittenFrom})}),KF(t)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:KF(t)}),(0,Q.jsx)(IF,{trace:t.protocolTrace,t:n})]}),(0,Q.jsx)(`span`,{className:`log-reqid block max-w-full truncate font-mono text-[11.5px] text-fg-subtle`,title:t.requestId,children:t.requestId??`-`})]})}),ee.effort&&(0,Q.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:LI(t)}),ee.tokens&&(0,Q.jsx)(`td`,{className:`text-right font-mono tabular-nums`,title:EI(t,n),children:(()=>{let e=II(t),{read:i,write:a}=TI(t);return e===void 0?(0,Q.jsx)(`span`,{className:`font-sans text-fg-subtle`,children:n(`logs.tokens.${t.usageStatus??`unreported`}`)}):(0,Q.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,Q.jsxs)(`span`,{children:[t.usageStatus===`estimated`?`~`:``,$e(e,r)]}),i!==void 0&&i>0&&(0,Q.jsxs)(`span`,{className:`text-[11.5px] leading-tight text-fg-subtle`,children:[`c `,$e(i,r)]}),a!==void 0&&a>0&&(0,Q.jsxs)(`span`,{className:`text-[11.5px] leading-tight text-fg-subtle`,children:[`w `,$e(a,r)]}),t.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,Q.jsx)(`span`,{className:`text-[11.5px] leading-tight text-fg-subtle`,children:n(wI(t.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),ee.rate&&(0,Q.jsx)(`td`,{className:`log-col-rate text-right font-mono tabular-nums`,children:(0,Q.jsxs)(`span`,{className:`logs-stack-end max-w-full`,children:[(0,Q.jsx)(`span`,{children:BI(t.displayMetrics?.tokPerSecond,S)}),a?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate max-w-full text-fg-subtle`,title:n(o.detail),children:[(0,Q.jsx)(`span`,{children:BI(a,S)}),(0,Q.jsx)(`span`,{className:`block max-w-full truncate font-sans text-[11px]`,children:n(o.short)})]})]})}),ee.cost&&(0,Q.jsx)(`td`,{className:X(`text-right tabular-nums`,t.displayMetrics?.cost?.kind===`value`?`font-mono`:`font-sans text-fg-subtle`),children:SI(t.displayMetrics?.cost,n,S)}),ee.duration&&(0,Q.jsxs)(`td`,{className:`text-right font-mono whitespace-nowrap text-fg-muted tabular-nums`,children:[t.durationMs,`ms`]}),(0,Q.jsx)(`td`,{className:`px-1!`,children:(0,Q.jsx)(`button`,{type:`button`,className:`log-detail-btn ui-v2 inline-grid size-7 cursor-pointer place-items-center rounded-[8px] text-fg-subtle no-underline transition-colors group-hover:text-fg hover:bg-accent-soft focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-highlight`,onClick:()=>f(t),"aria-label":c,title:n(`logs.details`),children:(0,Q.jsx)(lt,{"aria-hidden":!0,className:`size-4`})})})]},e.key)}),J>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:te,className:`logs-virtual-spacer p-0!`,style:{height:J}})})]})]})})})]}),d&&(0,Q.jsx)(oL,{detail:d,detailInfo:R,localeCode:r,localeTag:S,serverTimeZone:C,t:n,onClose:()=>f(null),onFilterConversation:e=>{m(t=>({...t,conversationId:e})),f(null)}})]})]})}function aL(e){let t=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function oL({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=aL(!0),[l,u]=(0,Z.useState)(!1),d=TI(e),f=e.displayMetrics?.cost,p=e.displayMetrics?.decodeTokPerSecond,m=qF(p?.kind===`value`?p:{}),h=RI(e),g=fI(e,a),_=mI(e,t,a),v=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,Q.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:`log-detail-title`,className:`flex min-w-0 flex-wrap items-center gap-2.5`,children:[(0,Q.jsx)(XP,{status:e.status,outcome:Xp(e),label:a($I(e)),announce:!1,className:`h-6 text-[13px]`}),_.label&&(0,Q.jsx)(`span`,{className:`logs-detail-info m-0`,children:_.label})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,Q.jsx)(Ie,{})})]}),_.description&&(0,Q.jsx)(`p`,{className:`modal-desc`,children:_.description}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,Q.jsx)(`span`,{className:`mono`,children:tL(e.timestamp,r,i)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.outcome.label`)}),(0,Q.jsx)(`span`,{children:a($I(e))}),g.cause&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.cause.label`)}),(0,Q.jsxs)(`span`,{children:[g.cause,g.stage&&` (${a(`logs.detail.stage.label`)}: ${g.stage})`]})]}),g.resend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.resend.label`)}),(0,Q.jsx)(`span`,{children:g.resend})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.sends.label`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[_.sends===void 0?a(`logs.detail.sends.unavailable`):_.sends,_.unresolved!==void 0&&_.unresolved>0&&` (${a(`logs.detail.sends.unresolved`)}: ${_.unresolved})`]}),_.retries!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.retries.label`)}),(0,Q.jsx)(`span`,{className:`mono`,children:_.retries})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void v(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,Q.jsx)(`span`,{className:`mono`,children:zI(e)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,Q.jsx)(`span`,{children:re(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[LI(e),h?` (${h})`:``]})]}),e.errorCode&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),gI(e.upstreamCondition,a)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,Q.jsx)(`span`,{children:gI(e.upstreamCondition,a)})]}),yI(e.failureDetail,a)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.failureDetail`)}),(0,Q.jsx)(`span`,{children:yI(e.failureDetail,a)})]})]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,Q.jsx)(`span`,{className:`mono`,children:(e.routeDecision.candidates??[]).map(e=>`${typeof e.provider==`string`&&e.provider.length>0?e.provider:`–`}/${typeof e.model==`string`&&e.model.length>0?e.model:`–`}${e.eligible===!0?` ✓`:e.eligible===!1?` ✗`:` ?`}`).join(` `)||`–`})]}):(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,Q.jsx)(LF,{trace:e.protocolTrace,t:a}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid log-detail-performance-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.endToEndTokPerSec`)}),(0,Q.jsx)(`span`,{className:`mono`,children:BI(e.displayMetrics?.tokPerSecond,r)}),p?.kind===`value`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,title:a(m.hint),children:a(m.detail)}),(0,Q.jsx)(`span`,{className:`mono`,children:BI(p,r)}),(0,Q.jsx)(`span`,{className:`logs-decode-basis-hint muted text-caption`,children:a(m.hint)})]}),e.firstOutputMs!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(JI(e.displayMetrics.tokPerSecond.reason))}),e.displayMetrics?.decodeTokPerSecond?.kind===`unavailable`&&(0,Q.jsxs)(`p`,{className:`log-detail-notes-line muted`,children:[a(`logs.detail.decodeTokPerSec`),`: `,a(JI(e.displayMetrics.decodeTokPerSecond.reason))]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:xI(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:xI(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:xI(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:xI(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:xI(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,Q.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,Q.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(ZI(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,Q.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,Q.jsx)(`li`,{children:a(YI(e))},e))})]}):(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,Q.jsx)(`span`,{children:f?.kind===`unavailable`?a(JI(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,Q.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`num`,children:`#`}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,Q.jsx)(`th`,{className:`num`,title:a(`logs.detail.endToEndTokPerSec`),children:a(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,Q.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=e.displayMetrics?.decodeTokPerSecond,i=qF(n?.kind===`value`?n:{}),o=RI(e),s=t?.kind===`value`?t.estimate.price:void 0,c=fI(e,a).cause??e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(XI(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(JI(t.reason)):a(`logs.detail.attempt.completed`));return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{children:re(e.provider,a)}),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[LI(e),o?` (${o})`:``]})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[s.jawcodeProvider??s.provider,`/`,s.modelId,` · `,a(`logs.detail.source.${s.source}`),` · `,a(ZI(s.status))]})]})]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[BI(e.displayMetrics?.tokPerSecond,r),n?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:a(i.detail),children:[(0,Q.jsx)(`span`,{children:BI(n,r)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:a(i.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:SI(t,a,r)}),(0,Q.jsx)(`td`,{className:`log-detail-break`,children:c})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?$e(e.usage.inputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?$e(e.usage.outputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:$e(d.read,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:$e(d.write,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:$e(e.usage.reasoningOutputTokens,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,Q.jsx)(`span`,{className:`mono`,children:II(e)===void 0?`—`:$e(II(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:$e(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,Q.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,Q.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,Q.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function sL(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(e);if(!t)return null;let[n,r,i,a,o]=t.slice(1).map(Number),s=new Date(`${e}:00`),c=s.getTime();return!Number.isSafeInteger(c)||c<0||s.getFullYear()!==n||s.getMonth()!==r-1||s.getDate()!==i||s.getHours()!==a||s.getMinutes()!==o?null:c}function cL(e,t){if(!e||!t)return{ok:!1,error:`required`};let n=sL(e),r=sL(t);return n===null||r===null?{ok:!1,error:`invalid`}:n>r?{ok:!1,error:`reversed`}:{ok:!0,window:{since:n,until:r+59999}}}function lL(e){return`${Math.round(e*100)}%`}function uL(e,t,n){return typeof e==`number`&&Number.isFinite(e)&&e>=0?$e(e,t):n}function dL(e,t){return typeof e==`number`&&Number.isFinite(e)?lL(e):t}function fL(e,t,n){if(typeof e.cacheHitRate!=`number`||!Number.isFinite(e.cacheHitRate))return n(`usage.cacheHitRate.unmeasured`);let r=e.cacheObservedInputTokens;if(!(typeof r!=`number`||!Number.isFinite(r)||r>=e.inputTokens))return n(`usage.cacheHitRate.partial`,{measured:$e(r,t),total:$e(e.inputTokens,t)})}function pL(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function mL(e,t){return pL(e.throughputTokensPerSec)?t(`usage.throughput.title`,{samples:e.throughputSamples??0}):t(`usage.throughput.unmeasured`)}function hL(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function gL(e,t){let n=new Map(e.map(e=>[e.date,e])),r=[],i=new Date;i.setHours(0,0,0,0),i.setDate(i.getDate()-(t-1));for(let e=0;e<t;e++){let e=hL(i),t=n.get(e);r.push({date:e,requests:t?.requests??0,measuredRequests:t?.measuredRequests??0,reportedRequests:t?.reportedRequests??0,totalTokens:t?.totalTokens??0,...t?.estimatedCostUsd===void 0?{}:{estimatedCostUsd:t.estimatedCostUsd},models:t?.models??[]}),i.setDate(i.getDate()+1)}return r}function _L(e,t){return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(new Date(`${e}T12:00:00`))}function vL(e,t,n){return n(`usage.chart.dayDetail`,{date:_L(e.date,t),requests:e.requests,tokens:$e(e.totalTokens,t)})}function yL(e){let t=window.innerWidth,n=window.innerHeight,r=Math.min(240,Math.max(0,t-16));return{left:Math.max(8,Math.min(e.left+e.width/2-r/2,t-8-r)),maxWidth:r,...e.top-8>n-e.bottom-8?(()=>{let t=Math.max(8,Math.min(n-8,n-e.top+8));return{bottom:t,maxHeight:Math.max(0,n-t-8)}})():(()=>{let t=Math.max(8,Math.min(n-8,e.bottom+8));return{top:t,maxHeight:Math.max(0,n-t-8)}})()}}function bL(e){if(!(e>0))return 1;let t=10**Math.floor(Math.log10(e));for(let n of[1,2,2.5,5,10])if(n*t>=e)return n*t;return 10*t}function xL(e){let t=e.filter(e=>e>0).sort((e,t)=>e-t);if(t.length===0)return[0,0,0,0];let n=e=>t[Math.min(t.length-1,Math.floor(e*t.length))];return[n(.25),n(.5),n(.75),n(.95)]}function SL(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function CL(e,t=!1){let n=xL(e.map(e=>e.totalTokens));if(t){let t=[],r=[],i=[],a,o=-1,s=-4,c=e=>{for(;i.length<e;)i.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:i.length})};for(let l of e){let[e,u,d]=l.date.split(`-`).map(Number),f=new Date(Date.UTC(e,u-1,d)),p=f.getUTCDay(),m=f.getTime()-p*864e5;a!==m&&(i.length>0&&(c(7),t.push(i)),i=[],a=m);let h=f.getUTCMonth();h!==o&&t.length-s>=4&&(r.push({month:h,col:t.length}),o=h,s=t.length),c(p),i.push({date:l.date,requests:l.requests,totalTokens:l.totalTokens,level:SL(l.totalTokens,n),dayOfWeek:p})}return i.length>0&&(c(7),t.push(i)),{weeks:t,months:r,buckets:n}}let r=new Map(e.map(e=>[e.date,e])),i=new Date;i.setHours(0,0,0,0);let a=new Date(i);a.setDate(a.getDate()-364),a.setDate(a.getDate()-a.getDay());let o=[],s=[],c=-4,l=-1,u=[],d=new Date(a);for(;d<=i;){let e=hL(d),t=d.getMonth();d.getDay()===0&&t!==l&&o.length-c>=4&&(s.push({month:t,col:o.length}),c=o.length,l=t);let i=r.get(e);u.push({date:e,requests:i?.requests??0,totalTokens:i?.totalTokens??0,level:i?SL(i.totalTokens,n):0,dayOfWeek:d.getDay()}),d.getDay()===6&&(o.push(u),u=[]),d.setDate(d.getDate()+1)}if(u.length>0){for(;u.length<7;)u.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:u.length});o.push(u)}return{weeks:o,months:s,buckets:n}}function wL({values:e}){if(e.length<2||e.every(e=>e<=0))return null;let t=Math.max(...e),n=Math.min(...e),r=t-n||1,i=e.map((t,i)=>`${(i/(e.length-1)*100).toFixed(2)},${(92-(t-n)/r*84).toFixed(2)}`).join(` `);return(0,Q.jsx)(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,"aria-hidden":`true`,className:`hidden h-7 w-14 shrink-0 text-fg-subtle @min-[13rem]:block`,children:(0,Q.jsx)(`polyline`,{points:i,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,vectorEffect:`non-scaling-stroke`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function TL({text:e}){return(0,Q.jsx)(`button`,{type:`button`,"aria-label":e,title:e,className:`ui-v2 inline-grid size-5 shrink-0 cursor-help place-items-center rounded-full text-fg-subtle transition-colors hover:bg-surface-2 hover:text-fg-muted focus-visible:outline-2 focus-visible:outline-highlight [&_svg]:size-3.5`,children:(0,Q.jsx)(He,{"aria-hidden":`true`})})}function EL({label:e,term:t,hint:n,value:r,spark:i,foot:a,meter:o}){return(0,Q.jsxs)(`div`,{className:`@container flex min-w-0 flex-col gap-2 px-4 py-3.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`truncate text-[13px] font-medium text-fg-muted`,children:e}),t&&(0,Q.jsx)(`span`,{className:`truncate font-mono text-[11px] text-fg-subtle`,children:t}),n&&(0,Q.jsx)(TL,{text:n})]}),(0,Q.jsxs)(`div`,{className:`mt-auto flex min-w-0 items-end justify-between gap-3`,children:[(0,Q.jsx)(`span`,{className:`stat-value truncate text-stat font-semibold tracking-[-0.025em] text-fg tabular-nums`,children:r}),i&&(0,Q.jsx)(wL,{values:i})]}),o!==void 0&&(0,Q.jsx)(`span`,{className:`block h-1 w-full overflow-hidden rounded-full bg-surface-2`,"aria-hidden":`true`,children:(0,Q.jsx)(`span`,{className:`block h-full rounded-full bg-fg`,style:{width:`${Math.max(0,Math.min(1,o))*100}%`}})}),a&&(0,Q.jsx)(`span`,{className:`truncate text-xs text-fg-subtle tabular-nums`,children:a})]})}function DL({summary:e,days:t,activeDays:n,locale:r,t:i}){let a=new Intl.NumberFormat(r),o=(e.unpricedRequests??0)+(e.unmeteredRequests??0),s=e.estimatedCostUsd!==void 0,c=t.some(e=>e.estimatedCostUsd!==void 0)?t.map(e=>e.estimatedCostUsd??0):void 0,l=e.cacheReadInputTokens??e.cachedInputTokens,u=e.cacheCreationInputTokens??0,d=[{label:i(`usage.card.measured`),value:a.format(e.measuredRequests)},{label:i(`usage.card.cachedTokens`),value:$e(l,r),title:i(`usage.card.cachedTokensHint`)},...u>0?[{label:i(`usage.card.cacheWriteTokens`),value:$e(u,r)}]:[],{label:i(`usage.col.tokPerSec`),value:pL(e.throughputTokensPerSec)?e.throughputTokensPerSec.toFixed(1):i(`usage.unavailable`),title:mL(e,i)},{label:i(`usage.card.activeDays`),value:a.format(n)}];return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2.5`,children:[(0,Q.jsx)(`div`,{className:`@container overflow-hidden rounded-[12px] bg-surface ring-1 ring-line`,role:`group`,"aria-label":i(`usage.section.overview`),children:(0,Q.jsxs)(`div`,{className:`grid grid-cols-1 *:-mt-px *:-ml-px *:border-t *:border-l *:border-line @md:grid-cols-2 @3xl:grid-cols-4`,children:[(0,Q.jsx)(EL,{label:i(`usage.card.requests`),value:a.format(e.requests),spark:t.map(e=>e.requests),foot:i(`usageV2.activeDaysFoot`,{days:a.format(n)})}),(0,Q.jsx)(EL,{label:i(`usage.card.totalTokens`),value:$e(e.totalTokens,r),spark:t.map(e=>e.totalTokens),foot:i(`usageV2.tokensSplit`,{input:$e(e.inputTokens,r),output:$e(e.outputTokens,r)})}),(0,Q.jsx)(EL,{label:i(`usageV2.costLabel`),term:i(`usage.col.apiListPrice`),hint:`${i(`usage.cost.total`)}. ${i(`usage.cost.disclaimer`)}`,value:s?sb(e.estimatedCostUsd??0,r):i(`usage.unavailable`),...s&&c?{spark:c}:{},foot:o>0?i(`usage.cost.unpricedNote`,{count:o}):i(s?`usageV2.costFoot`:`usageV2.costMissing`)}),(0,Q.jsx)(EL,{label:i(`usage.card.coverage`),hint:i(`usageV2.coverageHint`),value:lL(e.coverageRatio),meter:e.coverageRatio,foot:i(`usageV2.coverageFoot`,{measured:a.format(e.measuredRequests),requests:a.format(e.requests)})})]})}),(0,Q.jsx)(`dl`,{className:`m-0 flex flex-wrap items-baseline gap-x-5 gap-y-1 px-1 text-[13px]`,children:d.map(e=>(0,Q.jsxs)(`div`,{className:`usage-fact flex items-baseline gap-1.5`,title:e.title,children:[(0,Q.jsxs)(`dt`,{className:`text-fg-subtle`,children:[e.label,e.title&&(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` (`,e.title,`)`]})]}),(0,Q.jsx)(`dd`,{className:`usage-fact-value m-0 font-medium text-fg-muted tabular-nums`,children:e.value})]},e.label))})]})}function OL({anchor:e,className:t,children:n}){return(0,Dn.createPortal)((0,Q.jsx)(`div`,{className:`${t} chart-overlay`,role:`tooltip`,style:yL(e),children:n}),document.body)}function kL({bars:e,locale:t,t:n}){let[r,i]=(0,Z.useState)(null),a=bL(Math.max(0,...e.map(e=>e.totalTokens))),o=[a,a/2,0],s=e.find(e=>e.date===r?.date),c=e.length<=7,l=Math.max(1,Math.ceil(e.length/8)),u=t=>c||(e.length-1-t)%l==0,d=t=>c||(e.length-1-t)%(l*2)==0,f=e=>new Intl.DateTimeFormat(t,c?{weekday:`short`}:{month:`numeric`,day:`numeric`}).format(new Date(`${e}T12:00:00`)),p=(e,t)=>i({date:e.date,anchor:t.getBoundingClientRect()});return(0,Q.jsxs)(`div`,{className:`@container flex flex-col gap-2`,children:[(0,Q.jsxs)(`div`,{className:`flex gap-3`,children:[(0,Q.jsx)(`div`,{className:`-my-2 flex h-[220px] w-12 shrink-0 flex-col justify-between text-right text-[11px] text-fg-subtle tabular-nums`,"aria-hidden":`true`,children:o.map(e=>(0,Q.jsx)(`span`,{children:$e(e,t)},e))}),(0,Q.jsxs)(`div`,{className:`relative h-[220px] min-w-0 flex-1`,children:[(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-0 flex flex-col justify-between`,"aria-hidden":`true`,children:o.map(e=>(0,Q.jsx)(`span`,{className:X(`block h-px w-full`,e===0?`bg-line-strong`:`bg-line`)},e))}),(0,Q.jsx)(`div`,{className:X(`daybars absolute inset-0 flex h-auto items-stretch p-0`,e.length>40?`gap-px`:c?`gap-3`:`gap-1`),role:`group`,"aria-label":n(`usage.section.heatmap`),children:e.map(e=>{let o=Math.max(0,Math.min(100,e.totalTokens/a*100)),s=r?.date===e.date;return(0,Q.jsxs)(`button`,{type:`button`,className:`daybar group relative flex h-full min-w-0 flex-1 cursor-pointer flex-col items-center justify-end gap-0 rounded-[4px] p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,"aria-label":vL(e,t,n),onFocus:t=>p(e,t.currentTarget),onBlur:()=>i(t=>t?.date===e.date?null:t),onPointerEnter:t=>p(e,t.currentTarget),onPointerDown:t=>p(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&i(t=>t?.date===e.date?null:t)},children:[(0,Q.jsx)(`span`,{className:`absolute inset-x-0 inset-y-0 rounded-[4px] bg-transparent transition-colors group-hover:bg-surface-2/60`,"aria-hidden":`true`}),c&&e.totalTokens>0&&(0,Q.jsx)(`span`,{className:`daybar-count absolute left-1/2 -translate-x-1/2 text-[11px] font-medium text-fg-muted tabular-nums`,style:{bottom:`calc(${o}% + 4px)`},children:$e(e.totalTokens,t)}),(0,Q.jsx)(`span`,{className:X(`relative block w-full max-w-12 rounded-t-[3px] transition-colors`,e.totalTokens>0?`min-h-[2px]`:`min-h-0`,s?`bg-fg`:`bg-fg/70 group-hover:bg-fg`),style:{height:`${o}%`},"aria-hidden":`true`})]},e.date)})})]})]}),(0,Q.jsxs)(`div`,{className:`flex gap-3`,"aria-hidden":`true`,children:[(0,Q.jsx)(`div`,{className:`w-12 shrink-0`}),(0,Q.jsx)(`div`,{className:X(`flex min-w-0 flex-1`,e.length>40?`gap-px`:c?`gap-3`:`gap-1`),children:e.map((e,t)=>(0,Q.jsx)(`span`,{className:`daybar-label relative min-w-0 flex-1 text-center text-[11px] text-fg-subtle tabular-nums`,children:u(t)&&(0,Q.jsx)(`span`,{className:X(!c&&`absolute left-1/2 -translate-x-1/2 whitespace-nowrap`,!d(t)&&`hidden @xl:inline`),children:f(e.date)})},e.date))})]}),r&&s&&(0,Q.jsxs)(OL,{className:`daybar-tip`,anchor:r.anchor,children:[(0,Q.jsx)(`div`,{className:`daybar-tip-date`,children:_L(s.date,t)}),(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{children:n(`usage.heatmap.tooltipRequests`,{requests:s.requests})}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:$e(s.totalTokens,t)})})]}),s.models.slice(0,8).map(e=>(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{className:`daybar-tip-name`,children:RD(e.model)}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:$e(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]})]})}var AL=e=>new Intl.DateTimeFormat(e,{month:`short`});function jL({heatmap:e,locale:t,t:n}){let r=(0,Z.useRef)(null),i=(0,Z.useMemo)(()=>e.weeks.flat().filter(e=>e.date),[e]),[a,o]=(0,Z.useState)(()=>i.at(-1)?.date??``),[s,c]=(0,Z.useState)(null),l=(0,Z.useId)(),u=i.some(e=>e.date===a)?a:i.at(-1)?.date??``,d=(e,t)=>{o(e.date),c({date:e.date,anchor:t.getBoundingClientRect()})},f=(e,t)=>{let n=i.findIndex(e=>e.date===t.date),a=e.key===`ArrowUp`?-1:e.key===`ArrowDown`?1:e.key===`ArrowLeft`?-7:e.key===`ArrowRight`?7:0;if(!a||n<0)return;e.preventDefault();let s=i[Math.max(0,Math.min(i.length-1,n+a))];o(s.date);let l=r.current?.querySelector(`[data-date="${s.date}"]`);l&&(l.focus(),c({date:s.date,anchor:l.getBoundingClientRect()}))};(0,Z.useEffect)(()=>{let e=r.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[e]);let p=i.find(e=>e.date===u);return(0,Q.jsxs)(`div`,{className:`heatmap usage-v2-heatmap`,ref:r,children:[(0,Q.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${e.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,Q.jsx)(`span`,{className:`heatmap-day-spacer`}),e.months.map(e=>(0,Q.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:AL(t).format(new Date(2e3,e.month,1))},`${e.month}-${e.col}`))]}),(0,Q.jsxs)(`div`,{className:`heatmap-body`,children:[(0,Q.jsxs)(`div`,{className:`heatmap-days`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:n(`usage.dayMon`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:n(`usage.dayWed`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:n(`usage.dayFri`)}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`div`,{className:`heatmap-grid`,role:`group`,"aria-labelledby":`usage-heatmap-title`,"aria-describedby":l,style:{gridTemplateColumns:`repeat(${e.weeks.length}, var(--hm-cell))`},children:e.weeks.map((e,r)=>(0,Q.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,i)=>e.date?(0,Q.jsx)(`button`,{type:`button`,className:`heatmap-cell heatmap-cell-${e.level}`,"data-date":e.date,tabIndex:u===e.date?0:-1,"aria-label":vL(e,t,n),onFocus:t=>d(e,t.currentTarget),onBlur:()=>c(t=>t?.date===e.date?null:t),onKeyDown:t=>f(t,e),onPointerEnter:t=>d(e,t.currentTarget),onPointerDown:t=>d(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&c(t=>t?.date===e.date?null:t)}},e.date):(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-0`,"aria-hidden":`true`},`pad-${r}-${i}`))},e[0]?.date||`week-${r}`))})]}),(0,Q.jsx)(`span`,{id:l,className:`sr-only`,children:n(`usage.heatmap.keyboardLabel`)}),(0,Q.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:p?vL(p,t,n):``}),s&&(()=>{let e=i.find(e=>e.date===s.date);return e?.date?(0,Q.jsxs)(OL,{className:`heatmap-tip`,anchor:s.anchor,children:[(0,Q.jsx)(`div`,{className:`heatmap-tip-date`,children:_L(e.date,t)}),(0,Q.jsx)(`div`,{className:`heatmap-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:$e(e.totalTokens,t)})}),(0,Q.jsx)(`div`,{className:`heatmap-tip-req muted`,children:n(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,Q.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,Q.jsx)(`span`,{children:n(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,Q.jsx)(`span`,{children:n(`usage.heatmap.more`)})]})]})}function ML({defaultView:e,heatmap:t,bars:n,totalTokens:r,locale:i,t:a}){let[o,s]=(0,Z.useState)(e);return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4 rounded-[12px] bg-surface p-5 ring-1 ring-line`,"aria-labelledby":`usage-heatmap-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Q.jsx)(`h3`,{id:`usage-heatmap-title`,className:`m-0 text-[15px] font-semibold text-fg`,children:a(`usage.section.heatmap`)}),(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:a(`usageV2.chartCaption`,{tokens:$e(r,i)})})]}),(0,Q.jsx)(Mc,{size:`sm`,"aria-label":a(`usageV2.chartView`),value:o,onChange:s,items:[{value:`bars`,label:a(`usageV2.viewBars`)},{value:`calendar`,label:a(`usageV2.viewCalendar`)}]})]}),o===`bars`?(0,Q.jsx)(kL,{bars:n,locale:i,t:a}):(0,Q.jsx)(jL,{heatmap:t,locale:i,t:a})]})}function NL({row:e,locale:t,t:n}){if(e.estimatedCostUsd===void 0&&e.pricedRequests===void 0&&e.unpricedRequests===void 0)return(0,Q.jsx)(`span`,{className:`muted`,children:`—`});let r=e.unpricedRequests??0,i=n(r===1?`usage.cost.excludedOne`:`usage.cost.excluded`,{count:r});return e.estimatedCostUsd===void 0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:`—`}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:sb(e.estimatedCostUsd??0,t)}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]})}function PL({ratio:e}){let t=Math.max(0,Math.min(1,e));return(0,Q.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,Q.jsx)(`div`,{className:`usage-bar h-1.5 min-w-16 flex-1 overflow-hidden rounded-full bg-surface-2`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill h-full rounded-full bg-fg/75`,style:{width:`${Math.round(t*100)}%`}})}),(0,Q.jsx)(`span`,{className:`w-9 shrink-0 text-right font-mono text-xs text-fg-muted tabular-nums`,children:lL(t)})]})}function FL({title:e,titleId:t,meta:n,actions:r,children:i}){return(0,Q.jsxs)(`section`,{className:`usw-section flex min-w-0 flex-col gap-3 rounded-[12px] bg-surface p-5 ring-1 ring-line`,"aria-labelledby":t,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,Q.jsx)(`h3`,{id:t,className:`h-section m-0 text-[15px] leading-6 font-semibold tracking-normal text-fg`,children:e}),n&&(0,Q.jsx)(`span`,{className:`text-[13px] text-fg-subtle tabular-nums`,children:n})]}),r]}),i]})}function IL({models:e,totalModels:t,modelQuery:n,onModelQuery:r,locale:i,t:a}){let o=a(`usage.search.models`),s=`usage-models-list-price-disclaimer`,c=a(`usage.unavailable`);return(0,Q.jsxs)(FL,{title:a(`usage.section.models`),titleId:`usage-models-title`,meta:String(t),actions:(0,Q.jsxs)(`label`,{className:`usw-section-toolbar relative m-0 flex w-full max-w-60 items-center`,children:[(0,Q.jsx)(`span`,{className:`pointer-events-none absolute left-2.5 text-fg-subtle [&_svg]:size-3.5`,"aria-hidden":`true`,children:(0,Q.jsx)(We,{})}),(0,Q.jsx)(`input`,{className:`input h-[var(--ocx-control-h)] w-full rounded-control pl-8 text-[13px]`,"aria-label":o,placeholder:o,value:n,onChange:e=>r(e.target.value)})]}),children:[(0,Q.jsx)(`div`,{className:`tbl-wrap usage-v2-tbl`,children:(0,Q.jsxs)(`table`,{className:`tbl usage-models-tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:a(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:a(`usage.col.share`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":s,children:a(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.inputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.outputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.cacheHits`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.cacheWrites`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`usage.col.cacheHitRate`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=re(e.provider,a),n=fL(e,i,a),r=mL(e,a);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono font-medium text-fg`,title:e.model,children:RD(e.model)}),(0,Q.jsx)(`td`,{className:`muted`,title:t,children:t}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(PL,{ratio:e.shareRatio})}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.totalTokens,i)}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(NL,{row:e,locale:i,t:a})}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.inputTokens,i)}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.outputTokens,i)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:r,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:pL(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:c}),pL(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:r})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:uL(e.cacheReadInputTokens??e.cachedInputTokens,i,c)}),(0,Q.jsx)(`td`,{className:`num mono`,children:uL(e.cacheCreationInputTokens,i,c)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:n,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:dL(e.cacheHitRate,c)}),n!==void 0&&(0,Q.jsx)(`span`,{className:`sr-only`,children:n})]})]},`${e.provider}/${e.model}`)})})]})}),(0,Q.jsx)(`p`,{id:s,className:`m-0 text-xs text-fg-subtle`,children:a(`usage.cost.disclaimer`)})]})}function LL({apps:e,locale:t,t:n}){let r={codex:`Codex`,claude_code:`Claude Code`,claude_desktop:`Claude Desktop`,grok:`Grok`,opencode:`OpenCode`,aside:`Aside`,other:n(`usageV2.other`),unknown:n(`usageV2.unknown`),unclassified:n(`usageV2.unclassified`)},i=`usage-apps-list-price-disclaimer`;return(0,Q.jsx)(FL,{title:n(`usageV2.apps`),titleId:`usage-apps-title`,meta:e?String(e.length):void 0,children:!e||e.length===0?(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,role:`status`,children:n(e?`usageV2.appsEmpty`:`usageV2.appsUnavailable`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`tbl-wrap usage-v2-tbl`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`usageV2.app`)}),(0,Q.jsx)(`th`,{children:n(`usage.col.share`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":i,children:n(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)})]})}),(0,Q.jsx)(`tbody`,{children:e.toSorted((e,t)=>t.totalTokens-e.totalTokens).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`font-medium text-fg`,children:r[e.client]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(PL,{ratio:e.shareRatio})}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.totalTokens,t)}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(NL,{row:e,locale:t,t:n})}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests})]},e.client))})]})}),(0,Q.jsx)(`p`,{id:i,className:`m-0 text-xs text-fg-subtle`,children:n(`usage.cost.disclaimer`)})]})})}function RL({providers:e,locale:t,t:n}){let r=n(`usage.unavailable`),i=`usage-providers-list-price-disclaimer`;return(0,Q.jsxs)(FL,{title:n(`usage.section.providers`),titleId:`usage-providers-title`,meta:String(e.length),children:[(0,Q.jsx)(`div`,{className:`tbl-wrap usage-v2-tbl`,children:(0,Q.jsxs)(`table`,{className:`tbl usage-providers-tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:n(`usage.col.share`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":i,children:n(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokPerSec`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`font-medium text-fg`,children:re(e.provider,n)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(PL,{ratio:e.shareRatio})}),(0,Q.jsx)(`td`,{className:`num mono`,children:$e(e.totalTokens,t)}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(NL,{row:e,locale:t,t:n})}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsxs)(`td`,{className:`num mono`,title:mL(e,n),children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:pL(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:r}),pL(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:mL(e,n)})]})]},e.provider))})]})}),(0,Q.jsx)(`p`,{id:i,className:`m-0 text-xs text-fg-subtle`,children:n(`usage.cost.disclaimer`)})]})}function zL({summary:e,locale:t,t:n}){let r=new Intl.NumberFormat(t),i=Math.max(1,e.requests),a=Math.max(0,e.measuredRequests-e.reportedRequests-e.estimatedRequests),o=[{key:`reported`,label:n(`usage.coverage.reported`),count:e.reportedRequests+a,tone:`bg-fg`},{key:`estimated`,label:n(`usage.coverage.estimated`),count:e.estimatedRequests,tone:`bg-fg/45`},{key:`unreported`,label:n(`logs.tokens.unreported`),count:e.unreportedRequests,tone:`bg-warning`},{key:`unsupported`,label:n(`logs.tokens.unsupported`),count:e.unsupportedRequests,tone:`bg-line-strong`}];return(0,Q.jsxs)(FL,{title:n(`usage.section.coverage`),titleId:`usage-coverage-title`,meta:lL(e.coverageRatio),children:[(0,Q.jsx)(`div`,{className:`flex h-2 w-full gap-0.5 overflow-hidden rounded-full bg-surface-2`,"aria-hidden":`true`,children:o.filter(e=>e.count>0).map(e=>(0,Q.jsx)(`span`,{className:X(`block h-full first:rounded-l-full last:rounded-r-full`,e.tone),style:{width:`${e.count/i*100}%`}},e.key))}),(0,Q.jsxs)(`dl`,{className:`m-0 grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-3 lg:grid-cols-5`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,Q.jsx)(`dt`,{className:`text-xs text-fg-subtle`,children:n(`usage.coverage.measured`)}),(0,Q.jsx)(`dd`,{className:`m-0 text-[17px] font-semibold text-fg tabular-nums`,children:r.format(e.measuredRequests)})]}),o.map(t=>(0,Q.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-xs text-fg-subtle`,children:[(0,Q.jsx)(`span`,{className:X(`size-2 shrink-0 rounded-[2px]`,t.tone),"aria-hidden":`true`}),t.label]}),(0,Q.jsx)(`dd`,{className:`m-0 text-[17px] font-semibold text-fg tabular-nums`,children:r.format(t.key===`reported`?e.reportedRequests:t.count)})]},t.key))]}),(0,Q.jsx)(`p`,{className:`m-0 text-xs leading-5 text-fg-subtle`,children:n(`usage.coverage.note`)})]})}var BL=`h-[calc(var(--ocx-control-h)-4px)] gap-1.5 px-2.5 text-[13px]`;function VL({range:e,onRange:t,t:n}){return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":n(`usageV2.rangeLabel`),children:[`all`,`30d`,`7d`].map(r=>{let i=n(r===`all`?`usage.range.available`:`usage.range.${r}`);return(0,Q.jsx)(`button`,{type:`button`,className:X(`usage-segmented-btn${e===r?` active`:``}`,BL),"aria-label":i,"aria-pressed":e===r,onClick:()=>t(r),children:i},r)})})})}function HL({scope:e,onScope:t,t:n}){return(0,Q.jsxs)(`div`,{className:`usage-source-row m-0 flex items-center gap-2 text-[13px] text-fg-muted`,children:[(0,Q.jsx)(`span`,{children:n(`usage.source.connected`)}),(0,Q.jsx)(`div`,{className:`usage-segmented usage-scope-control`,role:`group`,"aria-label":n(`usage.scope.label`),children:[`machine`,`hub`].map(r=>(0,Q.jsx)(`button`,{type:`button`,className:X(`usage-segmented-btn${e===r?` active`:``}`,BL),"aria-pressed":e===r,onClick:()=>t(r),children:n(r===`machine`?`usage.scope.machine`:`usage.scope.hub`)},r))})]})}function UL({open:e,active:t,onToggle:n,t:r}){return(0,Q.jsxs)(`button`,{type:`button`,className:X(`usage-range-toggle ui-v2 inline-flex h-[var(--ocx-control-h)] cursor-pointer items-center gap-1.5 rounded-control border-0 px-3 text-[13px] font-medium whitespace-nowrap`,`transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,t||e?`bg-raised text-fg shadow-sm ring-1 ring-inset ring-line-strong dark:bg-surface-2`:`bg-transparent text-fg-muted hover:bg-surface hover:text-fg`,t&&`is-active`),"aria-expanded":e,"aria-controls":e?`usage-range-panel`:void 0,onClick:n,children:[(0,Q.jsx)(Pc,{icon:Fc,size:15,strokeWidth:1.8,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:r(`usage.range.custom`)}),(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`,className:`usage-range-chevron`})]})}function WL({window:e,locale:t,t:n}){let r=new Intl.DateTimeFormat(t,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,timeZoneName:`short`});return(0,Q.jsx)(`p`,{className:`usage-range-applied m-0 basis-full text-[13px] text-fg-muted`,role:`status`,children:n(`usage.range.applied`,{start:r.format(e.since),end:r.format(e.until)})})}function GL({label:e,value:t,invalid:n,describedBy:r,onChange:i}){return(0,Q.jsxs)(`label`,{className:`usage-range-field grid min-w-0 gap-1`,children:[(0,Q.jsx)(`span`,{className:`field-label m-0 text-xs font-medium text-fg-muted`,children:e}),(0,Q.jsx)(`input`,{className:`input h-[var(--ocx-control-h)]`,type:`datetime-local`,step:`60`,required:!0,value:t,"aria-invalid":n,"aria-describedby":r,onChange:e=>i(e.currentTarget.value)})]})}function KL({draft:e,error:t,onDraft:n,onApply:r,onClear:i,t:a}){let o=t?`usage-range-help usage-range-error`:`usage-range-help`;return(0,Q.jsxs)(`form`,{id:`usage-range-panel`,className:`usage-range-panel m-0 grid w-full max-w-full gap-3 rounded-[12px] border-0 bg-surface p-4 ring-1 ring-line sm:w-max`,"aria-label":a(`usage.range.custom`),noValidate:!0,onSubmit:e=>{e.preventDefault(),r()},children:[(0,Q.jsxs)(`div`,{className:`usage-range-fields`,children:[(0,Q.jsx)(GL,{label:a(`usage.range.start`),value:e.since,invalid:t!==null,describedBy:o,onChange:e=>n({since:e})}),(0,Q.jsx)(GL,{label:a(`usage.range.end`),value:e.until,invalid:t!==null,describedBy:o,onChange:e=>n({until:e})}),(0,Q.jsx)(Jp,{type:`submit`,variant:`primary`,size:`sm`,className:`usage-range-action h-9`,children:a(`usage.range.apply`)}),(0,Q.jsx)(Jp,{type:`button`,variant:`ghost`,size:`sm`,className:`usage-range-action h-9`,onClick:i,children:a(`usage.range.clear`)})]}),(0,Q.jsx)(`p`,{id:`usage-range-help`,className:`m-0 text-xs text-fg-subtle`,children:a(`usage.range.help`)}),t&&(0,Q.jsx)(`p`,{id:`usage-range-error`,role:`alert`,className:`notice notice-err m-0`,children:a(`usage.range.${t}`)})]})}function qL({children:e}){return(0,Q.jsx)(`div`,{className:`usage-range-bar flex flex-wrap items-center gap-2`,children:e})}var JL=[`requests`,`tokens`,`cost`,`quota`,`none`],YL=[6,24,72,168],XL=[`line`,`stackedBar`],ZL=[`total`,`input`,`output`,`cached`],QL=[`sum`,`average`,`max`],$L=[`model`,`modelAccount`],eR={requests:`usage.companion.menuRequests`,tokens:`usage.companion.menuTokens`,cost:`usage.companion.menuCost`,quota:`usage.companion.menuQuota`,none:`usage.companion.menuNone`},tR={6:`usage.companion.window6`,24:`usage.companion.window24`,72:`usage.companion.window72`,168:`usage.companion.window168`},nR={total:`usage.companion.metricTotal`,input:`usage.companion.metricInput`,output:`usage.companion.metricOutput`,cached:`usage.companion.metricCached`},rR=[[`showToday`,`usage.companion.sectionToday`],[`showChart`,`usage.companion.sectionChart`],[`showModels`,`usage.companion.sectionModels`],[`showCost`,`usage.companion.sectionCost`],[`showAccounts`,`usage.companion.sectionAccounts`]],iR={sum:`usage.companion.aggregationSum`,average:`usage.companion.aggregationAverage`,max:`usage.companion.aggregationMax`},aR={macos:[`usage.companion.installMacStep1`,`usage.companion.installMacStep2`,`usage.companion.installMacStep3`],windows:[`usage.companion.installWinStep1`,`usage.companion.installWinStep2`,`usage.companion.installWinStep3`],linux:[`usage.companion.installLinuxStep1`,`usage.companion.installLinuxStep2`,`usage.companion.installLinuxStep3`]},oR={macos:`usage.companion.osMac`,windows:`usage.companion.osWindows`,linux:`usage.companion.osLinux`},sR=`h-7 px-2.5 text-[13px]`,cR=`field-label text-xs font-medium text-fg-muted`;function lR({title:e,aside:t,className:n,children:r}){return(0,Q.jsxs)(`section`,{className:X(`flex min-w-0 flex-col gap-4 rounded-[12px] bg-surface p-5 ring-1 ring-line`,n),children:[(e||t)&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e&&(0,Q.jsx)(`h3`,{className:`m-0 text-[15px] font-semibold text-fg`,children:e}),t]}),r]})}function uR({value:e,onChange:t,t:n}){return(0,Q.jsx)(`div`,{className:`usage-segmented w-fit`,role:`group`,"aria-label":n(`usage.companion.installOs`),children:Object.keys(oR).map(r=>(0,Q.jsx)(`button`,{type:`button`,className:X(`usage-segmented-btn${e===r?` active`:``}`,sR),"aria-pressed":e===r,onClick:()=>t(r),children:n(oR[r])},r))})}function dR({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`div`,{className:`usage-companion-control grid min-w-0 gap-1.5`,children:[(0,Q.jsx)(`span`,{className:cR,children:e}),(0,Q.jsx)(`div`,{className:`usage-segmented flex w-fit max-w-full flex-wrap`,role:`group`,"aria-label":e,children:n.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:X(`usage-segmented-btn${e===t?` active`:``}`,sR),"aria-pressed":e===t,onClick:()=>i(e),children:r(e)},String(e)))})]})}function fR({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`label`,{className:`usage-companion-control grid min-w-0 gap-1.5`,children:[(0,Q.jsx)(`span`,{className:cR,children:e}),(0,Q.jsx)(Vn,{fullWidth:!0,label:e,triggerClassName:`h-9 py-0 text-[13px]`,value:t,onChange:e=>i(e),options:n.map(e=>({value:e,label:r(e)}))})]})}function pR({tone:e}){return(0,Q.jsx)(`span`,{className:X(`usage-companion-install-dot size-2 shrink-0 rounded-full`,e===`on`?`bg-success`:`bg-fg-subtle`),"aria-hidden":`true`})}function mR({response:e,fetchedAt:t,installOs:n,onInstallOs:r,onOpenInBrowser:i,t:a}){let o=e?.companion?.lastSeenAt??null,s=o!==null&&t!==null&&t-o<=6e5,c=o===null||t===null?``:qm(o,Jm(a),t),l=_f(),u=gf()??`2.100.5`,d=aR[n],f=(0,Q.jsxs)(`ol`,{className:`usage-companion-install-steps m-0 grid gap-2 pl-5 text-[13px] text-fg-muted`,children:[(0,Q.jsxs)(`li`,{children:[a(d[0]),` `,(0,Q.jsx)(`a`,{className:`font-medium text-highlight hover:underline`,href:`https://github.com/lidge-jun/opencodex/releases/latest`,target:`_blank`,rel:`noreferrer`,children:a(`common.github`)})]}),(0,Q.jsx)(`li`,{children:a(d[1])}),(0,Q.jsx)(`li`,{children:a(d[2])})]}),p=(0,Q.jsxs)(`div`,{className:`grid gap-3`,children:[(0,Q.jsx)(uR,{value:n,onChange:r,t:a}),f,n===`macos`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command block overflow-x-auto rounded-[8px] bg-bg px-3 py-2 text-xs ring-1 ring-line`,children:`xattr -d com.apple.quarantine /Applications/OpenCodex.app`}):n===`linux`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command block overflow-x-auto rounded-[8px] bg-bg px-3 py-2 text-xs ring-1 ring-line`,children:`chmod +x OpenCodex-*.AppImage`}):null]}),m=(e,t)=>(0,Q.jsxs)(`details`,{className:`usage-companion-install-guide grid gap-3 border-t border-line pt-3`,open:t,children:[(0,Q.jsx)(`summary`,{className:`w-fit cursor-pointer text-[13px] font-medium text-fg-muted hover:text-fg`,children:e}),(0,Q.jsx)(`div`,{className:`pt-3`,children:p})]}),h=l?{tone:`off`,text:a(`usage.companion.runningInDesktop`,{version:u})}:s?{tone:`on`,text:a(e?.companion?.kind===`desktop`?`usage.companion.connectedDesktop`:`usage.companion.connected`,{age:c})}:{tone:`off`,text:o===null?a(`usage.companion.notConnected`):a(`usage.companion.lastSeen`,{age:c})};return(0,Q.jsxs)(lR,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Q.jsx)(`h3`,{className:`m-0 text-[15px] font-semibold text-fg`,children:a(`usage.companion.title`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:a(`usage.companion.description`)})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l&&(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:i,children:a(`usage.companion.openInBrowser`)}),(0,Q.jsxs)(`a`,{className:`inline-flex h-8 items-center gap-1.5 rounded-control px-3 text-[13px] font-medium text-fg-muted no-underline transition-colors hover:bg-surface-2 hover:text-fg [&_svg]:size-3.5`,href:`https://opencodex.me/guides/macos-menu-bar/`,target:`_blank`,rel:`noreferrer`,children:[a(`usage.companion.installGuide`),(0,Q.jsx)(dt,{"aria-hidden":`true`})]})]})]}),(0,Q.jsxs)(`div`,{className:X(`usage-companion-install-status flex items-center gap-2 text-[13px]`,h.tone===`on`?`text-fg`:`text-fg-muted`),children:[(0,Q.jsx)(pR,{tone:h.tone}),(0,Q.jsx)(`span`,{className:`usage-companion-install-last-seen`,children:h.text})]}),l||s?m(a(`usage.companion.installAnother`),!1):m(a(`usage.companion.installTitle`),!0)]})}function hR({groups:e,current:t,availableModels:n,knownTotals:r,disabled:i,onUpdate:a,t:o}){let s=t.models??n,c=new Set(s);return(0,Q.jsxs)(`div`,{className:`usage-companion-models grid gap-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,Q.jsx)(`span`,{className:cR,children:o(`usage.companion.modelsOnChart`)}),(0,Q.jsx)(`span`,{className:`usage-companion-models-count text-xs whitespace-nowrap text-fg-subtle tabular-nums`,children:o(`usage.companion.modelsCount`,{selected:s.length,total:n.length})})]}),t.models!==null&&(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>a({models:null}),disabled:i,children:o(`usage.companion.modelsShowAll`)})]}),(0,Q.jsx)(`div`,{className:`usage-companion-models-list max-h-72 overflow-y-auto rounded-[8px] border-0 bg-bg ring-1 ring-line`,children:e.map(e=>{let o=e.models.filter(e=>c.has(e.id)).length,s=o===e.models.length;return(0,Q.jsxs)(`div`,{className:`usage-companion-model-group`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-model-group-header`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-model-provider`,children:e.provider}),(0,Q.jsx)(`span`,{className:`usage-companion-model-chip mono text-caption`,children:e.models.length}),(0,Q.jsx)(Rn,{on:s,mixed:o>0&&!s,onClick:()=>a({models:ze(t.models,n,e.models.map(e=>e.id),!s)}),disabled:i,label:e.provider,title:e.provider})]}),e.models.map(e=>{let o=c.has(e.id);return(0,Q.jsxs)(`div`,{className:`usage-companion-model-row${o?``:` is-off`}`,children:[(0,Q.jsx)(Rn,{on:o,onClick:()=>a({models:ze(t.models,n,[e.id],!o)}),disabled:i,label:e.id,title:e.id}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.id}),(0,Q.jsx)(`span`,{className:`usage-companion-model-total muted text-caption`,children:r.has(e.id)?it(e.total):`—`})]},e.id)})]},e.provider)})})]})}function gR({children:e}){return(0,Q.jsx)(`h4`,{className:`m-0 text-[13px] font-semibold text-fg`,children:e})}function _R({current:e,disabled:t,providerNames:n,onUpdate:r,t:i}){let a=new Set(e.hiddenProviders);return(0,Q.jsxs)(`fieldset`,{className:`usage-companion-controls m-0 flex min-w-0 flex-col gap-5 border-0 p-0`,disabled:t,children:[(0,Q.jsxs)(`div`,{className:`grid gap-3`,children:[(0,Q.jsx)(gR,{children:i(`usageV2.companionMenuBar`)}),(0,Q.jsx)(dR,{label:i(`usage.companion.menuBarShows`),value:e.menuBarMetric,options:JL,optionLabel:e=>i(eR[e]),onChange:e=>r({menuBarMetric:e})})]}),(0,Q.jsxs)(`div`,{className:`grid gap-3 border-t border-line pt-4`,children:[(0,Q.jsx)(gR,{children:i(`usageV2.companionChart`)}),(0,Q.jsx)(dR,{label:i(`usage.companion.window`),value:e.chartHours,options:YL,optionLabel:e=>i(tR[e]),onChange:e=>r({chartHours:e,bucketMinutes:ut(e)})}),(0,Q.jsx)(dR,{label:i(`usage.companion.style`),value:e.chartStyle,options:XL,optionLabel:e=>i(e===`line`?`usage.companion.styleLine`:`usage.companion.styleStacked`),onChange:e=>r({chartStyle:e})}),(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Q.jsx)(fR,{label:i(`usage.companion.metric`),value:e.tokenMetric,options:ZL,optionLabel:e=>i(nR[e]),onChange:e=>r({tokenMetric:e})}),(0,Q.jsx)(fR,{label:i(`usage.companion.groupBy`),value:e.chartGrouping,options:$L,optionLabel:e=>i(e===`model`?`usage.companion.groupModel`:`usage.companion.groupAccount`),onChange:e=>r({chartGrouping:e})})]})]}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-switches m-0 grid gap-1 border-0 border-t border-line p-0 pt-4`,children:[(0,Q.jsx)(`legend`,{className:`float-left mb-2 w-full p-0`,children:(0,Q.jsx)(gR,{children:i(`usage.companion.popoverSections`)})}),rR.map(([t,n])=>(0,Q.jsxs)(`div`,{className:`usage-companion-switch flex items-center justify-between gap-3 py-1 text-[13px] text-fg`,children:[(0,Q.jsx)(`span`,{children:i(n)}),(0,Q.jsx)(Rn,{on:e[t],label:i(n),onClick:()=>r({[t]:!e[t]})})]},t))]}),(0,Q.jsxs)(`details`,{className:`usage-companion-advanced border-t border-line pt-4`,children:[(0,Q.jsx)(`summary`,{className:`w-fit cursor-pointer text-[13px] font-semibold text-fg`,children:i(`usage.companion.advanced`)}),(0,Q.jsxs)(`div`,{className:`usage-companion-advanced-body grid gap-4 pt-3`,children:[(0,Q.jsx)(fR,{label:i(`usage.companion.aggregation`),value:e.aggregation,options:QL,optionLabel:e=>i(iR[e]),onChange:e=>r({aggregation:e})}),(0,Q.jsxs)(`label`,{className:`usage-companion-control grid min-w-0 gap-1.5`,children:[(0,Q.jsx)(`span`,{className:cR,children:i(`usage.companion.menuText`)}),(0,Q.jsx)(`input`,{className:`h-9 rounded-control text-[13px]`,value:e.menuBarTemplate??``,onChange:e=>r({menuBarTemplate:e.target.value}),maxLength:200}),(0,Q.jsxs)(`span`,{className:`text-xs text-fg-subtle`,children:[i(`usage.companion.placeholders`),` `,(0,Q.jsx)(`code`,{children:`{requests} {totalTokens} {inputTokens} {outputTokens} {costUsd} {quotaPercent}`})]})]}),n.length>0&&(0,Q.jsxs)(`fieldset`,{className:`usage-companion-check-list m-0 grid gap-2 border-0 p-0`,children:[(0,Q.jsx)(`legend`,{className:X(cR,`mb-1 p-0`),children:i(`usage.companion.hideProviders`)}),n.map(t=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.has(t),onChange:n=>r({hiddenProviders:n.target.checked?[...e.hiddenProviders,t]:e.hiddenProviders.filter(e=>e!==t)})}),` `,(0,Q.jsx)(`span`,{children:t})]},t))]})]})]})]})}function vR(e,t){return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`}).format(e)}function yR(e){return e instanceof Error&&e.message?e.message:String(e)}function bR(e){let[t,n]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{if(t||!e.current||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(n(!0),r.disconnect())},{rootMargin:`240px`});return r.observe(e.current),()=>r.disconnect()},[e,t]),t}function xR({apiBase:e,providers:t,onSettingsLoaded:n}){let{t:r,locale:i}=s(),a=(0,Z.useRef)(null),o=bR(a),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(`idle`),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),A=(0,Z.useRef)(null),j=(0,Z.useRef)(S),M=(0,Z.useRef)(u),N=(0,Z.useRef)(new Map),[P,F]=(0,Z.useState)(new Map),[I,L]=(0,Z.useState)(()=>{let e=xf();return e===`unknown`?`macos`:e});(0,Z.useEffect)(()=>{j.current=S},[S]),(0,Z.useEffect)(()=>{M.current=u},[u]);let R=(0,Z.useCallback)(async()=>{_(null);try{let t=await fetch(`${e}/api/companion/settings`);if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());let r=await t.json();l(r),T(Date.now()),d(r.settings),k.current=r.settings,n?.(r.settings.menuBarMetric)}catch(e){_(yR(e))}},[e,n]);(0,Z.useEffect)(()=>{if(!o||c)return;let e=setTimeout(()=>void R(),0);return()=>clearTimeout(e)},[R,c,o]),(0,Z.useEffect)(()=>{if(!o)return;let e=setInterval(()=>{j.current!==`saving`&&(M.current&&k.current!==M.current||R())},6e4);return()=>clearInterval(e)},[R,o]);let z=(0,Z.useMemo)(()=>u?Rt(u):null,[u]),B=(0,Z.useCallback)(async()=>{if(!z)return;A.current?.abort();let t=new AbortController;A.current=t,x(!0),y(null);try{let n=await fetch(`${e}/api/usage/timeline?${z}`,{signal:t.signal});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let r=await n.json(),i=u?Mt(r,u):r;p(i),h(i.availableModels);let a=new Map;for(let e of i.series)a.set(e.id,(a.get(e.id)??0)+e.total);for(let[e,t]of a)N.current.set(e,t);F(new Map(N.current))}catch(e){t.signal.aborted||y(yR(e))}finally{t.signal.aborted||x(!1)}},[u,e,z]);(0,Z.useEffect)(()=>{if(!o||!z)return;let e=setTimeout(()=>void B(),250),t=setInterval(()=>void B(),6e4);return()=>{clearTimeout(e),clearInterval(t),A.current?.abort()}},[z,B,o]);let V=(0,Z.useCallback)(e=>{c?.corrupt||(d(t=>t&&{...t,...e}),C(`saving`),D(null))},[c?.corrupt]);(0,Z.useEffect)(()=>{if(!c?.corrupt&&u&&k.current&&k.current!==u&&S===`saving`)return O.current&&clearTimeout(O.current),O.current=setTimeout(async()=>{try{let t=tt(u,m),n=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:t})}),r=await n.json();if(!n.ok)throw Error(r&&`error`in r&&r.error?r.error:`${n.status} ${n.statusText}`.trim());l(r),T(Date.now()),d(r.settings),k.current=r.settings,C(`saved`)}catch(e){D(yR(e)),C(`error`)}},300),()=>{O.current&&clearTimeout(O.current)}},[e,m,c?.corrupt,S,u]);let H=(0,Z.useRef)(m);(0,Z.useEffect)(()=>{H.current=m},[m]),(0,Z.useEffect)(()=>()=>{let t=M.current;t&&k.current&&k.current!==t&&j.current===`saving`&&fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:tt(t,H.current)}),keepalive:!0}).catch(()=>{})},[e]);let U=(0,Z.useCallback)(async()=>{C(`saving`),D(null);try{let t=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({reset:!0})});if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());await R(),C(`saved`)}catch(e){D(yR(e)),C(`error`)}},[e,R]),W=(0,Z.useCallback)(async()=>{try{let t=location.hash?`/${location.hash}`:`/#/usage`,n=await fetch(`${e}/api/companion/open-in-browser`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:t})});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim())}catch(e){D(yR(e))}},[e]);if(g)return(0,Q.jsx)(`section`,{ref:a,className:`usage-companion-panel`,children:(0,Q.jsx)(lR,{children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`m-0 text-[14px] text-fg`,children:r(`usage.companion.settingsUnavailable`)}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:()=>void R(),children:r(`common.retry`)})]})})});let ee=u;if(!ee)return(0,Q.jsx)(`section`,{ref:a,className:`usage-companion-panel`,"aria-busy":`true`,children:(0,Q.jsx)(`div`,{className:`usage-companion-loading grid min-h-40 place-items-center rounded-[12px] bg-surface text-[13px] text-fg-muted ring-1 ring-line`,children:r(`common.loading`)})});let G=t.map(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t).toSorted(),te=It(m,P),ne=S===`saved`&&c?.updatedAt?r(`usage.companion.saved`,{time:vR(c.updatedAt,i)}):S===`error`?r(`usage.companion.saveFailed`,{error:E??``}):``,K=c?.corrupt===!0;return(0,Q.jsxs)(`section`,{ref:a,className:`usage-companion-panel flex flex-col gap-4`,children:[K&&(0,Q.jsxs)(`div`,{className:`usage-companion-save-status is-error flex flex-wrap items-center justify-between gap-3 rounded-[12px] bg-danger-soft px-4 py-3 text-[13px] text-danger`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:r(`usage.companion.corrupt`)}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:()=>void U(),disabled:S===`saving`,children:r(`usage.companion.corruptReset`)})]}),(0,Q.jsx)(mR,{response:c,fetchedAt:w,installOs:I,onInstallOs:L,onOpenInBrowser:()=>void W(),t:r}),(0,Q.jsxs)(`div`,{className:`grid items-start gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,25rem)]`,children:[(0,Q.jsxs)(lR,{title:r(`usageV2.companionPreview`),children:[(0,Q.jsx)(ft,{timeline:f,chartStyle:ee.chartStyle,hours:ee.chartHours,loading:b,error:v,onRetry:()=>void B(),locale:i,t:r}),te.length>0&&(0,Q.jsx)(hR,{groups:te,current:ee,availableModels:m,knownTotals:P,disabled:K,onUpdate:V,t:r})]}),(0,Q.jsx)(lR,{title:r(`usageV2.companionSettings`),children:(0,Q.jsx)(_R,{current:ee,disabled:K,providerNames:G,onUpdate:V,t:r})})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 px-1`,children:[(0,Q.jsxs)(`div`,{className:X(`usage-companion-save-status flex min-h-8 items-center gap-2 text-[13px]`,S===`error`?`is-error text-danger`:`text-fg-muted`),role:S===`error`?`alert`:`status`,children:[ne||`\xA0`,S===`error`&&(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>{C(`saving`)},children:r(`common.retry`)})]}),(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>void U(),children:r(`usage.companion.reset`)})]}),(0,Q.jsx)(`p`,{className:`m-0 px-1 text-xs text-fg-subtle`,children:r(`usage.companion.footer`)})]})}function SR({apiBase:e,providers:t}){let[n,r]=(0,Z.useState)([]);return(0,Z.useEffect)(()=>{if(t.length>0)return;let n=new AbortController;return fetch(`${e}/api/config`,{signal:n.signal}).then(e=>Yn(e)).then(e=>{n.signal.aborted||r(Object.keys(e?.providers??{}).map(e=>({provider:e})))}).catch(()=>{}),()=>n.abort()},[e,t.length]),(0,Q.jsx)(xR,{apiBase:e,providers:t.length>0?t:n})}function CR(){return window.location.hash.replace(/^#\/?/,``)===`usage/companion`?`companion`:`report`}function wR(e){window.location.hash=e===`report`?`usage`:`usage/companion`}function TR(e){if(e.key===`ArrowLeft`||e.key===`Home`||e.key===`ArrowRight`||e.key===`End`){e.preventDefault();let t=e.key===`ArrowLeft`||e.key===`Home`?`report`:`companion`;wR(t),document.getElementById(`usage-tab-${t}`)?.focus()}}function ER(e){return window.addEventListener(L,e),()=>window.removeEventListener(L,e)}function DR(){return(0,Z.useEffect)(()=>{ne()},[]),(0,Z.useSyncExternalStore)(ER,r,r)}var OR=[`all`,`codex`,`claude_code`,`claude_desktop`,`grok`,`opencode`,`aside`,`other`,`unknown`];function kR(e){let t=new URLSearchParams({client:e.client,device:e.device.kind});return e.device.kind===`key`&&t.set(`apiKeyId`,e.device.id),t}function AR(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let n=e,r=n.device;if(Object.keys(n).sort().join(`,`)!==`client,device`||n.client!==t.client||!r||typeof r!=`object`||Array.isArray(r))return!1;let i=r;return i.kind===t.device.kind&&(t.device.kind===`key`?Object.keys(i).sort().join(`,`)===`id,kind`&&i.id===t.device.id:Object.keys(i).join(`,`)===`kind`)}function jR(e){return/(?:^|,)\s*no-store\s*(?:,|$)/i.test(e.headers.get(`cache-control`)??``)}function MR(e){if(!e||typeof e!=`object`)return!1;let{since:t,until:n,timeZone:r}=e;if(typeof t!=`number`||!Number.isSafeInteger(t)||typeof n!=`number`||!Number.isSafeInteger(n)||t>n||typeof r!=`string`||!r)return!1;try{let e=new Intl.DateTimeFormat(`en-US-u-ca-gregory`,{timeZone:r,year:`numeric`,month:`2-digit`,day:`2-digit`}),i=t=>{let n=e.formatToParts(new Date(t)),r=e=>Number(n.find(t=>t.type===e)?.value);return Date.UTC(r(`year`),r(`month`)-1,r(`day`))},a=i(t);return Number.isFinite(a)&&i(n)-a===25056e5&&i(t-1)<a}catch{return!1}}var NR=[`codex`,`claude_code`,`claude_desktop`,`grok`,`opencode`,`aside`,`other`,`unknown`,`unclassified`],PR=e=>!!e&&typeof e==`object`&&!Array.isArray(e),FR=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,IR=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0,LR=(e,t,n)=>t.every(t=>e[t]===void 0||n(e[t])),RR=(e,t)=>t.every(t=>FR(e[t])),zR=new Set(NR);function BR(e){if(e===void 0)return!0;if(!Array.isArray(e)||e.length>zR.size)return!1;let t=new Set;return e.every(e=>!PR(e)||typeof e.client!=`string`||!zR.has(e.client)||t.has(e.client)||!RR(e,[`requests`,`measuredRequests`,`pricedRequests`,`unpricedRequests`])||!IR(e.totalTokens)||!IR(e.shareRatio)||e.shareRatio>1||!(e.estimatedCostUsd===void 0&&e.pricedRequests===0||IR(e.estimatedCostUsd))?!1:(t.add(e.client),!0))}function VR(e,t=0){return typeof e==`number`?Number.isFinite(e):!e||typeof e!=`object`?!0:t>=16?!1:Object.values(e).every(e=>VR(e,t+1))}function HR(e){if(!PR(e)||!BR(e.apps)||!VR(e)||!PR(e.summary)||!Array.isArray(e.days)||!Array.isArray(e.models)||!Array.isArray(e.providers)||!FR(e.generatedAt)||e.since!==null&&!FR(e.since)||typeof e.historyTruncated!=`boolean`||typeof e.entriesTruncated!=`boolean`||!FR(e.truncatedPrefixBytes)||!FR(e.entriesDropped)||!FR(e.legacyUnclassifiedRequests)||!LR(e,[`snapshotWindowStart`,`snapshotWindowEnd`],e=>e===null||typeof e==`number`&&Number.isSafeInteger(e))||e.usageIncomplete!==void 0&&typeof e.usageIncomplete!=`boolean`||e.usageIncompleteReason!==void 0&&(e.usageIncomplete!==!0||e.usageIncompleteReason!==`oversized_rows`))return!1;let t=e.summary;if(!RR(t,[`requests`,`measuredRequests`,`reportedRequests`,`unreportedRequests`,`unsupportedRequests`,`estimatedRequests`])||![`inputTokens`,`outputTokens`,`cachedInputTokens`,`reasoningOutputTokens`,`totalTokens`].every(e=>IR(t[e]))||!IR(t.coverageRatio)||t.coverageRatio>1||!LR(t,[`cacheReadInputTokens`,`cacheCreationInputTokens`,`cacheObservedInputTokens`,`throughputOutputTokens`,`throughputDurationMs`],IR)||!LR(t,[`pricedRequests`,`unpricedRequests`,`unmeteredRequests`,`throughputSamples`,`attemptCount`,`sends`,`settledSends`,`unresolvedSends`,`spendRequests`,`cacheObservedRequests`,`cacheSynthesizedRequests`,`cacheUnknownRequests`],FR)||!LR(t,[`estimatedCostUsd`,`throughputTokensPerSec`],IR)||!LR(e,[`legacyUnclassifiedRequests`],FR)||!e.days.every(e=>PR(e)&&typeof e.date==`string`&&/^\d{4}-\d{2}-\d{2}$/.test(e.date)&&RR(e,[`requests`,`measuredRequests`,`reportedRequests`])&&IR(e.totalTokens)&&LR(e,[`estimatedCostUsd`],IR)&&Array.isArray(e.models)&&e.models.every(e=>PR(e)&&typeof e.model==`string`&&typeof e.provider==`string`&&RR(e,[`requests`])&&IR(e.totalTokens)&&LR(e,[`attemptCount`],FR)&&LR(e,[`inputTokens`,`outputTokens`,`cacheReadInputTokens`,`cacheCreationInputTokens`,`cacheObservedInputTokens`],IR))))return!1;let n=(e,t)=>PR(e)&&typeof e.provider==`string`&&(!t||typeof e.model==`string`)&&RR(e,[`requests`,`measuredRequests`,`reportedRequests`,`estimatedRequests`])&&IR(e.totalTokens)&&(!t||IR(e.inputTokens)&&IR(e.outputTokens))&&IR(e.shareRatio)&&LR(e,[`inputTokens`,`outputTokens`,`cachedInputTokens`,`cacheReadInputTokens`,`cacheCreationInputTokens`,`cacheObservedInputTokens`],IR)&&LR(e,[`pricedRequests`,`unpricedRequests`,`unmeteredRequests`,`throughputSamples`,`attemptCount`],FR)&&LR(e,[`estimatedCostUsd`,`throughputTokensPerSec`],IR)&&(e.cacheHitRate===void 0||e.cacheHitRate===null||IR(e.cacheHitRate))&&(e.resolvedModel===void 0||typeof e.resolvedModel==`string`);return e.models.every(e=>n(e,!0))&&e.providers.every(e=>n(e,!1))}var UR=class extends Error{},WR=class extends Error{};function GR(e,t,n,i,a,o){let s=JSON.stringify(n),c=`ocx.usage.resource:${JSON.stringify([e,t,n,a,o,i.generation])}`,l=n?.device.kind===`unconfigured`,u=(0,Z.useCallback)(async n=>{let c=JSON.parse(s);if(!c)throw new UR;let u=kR(c);u.set(`range`,t),u.set(`surface`,`all`),a!==void 0&&o!==void 0&&(u.set(`since`,String(a)),u.set(`until`,String(o)));let d=await fetch(`${e}/api/usage?${u}`,{signal:n,...l?{cache:`no-store`}:{}});if(n.aborted||r().generation!==i.generation)throw new UR;if(d.status===401)throw N(i.generation),new UR;if(d.status===403)throw new WR;let f=await ei(d);if(n.aborted||r().generation!==i.generation||!HR(f)||!AR(f.sourceFilter,c)||f.range!==t||f.surface!==`all`||l&&!jR(d)||a!==void 0&&(f.customWindow!==!0||f.since!==a||f.until!==o))throw new UR;return f},[e,s,t,i.generation,a,o,l]),d=mf(c,[c],u,{isEmpty:()=>!1,enabled:!i.blocked}),f=d.refresh,p=d.state.refreshing;(0,Z.useEffect)(()=>{if(!l||i.blocked||p)return;let e=setTimeout(()=>f({forceLoading:!0}),15e3);return()=>clearTimeout(e)},[l,i.blocked,p,d.state.kind,f]),(0,Z.useEffect)(()=>{if(!l||i.blocked)return;let t=()=>f({forceLoading:!0}),n=n=>{y(n,e)&&t()};return window.addEventListener(`focus`,t),window.addEventListener(G,n),()=>{window.removeEventListener(`focus`,t),window.removeEventListener(G,n)}},[l,i.blocked,e,f]);let m=d.state.error instanceof UR||d.state.error instanceof WR,h=i.blocked||m&&!d.state.refreshing,g=h||m||l&&(d.state.refreshing||d.state.showError),_=g?void 0:d.state.data,v=h?{...d.state,data:void 0,kind:`failed-cold`,showSkeleton:!1,showError:!0}:(l||m)&&g?{...d.state,data:void 0,kind:d.state.showError&&!d.state.refreshing?`failed-cold`:`cold`,showSkeleton:d.state.refreshing}:d.state;return{...d,data:_,state:v}}var KR={all:``,codex:`Codex`,claude_code:`Claude Code`,claude_desktop:`Claude Desktop`,grok:`Grok`,opencode:`OpenCode`,aside:`Aside`,other:``,unknown:``},qR=(e,t)=>e.kind===t.kind&&(e.kind!==`key`||t.kind===`key`&&e.id===t.id),JR=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,YR=[{kind:`all`},{kind:`no-key`},{kind:`unconfigured`}],XR={codex:`openai.svg`,claude_code:`claude-color.svg`,claude_desktop:`claude-color.svg`,grok:`grok.svg`,opencode:`opencode.svg`,aside:`aside.svg`};function ZR(e){let t=XR[e];return t?(0,Q.jsx)(`img`,{className:MF(t),src:`/provider-icons/${t}`,alt:``}):(0,Q.jsx)(at,{width:16,height:16,"aria-hidden":`true`})}function QR(e){if(![`ArrowDown`,`ArrowUp`,`ArrowLeft`,`ArrowRight`].includes(e.key))return;let t=e.target;if(t.getAttribute(`role`)!==`radio`)return;let n=[...t.closest(`[role="radiogroup"]`)?.querySelectorAll(`[role="radio"]`)??[]],r=n.indexOf(t);if(r<0||!n.length)return;e.preventDefault();let i=n[(r+(e.key===`ArrowDown`||e.key===`ArrowRight`?1:-1)+n.length)%n.length];i?.focus(),i?.click()}function $R(e,t){if(!e||!AR(e.sourceFilter,t)||!e.window||!Number.isFinite(e.window.since)||!MR(e.window)||typeof e.usageIncomplete!=`boolean`||!e.apps||!OR.every(t=>JR(e.apps[t]))||!JR(e.legacyUnclassifiedRequests)||e.unavailableConfiguredKeys!==void 0&&(!JR(e.unavailableConfiguredKeys)||e.unavailableConfiguredKeys>1024)||!Array.isArray(e.devices)||e.devices.length>1027)return!1;let n=new Set,r=new Set,i=0;for(let t of e.devices){if(!t||!JR(t.requests)||!t.device||typeof t.device!=`object`)return!1;let e=t.device;if(e.kind===`key`){if(typeof e.id!=`string`||!e.id||e.id!==e.id.trim()||e.id.length>256||(i+=e.id.length)>65536||Object.keys(e).sort().join(`,`)!==`id,kind`||r.has(e.id))return!1;r.add(e.id)}else{if(![`all`,`no-key`,`unconfigured`].includes(e.kind)||Object.keys(e).join(`,`)!==`kind`||n.has(e.kind))return!1;n.add(e.kind)}}return[`all`,`no-key`,`unconfigured`].every(e=>n.has(e))}function ez({apiBase:e,requested:t,generation:n,identity:i,resultKey:a,setResult:o,setKnownInventory:s,setRoster:c}){let l=!1,u=0,d,f,p=async()=>{let m=++u;f?.abort(),f=new AbortController;let h=f;o({key:a});try{let{facets:d,selectableInventory:f}=await J(6e4,h.signal,async r=>{try{let i=async e=>{let t=await fetch(e,{signal:r,cache:`no-store`});if(t.status===401&&!r.aborted&&m===u&&N(n),!t.ok||!jR(t))throw Error(`usage source unavailable`);return t},[a,o]=await Promise.all([i(`${e}/api/usage/source-facets?${kR(t)}`),i(`${e}/api/usage/devices`)]),s=await a.json();if(!$R(s,t))throw Error(`invalid facets`);let c=await o.json();if(!c||typeof c!=`object`||!Array.isArray(c.devices))throw Error(`invalid inventory`);let l=c.devices;if(l.length>1024)throw Error(`inventory too large`);let d=new Set,f=0;for(let e of l){if(!e||typeof e.apiKeyId!=`string`||!e.apiKeyId||e.apiKeyId.length>256||(f+=e.apiKeyId.length)>65536||d.has(e.apiKeyId)||e.alias!==null&&(typeof e.alias!=`string`||!e.alias.trim()||e.alias.length>255))throw Error(`invalid inventory`);d.add(e.apiKeyId)}return{facets:s,selectableInventory:l.filter(e=>e.apiKeyId===e.apiKeyId.trim())}}catch(e){throw h.abort(),e}});!l&&m===u&&r().generation===n&&(s({identity:i,items:f}),c({identity:i,devices:d.devices.map(e=>e.device)}),o({key:a,facets:d,inventory:f}))}catch{h.abort(),!l&&m===u&&o({key:a,failed:!0})}finally{!l&&m===u&&(d=setTimeout(p,15e3))}};p();let m=()=>{d&&clearTimeout(d),p()},h=t=>{y(t,e)&&m()};return window.addEventListener(`focus`,m),window.addEventListener(G,h),()=>{l=!0,u++,f?.abort(),d&&clearTimeout(d),window.removeEventListener(`focus`,m),window.removeEventListener(G,h)}}function tz({apiBase:e,filter:t,onClient:n,onDevice:r,deviceLocked:i,facetsAllowed:a,homeScope:o,session:s,t:c,locale:l}){let[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)({key:``}),[g,_]=(0,Z.useState)({identity:``,items:[]}),[v,b]=(0,Z.useState)({identity:``,devices:[]}),x=JSON.stringify([e,s.generation]),S=(0,Z.useRef)(null),C=JSON.stringify(t),w=e=>KR[e]||c(e===`all`?`usageV2.allApps`:e===`other`?`usageV2.otherApps`:`usageV2.unknown`),T=JSON.stringify([C,x]),E=!s.blocked&&m.key===T?m:{key:T},D=e=>{if(e.kind===`all`)return c(`usageV2.allDevices`);if(e.kind===`no-key`)return c(o?`usageV2.homeDevice`:xf()===`macos`?`usageV2.thisMac`:`usageV2.thisDevice`);if(e.kind===`unconfigured`)return c(`usageV2.unconfigured`);if(e.kind===`key`){let t=E.inventory??(!s.blocked&&g.identity===x?g.items:[]),n=t.findIndex(t=>t.apiKeyId===e.id),r=t[n],i=E.facets?.devices.filter(e=>e.device.kind===`key`).findIndex(t=>qR(t.device,e))??-1,a=Math.max(1,(r?n:i)+1);return r?.alias?r.alias:c(r?`usageV2.unknownLinkedDevice`:`usageV2.unknownDeviceNumber`,{number:a})}return c(`usageV2.unknown`)};(0,Z.useEffect)(()=>{let t=JSON.parse(C);if(u&&t&&a&&!s.blocked)return ez({apiBase:e,requested:t,generation:s.generation,identity:x,resultKey:T,setResult:h,setKnownInventory:_,setRoster:b})},[u,e,a,C,x,T,s.blocked,s.generation]),(0,Z.useEffect)(()=>{let t=()=>_({identity:``,items:[]}),n=n=>{y(n,e)&&t()},r=()=>{t(),b({identity:``,devices:[]}),h({key:``})};return window.addEventListener(`focus`,t),window.addEventListener(G,n),window.addEventListener(L,r),()=>{window.removeEventListener(`focus`,t),window.removeEventListener(G,n),window.removeEventListener(L,r)}},[e]);let O=e=>e===`codex`?[c(`usageV2.codexDetail`),E.facets&&!E.facets.usageIncomplete?c(`usageV2.codexUnclassified`,{count:E.facets.legacyUnclassifiedRequests.toLocaleString(l)}):null].filter(Boolean).join(` · `):e===`other`?c(`usageV2.otherDetail`):``,k=f.trim().toLocaleLowerCase(l),A=e=>!k||e.toLocaleLowerCase(l).includes(k),j=e=>E.facets&&!E.facets.usageIncomplete&&e!==void 0?e.toLocaleString(l):`—`,M=!s.blocked&&v.identity===x?v.devices:YR,N=t?.device,P=i?t?[t.device]:[]:N&&!M.some(e=>qR(e,N))?[...M,N]:M,F=OR.filter(e=>A(`${w(e)} ${O(e)}`)),I=P.filter(e=>A(D(e))),R=!!t&&F.includes(t.client),z=!!t&&I.some(e=>qR(t.device,e));return(0,Q.jsxs)(Vn.Popup,{open:u,onOpenChange:e=>{d(e),e?p(``):h({key:``})},label:c(`usageV2.source`),initialFocusRef:S,maxHeight:700,className:`ui-v2 overflow-auto rounded-panel bg-raised p-3 text-[13px] text-fg shadow-lg ring-1 ring-line`,onKeyDown:QR,trigger:(0,Q.jsxs)(Q.Fragment,{children:[ZR(t?.client??`all`),(0,Q.jsx)(`span`,{children:w(t?.client??`all`)}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsx)(`span`,{children:t?D(t.device):c(`usageV2.unknown`)})]}),children:[(0,Q.jsx)(`input`,{ref:S,className:`input w-full`,type:`search`,"aria-label":c(`usageV2.searchSources`),placeholder:c(`usageV2.searchSources`),value:f,onChange:e=>p(e.currentTarget.value)}),(0,Q.jsxs)(`div`,{role:`radiogroup`,"aria-label":c(`usageV2.apps`),className:`mt-3`,children:[(0,Q.jsxs)(`div`,{className:`flex justify-between px-2 text-fg-muted`,children:[(0,Q.jsx)(`span`,{children:c(`usageV2.apps`)}),(0,Q.jsx)(`span`,{children:c(`usageV2.last30`)})]}),F.map(e=>{let r=t?.client===e;return(0,Q.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,tabIndex:r||!R&&F[0]===e?0:-1,onClick:()=>n(e),className:X(`flex w-full items-center gap-3 rounded-control px-2 py-1.5 text-left hover:bg-surface focus-visible:outline-2 focus-visible:outline-highlight`,r&&`bg-surface`),children:[(0,Q.jsx)(`span`,{className:`shrink-0 text-fg-muted`,children:ZR(e)}),(0,Q.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`block`,children:w(e)}),O(e)&&(0,Q.jsx)(`span`,{className:`block text-xs text-fg-muted`,children:O(e)})]}),(0,Q.jsx)(`span`,{className:`text-fg-muted tabular-nums`,children:j(E.facets?.apps[e])}),r&&(0,Q.jsx)(st,{width:16,height:16,"aria-hidden":`true`})]},e)})]}),(0,Q.jsxs)(`div`,{role:`radiogroup`,"aria-label":c(`usageV2.devices`),className:`mt-3 border-t border-line pt-3`,children:[(0,Q.jsxs)(`div`,{className:`flex justify-between px-2 text-fg-muted`,children:[(0,Q.jsx)(`span`,{children:c(`usageV2.devices`)}),(0,Q.jsx)(`span`,{children:c(`usageV2.last30`)})]}),I.map(e=>{let n=!!t&&qR(t.device,e),a=e.kind===`key`&&E.inventory?.some(t=>t.apiKeyId===e.id);return(0,Q.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,tabIndex:t&&(n||!z&&I[0]===e)?0:-1,onClick:()=>r(e),disabled:i,className:X(`flex w-full items-center gap-3 rounded-control px-2 py-1.5 text-left hover:bg-surface focus-visible:outline-2 focus-visible:outline-highlight`,n&&`bg-surface`),children:[(0,Q.jsx)(`span`,{className:`shrink-0 text-fg-muted`,children:e.kind===`key`?(0,Q.jsx)(Pc,{icon:Uc,size:16,"aria-hidden":`true`}):e.kind===`unconfigured`?(0,Q.jsx)(fe,{width:16,height:16,"aria-hidden":`true`}):(0,Q.jsx)(Oe,{width:16,height:16,"aria-hidden":`true`})}),(0,Q.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`block`,children:D(e)}),a&&(0,Q.jsx)(`span`,{className:`block text-xs text-fg-muted`,children:c(`usageV2.remoteLink`)})]}),(0,Q.jsx)(`span`,{className:`text-fg-muted tabular-nums`,children:j(E.facets?.devices.find(t=>qR(t.device,e))?.requests)}),n&&(0,Q.jsx)(st,{width:16,height:16,"aria-hidden":`true`})]},e.kind===`key`?`key:${e.id}`:e.kind)})]}),(0,Q.jsx)(`p`,{className:`mb-0 mt-3 border-t border-line pt-3 text-fg-muted`,children:c(i?`usageV2.locked`:`usageV2.noKeyHelp`)}),!i&&(0,Q.jsx)(`p`,{className:`mb-0 text-fg-muted`,children:c(`usageV2.unconfiguredHelp`)}),(0,Q.jsx)(`p`,{className:`mb-0 text-fg-muted`,children:c(`usageV2.classificationHelp`)}),!!E.facets?.unavailableConfiguredKeys&&(0,Q.jsx)(`p`,{role:`status`,className:`mb-0 text-fg-muted`,children:c(`usageV2.unavailableKeys`,{count:E.facets.unavailableConfiguredKeys.toLocaleString(l)})}),(E.failed||E.facets?.usageIncomplete||!a)&&(0,Q.jsx)(`p`,{role:`status`,className:`mb-0 text-fg-muted`,children:c(`usageV2.countsUnavailable`)})]})}function nz({filtered:e,t}){return(0,Q.jsxs)(`div`,{className:`ui-v2 flex flex-col items-center justify-center gap-1 rounded-[12px] bg-surface px-6 py-14 text-center ring-1 ring-line`,children:[(0,Q.jsx)(`span`,{className:`mb-2 grid size-10 place-items-center rounded-control bg-raised text-fg-muted shadow-sm ring-1 ring-line dark:bg-surface-2`,"aria-hidden":`true`,children:(0,Q.jsx)(Pc,{icon:Ic,size:20,strokeWidth:1.8})}),(0,Q.jsx)(`p`,{className:`m-0 max-w-[48ch] text-[15px] font-medium text-fg text-balance`,children:t(`usage.empty`)}),e&&(0,Q.jsx)(`p`,{className:`m-0 max-w-[48ch] text-[13px] text-fg-muted`,children:t(`usageV2.emptyFiltered`)})]})}function rz({data:e,range:t,customWindow:n,bars:r,activeDays:i,filteredModels:a,modelQuery:o,onModelQuery:s,sortedProviders:c,allApps:l,filtered:u,locale:d,t:f}){let p=(0,Z.useMemo)(()=>CL(e?.days??[],n),[e?.days,n]);if(!e)return null;if(e.summary.requests===0)return(0,Q.jsx)(nz,{filtered:u,t:f});let m=n||t===`all`?`calendar`:`bars`,h=[{id:`overview`,body:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(DL,{summary:e.summary,days:r,activeDays:i,locale:d,t:f}),(0,Q.jsx)(ML,{defaultView:m,heatmap:p,bars:r,totalTokens:e.summary.totalTokens,locale:d,t:f},`${t}:${n}`)]})},{id:`models`,body:(0,Q.jsx)(IL,{models:a,totalModels:e.models.length,modelQuery:o,onModelQuery:s,locale:d,t:f})},{id:`providers`,body:(0,Q.jsx)(RL,{providers:c,locale:d,t:f})},...l?[{id:`apps`,body:(0,Q.jsx)(LL,{apps:e.apps,locale:d,t:f})}]:[],{id:`coverage`,body:(0,Q.jsx)(zL,{summary:e.summary,locale:d,t:f})}];return(0,Q.jsx)(`div`,{className:`usage-workspace-root`,children:(0,Q.jsx)(`section`,{className:`usage-workspace-main flex flex-col gap-4`,"aria-label":f(`usage.workspace.report`),children:h.map(e=>(0,Q.jsx)(`div`,{id:PN(`usage`,e.id),className:`usw-body usw-section-block flex flex-col gap-4`,children:e.body},e.id))})})}function iz({apiBase:e,connected:t=!1,apiKeyId:n,topology:r=t?`unknown`:`home`}){let{t:i,locale:a}=s(),[o,c]=(0,Z.useState)(CR);(0,Z.useEffect)(()=>{let e=()=>c(CR());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let[l,u]=(0,Z.useState)(`30d`),[d,f]=(0,Z.useState)(`all`),[p,m]=(0,Z.useState)({kind:`all`}),[h,g]=(0,Z.useState)(`machine`),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)({since:``,until:``}),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(!1),D=x?.since,O=x?.until,k=()=>{S(null),b({since:``,until:``}),w(null)},A=e=>{u(e),k()},j=()=>{let e=cL(y.since,y.until);e.ok===!1?w(e.error):(w(null),S(e.window))},M=t&&(h===`machine`||r===`link`||r===`unknown`),N=M?n?.trim()&&n===n.trim()?{kind:`key`,id:n}:null:p,P=N?{client:d,device:N}:null,F=DR(),I=GR(e,l,P,F,D,O),{state:L}=I,R=I.data??null,z=(0,Z.useMemo)(()=>{let e=R?.days??[];return x||l===`all`?e.toSorted((e,t)=>e.date.localeCompare(t.date)):gL(e,l===`7d`?7:30)},[R?.days,x,l]),B=(0,Z.useMemo)(()=>(R?.days??[]).filter(e=>e.requests>0).length,[R?.days]),V=(0,Z.useMemo)(()=>{let e=_.trim().toLowerCase(),t=(R?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[R?.models,_]),H=(0,Z.useMemo)(()=>(R?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[R?.providers]);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head usage-head`,children:(0,Q.jsx)(`h2`,{id:`usage-page-title`,children:i(`usage.title`)})}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`nav.usage`),children:[`report`,`companion`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`usage-tab-${e}`,"aria-selected":o===e,"aria-controls":`usage-panel-${e}`,tabIndex:o===e?0:-1,className:`page-tab${o===e?` page-tab--active`:``}`,onClick:()=>wR(e),onKeyDown:TR,children:i(e===`report`?`usage.workspace.report`:`usage.section.companion`)},e))}),o===`companion`?(0,Q.jsx)(`div`,{role:`tabpanel`,id:`usage-panel-companion`,"aria-labelledby":`usage-tab-companion`,children:(0,Q.jsx)(SR,{apiBase:e,providers:R?.providers??[]})}):(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`usage-panel-report`,"aria-labelledby":`usage-tab-report`,className:`usage-v2 usage-workspace-shell flex flex-col gap-4`,children:[(0,Q.jsx)(`p`,{className:`page-sub m-0 text-[13px]`,children:i(`usage.subtitle`)}),(0,Q.jsxs)(`section`,{className:`usage-range flex flex-col gap-3`,children:[(0,Q.jsxs)(qL,{children:[(0,Q.jsx)(tz,{apiBase:e,filter:P,onClient:f,onDevice:m,session:F,deviceLocked:M,facetsAllowed:r===`home`||r===`hub`,homeScope:t,t:i,locale:a}),(0,Q.jsx)(VL,{range:x?null:l,onRange:A,t:i}),(0,Q.jsx)(UL,{open:T,active:x!==null,onToggle:()=>{T&&w(null),E(!T)},t:i}),t&&r===`hub`&&(0,Q.jsx)(`div`,{className:`ml-auto`,children:(0,Q.jsx)(HL,{scope:h,onScope:e=>{g(e),m({kind:`all`})},t:i})}),x&&(0,Q.jsx)(WL,{window:x,locale:a,t:i})]}),T&&(0,Q.jsx)(KL,{draft:y,error:C,onDraft:e=>{b(t=>({...t,...e})),w(null)},onApply:j,onClear:k,t:i})]}),L.showSkeleton&&!R?(0,Q.jsx)(ck,{label:i(`usage.loading`),rows:6,className:`usage-v2-skeleton`}):L.kind===`failed-cold`?(0,Q.jsxs)(`div`,{className:`ui-v2 flex flex-col items-center gap-3 rounded-[12px] bg-surface px-6 py-12 text-center ring-1 ring-line`,role:`alert`,children:[(0,Q.jsx)(`span`,{className:`grid size-10 place-items-center rounded-control bg-danger-soft text-danger [&_svg]:size-5`,"aria-hidden":`true`,children:(0,Q.jsx)(St,{})}),(0,Q.jsx)(`p`,{className:`m-0 max-w-[56ch] text-[14px] text-fg`,children:L.error instanceof UR?`${i(`usage.loadError`)} ${i(`dash.codexRestartMalformed`)}`:L.error instanceof $r||L.error instanceof WR?i(`usage.loadError`):t?i(`usage.hubOffline`):L.error instanceof Error?`${i(`usage.loadError`)} ${L.error.message}`:i(`usage.loadError`)}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:()=>I.refresh(),children:i(`common.retry`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[L.showError&&(0,Q.jsx)($,{tone:`err`,children:i(t&&!(L.error instanceof $r)?`usage.hubOffline`:`usage.loadError`)}),(0,Q.jsx)(ni,{data:R}),(d===`grok`||d===`aside`||d===`other`)&&(0,Q.jsx)(`p`,{className:`text-fg-muted text-[13px]`,role:`status`,children:i(`usageV2.clientUnverified`)}),d===`codex`&&typeof R?.legacyUnclassifiedRequests==`number`&&(0,Q.jsx)(`p`,{className:`text-fg-muted text-[13px]`,role:`status`,children:i(`usageV2.legacy`,{count:R.legacyUnclassifiedRequests})}),R?.historyTruncated&&(0,Q.jsx)($,{tone:`warn`,children:(()=>{let e=az(R.snapshotWindowStart),t=az(R.snapshotWindowEnd);return e!==null&&t!==null?i(`usage.historyTruncatedWindow`,{start:e,end:t}):i(`usage.historyTruncated`)})()}),(0,Q.jsx)(rz,{data:R,range:l,customWindow:x!==null,bars:z,activeDays:B,filteredModels:V,modelQuery:_,onModelQuery:v,sortedProviders:H,allApps:d===`all`,filtered:d!==`all`||N?.kind!==`all`||l!==`all`||x!==null,locale:a,t:i})]})]})]})}function az(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function oz(e,t){if(e<1024)return`${e} B`;let n=[`KiB`,`MiB`,`GiB`,`TiB`],r=e,i=-1;do r/=1024,i++;while(r>=1024&&i<n.length-1);return`${r.toLocaleString(t,{maximumFractionDigits:1})} ${n[i]}`}var sz={en:{compact:`Compact`,compactComplete:`Compaction complete (logical / on-disk reclaimed)`,pagesUnit:`pages`,compactPartial:`Compaction partial (logical / on-disk reclaimed)`,confirmCompact:`Confirm compaction`,cancel:`Cancel`,inspectionOnly:`Inspection only`,externalSqliteHome:`External SQLite storage`,inspectionUnavailable:`Diagnostic log inspection is unavailable.`,metricsSkippedLarge:`Row metrics skipped: the database is above {threshold}, and scanning it would stall the proxy.`,protection:`Protection`,compat:`Compatibility`,quiet:`Quiet`,disable:`Disable protection`,repair:`Repair protection`,applying:`Applying protection…`,"error.generic":`Could not change Codex log protection.`,"error.codex_running":`Quit Codex before changing log protection.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. Protection was not changed.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for protection.`,"error.trigger_collision":`A reserved Log Guard trigger name is already in use. Protection was not changed.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.config_write_failed":`The database changed, but OpenCodex could not save the protection setting. Fix config storage, then run Repair.`},de:{compact:`Komprimieren`,compactComplete:`Komprimierung abgeschlossen (logisch / auf Datentraeger freigegeben)`,pagesUnit:`Seiten`,compactPartial:`Komprimierung teilweise (logisch / auf Datentraeger freigegeben)`,confirmCompact:`Komprimierung bestätigen`,cancel:`Abbrechen`,inspectionOnly:`Nur Inspektion`,externalSqliteHome:`Externer SQLite-Speicher`,inspectionUnavailable:`Die Diagnoseprotokoll-Inspektion ist nicht verfügbar.`,metricsSkippedLarge:`Zeilenmetriken übersprungen: Die Datenbank ist größer als {threshold}; ein Scan würde den Proxy blockieren.`,protection:`Schutz`,compat:`Kompatibilität`,quiet:`Leise`,disable:`Schutz deaktivieren`,repair:`Schutz reparieren`,applying:`Schutz wird angewendet…`,"error.generic":`Der Schutz der Codex-Protokolle konnte nicht geändert werden.`,"error.codex_running":`Beende Codex, bevor du den Protokollschutz änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Schutz wurde nicht geändert.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für den Schutz nicht unterstützt.`,"error.trigger_collision":`Ein reservierter Log-Guard-Triggername wird bereits verwendet. Der Schutz wurde nicht geändert.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.config_write_failed":`Die Datenbank wurde geändert, aber OpenCodex konnte die Schutzeinstellung nicht speichern. Repariere den Konfigurationsspeicher und führe danach Reparieren aus.`},fr:{compact:`Compacter`,compactComplete:`Compactage termine (logique / recupere sur disque)`,pagesUnit:`pages`,compactPartial:`Compactage partiel (logique / recupere sur disque)`,confirmCompact:`Confirmer le compactage`,cancel:`Annuler`,inspectionOnly:`Inspection uniquement`,externalSqliteHome:`Stockage SQLite externe`,inspectionUnavailable:`L’inspection des journaux de diagnostic est indisponible.`,metricsSkippedLarge:`Métriques de lignes ignorées : la base dépasse {threshold} et son analyse bloquerait le proxy.`,protection:`Protection`,compat:`Compatibilité`,quiet:`Silencieux`,disable:`Désactiver la protection`,repair:`Réparer la protection`,applying:`Application de la protection…`,"error.generic":`Impossible de modifier la protection des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier la protection des journaux.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. La protection n’a pas été modifiée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour la protection.`,"error.trigger_collision":`Un nom de déclencheur Log Guard réservé est déjà utilisé. La protection n’a pas été modifiée.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.config_write_failed":`La base de données a été modifiée, mais OpenCodex n’a pas pu enregistrer le paramètre de protection. Corrigez le stockage de configuration, puis lancez Réparer.`},ko:{compact:`압축`,compactComplete:`압축 완료 (논리 / 디스크 회수량)`,pagesUnit:`페이지`,compactPartial:`압축 부분 완료 (논리 / 디스크 회수량)`,confirmCompact:`압축 확인`,cancel:`취소`,inspectionOnly:`검사 전용`,externalSqliteHome:`외부 SQLite 저장소`,inspectionUnavailable:`진단 로그 검사를 사용할 수 없습니다.`,metricsSkippedLarge:`행 지표를 건너뛰었습니다. 데이터베이스가 {threshold}보다 커서 스캔하면 프록시가 멈춥니다.`,protection:`보호`,compat:`호환 모드`,quiet:`조용한 모드`,disable:`보호 비활성화`,repair:`보호 복구`,applying:`보호 적용 중…`,"error.generic":`Codex 로그 보호를 변경하지 못했습니다.`,"error.codex_running":`로그 보호를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 보호를 변경하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 보호 기능을 지원하지 않습니다.`,"error.trigger_collision":`예약된 Log Guard 트리거 이름이 이미 사용 중입니다. 보호를 변경하지 않았습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.config_write_failed":`데이터베이스는 변경되었지만 OpenCodex가 보호 설정을 저장하지 못했습니다. 구성 저장소를 수정한 뒤 복구를 실행하세요.`},zh:{compact:`压缩`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`页`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`确认压缩`,cancel:`取消`,inspectionOnly:`仅检查`,externalSqliteHome:`外部 SQLite 存储`,inspectionUnavailable:`诊断日志检查当前不可用。`,metricsSkippedLarge:`已跳过行指标:数据库超过 {threshold},扫描会阻塞代理。`,protection:`保护`,compat:`兼容模式`,quiet:`静默模式`,disable:`禁用保护`,repair:`修复保护`,applying:`正在应用保护…`,"error.generic":`无法更改 Codex 日志保护。`,"error.codex_running":`更改 Codex 日志保护前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未更改保护设置。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持保护功能。`,"error.trigger_collision":`保留的 Log Guard 触发器名称已被占用,因此未更改保护设置。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.config_write_failed":`数据库已更改,但 OpenCodex 无法保存保护设置。请先修复配置存储,然后运行“修复保护”。`},"zh-TW":{compact:`壓縮`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`頁`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`確認壓縮`,cancel:`取消`,inspectionOnly:`僅檢查`,externalSqliteHome:`外部 SQLite 儲存空間`,inspectionUnavailable:`診斷記錄檢查目前無法使用。`,metricsSkippedLarge:`已略過列指標:資料庫超過 {threshold},掃描會阻塞代理。`,protection:`保護`,compat:`相容模式`,quiet:`靜默模式`,disable:`停用保護`,repair:`修復保護`,applying:`正在套用保護…`,"error.generic":`無法變更 Codex 日誌保護。`,"error.codex_running":`變更 Codex 日誌保護前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未變更保護設定。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援保護功能。`,"error.trigger_collision":`保留的 Log Guard 觸發器名稱已被使用,因此未變更保護設定。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.config_write_failed":`資料庫已變更,但 OpenCodex 無法儲存保護設定。請先修復設定儲存空間,再執行「修復保護」。`},ru:{compact:`Сжать`,compactComplete:`Сжатие завершено (логически / освобождено на диске)`,pagesUnit:`страниц`,compactPartial:`Сжатие частичное (логически / освобождено на диске)`,confirmCompact:`Подтвердить сжатие`,cancel:`Отмена`,inspectionOnly:`Только проверка`,externalSqliteHome:`Внешнее хранилище SQLite`,inspectionUnavailable:`Проверка диагностических журналов недоступна.`,metricsSkippedLarge:`Метрики строк пропущены: база больше {threshold}, и её сканирование заблокировало бы прокси.`,protection:`Защита`,compat:`Совместимость`,quiet:`Тихий режим`,disable:`Отключить защиту`,repair:`Восстановить защиту`,applying:`Применение защиты…`,"error.generic":`Не удалось изменить защиту журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением защиты журналов.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Защита не изменена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает защиту.`,"error.trigger_collision":`Зарезервированное имя триггера Log Guard уже используется. Защита не изменена.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.config_write_failed":`База была изменена, но OpenCodex не смог сохранить настройку защиты. Исправьте хранилище конфигурации и затем запустите восстановление.`},ja:{compact:`圧縮`,compactComplete:`圧縮完了(論理 / ディスク解放)`,pagesUnit:`ページ`,compactPartial:`圧縮は部分的に完了(論理 / ディスク解放)`,confirmCompact:`圧縮を確認`,cancel:`キャンセル`,inspectionOnly:`検査のみ`,externalSqliteHome:`外部 SQLite ストレージ`,inspectionUnavailable:`診断ログの検査を利用できません。`,metricsSkippedLarge:`行メトリクスをスキップしました。データベースが {threshold} を超えており、走査するとプロキシが停止します。`,protection:`保護`,compat:`互換モード`,quiet:`静音モード`,disable:`保護を無効化`,repair:`保護を修復`,applying:`保護を適用中…`,"error.generic":`Codex ログ保護を変更できませんでした。`,"error.codex_running":`ログ保護を変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、保護は変更されませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマでは保護機能を使用できません。`,"error.trigger_collision":`予約済みの Log Guard トリガー名が既に使用されています。保護は変更されませんでした。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.config_write_failed":`データベースは変更されましたが、OpenCodex は保護設定を保存できませんでした。設定ストレージを修正してから保護を修復してください。`},tr:{compact:`Sıkıştır`,compactComplete:`Sikistirma tamamlandi (mantiksal / diskte geri kazanilan)`,pagesUnit:`sayfa`,compactPartial:`Sikistirma kismi (mantiksal / diskte geri kazanilan)`,confirmCompact:`Sıkıştırmayı onayla`,cancel:`İptal`,inspectionOnly:`Yalnızca inceleme`,externalSqliteHome:`Harici SQLite depolaması`,inspectionUnavailable:`Tanılama günlüğü incelemesi kullanılamıyor.`,metricsSkippedLarge:`Satır ölçümleri atlandı: veritabanı {threshold} sınırının üzerinde ve taranması proxy’yi kilitler.`,protection:`Koruma`,compat:`Uyumluluk`,quiet:`Sessiz`,disable:`Korumayı devre dışı bırak`,repair:`Korumayı onar`,applying:`Koruma uygulanıyor…`,"error.generic":`Codex günlük koruması değiştirilemedi.`,"error.codex_running":`Günlük korumasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Koruma değiştirilmedi.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması koruma için desteklenmiyor.`,"error.trigger_collision":`Ayrılmış bir Log Guard tetikleyici adı zaten kullanılıyor. Koruma değiştirilmedi.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.config_write_failed":`Veritabanı değişti ancak OpenCodex koruma ayarını kaydedemedi. Yapılandırma depolamasını düzeltip ardından korumayı onarın.`},vi:{compact:`Nén`,compactComplete:`Hoàn tất nén (logic / thu hồi trên đĩa)`,pagesUnit:`trang`,compactPartial:`Nén một phần (logic / thu hồi trên đĩa)`,confirmCompact:`Xác nhận nén`,cancel:`Hủy`,inspectionOnly:`Chỉ kiểm tra`,externalSqliteHome:`Lưu trữ SQLite bên ngoài`,inspectionUnavailable:`Tính năng kiểm tra nhật ký chẩn đoán không khả dụng.`,metricsSkippedLarge:`Đã bỏ qua số liệu hàng: cơ sở dữ liệu lớn hơn {threshold} và việc quét sẽ làm treo proxy.`,protection:`Bảo vệ`,compat:`Tương thích`,quiet:`Yên tĩnh`,disable:`Tắt bảo vệ`,repair:`Sửa chữa bảo vệ`,applying:`Đang áp dụng bảo vệ…`,"error.generic":`Không thể thay đổi bảo vệ nhật ký Codex.`,"error.codex_running":`Hãy thoát Codex trước khi thay đổi bảo vệ nhật ký.`,"error.process_enumeration_failed":`Không thể xác minh rằng Codex đã dừng. Bảo vệ chưa được thay đổi.`,"error.busy":`Cơ sở dữ liệu nhật ký Codex đang bận. Hãy thoát Codex và thử lại.`,"error.unsupported_schema":`Lược đồ nhật ký Codex này không được hỗ trợ để bảo vệ.`,"error.trigger_collision":`Tên trình kích hoạt Log Guard dành riêng đã được sử dụng. Bảo vệ chưa được thay đổi.`,"error.unsafe_path":`Đường dẫn cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra an toàn.`,"error.database_error":`Không thể cập nhật cơ sở dữ liệu nhật ký Codex.`,"error.config_write_failed":`Cơ sở dữ liệu đã thay đổi nhưng OpenCodex không thể lưu cài đặt bảo vệ. Vui lòng sửa lỗi lưu trữ cấu hình, sau đó chạy Sửa chữa.`},pt:{compact:`Compactar`,compactComplete:`Compactação concluída (lógico / recuperado em disco)`,pagesUnit:`páginas`,compactPartial:`Compactação parcial (lógico / recuperado em disco)`,confirmCompact:`Confirmar compactação`,cancel:`Cancelar`,inspectionOnly:`Somente inspeção`,externalSqliteHome:`Armazenamento SQLite externo`,inspectionUnavailable:`A inspeção do log de diagnóstico não está disponível.`,metricsSkippedLarge:`Métricas de linhas ignoradas: o banco de dados excede {threshold} e a varredura travaria o proxy.`,protection:`Proteção`,compat:`Compatibilidade`,quiet:`Silencioso`,disable:`Desativar proteção`,repair:`Reparar proteção`,applying:`Aplicando proteção…`,"error.generic":`Não foi possível alterar a proteção de logs do Codex.`,"error.codex_running":`Feche o Codex antes de alterar a proteção de logs.`,"error.process_enumeration_failed":`Não foi possível verificar se o Codex está parado. A proteção não foi alterada.`,"error.busy":`O banco de dados de logs do Codex está ocupado. Feche o Codex e tente novamente.`,"error.unsupported_schema":`Este esquema de logs do Codex não é suportado para proteção.`,"error.trigger_collision":`Um nome de trigger reservado do Log Guard já está em uso. A proteção não foi alterada.`,"error.unsafe_path":`O caminho do banco de dados de logs do Codex falhou na verificação de segurança.`,"error.database_error":`Não foi possível atualizar o banco de dados de logs do Codex.`,"error.config_write_failed":`O banco de dados foi alterado, mas o OpenCodex não conseguiu salvar a configuração de proteção. Corrija o armazenamento de configuração e execute Reparar.`}};function cz(e,t){return sz[e][t]}var lz={en:{applying:`Applying Log Guard change…`,"error.generic":`Could not update Codex log storage.`,"error.codex_running":`Quit Codex before changing Codex log storage.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. The Log Guard operation was not started.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for this operation.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.auto_vacuum_not_incremental":`This Codex logs database is not configured for incremental vacuum, so space cannot be reclaimed without a full rebuild.`,"error.integrity_check_failed":`The Codex logs database failed its integrity check. No space was reclaimed.`},de:{applying:`Log-Guard-Änderung wird angewendet…`,"error.generic":`Der Codex-Protokollspeicher konnte nicht aktualisiert werden.`,"error.codex_running":`Beende Codex, bevor du den Codex-Protokollspeicher änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Log-Guard-Vorgang wurde nicht gestartet.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für diesen Vorgang nicht unterstützt.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.auto_vacuum_not_incremental":`Diese Codex-Protokolldatenbank ist nicht fuer inkrementelles Vacuum konfiguriert; ohne vollstaendigen Neuaufbau kann kein Speicher freigegeben werden.`,"error.integrity_check_failed":`Die Integritaetspruefung der Codex-Protokolldatenbank ist fehlgeschlagen. Es wurde kein Speicher freigegeben.`},fr:{applying:`Application de la modification Log Guard…`,"error.generic":`Impossible de mettre à jour le stockage des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier le stockage des journaux Codex.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. L’opération Log Guard n’a pas été lancée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour cette opération.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.auto_vacuum_not_incremental":`Cette base de donnees de journaux Codex n'est pas configuree pour le vacuum incrementiel : l'espace ne peut pas etre recupere sans reconstruction complete.`,"error.integrity_check_failed":`La verification d'integrite de la base de donnees de journaux Codex a echoue. Aucun espace n'a ete recupere.`},ko:{applying:`Log Guard 변경 적용 중…`,"error.generic":`Codex 로그 저장소를 업데이트하지 못했습니다.`,"error.codex_running":`Codex 로그 저장소를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 Log Guard 작업을 시작하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 이 작업을 지원하지 않습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.auto_vacuum_not_incremental":`이 Codex 로그 데이터베이스는 증분 정리로 구성되어 있지 않아, 전체 재구축 없이는 공간을 회수할 수 없습니다.`,"error.integrity_check_failed":`Codex 로그 데이터베이스 무결성 검사에 실패했습니다. 공간이 회수되지 않았습니다.`},zh:{applying:`正在应用 Log Guard 更改…`,"error.generic":`无法更新 Codex 日志存储。`,"error.codex_running":`更改 Codex 日志存储前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未启动 Log Guard 操作。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持此操作。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},"zh-TW":{applying:`正在套用 Log Guard 變更…`,"error.generic":`無法更新 Codex 日誌儲存空間。`,"error.codex_running":`變更 Codex 日誌儲存空間前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未啟動 Log Guard 操作。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援此操作。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},ru:{applying:`Применение изменения Log Guard…`,"error.generic":`Не удалось обновить хранилище журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением хранилища журналов Codex.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Операция Log Guard не запущена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает эту операцию.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.auto_vacuum_not_incremental":`Эта база данных журналов Codex не настроена на инкрементальную очистку, поэтому освободить место без полной перестройки невозможно.`,"error.integrity_check_failed":`Проверка целостности базы данных журналов Codex не пройдена. Место не освобождено.`},ja:{applying:`Log Guard の変更を適用中…`,"error.generic":`Codex ログストレージを更新できませんでした。`,"error.codex_running":`Codex ログストレージを変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、Log Guard 操作を開始しませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマではこの操作を使用できません。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.auto_vacuum_not_incremental":`この Codex ログ データベースは増分バキューム用に構成されていないため、完全な再構築なしに領域を解放できません。`,"error.integrity_check_failed":`Codex ログ データベースの整合性チェックに失敗しました。領域は解放されていません。`},tr:{applying:`Log Guard değişikliği uygulanıyor…`,"error.generic":`Codex günlük depolaması güncellenemedi.`,"error.codex_running":`Codex günlük depolamasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Log Guard işlemi başlatılmadı.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması bu işlem için desteklenmiyor.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.auto_vacuum_not_incremental":`Bu Codex gunluk veritabani artimli vacuum icin yapilandirilmamis; tam yeniden olusturma olmadan alan geri kazanilamaz.`,"error.integrity_check_failed":`Codex gunluk veritabani butunluk denetiminden gecemedi. Alan geri kazanilmadi.`},vi:{applying:`Đang áp dụng thay đổi Log Guard…`,"error.generic":`Không thể cập nhật lưu trữ nhật ký Codex.`,"error.codex_running":`Hãy thoát Codex trước khi thay đổi lưu trữ nhật ký Codex.`,"error.process_enumeration_failed":`Không thể xác minh rằng Codex đã dừng. Thao tác Log Guard chưa được bắt đầu.`,"error.busy":`Cơ sở dữ liệu nhật ký Codex đang bận. Hãy thoát Codex và thử lại.`,"error.unsupported_schema":`Lược đồ nhật ký Codex này không được hỗ trợ cho thao tác này.`,"error.unsafe_path":`Đường dẫn cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra an toàn.`,"error.database_error":`Không thể cập nhật cơ sở dữ liệu nhật ký Codex.`,"error.auto_vacuum_not_incremental":`Cơ sở dữ liệu nhật ký Codex này không được định cấu hình cho tính năng incremental vacuum, do đó không thể thu hồi dung lượng nếu không xây dựng lại hoàn toàn.`,"error.integrity_check_failed":`Cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra tính toàn vẹn. Không có dung lượng nào được thu hồi.`},pt:{applying:`Aplicando alteração do Log Guard…`,"error.generic":`Não foi possível atualizar o armazenamento de logs do Codex.`,"error.codex_running":`Feche o Codex antes de alterar o armazenamento de logs do Codex.`,"error.process_enumeration_failed":`Não foi possível verificar se o Codex está parado. A operação do Log Guard não foi iniciada.`,"error.busy":`O banco de dados de logs do Codex está ocupado. Feche o Codex e tente novamente.`,"error.unsupported_schema":`Este esquema de logs do Codex não é suportado para esta operação.`,"error.unsafe_path":`O caminho do banco de dados de logs do Codex falhou na verificação de segurança.`,"error.database_error":`Não foi possível atualizar o banco de dados de logs do Codex.`,"error.auto_vacuum_not_incremental":`Este banco de dados de logs do Codex não está configurado para incremental vacuum; por isso, não é possível recuperar espaço sem uma reconstrução completa.`,"error.integrity_check_failed":`O banco de dados de logs do Codex falhou na verificação de integridade. Nenhum espaço foi recuperado.`}};function uz(e,t){return lz[e][t]}var dz={en:{schema:{compatible:`Compatible`,missing:`Database not found`,unreadable:`Database unavailable`,unsupported:`Unsupported`},protection:{off:`Off`,active:`Active`,drifted:`Needs repair`,unsupported:`Unsupported`,unknown:`Unknown`},mode:{off:`Off`,compat:`Compatibility`,quiet:`Quiet`,collision:`Unknown`}},de:{schema:{compatible:`Kompatibel`,missing:`Datenbank nicht gefunden`,unreadable:`Datenbank nicht lesbar`,unsupported:`Nicht unterstützt`},protection:{off:`Aus`,active:`Aktiv`,drifted:`Reparatur erforderlich`,unsupported:`Nicht unterstützt`,unknown:`Unbekannt`},mode:{off:`Aus`,compat:`Kompatibilität`,quiet:`Leise`,collision:`Unbekannt`}},fr:{schema:{compatible:`Compatible`,missing:`Base de données introuvable`,unreadable:`Base de données indisponible`,unsupported:`Non pris en charge`},protection:{off:`Désactivée`,active:`Active`,drifted:`Réparation requise`,unsupported:`Non prise en charge`,unknown:`Inconnue`},mode:{off:`Désactivé`,compat:`Compatibilité`,quiet:`Silencieux`,collision:`Inconnu`}},ko:{schema:{compatible:`호환됨`,missing:`데이터베이스 없음`,unreadable:`데이터베이스를 읽을 수 없음`,unsupported:`지원되지 않음`},protection:{off:`꺼짐`,active:`활성`,drifted:`복구 필요`,unsupported:`지원되지 않음`,unknown:`알 수 없음`},mode:{off:`꺼짐`,compat:`호환 모드`,quiet:`조용한 모드`,collision:`알 수 없음`}},zh:{schema:{compatible:`兼容`,missing:`未找到数据库`,unreadable:`无法读取数据库`,unsupported:`不受支持`},protection:{off:`关闭`,active:`已启用`,drifted:`需要修复`,unsupported:`不受支持`,unknown:`未知`},mode:{off:`关闭`,compat:`兼容模式`,quiet:`静默模式`,collision:`未知`}},"zh-TW":{schema:{compatible:`相容`,missing:`找不到資料庫`,unreadable:`無法讀取資料庫`,unsupported:`不支援`},protection:{off:`關閉`,active:`已啟用`,drifted:`需要修復`,unsupported:`不支援`,unknown:`未知`},mode:{off:`關閉`,compat:`相容模式`,quiet:`靜默模式`,collision:`未知`}},ru:{schema:{compatible:`Совместимо`,missing:`База не найдена`,unreadable:`База недоступна`,unsupported:`Не поддерживается`},protection:{off:`Выключено`,active:`Активно`,drifted:`Требуется восстановление`,unsupported:`Не поддерживается`,unknown:`Неизвестно`},mode:{off:`Выключено`,compat:`Совместимость`,quiet:`Тихий режим`,collision:`Неизвестно`}},ja:{schema:{compatible:`互換`,missing:`データベースが見つかりません`,unreadable:`データベースを読み取れません`,unsupported:`未対応`},protection:{off:`オフ`,active:`有効`,drifted:`修復が必要`,unsupported:`未対応`,unknown:`不明`},mode:{off:`オフ`,compat:`互換モード`,quiet:`静音モード`,collision:`不明`}},tr:{schema:{compatible:`Uyumlu`,missing:`Veritabanı bulunamadı`,unreadable:`Veritabanı okunamıyor`,unsupported:`Desteklenmiyor`},protection:{off:`Kapalı`,active:`Etkin`,drifted:`Onarım gerekli`,unsupported:`Desteklenmiyor`,unknown:`Bilinmiyor`},mode:{off:`Kapalı`,compat:`Uyumluluk`,quiet:`Sessiz`,collision:`Bilinmiyor`}},vi:{schema:{compatible:`Tương thích`,missing:`Không tìm thấy cơ sở dữ liệu`,unreadable:`Cơ sở dữ liệu không khả dụng`,unsupported:`Không được hỗ trợ`},protection:{off:`Tắt`,active:`Đang hoạt động`,drifted:`Cần sửa chữa`,unsupported:`Không được hỗ trợ`,unknown:`Không xác định`},mode:{off:`Tắt`,compat:`Tương thích`,quiet:`Yên tĩnh`,collision:`Không xác định`}},pt:{schema:{compatible:`Compatível`,missing:`Banco de dados não encontrado`,unreadable:`Banco de dados indisponível`,unsupported:`Não suportado`},protection:{off:`Desativada`,active:`Ativa`,drifted:`Requer reparo`,unsupported:`Não suportada`,unknown:`Desconhecida`},mode:{off:`Desativado`,compat:`Compatibilidade`,quiet:`Silencioso`,collision:`Desconhecido`}}};function fz(e,t){return dz[e].schema[t]}function pz(e,t){return dz[e].protection[t]}function mz(e,t){return dz[e].mode[t]}var hz={sessions:`storage.bucket.sessions`,archived_sessions:`storage.bucket.archived_sessions`,logs_db:`storage.bucket.logs_db`,state_db:`storage.bucket.state_db`,attachments:`storage.bucket.attachments`,deletion_manifests:`storage.bucket.deletion_manifests`,other:`storage.bucket.other`};function gz(e,t){let n=hz[e.key];return n?t(n):e.label}function _z(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function vz(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function yz(e,t){switch(t){case`codex_running`:return uz(e,`error.codex_running`);case`process_enumeration_failed`:return uz(e,`error.process_enumeration_failed`);case`busy`:return uz(e,`error.busy`);case`unsupported_schema`:return uz(e,`error.unsupported_schema`);case`trigger_collision`:return cz(e,`error.trigger_collision`);case`unsafe_path`:return uz(e,`error.unsafe_path`);case`database_error`:return uz(e,`error.database_error`);case`auto_vacuum_not_incremental`:return uz(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return uz(e,`error.integrity_check_failed`);case`config_write_failed`:return cz(e,`error.config_write_failed`);default:return uz(e,`error.generic`)}}function bz({report:e,locale:t,t:n,busy:r,error:i,compaction:a,onAction:o}){let s=e.metrics,c=e.capabilities.protection.state===`unsupported`||e.capabilities.reclaim.state===`unsupported`,l=e.protection,u=r||e.capabilities.protection.state!==`supported`,d=l!==void 0&&e.capabilities.reclaim.state===`supported`&&(s?.reclaimableBytes??0)>0,[f,p]=(0,Z.useState)(!1);return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:fz(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:cz(t,`inspectionOnly`)})]}):null]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:oz(e.files.databaseBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`WAL`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:oz(e.files.walBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`SHM`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:oz(e.files.shmBytes,t)})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`TRACE`})}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`freelist`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:oz(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,Q.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`muted`,children:cz(t,`metricsSkippedLarge`).replace(`{threshold}`,oz(e.metricsSkipped.thresholdBytes,t))})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`sqlite_home`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,Q.jsx)(`code`,{children:e.externalSqliteHome?cz(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:cz(t,`protection`)}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:(0,Q.jsx)(`code`,{children:pz(t,l.state)})}),(0,Q.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:mz(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:mz(t,l.observedMode)})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-compat`,disabled:u,"aria-pressed":l.desiredMode===`compat`,onClick:()=>o({action:`protect`,mode:`compat`}),children:cz(t,`compat`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-quiet`,disabled:u,"aria-pressed":l.desiredMode===`quiet`,onClick:()=>o({action:`protect`,mode:`quiet`}),children:cz(t,`quiet`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-unprotect`,disabled:u||l.desiredMode===`off`,onClick:()=>o({action:`unprotect`}),children:cz(t,`disable`)}),l.state===`drifted`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:cz(t,`repair`)}),r&&(0,Q.jsx)(`span`,{className:`muted`,role:`status`,children:uz(t,`applying`)})]}),i&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,Q.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,Q.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:cz(t,`confirmCompact`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:cz(t,`cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:cz(t,`compact`)})})}),a&&(0,Q.jsx)(`div`,{className:`stw-section`,children:(0,Q.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:(0,Q.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,Q.jsx)(`code`,{children:e.target})}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:(0,Q.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function xz({locale:e,t}){return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:cz(e,`inspectionUnavailable`)})]})}function Sz({report:e,locale:t,apiBase:n=``,logGuardBusy:r=!1,onLogGuardAction:i}){let a=b(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),g=(0,Z.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),_=g.find(e=>e.key===o)??null,v=c?.generation===e.generatedAt?c.report:e.codexLogs??null,y=f?.generation===e.generatedAt?f.message:null,x=m?.generation===e.generatedAt?m.summary:null,S=r||u,C=(0,Z.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),w=(0,Z.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,Q.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,Q.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":a(`storage.section.buckets`),children:[(0,Q.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-title`,children:a(`storage.section.buckets`)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-count`,children:g.length})]}),(0,Q.jsx)(`div`,{className:`storage-workspace-rail-list`,children:g.length===0?(0,Q.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:a(`storage.empty`)}):g.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${o===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>s(t=>t===e.key?null:e.key),"aria-current":o===e.key?`true`:void 0,children:[(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-name`,children:gz(e,a)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-size`,children:oz(e.bytes,t)})]}),(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,a(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,Q.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":_?gz(_,a):a(`storage.section.largest`),children:_?(0,Q.jsxs)(`div`,{className:`stw-detail`,children:[(0,Q.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>s(null),children:[(0,Q.jsx)(lt,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),a(`modal.back`)]})}),(0,Q.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,Q.jsx)(`h2`,{className:`stw-detail-title`,children:gz(_,a)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.size`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:oz(_.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.files`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:_.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.oldest`)}),(0,Q.jsx)(`dd`,{children:_z(_.oldest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.newest`)}),(0,Q.jsx)(`dd`,{children:_z(_.newest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:vz(_,t,a)})]})]}),(_.largest?.length??0)>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),_.largest.map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:oz(e.bytes,t)})]},e.path))]})]})]}):(0,Q.jsxs)(`div`,{className:`stw-overview`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.total`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:oz(e.total.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.files`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.home`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),v?(0,Q.jsx)(bz,{report:v,locale:t,t:a,busy:S,error:y,compaction:x,onAction:r=>{if(i){i(r);return}if(u)return;let a=e.generatedAt;(async()=>{d(!0),p(null),r.action===`compact`&&h(null);try{let e=r.action===`protect`?`protect`:r.action,i={method:`POST`,...r.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:r.mode})}:{}},o=await fetch(`${n}/api/storage/codex-logs/${e}`,i);if(!o.ok){let e=await o.json().catch(()=>({}));p({generation:a,message:yz(t,e.error)});return}if(r.action===`compact`){let e=(await o.json().catch(()=>null))?.report;if(e){let n=oz(e.logicalBytesReclaimed??0,t),r=oz(e.physicalDatabaseBytesReclaimed??0,t),i=e.complete?cz(t,`compactComplete`):cz(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;h({generation:a,summary:[`${i}${s}`,`${o.toLocaleString(t)} ${cz(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${n}/api/storage/codex-logs`);if(e.ok){let t=await e.json();l({generation:a,report:t})}}catch{}return}let s=await o.json();l({generation:a,report:s})}catch{p({generation:a,message:uz(t,`error.generic`)})}finally{d(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,Q.jsx)(xz,{locale:t,t:a}):null,C.length>0?(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),C.map(e=>{let n=w.get(e.bucketKey);return(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,Q.jsx)(`span`,{className:`stw-file-bucket`,children:gz(n,a)}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:oz(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,Q.jsxs)(`p`,{className:`stw-hint`,children:[(0,Q.jsx)(ce,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),a(`storage.workspace.selectBucket`)]})]})})]})}var Cz=1024**3,wz=[10,25,50],Tz=(e,t)=>{if(!(e instanceof Error))return t;let n=e.message;return n===`Failed to fetch`||n.includes(`NetworkError`)||n.includes(`network error`)||n.includes(`JSON`)||n.includes(`Unexpected end of`)?t:n||t};function Ez({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,Z.useState)(25),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(!1),x=(0,Z.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,Z.useEffect)(()=>{b.current=f},[f]),(0,Z.useEffect)(()=>{if(!c)return;y.current=document.activeElement,v.current?.focus();let e=e=>{e.key===`Escape`&&!b.current&&x()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),y.current?.focus()}},[c,x]);let S=(e,t,r)=>{switch(e){case`codex_busy`:return n(`storage.cleanup.err.codex_busy`);case`stale_preview`:return n(`storage.cleanup.err.stale_preview`);case`restore_pending_overlap`:return n(`storage.cleanup.err.restore_pending_overlap`);case`referenced_history`:return n(`storage.cleanup.err.referenced_history`);case`invalid_digest`:return n(`storage.cleanup.err.invalid_digest`);case`invalid_mode`:return n(`storage.cleanup.err.invalid_mode`);case`fs_failed`:return r?n(`storage.cleanup.err.fs_failed_trash`,{trashDir:r}):n(`storage.cleanup.err.fs_failed`);case`db_reconcile_failed`:return n(`storage.cleanup.err.db_reconcile_failed`);case`cleanup_failed`:return n(`storage.cleanup.err.cleanup_failed`);default:return t??n(`storage.cleanup.cleanupFailed`)}},C=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),w=async()=>{p(!0),_(null),h(null);try{let t=await fetch(`${e}/api/storage/cleanup/preview`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({percent:i})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(S(e.error,n(`storage.cleanup.previewFailed`)))}let r=await t.json();s(r),l(!0)}catch(e){_(Tz(e,n(`storage.cleanup.previewFailed`)))}finally{p(!1)}},T=async()=>{if(o){p(!0),_(null);try{let i=await fetch(`${e}/api/storage/cleanup`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({percent:o.percent,mode:u?`permanent`:`quarantine`,digest:o.digest})});if(!i.ok){let e=await i.json().catch(()=>({}));throw e.error===`stale_preview`&&x(!0),Error(S(e.error,e.message,e.trashDir))}let a=await i.json();if(!a.ok)throw a.error===`stale_preview`&&x(!0),Error(S(a.error,a.message,a.trashDir));x(!0);let s=n(u?`storage.cleanup.donePermanent`:`storage.cleanup.doneQuarantine`,{count:String(a.count),size:oz(a.bytes,t)});h(a.skippedReferencedPaths?.length?`${s} ${n(`storage.cleanup.skippedReferenced`,{count:String(a.skippedReferencedPaths.length)})}`:s),r()}catch(e){_(Tz(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,Q.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,Q.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,Q.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,Q.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,Q.jsx)(`div`,{className:`storage-manual-panel__presets`,children:wz.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:C(e)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void w(),children:n(`storage.cleanup.preview`)})]}),m&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&x(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:oz(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,Q.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,Q.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,Q.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,Q.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,Q.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:v,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>x(),children:n(`storage.cleanup.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void T(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function Dz({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[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=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{g.current=o},[o]);let _=(0,Z.useCallback)(()=>l(null),[]);(0,Z.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&_()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,_]);let v=(0,Z.useCallback)(async t=>{let r=await fetch(`${e}/api/storage/trash`,{signal:t});if(!r.ok)throw Error(n(`storage.trash.listFailed`));let i=await r.json(),o=Array.isArray(i.entries)?i.entries:[];return a?.(o),o},[e,a,n]),y=mf(`storage-trash:${e}`,[e,i],v,{isEmpty:e=>e.length===0}).state,b=y.data??[],x=(e,t)=>{switch(e){case`codex_busy`:return n(`storage.trash.err.codex_busy`);case`invalid_trash`:return n(`storage.trash.err.invalid_trash`);case`missing_trash`:return n(`storage.trash.err.missing_trash`);case`dest_exists`:return n(`storage.trash.err.dest_exists`);case`fs_failed`:return n(`storage.trash.err.fs_failed`);case`db_reconcile_failed`:return n(`storage.trash.err.db_reconcile_failed`);case`storage_mutation_busy`:return n(`storage.trash.err.storage_mutation_busy`);case`restore_failed`:return n(`storage.trash.err.restore_failed`);case`restore_worker_timeout`:return n(`storage.trash.err.restore_worker_timeout`);case`restore_worker_aborted`:return n(`storage.trash.err.restore_worker_aborted`);case`restore_worker_failed`:return t??n(`storage.trash.err.restore_worker_failed`);default:return t??n(`storage.trash.restoreFailed`)}},S=async()=>{if(c){s(!0),p(null);try{let i=await fetch(`${e}/api/storage/trash/restore`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:c.id})});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(x(e.error,e.message))}let a=await i.json();if(!a.ok)throw Error(x(a.error,a.message));_(),d(n(`storage.trash.done`,{count:String(a.count),size:oz(a.bytes,t)})),r()}catch(e){p(Tz(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},C=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},w=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),y.showError&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:y.error instanceof Error?y.error.message:n(`storage.trash.listFailed`)}),y.refreshing&&!y.showSkeleton&&(0,Q.jsx)(lk,{live:!y.showError,children:n(`storage.trash.loading`)}),y.showSkeleton?(0,Q.jsx)(ck,{label:n(`storage.trash.loading`),rows:2}):b.length===0?(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,Q.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:b.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted`,children:C(e)}),(0,Q.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,Q.jsx)(`td`,{className:`num mono`,children:oz(e.bytes,t)}),(0,Q.jsx)(`td`,{className:`muted`,children:w(e.mode)}),(0,Q.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&_(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:oz(c.bytes,t),id:c.id})}),f&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>_(),children:n(`storage.trash.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void S(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function Oz(e){let{job:t,...n}=e;return n}function kz(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/Cz*100)/100));return e.target.reduceToBytes===void 0?{policy:Oz(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:Oz(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/Cz*100)/100))}}async function Az(e){await new Promise(t=>window.setTimeout(t,e))}function jz({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=sf(i),o=(0,Z.useRef)(!!a),[s,c]=(0,Z.useState)(()=>a?.policy??null),[l,u]=(0,Z.useState)(()=>!a),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(()=>a?.targetMode??`percent`),[x,S]=(0,Z.useState)(()=>a?.percent??`25`),[C,w]=(0,Z.useState)(()=>a?.reduceGb??`4`),[T,E]=(0,Z.useState)(()=>a?.thresholdGb??`5`),D=(0,Z.useRef)(null),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(!1),A=(0,Z.useRef)(0),j=(0,Z.useCallback)(e=>{let t=kz(e);c(t.policy),E(t.thresholdGb),b(t.targetMode),S(t.percent),w(t.reduceGb),o.current=!0,df(i,t),O.current=!1},[i]),M=(0,Z.useCallback)(()=>{O.current=!0},[]),N=(0,Z.useCallback)(e=>{k.current=e},[]),P=(0,Z.useCallback)(async t=>{let r=++A.current;o.current||u(!0),v(null);try{let n=await fetch(`${e}/api/storage/cleanup-policy`,{signal:t});if(!n.ok)throw Error(`load_failed`);let i=await n.json();if(t?.aborted||r!==A.current||O.current||k.current)return;j(i)}catch{if(t?.aborted||r!==A.current)return;o.current||(c(null),v(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===A.current&&u(!1)}},[e,j,n]);(0,Z.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{P(e.signal)},0);return()=>{window.clearTimeout(t),A.current+=1,e.abort()}},[P]),(0,Z.useEffect)(()=>()=>{D.current?.abort(),D.current=null},[]);let F=()=>{if(!s)return null;let e=T.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(y===`reduce`){let e=C.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*Cz)}}else{let e=Number(x);if(!Number.isFinite(e)||e<1||e>100)return null;n={removeOldestPercent:Math.min(100,Math.max(1,Math.floor(e)))}}return{enabled:s.enabled,trigger:{archivedBytesOver:Math.floor(t*Cz)},target:n,schedule:s.schedule,mode:s.mode}},I=async t=>{let r=F();if(!r){v(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),v(null),g(null);try{let t=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i)});if(!t.ok){v(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){v(n(`storage.policy.saveFailed`));return}j(r.policy),g(n(`storage.policy.saved`))}catch{v(n(`storage.policy.saveFailed`))}finally{f(!1)}},L=async()=>{D.current?.abort();let i=new AbortController;D.current=i;let{signal:a}=i;m(!0),v(null),g(null);try{let i=F();if(!i){v(n(`storage.policy.invalid`));return}let o=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i),signal:a});if(a.aborted)return;if(!o.ok){v(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){v(n(`storage.policy.saveFailed`));return}j(s.policy);let c=await fetch(`${e}/api/storage/cleanup-policy/run`,{method:`POST`,signal:a});if(a.aborted)return;if(c.status===409){let e=await c.json().catch(()=>({}));if(a.aborted)return;e.policy&&j(e.policy),v(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&j(e.policy),e.error===`already_running`){v(n(`storage.policy.alreadyRunning`));return}v(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&j(l.policy),l.error===`already_running`){v(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){v(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await Az(250),a.aborted))return;let t=await fetch(`${e}/api/storage/cleanup-policy`,{signal:a});if(a.aborted)return;if(!t.ok)continue;let n=await t.json();if(a.aborted)return;p=Oz(n),j(n);let r=n.job;if(r&&r.status!==`running`&&(r.startedAt===u&&r.lastOutcome||r.finishedAt&&r.finishedAt>=u&&r.lastOutcome)){f=r.lastOutcome;break}}if(a.aborted)return;if(p&&j(p),!f){v(n(`storage.policy.runFailed`));return}f.skipped===`disabled`?g(n(`storage.policy.skippedDisabled`)):f.ok&&f.metadataPersistenceError?(v(n(`storage.policy.metadataSaveWarning`)),f.removed!==void 0&&r()):f.skipped===`under_threshold`?g(n(`storage.policy.skippedUnder`)):f.skipped===`nothing_selected`?g(n(`storage.policy.skippedEmpty`)):f.deferred===`codex_busy`||f.error===`codex_busy`?v(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:oz(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:oz(f.freedBytes??0,t)})),r()):v(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;v(n(`storage.policy.runFailed`))}finally{D.current===i&&(D.current=null),a.aborted||m(!1)}},R=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,Q.jsx)(`div`,{className:`storage-policy-enable`,children:(0,Q.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void I({enabled:!s.enabled}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,Q.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,Q.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,Q.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,Q.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:T,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>N(!0),onChange:e=>{M(),E(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(p_,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{M(),E(f_(T,.1,0,1e4,.1))},onDecrement:()=>{M(),E(f_(T,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`percent`,disabled:d||p,onChange:()=>{M(),b(`percent`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),y===`percent`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:x,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>N(!0),onChange:e=>{M(),S(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(p_,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{M(),S(f_(x,1,1,100))},onDecrement:()=>{M(),S(f_(x,-1,1,100))}})]})]}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`reduce`,disabled:d||p,onChange:()=>{M(),b(`reduce`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),y===`reduce`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:C,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>N(!0),onChange:e=>{M(),w(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(p_,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{M(),w(f_(C,.1,0,1e4,.1))},onDecrement:()=>{M(),w(f_(C,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,Q.jsx)(Vn,{id:`storage-policy-schedule`,fullWidth:!0,value:s.schedule,disabled:d||p,onChange:e=>{e!==s.schedule&&I({schedule:e})},options:[{value:`manual`,label:n(`storage.policy.schedule.manual`)},{value:`startup`,label:n(`storage.policy.schedule.startup`)},{value:`daily`,label:n(`storage.policy.schedule.daily`)},{value:`weekly`,label:n(`storage.policy.schedule.weekly`)}]})]}),(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,Q.jsx)(Vn,{id:`storage-policy-mode`,fullWidth:!0,value:s.mode,disabled:d||p,onChange:e=>{e!==s.mode&&I({mode:e})},options:[{value:`quarantine`,label:n(`storage.policy.mode.quarantine`)},{value:`permanent`,label:n(`storage.policy.mode.permanent`)}]})]})]}),s.mode===`permanent`&&(0,Q.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,Q.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[R(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:oz(s.lastRun.freedBytes,t)})}`:``]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,Q.jsx)(`span`,{className:`storage-policy-meta-value`,children:R(s.nextRun)})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void I(),children:n(`storage.policy.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,Q.jsx)(`span`,{className:`storage-policy-actions__status${_?` is-error`:``}`,role:_?`alert`:`status`,"aria-live":`polite`,children:_??h??``})]})]}):(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:_&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:_})})}function Mz({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,Z.useState)(`policy`),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=[{id:`policy`,label:n(`storage.cleanupCard.tab.policy`),ref:u},{id:`quarantine`,label:n(`storage.cleanupCard.tab.quarantine`),ref:d}],p=e=>{l(e),window.requestAnimationFrame(()=>(e===`policy`?u:d).current?.focus())},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(c===`policy`?`quarantine`:`policy`)):e.key===`Home`?(e.preventDefault(),p(`policy`)):e.key===`End`&&(e.preventDefault(),p(`quarantine`))};return(0,Q.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,Q.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,Q.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,Q.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,Q.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,Q.jsx)(jz,{apiBase:e,locale:t,t:n,onDone:o}),(0,Q.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,Q.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,Q.jsx)(Ez,{apiBase:e,locale:t,t:n,onDone:o}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,Q.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,Q.jsx)(Dz,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function Nz({apiBase:e}){let{t,locale:n}=s(),r=`ocx.storage.report.v1:${e}`,i=sf(r),[a,o]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(0),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)({apiBase:e,settled:!1,hasEntries:!1}),p=(0,Z.useCallback)(async n=>{try{let i=await fetch(`${e}/api/storage`,{signal:n});if(!i.ok)throw Error(t(`storage.error`));let a=await i.json();return df(r,a),u.current&&(u.current=!1,o(t(`storage.rescanned`))),a}catch(e){throw u.current&&(u.current=!1,o(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,r,t]),m=mf(`storage-report:${e}`,[e],p,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),h=m.state,g=h.data??i,_=h.refreshing||h.showSkeleton&&!g,v=m.refresh,y=(0,Z.useCallback)(()=>{o(null),u.current=!0,v(),l(e=>e+1)},[v]),b=(0,Z.useCallback)(t=>{f({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=d.apiBase===e&&d.settled,S=d.apiBase===e&&d.hasEntries,C=g?.error!==void 0,w=!_&&!h.showError&&!C&&g.total.fileCount===0&&x&&!S,T=g?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!g&&!C,D=E&&(g.total.fileCount>0||!x||S);return(0,Q.jsxs)(`div`,{className:`storage-v2 flex min-w-0 flex-col gap-4 font-sans text-fg`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 basis-80 flex-col gap-1`,children:[(0,Q.jsx)(`h2`,{id:`storage-page-title`,className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:t(`storage.title`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:t(`storage.subtitle`)})]}),(0,Q.jsxs)(`div`,{className:`storage-page-head-actions flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`storage-page-head-feedback text-[13px] text-fg-muted`,role:`status`,"aria-live":`polite`,children:a??``}),(0,Q.jsxs)(`button`,{type:`button`,className:X(HP,`disabled:cursor-default disabled:opacity-50`),disabled:_,onClick:()=>void y(),children:[(0,Q.jsx)(`span`,{className:X(`inline-flex`,_&&`animate-spin`),children:(0,Q.jsx)(Ke,{"aria-hidden":!0})}),t(`storage.refresh`)]})]})]}),g&&g.error===void 0&&(0,Q.jsxs)(`p`,{className:`storage-page-meta m-0 -mt-2`,children:[(0,Q.jsx)(`code`,{className:`mono storage-page-meta__home`,title:g.codexHome,children:g.codexHome}),(0,Q.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(g.generatedAt).toLocaleString(n)]})]}),h.showSkeleton&&!g?(0,Q.jsx)(ck,{label:t(`storage.loading`),rows:5}):h.kind===`failed-cold`&&!g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:h.error instanceof Error?h.error.message:t(`storage.error`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,Q.jsxs)(Q.Fragment,{children:[h.showError&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,Q.jsx)(Un,{title:t(`storage.empty`)}):g&&g.total.fileCount>0&&(0,Q.jsx)(Sz,{report:g,locale:n,apiBase:e})]}),g&&g.error===void 0&&h.refreshing&&!h.showSkeleton&&(0,Q.jsx)(lk,{live:!h.showError,children:t(`storage.loading`)}),E&&(0,Q.jsx)(Mz,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:c,onDone:()=>void y(),onTrashEntriesChange:b})]})}var Pz=`/api/codex-auth/features/default-mode-request-user-input`;function Fz({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++h.current,n=d(15e3);try{let i=await fetch(`${e}${Pz}`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(p.current||t!==h.current)return;m.current=o.enabled===!0,r(m.current),a(!0),l(!1)}catch{!p.current&&t===h.current&&l(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=$u(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async()=>{if(p.current||!i||c)return;let n=!m.current,o=m.current;m.current=n,r(n),p.current=!0,s(!0),f(null),h.current++;try{let i=await fetch(`${e}${Pz}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await Yn(i)??{};if(o.ok!==!0)throw Error(String(i.status));m.current=o.enabled===!0,r(m.current),a(!0),f({tone:`ok`,message:t(o.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){m.current=o,r(o);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);f({tone:`err`,message:n})}finally{p.current=!1,s(!1)}},[e,i,c,t]),v=o||!i||c;return(0,Q.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,Q.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
10
- default_mode_request_user_input = true`})]}),(0,Q.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},children:t(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{_()},disabled:v,"aria-pressed":n,"aria-label":t(`codexAuth.requestUserInput`),title:t(`codexAuth.requestUserInput`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Q.jsx)(`div`,{className:`codex-request-user-input-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function Iz({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(0),h=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++m.current,n=d(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(p.current||t!==m.current)return;r(o.ultraFastTier===!0),a(!0),l(!1)}catch{!p.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=$u(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,Z.useCallback)(async()=>{if(p.current||!i||c)return;let a=!n;p.current=!0,s(!0),f(null),r(a);let o=d(15e3);try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({ultraFastTier:a}),signal:o.signal});if(!n.ok)throw Error(`save`);let i=await n.json(),s=typeof i.ultraFastTier==`boolean`?i.ultraFastTier:a;r(s),f({tone:`ok`,message:t(s?`codexAuth.ultraFastEnabled`:`codexAuth.ultraFastDisabled`)})}catch{r(!a),f({tone:`err`,message:t(`codexAuth.ultraFastFailed`)})}finally{o.clear(),p.current=!1,s(!1)}},[e,n,i,c,t]),_=o||!i||c;return(0,Q.jsxs)(`div`,{className:`card card-row codex-ultrafast-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-ultrafast-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.ultraFastTitle`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.ultraFastLoadFailed`:`codexAuth.ultraFastDesc`)})]}),(0,Q.jsxs)(`div`,{className:`codex-ultrafast-controls`,children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:t(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:_,"aria-pressed":n,"aria-label":t(`codexAuth.ultraFastTitle`),title:t(`codexAuth.ultraFastTitle`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Q.jsx)(`div`,{className:`codex-ultrafast-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}var Lz=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function Rz(e){if(e==null)return null;if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`settings shape`);let t=`model`in e&&typeof e.model==`string`?e.model.trim():``;if(!t)throw Error(`settings shape`);let n=`reasoningEffort`in e?e.reasoningEffort:void 0;if(n!==void 0&&(typeof n!=`string`||!Lz.includes(n)))throw Error(`settings shape`);let r=`enabled`in e?e.enabled:void 0;if(r!==void 0&&typeof r!=`boolean`)throw Error(`settings shape`);return{model:t,...n?{reasoningEffort:n}:{},...r===void 0?{}:{enabled:r}}}function zz(e){if(!e||typeof e!=`object`)throw Error(`settings shape`);let t=e,n=t.mainAccountHardLock;if(typeof t.codexMainAccountHardLock!=`boolean`||!n||n.enabled!==t.codexMainAccountHardLock||!(n.enabled?[`unknown`,`ready`,`blocked`]:[`off`]).includes(n.state)||n.resetAt!==void 0&&(typeof n.resetAt!=`number`||!Number.isFinite(n.resetAt)))throw Error(`settings shape`);let r=Rz(t.codexMainAccountHardLockFallback);return{...t,codexMainAccountHardLock:t.codexMainAccountHardLock,mainAccountHardLock:n,codexMainAccountHardLockFallback:r}}function Bz({pending:e,thresholds:t,onCancel:n,onConfirm:r}){let i=b(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=o.current;return e&&!e.open&&e.showModal(),s.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Q.jsxs)(`dialog`,{ref:o,className:`modal-overlay`,"aria-labelledby":`${a}-title`,"aria-describedby":`${a}-body`,"aria-busy":e||void 0,onCancel:e=>{e.preventDefault(),n()},onKeyDown:t=>{if(t.key!==`Tab`||e)return;let n=t.shiftKey?s.current:c.current,r=t.shiftKey?c.current:s.current;document.activeElement===n&&(t.preventDefault(),r?.focus())},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`common.close`),disabled:e,onClick:n}),(0,Q.jsxs)(`div`,{className:`modal-card codex-main-hard-lock-dialog`,role:`document`,children:[(0,Q.jsx)(`h3`,{id:`${a}-title`,children:i(`codexAuth.mainHardLockConfirmTitle`,t)}),(0,Q.jsx)(`p`,{id:`${a}-body`,className:`modal-desc`,children:i(`codexAuth.mainHardLockConfirmBody`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:s,type:`button`,className:`btn btn-ghost`,disabled:e,onClick:n,children:i(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn btn-primary`,disabled:e,onClick:r,children:i(e?`common.saving`:`codexAuth.mainHardLockConfirm`)})]})]})]})}function Vz(e){return(0,Q.jsx)(Hz,{...e},e.apiBase)}function Hz({apiBase:e,onSaved:t}){let n=b(),r=(0,Z.useId)(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),[y,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)([]),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(!1),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(!1),A=(0,Z.useRef)(0),j=(0,Z.useRef)(null),M=(0,Z.useRef)(null),N=(0,Z.useRef)(!1),P=(0,Z.useCallback)(()=>{if(N.current||M.current)return;let t=new AbortController;M.current=t,(async()=>{try{let n=await fetch(`${e}/api/models`,{signal:t.signal});if(!n.ok)throw Error(`models`);let r=await n.json();if(!Array.isArray(r))throw Error(`models`);N.current=!0,k.current&&C(r.filter(e=>typeof e==`object`&&!!e&&typeof e.namespaced==`string`&&e.native!==!0&&e.disabled!==!0))}catch{}finally{M.current===t&&(M.current=null)}})()},[e]),F=(0,Z.useRef)(null),I=(0,Z.useRef)(null),L=(0,Z.useRef)(!1),R=(0,Z.useCallback)(async()=>{if(O.current)return;let t=++A.current;j.current?.abort();let n=d(15e3);j.current=n.controller;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let i=zz(await r.json());if(!k.current||t!==A.current)return;a(i),x(i.codexMainAccountHardLockFallback),s(!1),m(null)}catch{k.current&&t===A.current&&s(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{k.current=!0;let e=window.setTimeout(()=>{R()},0),t=$u(()=>{R()},3e4);return()=>{k.current=!1,A.current+=1,j.current?.abort(),M.current?.abort(),M.current=null,window.clearTimeout(e),t()}},[R]),(0,Z.useEffect)(()=>{_||h||!L.current||(F.current&&!F.current.disabled?(F.current.focus(),L.current=!1):I.current?.focus())},[_,h,o,i]);let z=async()=>{let e=!1;try{e=await t()}catch{}k.current&&f(!e)},B=async t=>{if(O.current||!i)return;O.current=!0,A.current+=1,j.current?.abort(),g(!0),l(!1),f(!1),m(null);let n=d(15e3),r=!1;try{let i=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLock:t}),signal:n.signal});if(!i.ok)throw Error(`save`);let o=await i.json();if(!o||typeof o!=`object`||!(`ok`in o)||o.ok!==!0)throw Error(`unconfirmed`);let c=zz(o);r=!0,k.current&&(a(c),s(!1),m(c.codexMainAccountHardLock))}catch{k.current&&(l(!0),s(!0))}finally{n.clear()}r&&await z(),O.current=!1,k.current&&(g(!1),v(!1),r||R())},V=()=>{O.current||v(!1)},H=async t=>{if(O.current||w||!i)return;O.current=!0,A.current+=1,j.current?.abort(),T(!0),D(!1);let n=d(15e3),r=!1;try{let i=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLockFallback:t}),signal:n.signal});if(!i.ok)throw Error(`save`);let o=await i.json();if(!o||typeof o!=`object`||!(`ok`in o)||o.ok!==!0)throw Error(`unconfirmed`);let c=zz(o);r=!0,k.current&&(a(c),x(c.codexMainAccountHardLockFallback),s(!1))}catch{k.current&&D(!0)}finally{n.clear()}r&&await z(),O.current=!1,k.current&&(T(!1),r||R())},U=y?.enabled!==!1&&!!y?.model,W=()=>{y?.model&&H({...y,enabled:!U})},ee=e=>{if(!e)return;let{enabled:t,...n}=y??{};H({...n,model:e,...y?.enabled===!1?{enabled:!0}:{}})},G=e=>{H({...y??{},...e?{reasoningEffort:e}:{reasoningEffort:void 0}})},te=async()=>{O.current||(O.current=!0,A.current+=1,g(!0),await z(),O.current=!1,k.current&&g(!1))},ne=i?.codexMainAccountHardLock,K=Pv(i?.mainAccountHardLock.thresholds);return(0,Q.jsxs)(`section`,{ref:I,id:`codex-main-hard-lock-setting`,tabIndex:-1,className:`card card-row codex-main-hard-lock-setting`,"aria-labelledby":`${r}-title`,"aria-busy":h||!i&&!o||void 0,onBlurCapture:e=>{e.relatedTarget!==null&&!e.currentTarget.contains(e.relatedTarget)&&(L.current=!1)},children:[(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-copy`,children:[(0,Q.jsx)(`strong`,{id:`${r}-title`,children:n(`codexAuth.mainHardLockTitle`,K)}),(0,Q.jsx)(`div`,{id:`${r}-desc`,className:`card-sub`,children:n(`codexAuth.mainHardLockDesc`,K)})]}),(0,Q.jsx)(`button`,{ref:F,type:`button`,className:`toggle ${ne===!0?`on`:``}`,disabled:h||ne===void 0||o,"aria-pressed":ne,"aria-label":n(`codexAuth.mainHardLockTitle`,K),"aria-describedby":`${r}-desc`,onClick:()=>{O.current||ne===void 0||o||(L.current=!0,ne?B(!1):v(!0))},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-feedback`,children:[i?.mainAccountHardLock.externalUsage&&(0,Q.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Q.jsx)(`p`,{role:`status`,children:n(`codexAuth.mainExternalUsageWarning`)})}),(c||o)&&(0,Q.jsxs)(`p`,{role:`alert`,children:[n(c?`codexAuth.mainHardLockSaveFailed`:`codexAuth.mainHardLockLoadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:h,onClick:()=>{R()},children:n(`common.retry`)})]}),p!==null&&!u&&(0,Q.jsx)(`p`,{role:`status`,children:n(p?`codexAuth.mainHardLockEnabled`:`codexAuth.mainHardLockDisabled`,K)}),u&&(0,Q.jsxs)(`p`,{role:`status`,children:[n(`codexAuth.mainHardLockRefreshFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:h,onClick:()=>{te()},children:n(`common.retry`)})]})]}),(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-fallback`,role:`group`,"aria-label":n(`codexAuth.mainHardLockFallbackTitle`),onFocusCapture:P,onPointerDownCapture:P,onClickCapture:P,style:{flexBasis:`100%`},children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,Q.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8,minWidth:0},children:(0,Q.jsx)(`span`,{className:`font-semibold`,children:n(`codexAuth.mainHardLockFallbackTitle`)})}),(0,Q.jsxs)(`div`,{className:`setting-controls`,style:{flex:`0 1 auto`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`switch ${U?`on`:``}`,onClick:W,disabled:w||o||!y?.model,"aria-label":n(`codexAuth.mainHardLockFallbackTitle`),"aria-pressed":U,children:(0,Q.jsx)(`span`,{className:`knob`})}),(0,Q.jsx)(Vn,{value:y?.model??``,options:[...new Set([y?.model,...S.map(e=>e.namespaced)].filter(e=>!!e))].map(e=>({value:e,label:Fe(e,n)})),onChange:ee,disabled:w||o,label:n(`codexAuth.mainHardLockFallbackModel`),align:`right`}),(0,Q.jsx)(Vn,{value:y?.reasoningEffort??``,options:[{value:``,label:n(`codexAuth.mainHardLockFallbackDefaultEffort`)},...Lz.map(e=>({value:e,label:n(`models.reasoningEffort.${e}`)}))],onChange:G,disabled:w||o||!U,label:n(`codexAuth.mainHardLockFallbackEffort`),align:`right`})]})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:n(`codexAuth.mainHardLockFallbackDesc`)}),i?.mainAccountHardLock.state===`blocked`&&U&&y?.model&&(0,Q.jsx)(`p`,{role:`status`,className:`codex-main-hard-lock-status is-blocked`,children:n(`codexAuth.mainHardLockFallbackActive`,{model:y.model})}),E&&(0,Q.jsxs)(`p`,{role:`alert`,children:[n(`codexAuth.mainHardLockFallbackSaveFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:w,onClick:()=>{R()},children:n(`common.retry`)})]})]}),_&&(0,Q.jsx)(Bz,{pending:h,thresholds:K,onCancel:V,onConfirm:()=>{B(!0)}})]})}function Uz({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(m.current)return;let t=++h.current,n=d(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(m.current||t!==h.current)return;if(typeof o.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);p.current=o.codexAccountPickerEnabled,r(o.codexAccountPickerEnabled),a(!0),l(!1)}catch{!m.current&&t===h.current&&l(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=$u(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async()=>{if(m.current||!i)return;let n=p.current,o=!n;p.current=o,r(o),m.current=!0,s(!0),f(null),h.current+=1;try{let n=await Yn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexAccountPickerEnabled:o})}))??{};if(n.ok!==!0||typeof n.codexAccountPickerEnabled!=`boolean`)throw Error(`unconfirmed`);p.current=n.codexAccountPickerEnabled,r(n.codexAccountPickerEnabled),a(!0),l(!1),f(n.catalogRefreshPending===!0?{tone:`warn`,message:t(`codexAuth.catalogRefreshPending`)}:{tone:`ok`,message:t(`codexAuth.accountPickerUpdated`)})}catch{p.current=n,r(n),f({tone:`err`,message:t(`codexAuth.accountPickerUpdateFailed`)})}finally{m.current=!1,s(!1)}},[e,i,t]),v=c&&!i;return(0,Q.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":o||!i&&!v||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.accountPickerTitle`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:v?`status`:void 0,children:t(v?`codexAuth.accountPickerLoadFailed`:i?n?`codexAuth.accountPickerOnDesc`:`codexAuth.accountPickerOffDesc`:`common.loading`)}),i&&n&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.accountPickerCompatibility`)}),i&&c&&(0,Q.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:t(`codexAuth.accountPickerRefreshFailed`)})]}),(0,Q.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},disabled:o,children:t(`common.retry`)}),i&&(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{_()},disabled:o,"aria-pressed":n,"aria-label":t(`codexAuth.accountPickerTitle`),title:t(`codexAuth.accountPickerTitle`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Q.jsx)(`div`,{className:`codex-account-picker-feedback is-${u.tone}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function Wz(e){if(!e||typeof e!=`object`)return`absent`;let t=e.providers;if(!t||typeof t!=`object`||Array.isArray(t)||!Object.hasOwn(t,`openai`))return`absent`;let n=t.openai;if(!n||typeof n!=`object`||Array.isArray(n))return`absent`;let r=n;return r.disabled===!0?`disabled`:r.codexAccountMode===`direct`?`direct`:r.codexAccountMode===void 0||r.codexAccountMode===`pool`?`pool`:`absent`}function Gz({state:e,busy:t,onEnable:n}){let r=b(),i=Oy();if(e===null)return null;let a=e===`pool`||e===`direct`,o=r(e===`pool`?`codexAuth.accountModePool`:`codexAuth.accountModeDirect`);return(0,Q.jsxs)(`div`,{className:`openai-account-mode-banner acc-mode flex flex-col gap-2 rounded-[12px] px-4 py-3 ring-1 ring-line ${a?`bg-transparent`:`bg-surface`}`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-[13px] font-medium text-fg-muted`,children:r(`codexAuth.accountModeTitle`)}),a&&(0,Q.jsxs)(`button`,{type:`button`,className:`badge badge-muted badge-clickable openai-account-mode-banner__badge-slot`,"aria-label":`${o} — ${r(`codexAuth.changeAccountMode`)}`,title:r(`codexAuth.changeAccountMode`),onClick:()=>mE(`openai`),children:[o,(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`})]}),a&&(0,Q.jsx)(j_,{open:i.open,controls:i.id,name:r(`codexAuth.accountModeTitle`),onToggle:i.toggle}),(e===`absent`||e===`disabled`)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm ml-auto`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),a&&(0,Q.jsxs)(M_,{id:i.id,open:i.open,children:[e===`pool`&&r(`codexAuth.accountModePoolDesc`),e===`direct`&&(0,Q.jsxs)(Q.Fragment,{children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>mE(`openai`),children:r(`codexAuth.changeAccountMode`)})]})]}),(e===`absent`||e===`disabled`)&&(0,Q.jsx)(`p`,{className:`card-sub m-0 text-[13px] text-fg-muted`,children:r(`codexAuth.openaiUnavailableDesc`)}),e===`invalid`&&(0,Q.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc m-0 text-[13px] text-fg-muted`,children:[r(`codexAuth.openaiMissing`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>fE(`openai`),children:r(`codexAuth.openProviders`)})]})]})}function Kz(e){if(!e||typeof e!=`object`)return;let t=e.providers;if(!t||typeof t!=`object`||Array.isArray(t)||!Object.hasOwn(t,`openai`))return;let n=t.openai;if(n&&typeof n==`object`&&!Array.isArray(n))return n}function qz({apiBase:e,targetKey:t}){return(0,Q.jsx)(Jz,{apiBase:e,targetKey:t},t??e)}function Jz({apiBase:e,targetKey:t}){let n=b(),r=zv(e,!0,t),{load:i}=r,a=(0,Z.useRef)(!1);(0,Z.useLayoutEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let o=(0,Z.useCallback)(()=>a.current?i(!1):Promise.resolve(!1),[i]),s=`ocx.codex-auth.config.v1:${t??e}`,c=sf(s),[l,u]=(0,Z.useState)(()=>c?.bannerState??null),[f,p]=(0,Z.useState)(()=>c?.accountModeState??null),m=(0,Z.useRef)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(``),[y,x]=(0,Z.useState)(!1);oT(t??e,()=>x(!0));let S=(0,Z.useCallback)(async()=>{let t=d(15e3);try{let n=await fetch(`${e}/api/config`,{signal:t.signal});if(!n.ok)throw Error(String(n.status));let r=await n.json(),i=nC(Kz(r));if(i===`absent`||i===`disabled`||i===`invalid`){u(i);let e=i===`disabled`?`disabled`:`absent`;p(e),df(s,{bannerState:i,accountModeState:e});return}let a=Wz(r);u(a),p(a),df(s,{bannerState:a,accountModeState:a})}catch{}finally{t.clear()}},[e,s]);(0,Z.useEffect)(()=>{m.current!==e&&(m.current=e,Promise.resolve().then(()=>{S()}));let t=$u(()=>{S()},3e4);return()=>{t()}},[e,S]);let C=async()=>{g(!0),v(``);try{if(l!==`absent`&&l!==`disabled`)return;await lC(e,l),await S()}catch(e){e instanceof cC?v(n(e.i18nKey)):v(e instanceof Error?e.message:n(`prov.saveFailed`))}finally{g(!1)}},w=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Gz,{state:l,busy:h,onEnable:()=>{C()}}),y&&(0,Q.jsx)(k_,{tone:`warn`,role:`status`,children:n(`prov.legacyTargetPreflight`)}),_&&(0,Q.jsx)(k_,{tone:`err`,role:`alert`,children:_})]});return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(Lb,{apiBase:e,targetKey:t,controller:r,hasMainHardLockSetting:!0,accountModeState:f,banner:w,advancedExtras:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Uz,{apiBase:e}),(0,Q.jsx)(Fz,{apiBase:e}),(0,Q.jsx)(Iz,{apiBase:e}),(0,Q.jsx)(Vz,{apiBase:e,onSaved:o})]})})})}var Yz={"base-instructions":`codexSet.layer.base-instructions`,"model-switch":`codexSet.layer.model-switch`,personality:`codexSet.layer.personality`,"context-window-guidance":`codexSet.layer.context-window-guidance`,realtime:`codexSet.layer.realtime`,"agents-md":`codexSet.layer.agents-md`,permissions:`codexSet.layer.permissions`,collaboration:`codexSet.layer.collaboration`,environment:`codexSet.layer.environment`,"environments-instructions":`codexSet.layer.environments-instructions`,apps:`codexSet.layer.apps`,plugins:`codexSet.layer.plugins`,tools:`codexSet.layer.tools`,skills:`codexSet.layer.skills`,"multi-agent-mode":`codexSet.layer.multi-agent-mode`,"git-attribution":`codexSet.layer.git-attribution`},Xz={"base-instructions":`codexSet.about.base-instructions`,"model-switch":`codexSet.about.model-switch`,personality:`codexSet.about.personality`,"context-window-guidance":`codexSet.about.context-window-guidance`,realtime:`codexSet.about.realtime`,"agents-md":`codexSet.about.agents-md`,permissions:`codexSet.about.permissions`,collaboration:`codexSet.about.collaboration`,environment:`codexSet.about.environment`,"environments-instructions":`codexSet.about.environments-instructions`,apps:`codexSet.about.apps`,plugins:`codexSet.about.plugins`,tools:`codexSet.about.tools`,skills:`codexSet.about.skills`,"multi-agent-mode":`codexSet.about.multi-agent-mode`,"git-attribution":`codexSet.about.git-attribution`},Zz={"model-switch":`codexSet.condition.model-switch`,realtime:`codexSet.condition.realtime`,"agents-md":`codexSet.condition.agents-md`,plugins:`codexSet.condition.plugins`,"git-attribution":`codexSet.condition.git-attribution`},Qz={base:`codexSet.class.base`,"config-toggle":`codexSet.class.config-toggle`,"feature-gated":`codexSet.class.feature-gated`,"runtime-conditional":`codexSet.class.runtime-conditional`,"extension-unknown":`codexSet.class.extension-unknown`};function $z({descriptor:e,toggle:t,bytes:n,transitionOnly:r=!1,busy:i,writesRefused:a,onToggle:o,onReset:s,onSelectBase:c,baseSelection:l,onOpen:u}){let d=b(),f=Yz[e.id],p=f?d(f):e.id,m=Zz[e.id],h=t?.defaultedUserValue??e.default??!0,g=l?.kind==="default";return(0,Q.jsxs)(`li`,{className:`codex-set-prompt__row`,"data-layer-id":e.id,"data-layer-class":e.class,children:[(0,Q.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:e.order===null?`·`:e.order+1}),(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>u(e.id),children:p}),e.key&&(0,Q.jsx)(`code`,{className:`codex-set-prompt__key`,children:e.key}),n!==null&&n>0&&(0,Q.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:d(`codexSet.dialog.sourceBytes`,{bytes:n}),children:n>=1024?Math.round(n/1024)+` KB`:n+` B`}),e.class===`base`&&c?(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${g?`on`:``}`,"aria-checked":g,"aria-label":p,disabled:i||a||l?.kind===`external`,onClick:()=>{c(!g)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}):e.class===`config-toggle`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${h?`on`:``}`,"aria-checked":h,"aria-label":p,disabled:i||a,onClick:()=>{o(e.id,!h)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),t!==void 0&&t.userFileValue!==null&&s&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:i||a,onClick:()=>{s(e.id)},children:d(`codexSet.row.resetDefault`,{value:String(t.default)})})]}):e.class===`feature-gated`?(0,Q.jsxs)(`span`,{className:`codex-set-prompt__note`,children:[d(`codexSet.row.featureGated`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>En(`integrations/codex`),children:d(`codexSet.row.openFeatures`)})]}):(0,Q.jsx)(`span`,{className:`codex-set-prompt__note codex-set-prompt__note--locked`,children:d(r?`codexSet.row.onChange`:m||`codexSet.row.alwaysOn`)})]})}function eB({descriptor:e,toggle:t,text:n,probe:r,busy:i,onToggle:a,onReset:o,onClose:s,onRemeasure:c}){let l=b(),u=(0,Z.useRef)(null),d=`codex-set-layer-dialog-`+e.id;(0,Z.useEffect)(()=>{let e=u.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),s()},[s]),p=Qz[e.class],m=Yz[e.id],h=Xz[e.id],g=Zz[e.id];return(0,Q.jsxs)(`dialog`,{ref:u,className:`modal-overlay`,"aria-labelledby":d,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":l(`common.close`),tabIndex:-1,onClick:s}),(0,Q.jsxs)(`div`,{className:`modal-card codex-set-layer-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:d,children:m?l(m):e.id}),e.class===`config-toggle`&&t&&(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${t.defaultedUserValue?`on`:``}`,"aria-checked":t.defaultedUserValue,"aria-label":m?l(m):e.id,disabled:i,onClick:()=>{a(e.id,!t.defaultedUserValue)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:l(`common.close`)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:l(h||`codexSet.dialog.unknownLayer`)}),(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.class`)}),(0,Q.jsx)(`span`,{children:l(p)})]}),e.key&&(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.key`)}),(0,Q.jsx)(`code`,{className:`api-code`,children:e.key}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{navigator.clipboard?.writeText(e.key??``)},children:l(`codexSet.dialog.copyKey`)})]}),e.class===`config-toggle`&&t&&(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.fileValue`)}),(0,Q.jsx)(`span`,{children:t.userFileValue===null?l(`codexSet.dialog.absentDefault`,{value:String(t.default)}):l(`codexSet.dialog.setValue`,{value:String(t.userFileValue),fallback:String(t.default)})}),t.userFileValue!==null&&o&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:i,onClick:()=>{o(e.id)},children:l(`codexSet.row.resetDefault`,{value:String(t.default)})})]}),e.class===`runtime-conditional`&&g&&(0,Q.jsx)(`p`,{className:`muted small`,children:l(g)}),e.class===`feature-gated`&&(0,Q.jsx)(`div`,{className:`codex-set-layer-dialog__line`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>En(`integrations/codex`),children:l(`codexSet.row.openFeatures`)})}),n?.reason===`ok`&&n.text?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.sourceText`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:l(`codexSet.dialog.sourceBytes`,{bytes:n.bytes})})]}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-layer-dialog__text`,children:n.text})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted small codex-set-layer-dialog__no-text`,children:n?.reason===`empty-source`?l(`codexSet.dialog.emptySource`,{path:n.sourcePath??``}):n?.reason===`not-rendered`?l(`codexSet.dialog.notRendered`):n?.reason===`unmapped`?l(`codexSet.dialog.unmapped`):n?.reason===`not-exposed`?l(`codexSet.dialog.notExposed`):r&&r.ok===!1?r.failure?.kind===`program-not-found`?l(`codexSet.dialog.probeNotFound`):r.failure?.kind===`command-unsupported`?l(`codexSet.dialog.probeUnsupported`):r.failure?.kind===`output-invalid`?l(`codexSet.dialog.probeInvalid`):r.failure?.kind===`execution-failed`||r.failure?.kind===`request-failed`?l(`codexSet.dialog.probeFailed`):l(`codexSet.dialog.probeBusy`):l(`codexSet.dialog.textUnavailable`)}),r&&r.ok===!1&&r.failure===void 0&&c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:l(`common.retry`)})]})]})]})}var tB=65536;function nB(e){let t=0;for(let n of e){let e=n.codePointAt(0);t+=e<128?1:e<2048?2:e<65536?3:4}return t}function rB(e){return e.replace(/\r\n/g,`
11
- `).replace(/\r/g,`
12
- `).replace(/\t/g,` `)}function iB(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(n!==`
13
- `&&(e<32||e===127)||e>=55296&&e<=57343)return{position:t};t+=1}return null}function aB(e,t){let n=e.title;if(n.trim().length===0)return{kind:`title-empty`};if(n.length>80)return{kind:`title-too-long`,length:n.length};if(/[\r\n]/.test(n))return{kind:`title-multiline`};let r=rB(e.body),i=nB(r);if(i>65536)return{kind:`body-too-large`,bytes:i};let a=iB(r);if(a)return{kind:`invalid-character`,position:a.position};let o=nB([...t.filter(t=>t.enabled&&t.id!==e.id).map(e=>e.body),...e.enabled?[r]:[]].join(`
14
-
15
- `));return o>131072?{kind:`composed-too-large`,bytes:o}:null}function oB(e){let t=new Set(e.map(e=>e.id));for(;;){let e=``;for(let t=0;t<6;t+=1)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];if(!t.has(e))return e}}function sB(e){return e.filter(e=>e.enabled).map(e=>e.body).join(`
16
-
17
- `)}var cB=null;function lB(){return cB??1e4}function uB(e,t,n){let r=[...e],i=r.findIndex(e=>e.id===t);if(i===-1)return r;let a=i+n;if(a<0||a>=r.length)return r;let[o]=r.splice(i,1);return r.splice(a,0,o),r}function dB({layer:e,index:t,total:n,busy:r,onToggle:i,onEdit:a,onDelete:o,onMove:s}){let c=b();return(0,Q.jsxs)(`li`,{className:`codex-set-prompt__row codex-set-custom__row`,"data-custom-id":e.id,onKeyDown:i=>{i.altKey&&!r&&(i.key===`ArrowUp`&&t>0?(i.preventDefault(),s(e.id,-1)):i.key===`ArrowDown`&&t<n-1&&(i.preventDefault(),s(e.id,1)))},children:[(0,Q.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:t+1}),(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>a(e.id),children:e.title}),(0,Q.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:c(`codexSet.dialog.sourceBytes`,{bytes:nB(e.body)}),children:nB(e.body)>=1024?Math.round(nB(e.body)/1024)+` KB`:nB(e.body)+` B`}),(0,Q.jsxs)(`span`,{className:`codex-set-custom__reorder`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveUp`,{title:e.title}),disabled:t===0||r,onClick:()=>s(e.id,-1),children:`↑`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveDown`,{title:e.title}),disabled:t===n-1||r,onClick:()=>s(e.id,1),children:`↓`})]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${e.enabled?`on`:``}`,"aria-checked":e.enabled,"aria-label":e.title,disabled:r,onClick:()=>i(e.id,!e.enabled),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-set-custom__delete`,"aria-label":c(`codexSet.custom.delete`,{title:e.title}),disabled:r,onClick:()=>o(e.id),children:`×`})]})}var fB=8192,pB=[{rule:`identity`,level:`warn`,messageKey:`codexSet.lint.identity`,pattern:/you\s+are\s+(claude|grok|gemini|gpt-|chatgpt)/gi},{rule:`foreign-tool`,level:`warn`,messageKey:`codexSet.lint.foreignTool`,pattern:/\b(Read|Edit|Write|Bash|Glob|Grep)\s+tool\b/g},{rule:`placeholder`,level:`warn`,messageKey:`codexSet.lint.placeholder`,pattern:/\$\{\{[\s\S]*?\}\}/g},{rule:`apply-patch`,level:`warn`,messageKey:`codexSet.lint.applyPatch`,pattern:/apply_patch\s+(?:is|must|should|means|works)/gi},{rule:`approval-vocab`,level:`warn`,messageKey:`codexSet.lint.approvalVocab`,pattern:/\b(always-approve|ask mode|acceptEdits)\b/gi},{rule:`environment`,level:`warn`,messageKey:`codexSet.lint.environment`,pattern:/\b(your (?:cwd|working directory) is|today's date is|you have no network access|you are running on (?:macos|linux|windows))/gi},{rule:`secret`,level:`warn`,messageKey:`codexSet.lint.secret`,redactSpan:!0,pattern:/(sk-[a-zA-Z0-9_-]{20,}|ghp_[0-9a-zA-Z]{36}|github_pat_[0-9a-zA-Z_]{22,}|glpat-[0-9a-zA-Z_-]{20,}|xox[baprs]-[0-9a-zA-Z-]{10,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/g},{rule:`ignore-instructions`,level:`warn`,messageKey:`codexSet.lint.ignoreInstructions`,pattern:/\b(?:ignore|disregard|forget|override)\s+(?:all\s+|any\s+)?(?:the\s+)?(?:previous|prior|above|earlier|system)\s+(?:instructions?|prompts?|rules?)\b/gi},{rule:`identity-ko`,level:`warn`,messageKey:`codexSet.lint.identity`,pattern:/(?:(?:당신은|너는)\s*(?:claude|grok|gemini|chatgpt|gpt)\b)|(?:(?:당신은|너는)\s*(?:클로드|그록|제미나이|챗gpt))/gi}];function mB(e){let t=0;for(let n of e){let e=n.codePointAt(0);t+=e<128?1:e<2048?2:e<65536?3:4}return t}function hB(e){let t=[],n=[];for(let r of pB){let i=new RegExp(r.pattern.source,r.pattern.flags);for(let a=i.exec(e);a!==null;a=i.exec(e)){let e=[a.index,a.index+a[0].length];r.redactSpan&&n.push(e),t.push({level:r.level,rule:r.rule,messageKey:r.messageKey,span:r.redactSpan?void 0:e}),a[0].length===0&&(i.lastIndex+=1)}}if(n.length>0)for(let e of t)e.span&&n.some(([t,n])=>e.span[0]<n&&t<e.span[1])&&(e.span=void 0);return mB(e)>fB&&t.push({level:`info`,rule:`size`,messageKey:`codexSet.lint.size`}),t.sort((e,t)=>(e.span?.[0]??1/0)-(t.span?.[0]??1/0))}function gB({layer:e,seed:t,others:n,busy:r,navigation:i,onSave:a,onClose:o}){let s=b(),c=(0,Z.useRef)(null),[l,u]=(0,Z.useState)(e?.title??t?.title??``),[d,f]=(0,Z.useState)(e?.body??t?.body??``),p=(0,Z.useRef)(new Map),[m,h]=(0,Z.useState)(!1),g=e?.id??null,_=(0,Z.useRef)(g),v=(0,Z.useRef)({title:l,body:d});(0,Z.useEffect)(()=>{v.current={title:l,body:d}},[l,d]),(0,Z.useEffect)(()=>{if(_.current===g)return;_.current!==null&&p.current.set(_.current,v.current),_.current=g;let t=g===null?void 0:p.current.get(g);u(t?.title??e?.title??``),f(t?.body??e?.body??``)},[g,e]),(0,Z.useEffect)(()=>{h([...p.current].some(([e,t])=>{if(e===g)return!1;let r=n.find(t=>t.id===e);return r===void 0||t.title!==r.title||t.body!==r.body}))},[g,n]);let[y,x]=(0,Z.useState)(null),S=`codex-set-custom-dialog`,C=e?.title??t?.title??``,w=e?.body??t?.body??``,T=l!==C||d!==w;(0,Z.useEffect)(()=>{let e=c.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let E=(0,Z.useCallback)(()=>{T||m?x({kind:`close`}):o()},[T,m,o]),D=(0,Z.useCallback)(e=>{e.preventDefault(),E()},[E]),O={id:e?.id??null,title:l,body:d,enabled:e?.enabled??!0},k=aB(O,n),A=rB(d),j=A!==d,M=(0,Z.useMemo)(()=>hB(A),[A]),N=nB(A),P=e=>{r||k!==null||e!==g||a({...O,body:A})},F=()=>{r||k!==null||(m?x({kind:`save`,targetId:g}):P(g))},I=k?k.kind===`title-empty`?s(`codexSet.custom.titleRequired`):k.kind===`title-too-long`?s(`codexSet.custom.titleTooLong`,{count:k.length,max:80}):k.kind===`title-multiline`?s(`codexSet.custom.titleMultiline`):k.kind===`body-too-large`?s(`codexSet.custom.bodyTooLarge`,{bytes:k.bytes,max:tB}):k.kind===`composed-too-large`?s(`codexSet.custom.composedTooLarge`,{bytes:k.bytes}):s(`codexSet.custom.invalidCharacter`,{position:k.position}):null;return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":S,onCancel:D,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:E}),(0,Q.jsxs)(`div`,{className:`modal-card codex-set-custom-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:S,children:s(e?`codexSet.custom.editTitle`:`codexSet.custom.newTitle`)}),i&&(0,Q.jsxs)(`span`,{className:`codex-set-custom-dialog__nav`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":s(`codexSet.custom.prevLayer`),disabled:i.position<=1||r||y!==null,onClick:i.onPrev,children:`←`}),(0,Q.jsx)(`span`,{className:`codex-set-custom-dialog__nav-pos`,children:s(`codexSet.custom.navPosition`,{position:i.position,total:i.total})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":s(`codexSet.custom.nextLayer`),disabled:i.position>=i.total||r||y!==null,onClick:i.onNext,children:`→`})]})]}),(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`codexSet.custom.titleLabel`)}),(0,Q.jsx)(`input`,{className:`input`,type:`text`,value:l,maxLength:100,onChange:e=>u(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`codexSet.custom.bodyLabel`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:10,value:d,onChange:e=>f(e.target.value)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:s(`codexSet.custom.bodySize`,{bytes:N,max:tB})}),j&&(0,Q.jsx)(`p`,{className:`muted small codex-set-custom-dialog__normalized`,children:s(`codexSet.custom.normalized`)}),I&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:I}),M.length>0&&(0,Q.jsx)(`ul`,{className:`codex-set-custom-dialog__lint`,children:M.map((e,t)=>(0,Q.jsxs)(`li`,{"data-lint-rule":e.rule,"data-lint-level":e.level,children:[s(e.messageKey),e.span&&(0,Q.jsx)(`code`,{className:`codex-set-custom-dialog__span`,children:A.slice(e.span[0],e.span[1])})]},e.rule+`:`+t))}),y?(0,Q.jsxs)(`div`,{className:`modal-actions codex-set-custom-dialog__discard`,role:`alertdialog`,"aria-labelledby":S+`-discard`,children:[(0,Q.jsx)(`span`,{id:S+`-discard`,className:`muted small`,children:s(y.kind===`save`?`codexSet.custom.discardOthersAndSave`:`codexSet.custom.discardPrompt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>x(null),children:s(`codexSet.custom.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:y.kind===`save`&&(k!==null||r||y.targetId!==g),onClick:()=>y.kind===`save`?P(y.targetId):o(),children:s(y.kind===`save`?`common.save`:`common.discard`)})]}):(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k!==null||r,onClick:F,children:s(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:E,children:s(`common.cancel`)})]})]})]})}var _B=Object.freeze([{id:`concise`,nameKey:`codexSet.preset.concise.name`,descriptionKey:`codexSet.preset.concise.description`,provenanceKey:`codexSet.preset.concise.provenance`,body:[`Answer directly. Skip preamble, restatement of the question, and summaries of the work about to be done.`,`Prefer a short paragraph over a list, and a list over a table, unless the structure carries real meaning.`,`When the answer is a single fact, give the fact and stop.`].join(`
18
- `)},{id:`plan-first`,nameKey:`codexSet.preset.planFirst.name`,descriptionKey:`codexSet.preset.planFirst.description`,provenanceKey:`codexSet.preset.planFirst.provenance`,body:[`Before changing anything non-trivial, state the plan in two or three sentences: what will change, where, and how it will be verified.`,`If the plan turns out to be wrong mid-way, say so and revise it rather than continuing quietly.`].join(`
19
- `)},{id:`explain-why`,nameKey:`codexSet.preset.explainWhy.name`,descriptionKey:`codexSet.preset.explainWhy.description`,provenanceKey:`codexSet.preset.explainWhy.provenance`,body:[`When a choice had alternatives, name the alternative and why it lost.`,`Explain reasoning where it changes what the reader should do, not as a narration of every step.`,`State uncertainty plainly instead of presenting a guess as a conclusion.`].join(`
20
- `)},{id:`test-first`,nameKey:`codexSet.preset.testFirst.name`,descriptionKey:`codexSet.preset.testFirst.description`,provenanceKey:`codexSet.preset.testFirst.provenance`,body:[`For a behavior change, write the failing test first and show that it fails for the expected reason.`,`A test that passes before the change is not evidence; say so rather than counting it.`].join(`
21
- `)},{id:`korean`,nameKey:`codexSet.preset.korean.name`,descriptionKey:`codexSet.preset.korean.description`,provenanceKey:`codexSet.preset.korean.provenance`,body:[`Reply in Korean regardless of the language of the request, unless explicitly asked for another language.`,`Keep code, identifiers, file paths, and command output unchanged.`,`Write plain Korean: no translationese, one consistent register throughout.`].join(`
22
- `)}]);function vB({onBlank:e,onPreset:t,disabled:n,presets:r=_B}){let i=b(),[a,o]=(0,Z.useState)(!1),s=(0,Z.useRef)(null),c=a&&!n;(0,Z.useEffect)(()=>{if(!c)return;let e=e=>{s.current?.contains(e.target)||o(!1)},t=e=>{e.key===`Escape`&&o(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let l=e=>{o(!1),e()};return r.length===0?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm codex-set-custom__add`,disabled:n,onClick:e,children:i(`codexSet.custom.add`)}):(0,Q.jsxs)(`div`,{className:`codex-set-preset`,ref:s,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm codex-set-custom__add`,"aria-expanded":c,disabled:n,onClick:()=>o(e=>!e),children:i(`codexSet.custom.add`)}),c&&(0,Q.jsxs)(`div`,{className:`codex-set-preset__menu`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`codex-set-preset__item`,onClick:()=>l(e),children:(0,Q.jsx)(`span`,{className:`codex-set-preset__name`,children:i(`codexSet.preset.blank`)})}),r.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`codex-set-preset__item`,"data-preset-id":e.id,onClick:()=>l(()=>t(e.body,i(e.nameKey))),children:[(0,Q.jsx)(`span`,{className:`codex-set-preset__name`,children:i(e.nameKey)}),(0,Q.jsx)(`span`,{className:`codex-set-preset__desc`,children:i(e.descriptionKey)}),(0,Q.jsx)(`span`,{className:`codex-set-preset__provenance`,children:i(e.provenanceKey)}),(0,Q.jsx)(`span`,{className:`codex-set-preset__preview`,children:e.body})]},e.id))]})]})}var yB=48,bB=`new`,xB=`field mt-3 grid gap-1`;function SB({variants:e,selection:t,maxVariants:n,busy:r,importPreview:i,importRefusal:a,onSelect:o,onSave:s,onDelete:c,onImport:l,onImportTitle:u,onClose:d}){let f=b(),p=(0,Z.useRef)(null),m=[{kind:`default`},...e.map(e=>({kind:`variant`,variant:e})),...e.length<n?[{kind:`new`}]:[]],h=t.kind===`variant`?Math.max(0,m.findIndex(e=>e.variant?.id===t.id)):0,[g,_]=(0,Z.useState)(h),v=m[Math.min(g,m.length-1)],[y,x]=(0,Z.useState)(v.variant?.title??``),[S,C]=(0,Z.useState)(v.variant?.body??``),w=v.kind==="default"?null:v.variant?.id??bB,T=(0,Z.useRef)(new Map),E=(0,Z.useRef)(w),D=(0,Z.useRef)(v),O=(0,Z.useRef)(null),k=(0,Z.useRef)(new Set),A=(0,Z.useRef)({title:y,body:S});(0,Z.useEffect)(()=>{A.current={title:y,body:S}},[y,S]),(0,Z.useEffect)(()=>{let t=k.current,n=new Set(e.map(e=>e.id)),r=O.current,i=r!==null&&(r.id===null?e.some(e=>!t.has(e.id)&&e.title===(r.title||e.id)&&e.body===r.body):e.some(e=>e.id===r.id&&e.title===r.title&&e.body===r.body));if(E.current!==w&&E.current!==null){let t=A.current,a=e.find(e=>e.id===E.current)??D.current.variant,o=a===void 0?t.title===``&&t.body===``:t.title===a.title&&t.body===a.body,s=E.current!==bB&&!n.has(E.current),c=i&&r!==null&&E.current===(r.id??bB)&&t.title===r.title&&t.body===r.body;o||s||c?T.current.delete(E.current):T.current.set(E.current,t)}for(let e of[...T.current.keys()])e!==bB&&!n.has(e)&&T.current.delete(e);if(r&&i&&T.current.delete(r.id??bB),r&&(i||r.id!==null&&!n.has(r.id))&&(O.current=null),k.current=n,E.current!==w){let e=w===null?void 0:T.current.get(w);x(e?.title??v.variant?.title??``),C(e?.body??v.variant?.body??``)}E.current=w,D.current=v},[w,v,e]);let[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{P([...T.current].some(([t,n])=>{if(t===w)return!1;if(t===bB)return n.title!==``||n.body!==``;let r=e.find(e=>e.id===t);return r===void 0||n.title!==r.title||n.body!==r.body}))},[w,e,y,S]);let F=N||w!==null&&(y!==(v.variant?.title??``)||S!==(v.variant?.body??``)),[I,L]=(0,Z.useState)(i?.effectiveTitle??``),R=i?.effectiveTitle??null,[z,B]=(0,Z.useState)(R);R!==z&&(B(R),L(R??``));let V=(0,Z.useCallback)(e=>{_(t=>{let n=t+e;return n<0?m.length-1:n>=m.length?0:n})},[m.length]);(0,Z.useEffect)(()=>{let e=p.current;e&&!e.open&&e.showModal()},[]);let H=(0,Z.useRef)(null),U=e=>{H.current={x:e.clientX,y:e.clientY}},W=e=>{let t=H.current;if(H.current=null,!t||r||j!==null)return;let n=e.clientX-t.x,i=e.clientY-t.y;Math.abs(n)<yB||Math.abs(n)<=Math.abs(i)||V(n<0?1:-1)},ee=e=>{if(r||j!==null)return;let t=e.target.tagName;t!==`TEXTAREA`&&t!==`INPUT`&&(e.key===`ArrowLeft`&&(e.preventDefault(),V(-1)),e.key===`ArrowRight`&&(e.preventDefault(),V(1)))},G=(0,Z.useCallback)(()=>{F?M({kind:`close`}):d()},[F,d]),te=(0,Z.useCallback)(e=>{e.preventDefault(),G()},[G]),ne=v.kind==="default"?t.kind==="default":v.kind===`variant`&&t.kind===`variant`&&t.id===v.variant.id,K=t.kind===`external`,q=rB(S),J=nB(q),re=iB(q),Y=J>65536?{kind:`body-too-large`,bytes:J}:re===null?null:{kind:`invalid-character`,position:re.position},ie=q!==S,ae=hB(q),oe=Y?Y.kind===`body-too-large`?f(`codexSet.custom.bodyTooLarge`,{bytes:Y.bytes,max:tB}):f(`codexSet.custom.invalidCharacter`,{position:Y.position}):null,se=async e=>{if(r||Y!==null||S.trim().length===0||e!==w)return;let t={title:y,body:S},n=y.replace(/[\r\n]+/g,` `).trim()||v.variant?.id||``;if(O.current={id:v.variant?.id??null,title:n,body:q},!await s({id:v.variant?.id??null,title:y,body:q})){O.current=null;return}let i=e??bB;if(T.current.delete(i),i!==bB&&E.current===e&&A.current.title===t.title&&A.current.body===t.body&&(A.current={title:n,body:q},x(n),C(q)),j?.kind===`save`){for(let e of[...T.current.keys()])e!==i&&T.current.delete(e);M(null)}};return(0,Q.jsx)(`dialog`,{ref:p,className:`modal-overlay codex-set-base-dialog`,"aria-label":f(`codexSet.base.title`),onCancel:te,onClose:d,onKeyDown:ee,onPointerDown:U,onPointerUp:W,children:(0,Q.jsxs)(`div`,{className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:f(`codexSet.base.title`)}),(0,Q.jsxs)(`span`,{className:`codex-set-base-dialog__nav`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":f(`codexSet.base.prev`),disabled:r||m.length<2||j!==null,onClick:()=>V(-1),children:`←`}),(0,Q.jsx)(`span`,{className:`codex-set-base-dialog__pos`,"data-slot-kind":v.kind,children:f(`codexSet.base.position`,{position:g+1,total:m.length})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":f(`codexSet.base.next`),disabled:r||m.length<2||j!==null,onClick:()=>V(1),children:`→`})]})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:f(`codexSet.base.swipeHint`)}),m.length>1&&(0,Q.jsx)(`div`,{className:`codex-set-base-dialog__dots`,"aria-hidden":`true`,children:m.map((e,t)=>(0,Q.jsx)(`span`,{className:`codex-set-base-dialog__dot${t===g?` active`:``}`},t))}),K&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:f(`codexSet.base.externalBlocked`,{path:t.path})}),K&&(i?(0,Q.jsxs)(Q.Fragment,{children:[a!==null&&(0,Q.jsx)(`p`,{className:`muted small`,children:a}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.importPreview`,{path:i.resolvedPath??i.rawPath??``})}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-custom__adopt-preview`,children:i.serialized}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.importFormat`,{bodyBytes:i.bodyBytes,serializedBytes:i.serializedBytes})}),(0,Q.jsxs)(`label`,{className:xB,children:[(0,Q.jsx)(`span`,{children:f(`codexSet.base.importTitle`)}),(0,Q.jsx)(`input`,{className:`input`,type:`text`,value:I,disabled:r,maxLength:80,onChange:e=>{L(e.target.value),u(e.target.value)}})]}),I.trim()!==i.effectiveTitle&&(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.importTitlePending`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:r||I.trim()!==i.effectiveTitle,onClick:()=>l(!0,I.trim()||void 0),children:f(`codexSet.base.importConfirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:G,children:f(`common.cancel`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[a!==null&&(0,Q.jsx)(`p`,{className:`muted small`,children:a}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:r,onClick:()=>l(!1),children:f(`codexSet.base.import`)})]})),v.kind==="default"?(0,Q.jsxs)(`div`,{className:`codex-set-base-dialog__default`,children:[(0,Q.jsx)(`strong`,{children:f(`codexSet.base.defaultTitle`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.defaultBody`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:xB,children:[(0,Q.jsx)(`span`,{children:f(`codexSet.base.variantTitle`)}),(0,Q.jsx)(`input`,{className:`input`,type:`text`,value:y,disabled:r||K,onChange:e=>x(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:xB,children:[(0,Q.jsx)(`span`,{children:f(`codexSet.base.variantBody`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:12,value:S,disabled:r||K,onChange:e=>C(e.target.value)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.custom.bodySize`,{bytes:J,max:tB})}),ie&&(0,Q.jsx)(`p`,{className:`muted small codex-set-custom-dialog__normalized`,children:f(`codexSet.custom.normalized`)}),oe&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:oe}),ae.length>0&&(0,Q.jsx)(`ul`,{className:`codex-set-custom-dialog__lint`,children:ae.map((e,t)=>(0,Q.jsxs)(`li`,{"data-lint-rule":e.rule,"data-lint-level":e.level,children:[f(e.messageKey),e.span&&(0,Q.jsx)(`code`,{className:`codex-set-custom-dialog__span`,children:q.slice(e.span[0],e.span[1])})]},e.rule+`:`+t))}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.replacesWarning`)})]}),j?(0,Q.jsxs)(`div`,{className:`modal-actions codex-set-custom-dialog__discard`,role:`alertdialog`,"aria-labelledby":`codex-set-base-dialog-discard`,children:[(0,Q.jsx)(`span`,{id:`codex-set-base-dialog-discard`,className:`muted small`,children:f(j.kind===`save`?`codexSet.custom.discardOthersAndSave`:`codexSet.custom.discardPrompt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>M(null),children:f(`codexSet.custom.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:j.kind===`save`&&(Y!==null||r||S.trim().length===0||j.targetKey!==w),onClick:()=>j.kind===`save`?void se(j.targetKey):d(),children:f(j.kind===`save`?`common.save`:`common.discard`)})]}):(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[v.kind!=="default"&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:r||K||Y!==null||S.trim().length===0,onClick:()=>{r||Y!==null||(N?M({kind:`save`,targetKey:w}):se(w))},children:f(`common.save`)}),!ne&&v.kind!==`new`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:r||K,onClick:()=>o(v.kind==="default"?{kind:`default`}:{kind:`variant`,id:v.variant.id}),children:f(`codexSet.base.use`)}),ne&&(0,Q.jsx)(`span`,{className:`pill`,children:f(`codexSet.base.inUse`)}),v.kind===`variant`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:r||K,onClick:()=>c(v.variant.id),children:f(`common.delete`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:G,children:f(`common.close`)})]})]})})}function CB(e){return`codex-prompt:`+e}var wB={"journal-present":`codexSet.drift.journalPresent`,"projection-stale":`codexSet.drift.projectionStale`,"store-missing":`codexSet.drift.storeMissing`,"owned-malformed":`codexSet.drift.ownedMalformed`};function TB({apiBase:e}){let t=b(),n=CB(e),[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(!1),[y,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),E=(0,Z.useRef)(0),D=(0,Z.useRef)(!1),O=(0,Z.useRef)(null),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let P=(0,Z.useCallback)(()=>{A(null)},[]),F=(0,Z.useCallback)(async t=>{let n=await fetch(e+`/api/codex-prompt`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},[e]),I=mf(n,[e],F,{isEmpty:e=>e.inventory.length===0}),L=I.data,R=I.state,z=async(r,a)=>{if(L){o(r),i(``);try{let o=await fetch(e+`/api/codex-prompt/toggle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({id:r,enabled:a,revision:L.revision})}),s=await o.json();if(!o.ok||!s.ok||!s.snapshot){if(s.code===`stale_revision`){I.refresh(),i(t(`codexSet.prompt.staleRevision`));return}i(s.message??t(`codexSet.prompt.writeFailed`)),I.refresh();return}Sn(n,s.snapshot),P(),A(null)}catch{i(t(`codexSet.prompt.writeFailed`)),I.refresh()}finally{o(null)}}},B=async(r,s)=>{if(!L||a!==null)return!1;o(`base`),i(``);try{let a=await fetch(e+r,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({...s,revision:L.revision})}),o=await a.json();return!a.ok||!o.ok||!o.snapshot?o.code===`stale_revision`?(I.refresh(),i(t(`codexSet.prompt.staleRevision`)),!1):(i(o.message??t(`codexSet.prompt.writeFailed`)),I.refresh(),!1):(Sn(n,o.snapshot),P(),A(null),!0)}catch{return i(t(`codexSet.prompt.writeFailed`)),I.refresh(),!1}finally{o(null)}},V=async(r,a)=>{if(!L||D.current)return;r&&(D.current=!0,O.current&&=(clearTimeout(O.current),null));let s=++E.current;r&&o(`base-import`),i(``);try{let o=await fetch(e+`/api/codex-prompt/base/import`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r?{confirm:!0,revision:L.revision,...a===void 0?{}:{title:a},previewSha256:S?.previewSha256}:{confirm:!1,...a===void 0?{}:{title:a}})}),c=await o.json();if(!(r||s===E.current))return;if(!o.ok||!c.ok){if(I.refresh(),c.code===`stale_revision`){i(t(`codexSet.prompt.staleRevision`));return}T(c.code===`import_body_changed`?t(`codexSet.base.importChanged`):c.message??t(`codexSet.base.importFailed`)),r&&C(null);return}if(c.snapshot){Sn(n,c.snapshot),P(),C(null),T(null);return}T(null),C(c.preview??null)}catch{if(!(r||s===E.current))return;i(t(`codexSet.prompt.writeFailed`)),I.refresh()}finally{r&&(D.current=!1),(r||s===E.current)&&o(e=>e===`base-import`?null:e)}},H=e=>{D.current||(E.current+=1,O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{O.current=null,V(!1,e)},350))},U=()=>{E.current+=1,O.current&&=(clearTimeout(O.current),null),c(null),C(null),T(null),D.current||o(e=>e===`base-import`?null:e),I.refresh()},W=async(r,s)=>{if(!L||a!==null)return!1;o(s),i(``);let c=L.custom;try{let a=await fetch(e+`/api/codex-prompt/custom`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({layers:r,revision:L.revision})}),o=await a.json();return!a.ok||!o.ok||!o.snapshot?o.code===`stale_revision`?(I.refresh(),i(t(`codexSet.prompt.staleRevision`)),!1):(i(o.message??t(`codexSet.prompt.writeFailed`)),Sn(n,{...L,custom:c}),I.refresh(),!1):(Sn(n,o.snapshot),P(),!0)}catch{return i(t(`codexSet.prompt.writeFailed`)),I.refresh(),!1}finally{o(null)}},ee=async e=>{if(!L)return;let t=L.custom,n=e.id===null?[...t,{id:oB(t),title:e.title,body:e.body,enabled:!0}]:t.map(t=>t.id===e.id?{...t,title:e.title,body:e.body}:t);await W(n,e.id??`new`)&&u(null)},G=async r=>{if(L){o(`adopt`),i(``);try{let a=await fetch(e+`/api/codex-prompt/adopt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r?{confirm:!0,revision:L.revision}:{confirm:!1})}),o=await a.json();if(!a.ok||!o.ok){i(o.message??t(`codexSet.custom.adoptRefused`)),m(null),g(o.code===`adopt_unsupported_form`?{path:o.path,line:o.line,rawLine:o.rawLine}:null);return}if(o.snapshot){Sn(n,o.snapshot),P(),m(null);return}m(o.preview??null)}catch{i(t(`codexSet.prompt.writeFailed`))}finally{o(null)}}},te=async r=>{if(L&&L.drift!==null){v(!0),i(``);try{let a=await fetch(e+`/api/codex-prompt/repair`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r?{confirm:!0,revision:L.revision}:{confirm:!1})}),o=await a.json();if(!a.ok||!o.ok){if(o.code===`stale_revision`){I.refresh(),P(),i(t(`codexSet.prompt.staleRevision`));return}i(o.message??t(`codexSet.prompt.repairFailed`));return}o.snapshot?Sn(n,o.snapshot):I.refresh(),P()}catch{i(t(`codexSet.prompt.repairFailed`))}finally{v(!1)}}},ne=[...L?.inventory??[]].filter(e=>e.class!==`extension-unknown`).sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),K=new Set([`realtime`,`model-switch`]),q=ne.filter(e=>!K.has(e.id)),J=ne.filter(e=>K.has(e.id)),re=ne.find(e=>e.id===s)??null,Y=l===null||l===`new`?-1:L?.custom.findIndex(e=>e.id===l)??-1,ie=Y>=0?L.custom[Y]:null,ae=l!==null&&l!==`new`&&L!==void 0&&Y<0;return(0,Z.useEffect)(()=>{if(k!==null)return;let t=new AbortController,n=!1;return(async()=>{try{let r=await fetch(e+`/api/codex-prompt/text`,{signal:t.signal});if(!r.ok){n||A({ok:!1,failure:{kind:`request-failed`}});return}let i=await r.json();n||A(i)}catch{n||A({ok:!1,failure:{kind:`request-failed`}})}})(),()=>{n=!0,t.abort()}},[k,e]),(0,Q.jsxs)(`div`,{className:`panel codex-set-prompt`,children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:t(`codexSet.prompt.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k===null||a!==null,onClick:P,children:t(`codexSet.prompt.remeasure`)})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:t(`codexSet.prompt.timing`)}),R.refreshing&&(0,Q.jsx)(lk,{live:!R.showError,children:t(`common.loading`)}),R.showSkeleton&&(0,Q.jsx)(ck,{label:t(`common.loading`),rows:5}),L&&!L.readable&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`codexSet.prompt.unreadable`)}),R.showError&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`codexSet.prompt.loadFailed`)}),(r||ae)&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:ae?t(`codexSet.custom.layerGone`):r}),L?.drift&&(0,Q.jsxs)(`div`,{className:`notice codex-set-prompt__drift`,role:`alert`,"data-drift":L.drift,children:[(0,Q.jsx)(`span`,{children:t(wB[L.drift])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:_,onClick:()=>{te(!0)},children:t(`codexSet.prompt.repair`)})]}),(0,Q.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:q.map(e=>(0,Q.jsx)($z,{descriptor:e,toggle:L?.toggles.find(t=>t.id===e.id),bytes:k?.layers?.[e.id]?.bytes??null,busy:a===e.id,writesRefused:L?.readable===!1,onToggle:(e,t)=>{z(e,t)},onReset:e=>{z(e,null)},onSelectBase:e.class===`base`&&L?(t=>{if(t){B(`/api/codex-prompt/base/select`,{kind:`default`});return}let n=L.baseVariants[0];n?B(`/api/codex-prompt/base/select`,{kind:`variant`,id:n.id}):c(e.id)}):void 0,baseSelection:L?.baseSelection,onOpen:c},e.id))}),J.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`row codex-set-prompt__group`,children:(0,Q.jsx)(`strong`,{children:t(`codexSet.group.transition`)})}),(0,Q.jsx)(`p`,{className:`muted small`,children:t(`codexSet.group.transitionDesc`)}),(0,Q.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:J.map(e=>(0,Q.jsx)($z,{descriptor:e,toggle:L?.toggles.find(t=>t.id===e.id),bytes:k?.layers?.[e.id]?.bytes??null,transitionOnly:!0,busy:a===e.id,writesRefused:L?.readable===!1,onToggle:(e,t)=>{z(e,t)},onReset:e=>{z(e,null)},onOpen:c},e.id))})]}),L&&!L.extensionLayersEnumerable&&(0,Q.jsx)(`p`,{className:`muted small codex-set-prompt__extensions`,children:t(`codexSet.prompt.extensionsUnknown`)}),re&&(re.class===`base`&&L?(0,Q.jsx)(SB,{variants:L.baseVariants,selection:L.baseSelection,maxVariants:L.maxBaseVariants,busy:a!==null||!L.readable,importPreview:S,importRefusal:w,onSelect:e=>{B(`/api/codex-prompt/base/select`,e)},onSave:e=>B(`/api/codex-prompt/base`,e),onDelete:e=>{B(`/api/codex-prompt/base`,{id:e,delete:!0})},onImport:(e,t)=>{V(e,t)},onImportTitle:H,onClose:U}):(0,Q.jsx)(eB,{descriptor:re,toggle:L?.toggles.find(e=>e.id===re.id),text:k?.layers?.[re.id],probe:k,busy:a!==null,onToggle:(e,t)=>{z(e,t)},onReset:e=>{z(e,null)},onClose:()=>c(null),onRemeasure:P})),L&&(0,Q.jsxs)(`section`,{className:`codex-set-custom`,children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:t(`codexSet.custom.heading`)}),L.developerInstructionsState===`external`?null:(0,Q.jsx)(vB,{disabled:L.custom.length>=32||a!==null||!L.readable,onBlank:()=>{x(null),u(`new`)},onPreset:(e,t)=>{x({body:e,title:t}),u(`new`)}})]}),L.custom.length>=32&&(0,Q.jsx)(`p`,{className:`muted small`,children:t(`codexSet.custom.limitReached`,{max:32})}),L.developerInstructionsState===`external`&&L.modelInstructionsFile===null&&(0,Q.jsxs)(`div`,{className:`codex-set-custom__adopt`,children:[(0,Q.jsx)(`p`,{className:`muted small`,children:t(`codexSet.custom.notOwned`)}),h&&(0,Q.jsx)(`p`,{className:`muted small codex-set-custom__adopt-refusal`,children:t(`codexSet.custom.adoptUnsupported`,{path:h.path??``,line:h.line??0})}),p?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`pre`,{className:`api-code codex-set-custom__adopt-preview`,children:p.decodedBody}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:a!==null,onClick:()=>{G(!0)},children:t(`codexSet.custom.adoptConfirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>m(null),children:t(`common.cancel`)})]})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:a!==null,onClick:()=>{G(!1)},children:t(`codexSet.custom.adopt`)})]}),L.baseSelection.kind===`external`&&(0,Q.jsxs)(`p`,{className:`muted small codex-set-custom__replaced`,children:[t(`codexSet.custom.baseReplaced`,{path:L.baseSelection.path}),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>c(`base-instructions`),children:t(`codexSet.custom.baseReplacedOpen`)})]}),(0,Q.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:L.custom.map((e,t)=>(0,Q.jsx)(dB,{layer:e,index:t,total:L.custom.length,busy:a!==null||!L.readable,onToggle:(e,t)=>{W(L.custom.map(n=>n.id===e?{...n,enabled:t}:n),e)},onEdit:u,onDelete:f,onMove:(e,t)=>{W(uB(L.custom,e,t),e)}},e.id))}),L.custom.length>0&&(()=>{let e=sB(L.custom),n=nB(e);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:n>131072?`notice notice-err`:`muted small`,children:t(`codexSet.custom.composedSize`,{bytes:n,max:131072})}),e.length>0&&(0,Q.jsxs)(`details`,{className:`codex-set-custom__preview`,children:[(0,Q.jsx)(`summary`,{className:`muted small`,children:t(`codexSet.custom.composedPreview`)}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-custom__preview-body`,children:e})]})]})})(),j&&(0,Q.jsxs)(`div`,{className:`notice codex-set-custom__deleted`,role:`status`,children:[(0,Q.jsx)(`span`,{children:t(`codexSet.custom.deletedNamed`,{title:j.layer.title})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:a!==null,onClick:()=>{let{layer:e,index:t}=j,n=[...L.custom];n.splice(Math.min(t,n.length),0,e),N.current&&clearTimeout(N.current),N.current=null,(async()=>{await W(n,e.id)?M(null):N.current=setTimeout(()=>M(null),lB())})()},children:t(`common.undo`)})]}),d&&(0,Q.jsxs)(`div`,{className:`notice codex-set-custom__confirm`,role:`alertdialog`,"aria-labelledby":`codex-set-delete-confirm`,children:[(0,Q.jsx)(`span`,{id:`codex-set-delete-confirm`,children:t(`codexSet.custom.deleteConfirmNamed`,{title:L.custom.find(e=>e.id===d)?.title??``})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:()=>{let e=d,t=L.custom.findIndex(t=>t.id===e),n=t>=0?L.custom[t]:null;f(null),(async()=>{await W(L.custom.filter(t=>t.id!==e),e)&&n&&(N.current&&clearTimeout(N.current),M({layer:n,index:t}),N.current=setTimeout(()=>M(null),lB()))})()},children:t(`common.delete`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>f(null),children:t(`common.cancel`)})]})]}),l&&L&&!ae&&(0,Q.jsx)(gB,{layer:l===`new`?null:ie,seed:l===`new`?y:null,others:L.custom,busy:a!==null,navigation:Y>=0&&L.custom.length>1?{position:Y+1,total:L.custom.length,onPrev:()=>{Y>0&&u(L.custom[Y-1].id)},onNext:()=>{Y<L.custom.length-1&&u(L.custom[Y+1].id)}}:void 0,onSave:ee,onClose:()=>{u(null),x(null)}})]})}var EB=[`npm`,`pnpm`,`bun`,`source`,`mise`,`desktop-app`,`goat`,`standalone`,`ocx-child`,`unknown`],DB=[`observe`,`sync`,`restart-codex`,`update`],OB=e=>typeof e==`string`&&e.length>0&&e.length<=256?e:null,kB=e=>typeof e==`number`&&Number.isFinite(e)?e:null,AB=e=>typeof e==`boolean`?e:null,jB=(e,t)=>e.includes(t)?t:null;function MB(e){if(!rV(e))return null;let t=OB(e.homeVersion),n=rV(e.update)?e.update:null,r=rV(e.catalog)?e.catalog:null,i=rV(e.activity)?e.activity:null,a=rV(e.activeJob)?e.activeJob:null,o=rV(e.lastOperation)?e.lastOperation:null,s=rV(e.codex)?{appServers:jB([`fresh`,`stale`,`not_running`,`unknown`],e.codex.appServers)??`unknown`,staleCount:kB(e.codex.staleCount)??0,catalogMatchesHome:AB(e.codex.catalogMatchesHome),catalogSyncedAt:kB(e.codex.catalogSyncedAt),reportedAt:kB(e.codex.reportedAt)??0}:null;if(!t||!n||!r||!i)return null;let c=jB(DB,o?.op);return{homeVersion:t,runningVersion:OB(e.runningVersion),installedVersion:OB(e.installedVersion),installKind:jB(EB,e.installKind),versionSkew:jB([`same`,`behind`,`ahead`,`unknown`],e.versionSkew)??`unknown`,update:{route:jB([`orchestrated`,`desktop-request`,`owner-action`,`replant`,`none`],n.route),reason:OB(n.reason),observedAt:OB(n.observedAt)},catalog:{state:jB([`current`,`behind`,`unknown`],r.state)??`unknown`,pulledAt:kB(r.pulledAt),homeChangedAt:kB(r.homeChangedAt)},codex:s,childBuild:OB(e.childBuild),activity:{idle:i.idle===!0,inFlight:kB(i.inFlight)??0,lastDataEndAt:kB(i.lastDataEndAt)},activeJob:a&&OB(a.jobId)&&a.state!==`done`&&jB(DB,a.op)?{jobId:OB(a.jobId),op:jB(DB,a.op),state:a.state===`queued`?`queued`:`running`}:null,lastOperation:o&&c&&OB(o.jobId)?{op:c,jobId:OB(o.jobId),state:OB(o.state)??`failed`,reason:OB(o.reason),fromVersion:OB(o.fromVersion),toVersion:OB(o.toVersion),finishedAt:OB(o.finishedAt)}:null}}function NB(e){if(!rV(e)||e.schema!==`ocx.link.child-job/1`||!OB(e.jobId)||!Array.isArray(e.items))throw Error(`invalid job`);let t=jB(DB,e.op);if(!t)throw Error(`invalid job op`);return{jobId:OB(e.jobId),op:t,trigger:e.trigger===`auto`?`auto`:`manual`,restart:jB([`none`,`app-server`,`codex`],e.restart)??`none`,state:jB([`queued`,`running`,`done`],e.state)??`running`,items:e.items.filter(rV).map(e=>{let t=rV(e.sync)?{state:OB(e.sync.state)??`failed`,reason:OB(e.sync.reason)}:null,n=rV(e.restart)?{requested:OB(e.restart.requested)??`app-server`,outcome:OB(e.restart.outcome)??``}:null;return{linkId:OB(e.linkId)??``,alias:OB(e.alias)??``,state:OB(e.state)??`failed`,reason:OB(e.reason),hint:OB(e.hint),fromVersion:OB(e.fromVersion),toVersion:OB(e.toVersion),sync:t,restart:n}})}}function PB(e){let t=rV(e)&&rV(e.policy)?e.policy:null,n=t?kB(t.idleAfterMs):null;if(!t||n===null)throw Error(`invalid policy`);return{policy:{catalogFanout:jB([`auto`,`manual`],t.catalogFanout)??`manual`,childCodexRestart:jB([`never`,`app-server-when-idle`],t.childCodexRestart)??`never`,updates:jB([`off`,`notify`,`auto-when-idle`],t.updates)??`off`,idleAfterMs:n},warning:rV(e)&&e.warning===`policy-file-invalid`?`policy-file-invalid`:null}}var FB={"content-type":`application/json`},IB=3e4;async function LB(e,t,n=IB){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return NB((await YB(gV(e,`/api/link/children/operations`,{method:`POST`,headers:FB,body:JSON.stringify(t),signal:r.signal}),r.signal)).job)}finally{clearTimeout(i)}}async function RB(e,t,n){return NB((await gV(e,`/api/link/children/jobs/${encodeURIComponent(t)}`,{signal:n})).job)}async function zB(e,t){return PB(await gV(e,`/api/link/children/policy`,{signal:t}))}async function BB(e,t){return PB(await gV(e,`/api/link/children/policy`,{method:`PUT`,headers:FB,body:JSON.stringify(t)}))}function VB(e){return e.versionSkew===`behind`&&(e.update.route===`orchestrated`||e.update.route===`desktop-request`)}function HB(e){return e.codex!==null&&(e.codex.appServers===`stale`||e.codex.catalogMatchesHome===!1)}function UB(e,t){return e===`hub-initiated`&&t!==null}function WB(e){return e===`skipped`}function GB(e,t){return e.some(e=>e.state!==`done`&&e.items.some(e=>e.linkId===t&&(e.state===`queued`||e.state===`running`)))}var KB=2e3;function qB(e,t=64){let n=Math.ceil(e.length/t),r=n>0?Math.floor(e.length/n):0,i=n>0?e.length%n:0,a=[],o=0;for(let t=0;t<n;t+=1){let n=r+ +(t<i);a.push(e.slice(o,o+n)),o+=n}return a}var JB=15e3;function YB(e,t){return new Promise((n,r)=>{let i=()=>r(t.reason??new DOMException(`aborted`,`AbortError`));t.aborted?i():(t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i)))})}function XB(e,t){let n={};for(let r of[`catalogFanout`,`childCodexRestart`,`updates`,`idleAfterMs`])t[r]!==e[r]&&Object.assign(n,{[r]:t[r]});return n}var ZB=[`pairing_required`,`standalone_required`,`join_port_mismatch`],QB=[`connecting`,`connected`,`reconnecting`,`failed`,`idle`],$B=[`standalone`,`home`,`child`];function eV(e){let t=typeof e.linkId==`string`&&/^lnk_[0-9a-f]{16}$/.test(e.linkId)?e.linkId:null;if(t===null)return{step:`noLink`,linkId:null};if(e.residualKind===`plant`)return{step:e.remotePlatform===`windows`?`purgeWindows`:e.remotePlatform===`posix`?`purge`:`purgeAny`,linkId:t};let n=e.remotePlatform===`posix`||e.remotePlatform===`windows`?e.remotePlatform:void 0;return{step:e.residualInstall===`ephemeral`||e.residualInstall===`full`?e.residualInstall:`unknown`,linkId:t,...n?{platform:n}:{}}}var tV=class extends Error{code;status;hint;residual;constructor(e,t,n=null,r=null){super(e),this.name=`LinkApiError`,this.code=e,this.status=t,this.hint=n,this.residual=r}},nV=160;function rV(e){return typeof e==`object`&&!!e}function iV(e){return e<32||e>=127&&e<=159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e===65279}function aV(e){if(typeof e!=`string`)return null;let t=Array.from(e,e=>iV(e.codePointAt(0)??0)?` `:e).join(``).replace(/\s+/g,` `).trim();if(!t)return null;let n=Array.from(t);return n.length>nV?`${n.slice(0,159).join(``)}\u2026`:t}var oV=[`child_link_mismatch`,`child_residual`,`child_disconnect_pending`,`expect_link_unsupported`];function sV(e){return oV.find(t=>t===e)??null}function cV(e){return typeof e==`string`&&e.length>0}var lV=/^lnk_[0-9a-f]{16}$/;function uV(e){return typeof e==`string`&&lV.test(e)}function dV(e){return typeof e==`string`&&QB.includes(e)}function fV(e){if(!rV(e)||!$B.includes(e.role))throw Error(`invalid status`);let t=e.listener;if(!rV(t)||![`off`,`listening`,`failed`].includes(String(t.state))||t.port!==null&&typeof t.port!=`number`)throw Error(`invalid listener`);if(!Array.isArray(e.links))throw Error(`invalid links`);let n=e.links.map(e=>{if(!rV(e)||!uV(e.id)||!cV(e.alias)||![`hub-initiated`,`client-initiated`].includes(String(e.direction))||!dV(e.state)||!cV(e.since)||e.reason!==null&&typeof e.reason!=`string`||typeof e.tunnelPort!=`number`)throw Error(`invalid link`);let t=e.childKind===`full`||e.childKind===`ephemeral`?e.childKind:null,n=cV(e.appliedCodexSettingsDigest)?e.appliedCodexSettingsDigest:null;return{id:e.id,alias:e.alias,direction:e.direction,state:e.state,since:e.since,reason:e.reason,tunnelPort:e.tunnelPort,childKind:t,appliedCodexSettingsDigest:n,child:MB(e.child)}}),r=null;if(e.child!==null){if(!rV(e.child)||!cV(e.child.alias)||!dV(e.child.state)||!cV(e.child.since)||e.child.reason!==null&&typeof e.child.reason!=`string`)throw Error(`invalid child`);r={alias:e.child.alias,state:e.child.state,since:e.child.since,reason:e.child.reason}}let i=ZB.includes(e.joinDenied)?e.joinDenied:null,a=cV(e.homeCodexSettingsDigest)?e.homeCodexSettingsDigest:null;return{role:e.role,listener:{state:t.state,port:t.port},links:n,child:r,joinAvailable:e.joinAvailable===!0,joinDenied:i,homeCodexSettingsDigest:a}}function pV(e){if(!rV(e)||!cV(e.alias)||!cV(e.fingerprint))throw Error(`invalid confirmation`);let t=e.runtimeKind===`ephemeral`||e.runtimeKind===`missing`?e.runtimeKind:`full`;if(t===`missing`){if(e.ocxVersion!==null&&e.ocxVersion!==void 0)throw Error(`invalid confirmation`)}else if(!cV(e.ocxVersion))throw Error(`invalid confirmation`);return{alias:e.alias,fingerprint:e.fingerprint,ocxVersion:t===`missing`?null:String(e.ocxVersion),runtimeKind:t,targetTriple:cV(e.targetTriple)?e.targetTriple:null,plantable:e.plantable===!0,binarySizeBytes:typeof e.binarySizeBytes==`number`&&Number.isFinite(e.binarySizeBytes)&&e.binarySizeBytes>0?e.binarySizeBytes:null,plantUnavailableReason:cV(e.plantUnavailableReason)?e.plantUnavailableReason:null}}function mV(e){return!e||!Number.isFinite(e)||e<=0?`~0.9 MB`:`~${Math.max(.1,e/1048576).toFixed(1)} MB`}async function hV(e){let t;try{t=await e.json()}catch{}if(!e.ok){let n=rV(t)&&rV(t.error)?t.error:null,r=n&&typeof n.code==`string`?n.code:`unknown`,i=rV(t)&&t.residual===!0?eV(t):null;throw new tV(r,e.status,aV(n?.hint),i)}if(t==null)throw new tV(`invalid_body`,e.status);return t}async function gV(e,t,n){return hV(await fetch(`${e}${t}`,{...n,cache:`no-store`}))}async function _V(e,t,n=fetch){try{let r=await n(`${e}/healthz`,{cache:`no-store`,signal:t});if(!r.ok)return null;let i=await r.json();return!rV(i)||i.service!==`opencodex`?null:{role:typeof i.role==`string`?i.role:null,pid:typeof i.pid==`number`?i.pid:null}}catch{return null}}var vV=1e3,yV=5e3,bV=145e3,xV=2e3;function SV(e,t){return new Promise(n=>{let r=setTimeout(i,e);function i(){clearTimeout(r),t.removeEventListener(`abort`,i),n()}t.addEventListener(`abort`,i,{once:!0})})}async function CV(e,t,n,r={}){let i=r.now??Date.now,a=r.sleep??SV,o=i()+bV,s=!1;for(;;){if(n.aborted)return`aborted`;let c=await _V(e,AbortSignal.any([n,AbortSignal.timeout(xV)]),r.fetchImpl);if(n.aborted)return`aborted`;if(c?.role===`client`&&(t===null||c.pid!==t))return`ready`;!s&&i()>=o&&(s=!0,r.onSlow?.()),await a(s?yV:vV,n)}}var wV=/^ocx_pair_[A-Za-z0-9_-]{43}$/,TV=1e4,EV=class extends Error{kind;constructor(e){super(`pairing_${e}`),this.kind=e,this.name=`PairingError`}},DV=16384;function OV(e,t=``){return e.headers.get(`cf-mitigated`)?.trim().toLowerCase()===`challenge`||/<title>\s*Just a moment\.\.\./i.test(t)||/cf-chl-|challenge-platform|challenges\.cloudflare\.com/i.test(t)}async function kV(e,t=DV){let n=e.body?.getReader();if(!n)return``;let r=[],i=0;try{for(;i<t;){let{done:e,value:a}=await n.read();if(e||!a)break;let o=a.subarray(0,t-i);if(r.push(o),i+=o.byteLength,o.byteLength<a.byteLength)break}}finally{try{n.cancel().catch(()=>{})}catch{}}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)}async function AV(e){return OV(e)?!0:e.headers.get(`content-type`)?.toLowerCase().includes(`text/html`)?OV(e,await kV(e)):!1}async function jV(e,t,n,r){r?.throwIfAborted();let i=t.trim();if(!wV.test(i))throw new EV(`invalid-code`);let a=n??((e,t)=>window.fetch(e,t)),o=A(e.id);return J(TV,r,async t=>{let n;try{n=await a(e.bootstrapPath,{method:`POST`,signal:t,headers:{"Content-Type":`application/json`,Accept:`text/html`},body:JSON.stringify({grant:i})})}catch(e){throw r?.aborted?e:new EV(`unreachable`)}if(!n.ok)throw await AV(n)?new EV(`cloudflare-challenge`):(_(n),n.status===401?new EV(`refused`):n.status===403?new EV(`origin-denied`):new EV(`request-failed`));let s;try{s=await n.text()}catch(e){throw r?.aborted?e:new EV(`invalid-response`)}if(t.throwIfAborted(),OV(n,s))throw new EV(`cloudflare-challenge`);if(!o.install(s))throw o.rollback(),new EV(`invalid-response`);return o}).catch(e=>{throw o.rollback(),r?.throwIfAborted(),e instanceof EV?e:new EV(`unreachable`)})}async function MV(e,t,n){n?.throwIfAborted();let r=t??((e,t)=>M(`shared`,e,t??{}));return J(TV,n,async t=>{let n;try{n=await r(`${e}/api/link/status`,{cache:`no-store`,signal:t,headers:{Accept:`application/json`}})}catch{throw t.throwIfAborted(),new EV(`unreachable`)}if(t.throwIfAborted(),!n.ok)throw await AV(n)?new EV(`cloudflare-challenge`):await f(n)?new EV(`client-state-changed`):(_(n),n.status===401?new EV(`remote-link-unauthorized`):n.status===403?new EV(`remote-link-forbidden`):new EV(`request-failed`));if(await AV(n))throw new EV(`cloudflare-challenge`);if(!q(`shared`))throw new EV(`invalid-response`);try{let e=await n.json();t.throwIfAborted(),fV(e)}catch{throw t.throwIfAborted(),new EV(`invalid-response`)}}).catch(e=>{throw n?.throwIfAborted(),e instanceof EV?e:new EV(`unreachable`)})}var NV=`/api/codex/desktop-compatibility/`,PV=e=>!!e&&typeof e==`object`&&!Array.isArray(e),FV=class extends Error{code;constructor(e){super(e),this.code=e}};async function IV(e){if(e.status===401)throw await e.body?.cancel(),new FV(`desktop_authorization_required`);let t;try{t=await e.json()}catch{throw new FV(`invalid_response`)}if(!PV(t))throw new FV(`invalid_response`);if(!e.ok||t.ok!==!0){let e=t.error??(PV(t.activation)?t.activation.reason:void 0)??(PV(t.launch)?t.launch.reason:void 0);throw new FV(typeof e==`string`&&/^[a-z][a-z_-]{0,79}$/.test(e)?e:`operation_unconfirmed`)}return t}function LV(e){if(!PV(e)||typeof e.startOnProxyStart!=`boolean`||typeof e.revision!=`string`||!/^[a-f0-9]{64}$/.test(e.revision))throw new FV(`invalid_startup_settings`);return{startOnProxyStart:e.startOnProxyStart,revision:e.revision}}async function RV(e,t){return LV((await IV(await fetch(e+`/api/codex/desktop-compatibility/settings`,{signal:t}))).settings)}async function zV(e,t,n,r){return LV((await IV(await te(e+`/api/codex/desktop-compatibility/settings`,{method:`POST`,signal:r,headers:{"content-type":`application/json`},body:JSON.stringify({startOnProxyStart:n,revision:t.revision,confirmed:!0})}))).settings)}function BV(e){if(!PV(e)||typeof e.supported!=`boolean`||typeof e.state!=`string`||![`missing`,`invalid`,`expired`,`renewal-required`,`prepared`,`trusted`,`unknown`].includes(e.state)||!(e.busy===null||typeof e.busy==`string`&&[`prepare`,`trust`,`remove-trust`,`renew`].includes(e.busy))||e.fingerprint!==void 0&&(typeof e.fingerprint!=`string`||!/^[A-F0-9]{64}$/.test(e.fingerprint))||e.expiresAt!==void 0&&(typeof e.expiresAt!=`number`||!Number.isFinite(e.expiresAt)||Math.abs(e.expiresAt)>864e13))throw new FV(`invalid_certificate_status`);return{supported:e.supported,state:e.state,busy:e.busy,...typeof e.mutationAuthorized==`boolean`?{mutationAuthorized:e.mutationAuthorized}:{},...e.fingerprint===void 0?{}:{fingerprint:e.fingerprint},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},renewalDue:e.renewalDue===!0}}function VV(e){if(!PV(e)||typeof e.supported!=`boolean`||typeof e.running!=`boolean`||typeof e.phase!=`string`||![`off`,`starting`,`running`,`stopping`,`cleanup-required`].includes(e.phase)||e.phase===`running`&&!e.running||(e.phase===`off`||e.phase===`starting`)&&e.running)throw new FV(`invalid_runtime_status`);let t={supported:e.supported,running:e.running,phase:e.phase};if(e.contextFailure!==void 0){if(e.contextFailure!==null&&e.contextFailure!==`build_unverified`&&e.contextFailure!==`native_routing_unverified`)throw new FV(`invalid_runtime_status`);t.contextFailure=e.contextFailure}if(e.buildAssessment!==void 0){if(e.buildAssessment===null)t.buildAssessment=null;else{let n=e.buildAssessment,r=e=>typeof e==`string`&&/^\d{1,5}(\.\d{1,5}){3}$/.test(e);if(!PV(n)||!r(n.assessedVersion)||!(n.observedVersion===null||r(n.observedVersion))||typeof n.verified!=`boolean`||!Number.isSafeInteger(n.completedAt)||Number(n.completedAt)<0||Number(n.completedAt)>864e13||n.verified===!0&&n.observedVersion!==n.assessedVersion)throw new FV(`invalid_runtime_status`);t.buildAssessment={assessedVersion:n.assessedVersion,observedVersion:n.observedVersion===null?null:n.observedVersion,verified:n.verified,completedAt:n.completedAt}}}if(e.usage!==void 0){if(!PV(e.usage)||typeof e.usage.mode!=`string`||![`observe`,`apply`].includes(e.usage.mode)||typeof e.usage.phase!=`string`||!/^[a-z-]{1,80}$/.test(e.usage.phase)||!Number.isSafeInteger(e.usage.outputs)||Number(e.usage.outputs)<0||e.usage.appCacheConfirmed!==!1)throw new FV(`invalid_runtime_status`);if(t.usage={mode:e.usage.mode,phase:e.usage.phase,outputs:e.usage.outputs,appCacheConfirmed:!1},e.usage.observation!==void 0){let n=e.usage.observation;if(!PV(n)||![n.jsonSnapshots,n.streamSnapshots,n.validatedActiveStreams].every(e=>Number.isSafeInteger(e)&&Number(e)>=0)||!(n.lastSnapshotAt===null||typeof n.lastSnapshotAt==`number`&&Number.isSafeInteger(n.lastSnapshotAt)&&n.lastSnapshotAt>=0&&n.lastSnapshotAt<=864e13)||n.sourceProcessVerified!==!1||n.composerRecoveryVerified!==!1)throw new FV(`invalid_runtime_status`);t.usage.observation={jsonSnapshots:n.jsonSnapshots,streamSnapshots:n.streamSnapshots,validatedActiveStreams:n.validatedActiveStreams,lastSnapshotAt:n.lastSnapshotAt,sourceProcessVerified:!1,composerRecoveryVerified:!1}}}return t}async function HV(e,t){return VV((await IV(await fetch(e+`/api/codex/desktop-compatibility/runtime`,{signal:t}))).runtime)}async function UV(e,t){return BV((await IV(await fetch(e+`/api/codex/desktop-compatibility/certificate`,{signal:t}))).certificate)}async function WV(e,t){let[n,r]=await Promise.all([UV(e,t),HV(e,t)]);return{certificate:n,runtime:r}}async function GV(e,t,n){if(t.target===`certificate`&&t.action!==`prepare`&&(!t.fingerprint||!/^[A-F0-9]{64}$/.test(t.fingerprint)))throw new FV(`certificate_fingerprint_required`);await IV(await te(e+NV+t.target,{method:`POST`,signal:n,headers:{"content-type":`application/json`},body:JSON.stringify({action:t.action,confirmed:!0,...t.target===`certificate`&&t.action!==`prepare`?{fingerprint:t.fingerprint}:{},...t.target===`runtime`&&t.action===`apply`?{accountWideConsent:!0}:{}})}))}async function KV(e,t){let n=await IV(await te(e+`/api/codex/desktop-compatibility/authorization`,{signal:t,cache:`no-store`}));if(typeof n.authorized!=`boolean`||typeof n.supported!=`boolean`)throw new FV(`invalid_response`);return{supported:n.supported,authorized:n.authorized,rememberedSession:n.rememberedSession===!0}}async function qV(e,t,n){if(!/^ocx_pair_[A-Za-z0-9_-]{43}$/.test(t))throw new FV(`invalid_request`);await IV(await te(e+`/api/codex/desktop-compatibility/authorization`,{method:`POST`,signal:n,headers:{"content-type":`application/json`},body:JSON.stringify({grant:t})}));let r=await KV(e,n);if(!r.authorized)throw new FV(`desktop_authorization_required`);return r}function JV({apiBase:e,active:t,authorized:n}){let r=b(),i=`desktop-compatibility-startup:${e}`,a=vn(i,t=>RV(e,t),{enabled:t,deadlineMs:15e3,staleAfterMs:0}),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,f]=(0,Z.useState)(null),p=(0,Z.useRef)({alive:!0,pending:!1,generation:0,refreshRequired:!1,operation:null});(0,Z.useEffect)(()=>{let e=p.current;e.alive=!0;let t=()=>{e.generation++,e.pending=!1,e.operation?.controller.abort(),e.operation?.clear(),e.operation=null},n=n=>{if(n.detail?.plane!==`machine`)return;let r=e.pending;r&&(e.refreshRequired=!0),t(),s(!1),r&&(l(!0),f(`connection_unconfirmed`))};return window.addEventListener(D,n),()=>{window.removeEventListener(D,n),e.alive=!1,t()}},[]);async function m(t){let r=p.current;if(!r.alive||r.pending||t&&(r.refreshRequired||!a.data||!n))return;r.pending=!0;let o=++r.generation;s(!0),f(null);let c=d(15e3);r.operation=c;let u=()=>r.alive&&r.generation===o&&r.operation===c;try{if(t&&await zV(e,a.data,!a.data.startOnProxyStart,c.signal),!u())return;c.signal.throwIfAborted();let n=await RV(e,c.signal);if(!u())return;c.signal.throwIfAborted(),r.refreshRequired=!1,Sn(i,n),l(!1)}catch(t){u()&&(r.refreshRequired=!0,l(!0),f(t instanceof FV?t.code:`connection_unconfirmed`),t instanceof FV&&t.code===`desktop_authorization_required`&&Sn(`desktop-authorization:${e}`,{supported:!0,authorized:!1}))}finally{c.clear(),r.operation===c&&(r.operation=null),r.generation===o&&(r.pending=!1,r.alive&&s(!1))}}let h=a.error instanceof FV?a.error.code:a.error?`connection_unconfirmed`:null;return(0,Q.jsxs)(`div`,{className:`panel acc-desktop__setting`,children:[(0,Q.jsx)(Rn,{on:a.data?.startOnProxyStart===!0,label:r(`desktopCompat.autoStart`),showLabel:!0,disabled:!n||o||c||!a.lastAttemptOk||a.refreshing,onClick:()=>void m(!0)}),(0,Q.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.autoStartHint`)}),(u||h)&&(0,Q.jsxs)(k_,{tone:`err`,role:`alert`,children:[r(`desktopCompat.error`),` `,(0,Q.jsx)(`code`,{children:u??h})]}),(c||h)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:o,onClick:()=>void m(!1),children:r(`desktopCompat.refresh`)})]})}function YV({apiBase:e,authorized:t,onAuthorized:n}){let r=b(),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)({alive:!0,pending:!1,operation:null});(0,Z.useEffect)(()=>{let e=u.current;return e.alive=!0,()=>{e.alive=!1,e.operation?.controller.abort(),e.operation?.clear()}},[]);async function f(t){t.preventDefault();let r=u.current;if(r.pending)return;r.pending=!0,s(!0),l(null);let o=i.trim();a(``);let c=d(15e3);r.operation=c;try{await qV(e,o,c.signal),r.alive&&await n()}catch(e){r.alive&&l(e instanceof FV?e.code:`connection_unconfirmed`)}finally{c.clear(),r.pending=!1,r.operation=null,r.alive&&s(!1)}}return(0,Q.jsxs)(`div`,{className:`panel`,children:[(0,Q.jsx)(`p`,{className:t?`notice-ok`:`notice-warn`,children:r(t?`desktopCompat.authorized`:`desktopCompat.authorizeHint`)}),!t&&(0,Q.jsxs)(`form`,{onSubmit:e=>void f(e),children:[(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:`ocx gui pair --desktop --origin ${new URL(e||`/`,window.location.href).origin}`})}),(0,Q.jsxs)(`label`,{children:[r(`desktopCompat.authorizationCode`),(0,Q.jsx)(`input`,{className:`input`,type:`password`,autoComplete:`off`,value:i,disabled:o,onChange:e=>a(e.target.value)})]}),(0,Q.jsx)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:o||!i.trim(),children:r(`desktopCompat.authorize`)})]}),c&&(0,Q.jsxs)(`p`,{className:`notice-err`,role:`alert`,children:[r(`desktopCompat.authorizeHint`),` `,(0,Q.jsx)(`code`,{children:c})]})]})}var XV={prepare:`desktopCompat.prepare`,trust:`desktopCompat.trust`,"remove-trust":`desktopCompat.remove`,renew:`desktopCompat.renew`,start:`desktopCompat.start`,stop:`desktopCompat.stop`,launch:`desktopCompat.launch`,observe:`desktopCompat.observe`,apply:`desktopCompat.apply`},ZV={build_unverified:`desktopCompat.blockedByBuild`,egress_proxy_invalid:`desktopCompat.blockedByProxy`,desktop_authorization_required:`desktopCompat.authorizeHint`,renewal_required:`desktopCompat.renew`,native_routing_unverified:`desktopCompat.routingChanged`,connection_unavailable:`desktopCompat.connectionUnavailable`,connection_invalid:`desktopCompat.connectionUnavailable`,connection_changed:`desktopCompat.connectionUnavailable`,app_running:`desktopCompat.closeApp`,local_dashboard_confirmation_required:`desktopCompat.localOnly`};function QV({apiBase:e,active:t}){let{t:n,locale:r}=s(),[i,a]=(0,Z.useState)(!1),[o,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(!0),b=`desktop-authorization:${e}`,x=vn(b,t=>KV(e,t),{enabled:t,deadlineMs:1e4,staleAfterMs:0,pollMs:5e3}),S=x.lastAttemptOk&&x.data?.authorized===!0,[C,w]=(0,Z.useState)(S);C!==S&&(w(S),h(null),_(!1));let T=(0,Z.useRef)({alive:!0,pending:!1,generation:0,operations:new Set}),E=`desktop-compatibility-certificate:${e}`,O=`desktop-compatibility-runtime:${e}`,k=vn(E,t=>UV(e,t),{enabled:t,deadlineMs:15e3,staleAfterMs:0}),A=vn(O,t=>HV(e,t),{enabled:t,deadlineMs:1e4,staleAfterMs:0,pollMs:5e3}),j=k.data&&A.data?{certificate:k.data,runtime:A.data}:null,M=!i&&k.lastAttemptOk&&A.lastAttemptOk&&!k.refreshing&&!A.refreshing,N=o||k.loading||A.loading,P=k.error??A.error,F=l??(P?P instanceof FV?P.code:`connection_unconfirmed`:null),I=S&&v;(0,Z.useEffect)(()=>{let e=T.current;e.alive=!0;let t=t=>{if(t.detail?.plane===`machine`){e.generation++,e.pending=!1;for(let t of e.operations)t.controller.abort(),t.clear();e.operations.clear(),c(!1),y(!1),a(!0),h(null),_(!1),p(!1)}};return window.addEventListener(D,t),()=>{window.removeEventListener(D,t),e.alive=!1,e.generation++,e.pending=!1;for(let t of e.operations)t.controller.abort(),t.clear();e.operations.clear()}},[]);let L=(0,Z.useCallback)(async t=>{let n=T.current;if(n.pending||t&&!I)return;n.pending=!0;let r=++n.generation;c(!0),u(null),p(!1),a(!0);let i=d(t?14e4:15e3);n.operations.add(i);try{t&&await GV(e,t,i.signal);let o=await WV(e,i.signal);n.alive&&n.generation===r&&(Sn(E,o.certificate),Sn(O,o.runtime),a(!1),y(!0),p(!!t),h(null),_(!1))}catch(e){n.alive&&n.generation===r&&(u(e instanceof FV?e.code:`connection_unconfirmed`),h(null),_(!1),e instanceof FV&&e.code===`desktop_authorization_required`&&Sn(b,{supported:!0,authorized:!1}))}finally{n.operations.delete(i),i.clear(),n.generation===r&&(n.pending=!1,n.alive&&c(!1))}},[e,E,O,b,I]);async function R(){h(null),_(!1),p(!1),a(!0);let t=d(15e3);T.current.operations.add(t);try{let n=await RV(e,t.signal);if(!T.current.alive)return;Sn(`desktop-compatibility-startup:${e}`,n),await L();let r=await KV(e,t.signal);T.current.alive&&Sn(b,r)}finally{t.clear(),T.current.operations.delete(t)}}let z=!!j?.certificate.supported&&!!j.runtime.supported,B=j?.runtime.phase===`off`&&!j.certificate.busy,V=j?.runtime.phase===`running`,H=[];if(j&&z){let e=j.certificate;B&&e.state===`missing`&&H.push({target:`certificate`,action:`prepare`}),B&&e.fingerprint&&(e.state===`prepared`&&H.push({target:`certificate`,action:`trust`,fingerprint:e.fingerprint}),[`trusted`,`expired`,`renewal-required`,`unknown`].includes(e.state)&&H.push({target:`certificate`,action:`remove-trust`,fingerprint:e.fingerprint}),[`prepared`,`trusted`,`expired`,`renewal-required`].includes(e.state)&&H.push({target:`certificate`,action:`renew`,fingerprint:e.fingerprint})),B&&e.state===`trusted`&&H.push({target:`runtime`,action:`start`}),V&&H.push({target:`runtime`,action:`launch`},{target:`runtime`,action:`observe`},{target:`runtime`,action:`apply`}),(V||j.runtime.phase===`cleanup-required`)&&H.push({target:`runtime`,action:`stop`})}let U=j?.certificate.state===`trusted`?`ok`:j?.certificate.state===`missing`?`idle`:`warn`,W=V?`ok`:`idle`;return(0,Q.jsxs)(`section`,{className:`panel acc-desktop relative flex flex-col gap-4`,children:[(0,Q.jsxs)(`div`,{className:`acc-desktop__intro flex flex-col gap-1 pr-36`,children:[(0,Q.jsx)(`h2`,{children:n(`desktopCompat.title`)}),(0,Q.jsx)(`p`,{className:`muted text-body`,children:n(`desktopCompat.description`)}),(0,Q.jsx)(`p`,{className:`muted text-control`,children:n(`desktopCompat.localOnly`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm acc-desktop__refresh`,disabled:N,onClick:()=>void L(),children:n(N?`common.loading`:`desktopCompat.refresh`)}),x.data?.supported===!1&&(0,Q.jsx)(`p`,{className:`notice-warn`,role:`status`,children:n(`desktopCompat.authorizationUnavailable`)}),x.data?.supported&&x.data.rememberedSession&&(0,Q.jsx)(`p`,{className:`notice-warn`,role:`status`,children:n(`desktopCompat.rememberedSession`)}),x.data?.supported&&!x.data.rememberedSession&&(0,Q.jsx)(`div`,{className:`acc-desktop__card`,children:(0,Q.jsx)(YV,{apiBase:e,authorized:I,onAuthorized:R})}),(0,Q.jsx)(JV,{apiBase:e,active:t,authorized:I&&!i}),F&&(0,Q.jsxs)(k_,{tone:`err`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:n(F in ZV?ZV[F]:`desktopCompat.error`)}),(0,Q.jsx)(`code`,{className:`text-[12px] text-fg-muted`,children:F})]}),f&&(0,Q.jsx)(k_,{tone:`ok`,role:`status`,children:n(`desktopCompat.done`)}),j&&(0,Q.jsxs)(Q.Fragment,{children:[!z&&(0,Q.jsx)(k_,{tone:`warn`,children:n(`desktopCompat.unsupported`)}),(0,Q.jsxs)(`dl`,{className:`acc-desktop__status`,children:[(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:n(`desktopCompat.certificate`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsxs)(`span`,{className:`acc-desktop__state`,children:[(0,Q.jsx)(A_,{tone:U}),(0,Q.jsx)(`code`,{children:j.certificate.state})]})}),j.certificate.fingerprint&&(0,Q.jsx)(`dd`,{className:`mono text-label acc-desktop__detail`,style:{overflowWrap:`anywhere`},children:j.certificate.fingerprint})]}),j.certificate.expiresAt!==void 0&&(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:n(`desktopCompat.expiry`)}),(0,Q.jsx)(`dd`,{children:new Date(j.certificate.expiresAt).toLocaleString(r)})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:n(`desktopCompat.runtime`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsxs)(`span`,{className:`acc-desktop__state`,children:[(0,Q.jsx)(A_,{tone:W}),(0,Q.jsx)(`code`,{children:j.runtime.phase}),j.runtime.usage&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,(0,Q.jsx)(`code`,{children:j.runtime.usage.mode})]})]})})]}),j.runtime.buildAssessment&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:n(`desktopCompat.assessedPackage`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:j.runtime.buildAssessment.assessedVersion})})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:n(`desktopCompat.observedPackage`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:j.runtime.buildAssessment.observedVersion??n(`desktopCompat.noObservedPackage`)})})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:n(`desktopCompat.lastObservedAt`)}),(0,Q.jsx)(`dd`,{children:new Date(j.runtime.buildAssessment.completedAt).toLocaleString(r)})]})]})]}),j.certificate.renewalDue&&(0,Q.jsx)(k_,{tone:`warn`,children:n(`desktopCompat.renewalDue`)}),j.runtime.usage?.mode===`apply`&&(0,Q.jsx)(k_,{tone:`warn`,children:n(`desktopCompat.trialRisk`)}),j.runtime.usage?.mode===`observe`&&j.runtime.usage.phase.endsWith(`awaiting-original-response`)&&(0,Q.jsx)(k_,{tone:`warn`,role:`status`,children:n(`desktopCompat.cacheRefreshHint`)}),j.runtime.contextFailure&&(0,Q.jsx)(k_,{tone:`warn`,role:`status`,children:n(ZV[j.runtime.contextFailure])}),V&&(0,Q.jsx)(`p`,{className:`muted text-control`,children:n(`desktopCompat.reconnectHint`)}),j.runtime.usage?.observation&&(0,Q.jsx)(`p`,{className:`muted text-control`,role:`status`,children:n(`desktopCompat.observation`,{json:j.runtime.usage.observation.jsonSnapshots,sse:j.runtime.usage.observation.streamSnapshots,streams:j.runtime.usage.observation.validatedActiveStreams})})]}),H.length>0&&(0,Q.jsx)(`div`,{className:`acc-desktop__actions flex flex-wrap gap-2`,children:H.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:N||!M||!I,onClick:()=>{[`trust`,`remove-trust`,`renew`,`apply`].includes(e.action)?(h(e),_(!1),p(!1)):L(e)},children:n(XV[e.action])},e.action))}),m&&(0,Q.jsxs)(`fieldset`,{className:`acc-desktop__confirm`,disabled:N||!I,children:[(0,Q.jsx)(`legend`,{children:n(XV[m.action])}),(0,Q.jsx)(k_,{tone:`warn`,children:n(m.action===`apply`?`desktopCompat.trialRisk`:`desktopCompat.risk`)}),m.action===`apply`&&(0,Q.jsx)(`p`,{className:`muted text-control`,children:n(`desktopCompat.cacheRefreshHint`)}),m.target===`certificate`&&m.fingerprint&&(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:m.fingerprint}),(0,Q.jsxs)(`label`,{className:`row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked)}),n(`desktopCompat.acknowledge`)]}),(0,Q.jsxs)(`div`,{className:`row`,style:{gap:`var(--space-2)`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!g||!M||!I,onClick:()=>void L(m),children:n(`desktopCompat.confirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h(null),_(!1)},children:n(`common.cancel`)})]})]})]})}function $V(e){let{t}=s();return e.connected?(0,Q.jsxs)(`section`,{className:`panel acc-desktop flex flex-col gap-4`,children:[(0,Q.jsx)(`h2`,{children:t(`desktopCompat.title`)}),(0,Q.jsx)(k_,{tone:`warn`,children:t(`desktopCompat.connectedUnavailable`)})]}):(0,Q.jsx)(QV,{...e},e.apiBase)}function eH({target:e,onConnected:t,onCommitted:n,onPairingStart:r,local:i=!1,focusOnMount:a=!1}){let o=b(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(!1),h=(0,Z.useRef)(null),g=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{a&&g.current?.focus()},[a]);let _=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{_.current?.abort(),h.current?.rollback()},[]);let v=z_(),y=`ocx gui pair --origin "${window.location.origin}"`,x=v.outcomeFor(y);return(0,Q.jsxs)(`section`,{className:`connect-pairing flex min-w-0 flex-col rounded-[12px] bg-surface p-1 font-sans text-fg ring-1 ring-line`,"aria-labelledby":`connect-pairing-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1 px-4 pt-3 pb-3`,children:[(0,Q.jsx)(`h2`,{id:`connect-pairing-title`,className:`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em]`,children:o(i?`connection.pairing.code`:`connection.pairing.title`)}),(0,Q.jsxs)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:[!i&&(0,Q.jsxs)(Q.Fragment,{children:[o(`connection.pairing.hub`),`: `]}),(0,Q.jsx)(`code`,{className:`font-mono text-fg`,children:e.serverOrigin})]})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 rounded-[8px] bg-bg p-4 text-[13px] leading-5 text-fg-muted ring-1 ring-line`,children:[!i&&(0,Q.jsx)(`p`,{className:`m-0`,children:o(`connection.pairing.getCode`)}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-start gap-1 rounded-[8px] bg-surface py-1 pr-1 pl-3 ring-1 ring-line`,children:[(0,Q.jsx)(`pre`,{className:`m-0 min-w-0 flex-1 py-1.5 font-mono text-[12.5px] leading-[18px] whitespace-pre-wrap text-fg [overflow-wrap:anywhere]`,children:(0,Q.jsx)(`code`,{children:y})}),(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>v.copy(y,y),children:o(x===`copied`?`startup.copied`:`startup.copy`)})]}),x===`unavailable`&&(0,Q.jsx)(`p`,{className:`m-0`,role:`status`,children:o(`prov.linkCopyUnavailable`)}),!i&&(0,Q.jsx)(`p`,{className:`m-0`,children:o(`connection.pairing.askOperator`)}),(0,Q.jsx)(`p`,{className:`m-0`,children:o(`connection.pairing.notApiKey`)}),(0,Q.jsxs)(`form`,{onSubmit:async i=>{if(i.preventDefault(),_.current)return;h.current||r?.(),u(!0),f(null);let a=new AbortController;_.current=a;try{h.current||(h.current=await jV(e,s,void 0,a.signal),a.signal.aborted&&(h.current.rollback(),h.current=null,a.signal.throwIfAborted()),c(``),m(!0)),a.signal.aborted||(await t(a.signal),a.signal.throwIfAborted(),h.current?.commit(),h.current=null,m(!1),n?.())}catch(e){if(!a.signal.aborted){let t=e instanceof EV?e.kind:`unreachable`;(t===`refused`||t===`remote-link-unauthorized`||t===`remote-link-forbidden`)&&(h.current?.rollback(),h.current=null,m(!1)),f(t)}}finally{a.signal.aborted||u(!1),_.current===a&&(_.current=null)}},className:`flex min-w-0 flex-col gap-1.5`,children:[(0,Q.jsx)(`label`,{htmlFor:`connect-pairing-code`,className:`text-[13px] font-semibold text-fg`,children:o(`connection.pairing.code`)}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`input`,{ref:g,id:`connect-pairing-code`,name:`pairingCode`,value:s,onChange:e=>c(e.currentTarget.value),autoComplete:`off`,spellCheck:!1,disabled:l||p,className:`input mono min-w-0 flex-1 font-mono`,"aria-invalid":!!d||void 0,"aria-describedby":d?`connect-pairing-error`:void 0}),(0,Q.jsx)(Jp,{type:`submit`,variant:`primary`,disabled:l||!p&&!s.trim(),children:o(l?`connection.pairing.submitting`:p?`connection.pairing.retryValidation`:`connection.pairing.submit`)})]}),d&&(0,Q.jsx)(`p`,{id:`connect-pairing-error`,className:`m-0 text-[13px] text-danger`,role:`alert`,children:o(p?`connection.pairing.validationPending`:d===`invalid-code`?`connection.pairing.notApiKey`:d===`unreachable`?`connection.pairing.networkError`:d===`request-failed`?`connection.pairing.requestError`:d===`origin-denied`?`connection.pairing.originDenied`:d===`cloudflare-challenge`?`connection.pairing.cloudflareChallenge`:d===`remote-link-unauthorized`||d===`remote-link-forbidden`?`connection.pairing.sessionNotAuthorized`:d===`client-state-changed`?`connection.clientStateChanged`:d===`invalid-response`?`connection.pairing.responseError`:`connection.pairing.error`)})]}),e.transport===`relay`&&(0,Q.jsx)(`p`,{className:`m-0 text-fg-subtle`,children:o(`connection.pairing.relayWarning`)})]})]})}var tH=class extends Error{code;status;retryable;constructor(e,t,n){super(e),this.code=e,this.status=t,this.retryable=n}},nH=new Set([`npm-global`,`app-bundle`,`version-manager`,`standalone-unverified`,`unknown`]),rH=new Set([`none`,`active`,`unknown`,`not-evaluated`]),iH=new Set([`queued`,`running`,`applied`,`not_applied`,`refused`,`ambiguous`]),aH=new Set([`active`,`unknown`,`finished`]),oH=new Set([`job_store_busy`,`admission_failed`,`network`]),sH=e=>typeof e==`string`?e:null;function cH(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.session;if(typeof t.applicable!=`boolean`||typeof t.managed!=`boolean`||!nH.has(t.provenance)||!n||!rH.has(n.state))return null;let r=Array.isArray(t.command)&&t.command.every(e=>typeof e==`string`)?t.command:null;return{applicable:t.applicable,refusal:sH(t.refusal),planId:sH(t.planId),provenance:t.provenance,managed:t.managed,installedVersion:sH(t.installedVersion),targetVersion:sH(t.targetVersion),location:sH(t.location),session:{state:n.state,matches:typeof n.matches==`number`?n.matches:null},command:r}}function lH(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.jobId!=`string`||!iH.has(t.status)||!aH.has(t.ownerState)||typeof t.planId!=`string`?null:{jobId:t.jobId,status:t.status,ownerState:t.ownerState,planId:t.planId,reason:sH(t.reason)}}function uH(e,t){return!!e&&e.applicable&&e.refusal===null&&e.planId!==null&&t}function dH(e){return e.status!==`queued`&&e.status!==`running`&&e.ownerState!==`active`}async function fH(e,t){try{let n=await e.json();return typeof n.error==`string`?n.error:t}catch{return t}}async function pH(e,t){let n=await fetch(`${e}/api/codex/cli-update/plan`,{signal:t,cache:`no-store`});if(!n.ok)throw new tH(await fH(n,`plan_unavailable`),n.status,!1);let r=cH(await n.json());if(!r)throw new tH(`plan_unavailable`,n.status,!1);return r}async function mH(e,t,n){let r;try{r=await fetch(`${e}/api/codex/cli-update/apply`,{method:`POST`,signal:n,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t.requestId,planId:t.planId,confirmed:!0})})}catch(e){throw n.aborted?e:new tH(`network`,0,!0)}if(!r.ok){let e=await fH(r,`admission_failed`);throw new tH(e,r.status,oH.has(e))}let i=lH((await r.json()).job);if(!i)throw new tH(`job_result_unknown`,r.status,!1);return i}async function hH(e,t,n){let r;try{r=await fetch(`${e}/api/codex/cli-update/jobs/${encodeURIComponent(t)}`,{signal:n,cache:`no-store`})}catch(e){throw n.aborted?e:new tH(`network`,0,!0)}if(!r.ok){let e=await fH(r,`job_state_unavailable`);throw new tH(e,r.status,e!==`job_not_found`)}let i=lH(await r.json());if(!i)throw new tH(`job_state_unavailable`,r.status,!0);return i}function gH(e){return e?`ocx system codex-cli-update apply --plan-id ${e} --yes`:`ocx system codex-cli-update plan`}function _H(e){return`ocx system codex-cli-update status ${e} --json`}function vH(){let e=globalThis.crypto;try{if(e&&typeof e.randomUUID==`function`)return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join(`-`)}return null}var yH=1500,bH=5,xH=new Set([`store_full`,`unsupported_store`,`unsafe_store`]),SH={"npm-global":`codexCliUpdate.provNpmGlobal`,"app-bundle":`codexCliUpdate.provAppBundle`,"version-manager":`codexCliUpdate.provVersionManager`,"standalone-unverified":`codexCliUpdate.provStandaloneUnverified`,unknown:`codexCliUpdate.unknown`},CH={windows_inspection_deferred:`codexCliUpdate.refusalWindowsInspectionDeferred`,windows_apply_disabled:`codexCliUpdate.refusalWindowsApplyDisabled`,not_managed:`codexCliUpdate.refusalNotManaged`,installed_version_unverified:`codexCliUpdate.refusalInstalledVersionUnverified`,install_content_unverified:`codexCliUpdate.refusalInstallContentUnverified`,target_unresolved:`codexCliUpdate.refusalTargetUnresolved`,already_current:`codexCliUpdate.refusalAlreadyCurrent`,target_not_newer:`codexCliUpdate.refusalTargetNotNewer`,blocked_active_session:`codexCliUpdate.refusalBlockedActiveSession`,blocked_process_state_unknown:`codexCliUpdate.refusalBlockedProcessStateUnknown`},wH={queued:`codexCliUpdate.jobQueued`,running:`codexCliUpdate.jobRunning`,applied:`codexCliUpdate.jobApplied`,not_applied:`codexCliUpdate.jobNotApplied`,refused:`codexCliUpdate.jobRefused`,ambiguous:`codexCliUpdate.jobAmbiguous`};function TH(e,t){switch(e.session.state){case`none`:return t(`codexCliUpdate.sessionNone`);case`active`:return t(`codexCliUpdate.sessionActive`,{count:String(e.session.matches??1)});case`unknown`:return t(`codexCliUpdate.sessionUnknown`);default:return t(`codexCliUpdate.sessionNotEvaluated`)}}function EH({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,x]=(0,Z.useState)(!1),S=(0,Z.useRef)(0),C=(0,Z.useRef)(new Set),w=(0,Z.useRef)(null),T=(0,Z.useCallback)(()=>{let e=new AbortController;return C.current.add(e),e},[]),E=(0,Z.useCallback)(()=>{for(let e of C.current)e.abort();C.current.clear()},[]);(0,Z.useEffect)(()=>{let e=()=>u(!1),t=S;return window.addEventListener(D,e),()=>{window.removeEventListener(D,e),t.current++,E()}},[E]);let O=(0,Z.useCallback)(async(t,n)=>{let r=t,i=0;for(;!dH(r);){if(await new Promise(e=>setTimeout(e,yH)),S.current!==n)return;let t=T();try{r=await hH(e,r.jobId,t.signal),i=0,S.current===n&&m(r)}catch(e){if(S.current!==n||t.signal.aborted)return;if((e instanceof tH?e.code:`job_state_unavailable`)===`job_not_found`){v(`job_not_found`);return}if(++i>=bH){v(`job_state_unavailable`);return}}finally{C.current.delete(t)}}},[e,T]),k=(0,Z.useCallback)(async()=>{let t=++S.current;E(),r(!0),a(null),s(null),u(!1),m(null),g(null),v(null),x(!1),f(!1),w.current=null;let n=T();try{let r=await pH(e,n.signal);S.current===t&&a(r)}catch(e){S.current===t&&!n.signal.aborted&&s(e instanceof tH?e.code:`plan_unavailable`)}finally{C.current.delete(n),S.current===t&&r(!1)}},[e,E,T]),A=(0,Z.useCallback)(async()=>{if(!i||!uH(i,l)||d||p)return;let t=S.current;if(w.current??=vH(),!w.current){g({code:`request_id_unavailable`,retryable:!1});return}f(!0),g(null);let n=T();try{let r=await mH(e,{requestId:w.current,planId:i.planId},n.signal);if(S.current!==t)return;m(r),f(!1),await O(r,t)}catch(e){if(S.current!==t||n.signal.aborted)return;let r=e instanceof tH?{code:e.code,retryable:e.retryable}:{code:`network`,retryable:!0};g(r),r.code===`local_dashboard_confirmation_required`&&x(!0),f(!1)}finally{C.current.delete(n)}},[e,i,l,d,p,O,T]),j=i?.refusal?CH[i.refusal]:void 0,M=n||d,N=p?dH(p):!1,P=gH(i?.planId??null);return(0,Q.jsxs)(`section`,{className:`panel acc-desktop relative flex flex-col gap-4`,"aria-labelledby":`codex-cli-update-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Q.jsx)(`h2`,{id:`codex-cli-update-title`,children:t(`codexCliUpdate.title`)}),(0,Q.jsx)(`p`,{className:`muted text-body`,children:t(`codexCliUpdate.description`)}),(0,Q.jsx)(`p`,{className:`muted text-control`,children:t(`codexCliUpdate.checkHint`)})]}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M||!!p&&!N&&!_,"aria-busy":n||void 0,onClick:()=>void k(),children:t(n?`codexCliUpdate.checking`:`codexCliUpdate.check`)})}),o&&(0,Q.jsxs)(k_,{tone:`err`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:t(`codexCliUpdate.errPlanUnavailable`)}),(0,Q.jsx)(`code`,{className:`text-[12px] text-fg-muted`,children:o})]}),i&&(0,Q.jsxs)(`dl`,{className:`acc-desktop__status`,"data-testid":`codex-cli-update-plan`,children:[(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldProvenance`)}),(0,Q.jsx)(`dd`,{children:t(SH[i.provenance])})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldManaged`)}),(0,Q.jsx)(`dd`,{children:i.managed?t(`codexCliUpdate.yes`):t(`codexCliUpdate.no`)})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldInstalled`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:i.installedVersion??t(`codexCliUpdate.unknown`)})})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldTarget`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:i.targetVersion??t(`codexCliUpdate.unknown`)})})]}),(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldSession`)}),(0,Q.jsx)(`dd`,{children:TH(i,t)})]}),i.location&&(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldLocation`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:i.location})})]}),i.command&&(0,Q.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Q.jsx)(`dt`,{children:t(`codexCliUpdate.fieldCommand`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:i.command.join(` `)})})]})]}),i&&i.refusal&&(0,Q.jsxs)(k_,{tone:i.refusal===`already_current`?`ok`:`warn`,role:`status`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:j?t(j):i.refusal}),!j&&(0,Q.jsx)(`code`,{className:`text-[12px] text-fg-muted`,children:i.refusal})]}),i&&uH(i,!0)&&!p&&(0,Q.jsxs)(`fieldset`,{className:`acc-desktop__confirm`,disabled:M,children:[(0,Q.jsx)(`legend`,{children:t(`codexCliUpdate.apply`)}),(0,Q.jsx)(`p`,{className:`m-0`,children:t(`codexCliUpdate.ready`)}),(0,Q.jsxs)(`label`,{className:`row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),t(`codexCliUpdate.confirm`)]}),(0,Q.jsx)(`div`,{className:`row`,style:{gap:`var(--space-2)`},children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!uH(i,l)||d||!!h&&!h.retryable,onClick:()=>void A(),children:d?t(`codexCliUpdate.applying`):h?.retryable?t(`codexCliUpdate.retry`):t(`codexCliUpdate.apply`)})})]}),h&&(0,Q.jsxs)(k_,{tone:`err`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:h.code===`local_dashboard_confirmation_required`?t(`codexCliUpdate.errLocalOnly`):h.code===`idempotency_conflict`?t(`codexCliUpdate.errIdempotencyConflict`):xH.has(h.code)?t(`codexCliUpdate.errStore`):h.retryable?t(`codexCliUpdate.errRetry`):t(`codexCliUpdate.errApplyFailed`)}),h.code===`local_dashboard_confirmation_required`&&(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:P}),(0,Q.jsx)(`code`,{className:`text-[12px] text-fg-muted`,children:h.code})]}),y&&(0,Q.jsx)(`div`,{className:`acc-desktop__card`,children:(0,Q.jsx)(eH,{local:!0,target:c(e).machine,onConnected:()=>void 0,onCommitted:()=>{x(!1),g(null),u(!1)}})}),p&&(0,Q.jsxs)(k_,{tone:p.status===`applied`&&N?`ok`:N?`warn`:`info`,role:`status`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:t(wH[N?p.status:p.status===`queued`?`queued`:`running`])}),N&&p.reason===`owner_state_unknown`&&(0,Q.jsx)(`p`,{className:`m-0`,children:t(`codexCliUpdate.reasonOwnerStateUnknown`)}),N&&p.reason&&(0,Q.jsxs)(`p`,{className:`m-0 text-[12px] text-fg-muted`,children:[t(`codexCliUpdate.reasonLabel`),`: `,(0,Q.jsx)(`code`,{children:p.reason})]})]}),_&&p&&(0,Q.jsxs)(k_,{tone:`warn`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:t(_===`job_not_found`?`codexCliUpdate.errJobNotFound`:`codexCliUpdate.errJobUnreadable`)}),_===`job_state_unavailable`&&(0,Q.jsx)(`code`,{children:_H(p.jobId)})]})]})}function DH({apiBase:e,connected:t=!1}){let n=b();return t||p()?(0,Q.jsxs)(`section`,{className:`panel acc-desktop flex flex-col gap-4`,children:[(0,Q.jsx)(`h2`,{children:n(`codexCliUpdate.title`)}),(0,Q.jsx)(k_,{tone:`warn`,children:n(`codexCliUpdate.connectedUnavailable`)})]}):(0,Q.jsx)(EH,{apiBase:e},e)}var OH=[`multiauth`,`prompt`,`desktop`,`cli`];function kH(){let e=window.location.hash.replace(/^#\/?/,``);return e===`codex-set/desktop`?`desktop`:e===`codex-set/prompt`?`prompt`:e===`codex-set/cli`?`cli`:`multiauth`}function AH(e){window.location.hash=e===`multiauth`?`codex-set`:`codex-set/${e}`}function jH(e){if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(e.key))return;e.preventDefault();let t=OH.indexOf(kH()),n=OH[e.key===`Home`?0:e.key===`End`?OH.length-1:(t+(e.key===`ArrowRight`?1:-1)+OH.length)%OH.length];AH(n),document.getElementById(`codex-set-tab-${n}`)?.focus()}function MH({apiBase:e,machineApiBase:t=e,connected:n=!1,targetKey:r}){let i=b(),[a,o]=(0,Z.useState)(kH),[s,c]=(0,Z.useState)(()=>kH()===`prompt`),[l,u]=(0,Z.useState)(()=>kH()===`multiauth`),[d,f]=(0,Z.useState)(()=>kH()===`desktop`);(0,Z.useEffect)(()=>{let e=()=>o(kH());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let p=s||a===`prompt`,m=l||a===`multiauth`;p!==s&&c(!0),m!==l&&u(!0);let h=d||a===`desktop`;h!==d&&f(!0);let[g,_]=(0,Z.useState)(()=>kH()===`cli`),v=g||a===`cli`;return v!==g&&_(!0),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`nav.codexSet`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-multiauth`,"aria-selected":a===`multiauth`,"aria-controls":`codex-set-panel-multiauth`,tabIndex:a===`multiauth`?0:-1,className:`page-tab${a===`multiauth`?` page-tab--active`:``}`,onClick:()=>AH(`multiauth`),onKeyDown:jH,children:i(`codexSet.tab.multiauth`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-prompt`,"aria-selected":a===`prompt`,"aria-controls":`codex-set-panel-prompt`,tabIndex:a===`prompt`?0:-1,className:`page-tab${a===`prompt`?` page-tab--active`:``}`,onClick:()=>AH(`prompt`),onKeyDown:jH,children:i(`codexSet.tab.prompt`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-desktop`,"aria-selected":a===`desktop`,"aria-controls":`codex-set-panel-desktop`,tabIndex:a===`desktop`?0:-1,className:`page-tab${a===`desktop`?` page-tab--active`:``}`,onClick:()=>AH(`desktop`),onKeyDown:jH,children:i(`desktopCompat.title`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-cli`,"aria-selected":a===`cli`,"aria-controls":`codex-set-panel-cli`,tabIndex:a===`cli`?0:-1,className:`page-tab${a===`cli`?` page-tab--active`:``}`,onClick:()=>AH(`cli`),onKeyDown:jH,children:i(`codexCliUpdate.tab`)})]}),p&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-prompt`,"aria-labelledby":`codex-set-tab-prompt`,hidden:a!==`prompt`,children:(0,Q.jsx)(TB,{apiBase:e})}),m&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-multiauth`,"aria-labelledby":`codex-set-tab-multiauth`,hidden:a!==`multiauth`,children:(0,Q.jsx)(qz,{apiBase:e,targetKey:r})}),h&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-desktop`,"aria-labelledby":`codex-set-tab-desktop`,hidden:a!==`desktop`,children:(0,Q.jsx)($V,{apiBase:t,active:a===`desktop`,connected:n})}),v&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-cli`,"aria-labelledby":`codex-set-tab-cli`,hidden:a!==`cli`,children:(0,Q.jsx)(DH,{apiBase:e,connected:n})})]})}var NH=[`qoder`,`qoder-cn`,`workbuddy`,`workbuddy-ai`,`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`,`gentle-shell`,`t3code`],PH={qoder:`api.clientConfig.clientQoder`,"qoder-cn":`integrations.tab.qoderCn`,workbuddy:`integrations.tab.workbuddy`,"workbuddy-ai":`integrations.tab.workbuddyAi`,opencode:`api.clientConfig.clientOpencode`,pi:`api.clientConfig.clientPi`,"gentle-shell":`integrations.tab.gentleShell`,omp:`api.clientConfig.clientOmp`,hermes:`api.clientConfig.clientHermes`,openclaw:`api.clientConfig.clientOpenclaw`,kimi:`api.clientConfig.clientKimi`,gajae:`api.clientConfig.clientGajae`,dsh:`api.clientConfig.clientDsh`,mcode:`api.clientConfig.clientMcode`,zcode:`api.clientConfig.clientZcode`,commandcode:`api.clientConfig.clientCommandCode`,prime:`api.clientConfig.clientPrime`,aside:`api.clientConfig.clientAside`,raycast:`api.clientConfig.clientRaycast`,omo:`api.clientConfig.clientOmo`,cline:`api.clientConfig.clientCline`,kilo:`api.clientConfig.clientKilo`,droid:`api.clientConfig.clientDroid`,t3code:`api.clientConfig.clientT3code`},FH={qoder:`/provider-icons/qoder.svg`,"qoder-cn":`/provider-icons/qoder.svg`,opencode:`/provider-icons/opencode.svg`,pi:`/provider-icons/pi.svg`,omp:`/provider-icons/oh-my-pi.svg`,hermes:`/provider-icons/hermes-agent.svg`,openclaw:`/provider-icons/openclaw.svg`,kimi:`/provider-icons/kimi-color.svg`,gajae:`/provider-icons/gajae-code.svg`,dsh:`/provider-icons/deepseek-harness.svg`,mcode:`/provider-icons/minimax.svg`,zcode:`/provider-icons/zcode.svg`,prime:`/provider-icons/prime-agent.svg`,aside:`/provider-icons/aside.svg`,raycast:`/provider-icons/raycast.svg`,omo:`/provider-icons/omo.svg`,cline:`/provider-icons/cline-color.svg`,commandcode:`/provider-icons/commandcode-color.svg`,kilo:`/provider-icons/kilo.svg`,droid:`/provider-icons/factory-droid.svg`,t3code:`/provider-icons/t3code.svg`},IH=new Set([`opencode`,`kimi`,`prime`,`aside`,`hermes`]),LH={codex:`/provider-icons/openai.svg`,claude:`/provider-icons/claude-color.svg`,claudeDesktop:`/provider-icons/claude-color.svg`,grok:`/provider-icons/grok.svg`,cursor:`/provider-icons/cursor-color.svg`},RH={...LH,opencode:FH.opencode??null,pi:FH.pi??null,"gentle-shell":null,omp:FH.omp??null,hermes:FH.hermes??null,openclaw:FH.openclaw??null,kimi:FH.kimi??null,gajae:FH.gajae??null,dsh:FH.dsh??null,mcode:FH.mcode??null,zcode:FH.zcode??null,prime:FH.prime??null,aside:FH.aside??null,raycast:FH.raycast??null,omo:FH.omo??null,cline:FH.cline??null,commandcode:FH.commandcode??null,kilo:FH.kilo??null,droid:FH.droid??null,qoder:FH.qoder??null,"qoder-cn":FH[`qoder-cn`]??null,workbuddy:null,"workbuddy-ai":null,t3code:FH.t3code??null},zH=[LH.grok],BH=new Set([...[...IH].map(e=>FH[e]).filter(e=>e!==void 0),...zH]);function VH(e){return RH[e]}function HH({src:e,label:t,size:n=20,className:r}){let i=r?`client-mark ${r}`:`client-mark`,a={"--client-mark-size":String(n)+`px`};return e?BH.has(e)?(0,Q.jsx)(`span`,{className:`${i} client-mark--mask`,style:{...a,maskImage:`url(${e})`,WebkitMaskImage:`url(${e})`},"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`${i} client-mark--img`,style:a,"aria-hidden":`true`,children:(0,Q.jsx)(`img`,{src:e,alt:``,width:n,height:n})}):(0,Q.jsx)(`span`,{className:`${i} client-mark--monogram`,style:a,"aria-hidden":`true`,children:t.slice(0,1)})}function UH(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function WH(e){let t=e.id.indexOf(`/`),n=typeof e.owned_by==`string`&&e.owned_by.trim()?e.owned_by.trim():void 0,r=e.is_combo===!0?`combo`:t>0?e.id.slice(0,t):n??`openai`,i=t<0&&r===`openai`,a=r!==`openai`&&r!==`combo`;return{id:e.id,displayName:e.id,provider:r,native:i,custom:a}}function GH(e){return e.id}function KH(e,t,n){let r=(0,Z.useRef)(0),i=(0,Z.useRef)(!1),a=(0,Z.useCallback)((e=`pairing`)=>{r.current++,n(e)},[n]),o=(0,Z.useCallback)(()=>{i.current=!1,r.current++},[]);return(0,Z.useLayoutEffect)(()=>(i.current=!0,a(`lifecycle`),o),[e,t,a,o]),(0,Z.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&a(`session`)},t=()=>{Ht()&&a(`lifecycle`)};window.addEventListener(B,e),window.addEventListener(D,e);let n=Ut(t);return()=>{window.removeEventListener(B,e),window.removeEventListener(D,e),n()}},[a]),{generation:r,invalidate:a,current:(0,Z.useCallback)(e=>i.current&&t&&!Ht()&&r.current===e,[t])}}function qH(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.ambiguous===!0||!(typeof t.requests7d!=`number`||!Number.isFinite(t.requests7d)||typeof t.totalRequests!=`number`||!Number.isFinite(t.totalRequests)||t.lastUsedAt!==void 0&&(typeof t.lastUsedAt!=`string`||Number.isNaN(new Date(t.lastUsedAt).getTime())))}var JH=new Set([`required`,`accepted`,`rejected`]);function YH(e){return Array.isArray(e)&&e.length>0&&e.every(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.endpoint==`string`&&JH.has(t.bearer)&&JH.has(t.dedicated)&&JH.has(t.xApiKey)})}var XH=new Set([`fixed`,`api-surfaces`,`claude-code-legacy`,`invalid`]),ZH=[`responses`,`chat`,`messages`];function QH(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n={};for(let e of ZH){let r=t[e];if(!r||typeof r!=`object`||Array.isArray(r))return;let{enabled:i,source:a}=r;if(typeof i!=`boolean`||!XH.has(a))return;n[e]={enabled:i,source:a}}return n}function $H(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let n=e,r=new Set([`transcriptionEndpoint`,`dictationStreamEndpoint`,`liveEndpoint`,`realtimeCallsEndpoint`,`transcriptionModel`,`liveModel`,`transcriptionConfigured`,`dictationConfigured`,`liveConfigured`]);if(Object.keys(n).some(e=>!r.has(e)))return!1;try{let e=new URL(t);if(![`http:`,`https:`].includes(e.protocol)||e.username||e.password||e.search||e.hash)return!1;for(let[t,[r,i]]of Object.entries({transcriptionEndpoint:[`/audio/transcriptions`,!1],dictationStreamEndpoint:[`/audio/transcriptions/stream`,!0],liveEndpoint:[`/live`,!0],realtimeCallsEndpoint:[`/realtime/calls`,!1]})){if(typeof n[t]!=`string`)return!1;let a=new URL(n[t]),o=i?e.protocol===`https:`?`wss:`:`ws:`:e.protocol;if(a.protocol!==o||a.username||a.password||a.search||a.hash||(a.protocol=e.protocol,a.origin!==e.origin||a.pathname!==`${e.pathname.replace(/\/$/,``)}${r}`))return!1}return n.transcriptionModel===`gpt-4o-transcribe`&&n.liveModel===`gpt-live-1-codex`&&[n.transcriptionConfigured,n.dictationConfigured,n.liveConfigured].every(e=>typeof e==`boolean`)}catch{return!1}}var eU={baseUrl:`http://127.0.0.1:10100/v1`,responses:`http://127.0.0.1:10100/v1/responses`,chatCompletions:`http://127.0.0.1:10100/v1/chat/completions`,messages:`http://127.0.0.1:10100/v1/messages`,models:`http://127.0.0.1:10100/v1/models`};function tU(e){let t=e||eU.responses,n=t.match(/^(.*)\/v1\/responses\/?$/),r=n?`${n[1]}/v1`:t.replace(/\/responses\/?$/,``);return{baseUrl:r,responses:t,chatCompletions:`${r}/chat/completions`,messages:`${r}/messages`,models:`${r}/models`}}function nU(e,t){let n=new Date(e);return!e||Number.isNaN(n.getTime())?`—`:n.toLocaleDateString(t)}function rU({url:e}){return(0,Q.jsx)(iU,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,Q.jsx)(`code`,{className:`api-code api-code-inline api-endpoint-url`,children:e})})}function iU({text:e,hintKey:t,copiedKey:n,className:r,children:i}){let{t:a}=s(),o=(0,Z.useId)(),c=(0,Z.useRef)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(null),g=l||d;(0,Z.useEffect)(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]),(0,Z.useLayoutEffect)(()=>{if(!g)return;let e=()=>{let e=c.current;if(!e)return;let t=e.getBoundingClientRect();m({top:Math.max(8,t.top-8),left:t.left+t.width/2})};return e(),window.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[g]);let _=()=>u(!0),v=()=>u(!1),y=async()=>{try{await navigator.clipboard.writeText(e),f(!0),h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>f(!1),1500)}catch{f(!1)}},b=g&&p?(0,Dn.createPortal)((0,Q.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble api-copy-tip-fixed`,role:`tooltip`,style:{top:p.top,left:p.left},children:a(d?n:t)}),document.body):null,x={ref:c,className:`ocx-tooltip ${r}`,onMouseEnter:_,onMouseLeave:v,onFocus:_,onBlur:v,onClick:e=>{if(typeof window<`u`&&window.getSelection()?.toString())return;let t=e.target;if(t instanceof HTMLElement&&t!==e.currentTarget){let n=t.getBoundingClientRect();if(t.scrollHeight>t.clientHeight+1&&e.clientX>=n.right-16||t.scrollWidth>t.clientWidth+1&&e.clientY>=n.bottom-16)return}y()},onKeyDown:e=>{e.key===`Escape`&&v()},"aria-label":a(t),"aria-describedby":g?o:void 0};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,...x,children:i}),b]})}function aU({text:e}){return(0,Q.jsx)(iU,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,Q.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}var oU=`claude/code`,sU={fixed:`api.surface.source.fixed`,"api-surfaces":`api.surface.source.explicit`,"claude-code-legacy":`api.surface.source.inherited`,invalid:`api.surface.source.invalid`},cU=[{id:`responses`,titleKey:`api.responsesEndpoint`,url:e=>e.responses},{id:`chat`,titleKey:`api.chatCompletionsEndpoint`,url:e=>e.chatCompletions},{id:`messages`,titleKey:`api.messagesEndpoint`,url:e=>e.messages}];function lU({apiBase:e,endpoints:t,surfaces:n,onChanged:r}){let{t:i}=s(),[a,o]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=async t=>{if(!a){o(!0),l(null);try{let n=await cw(e,{messagesEnabled:!t.enabled});n.kind===`ok`?r():l(n.kind===`unavailable`?`unavailable`:`failed`)}finally{o(!1)}}};return(0,Q.jsx)(`div`,{className:`api-endpoints api-surface-cards`,children:cU.map(e=>{let r=n[e.id],o=r.enabled?i(`api.surface.on`):i(`api.surface.off`);return(0,Q.jsxs)(`div`,{className:`api-surface-card${r.enabled?``:` api-surface-card-off`}`,"data-surface":e.id,children:[(0,Q.jsxs)(`div`,{className:`api-surface-card-head`,children:[(0,Q.jsx)(`span`,{className:`api-surface-card-title`,children:i(e.titleKey)}),e.id===`messages`?(0,Q.jsx)(Rn,{on:r.enabled,disabled:a,onClick:()=>{u(r)},label:`${i(`api.surface.messagesToggle`)}: ${o}`}):null,(0,Q.jsx)(`span`,{className:`badge ${r.enabled?`badge-green`:`badge-muted`}`,children:o})]}),(0,Q.jsx)(rU,{url:e.url(t)}),(0,Q.jsx)(`span`,{className:`small ${r.source===`invalid`?`api-surface-invalid`:`muted`}`,children:i(sU[r.source])}),e.id===`messages`?(0,Q.jsxs)(Q.Fragment,{children:[r.enabled?null:(0,Q.jsx)(`span`,{className:`muted small`,children:i(`api.surface.closedNote`)}),r.enabled?(0,Q.jsx)(`span`,{className:`muted small`,children:i(`api.surface.messagesCloseNote`)}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm api-surface-card-link`,onClick:()=>En(oU),children:i(`api.surface.openClaude`)}),c?(0,Q.jsx)($,{tone:`err`,children:i(c===`unavailable`?`api.surface.toggleUnavailable`:`api.surface.toggleFailed`)}):null]}):null]},e.id)})})}function uU(e,t){return t(e===`required`?`api.auth.required`:e===`accepted`?`api.auth.accepted`:`api.auth.rejected`)}function dU({endpoints:e,claudeCodeEnabled:t,authMatrix:n,surfaces:r,apiBase:i,onSurfacesChanged:a}){let{t:o}=s(),c=r&&i!==void 0&&a?{surfaces:r,apiBase:i,onChanged:a}:null;return(0,Q.jsxs)(`div`,{className:`panel api-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:o(`api.endpointsTitle`)}),(0,Q.jsxs)(`div`,{className:`api-endpoints`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:o(`api.baseUrl`)}),(0,Q.jsx)(rU,{url:e.baseUrl})]}),c?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:o(`api.responsesEndpoint`)}),(0,Q.jsx)(rU,{url:e.responses})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:o(`api.chatCompletionsEndpoint`)}),(0,Q.jsx)(rU,{url:e.chatCompletions})]}),t&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:o(`api.messagesEndpoint`)}),(0,Q.jsx)(rU,{url:e.messages})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:o(`api.modelsEndpoint`)}),(0,Q.jsx)(rU,{url:e.models})]})]}),c?(0,Q.jsx)(lU,{endpoints:e,...c}):null,(0,Q.jsx)(`p`,{className:`muted small`,children:o(`api.endpointNote`)}),(0,Q.jsxs)(`div`,{className:`api-auth-matrix-block`,children:[(0,Q.jsx)(`h4`,{className:`api-auth-matrix-title`,children:o(`api.authTitle`)}),(0,Q.jsx)(`div`,{className:`api-auth-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`api-auth-matrix`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:o(`api.auth.endpoint`)}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`code`,{children:`Authorization: Bearer`})}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`code`,{children:`x-opencodex-api-key`})}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`code`,{children:`x-api-key`})})]})}),(0,Q.jsx)(`tbody`,{children:n.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.endpoint})}),(0,Q.jsx)(`td`,{children:uU(e.bearer,o)}),(0,Q.jsx)(`td`,{children:uU(e.dedicated,o)}),(0,Q.jsx)(`td`,{children:uU(e.xApiKey,o)})]},e.endpoint))})]})}),(0,Q.jsx)(`p`,{className:`muted small`,children:o(`api.authLoopback`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:o(`api.authBaseUrlNote`)})]})]})}function fU({keys:e,keysLoading:t=!1,keysLoadFailed:n,newName:r,creating:i,newKey:a,copied:o,confirmDelete:c,localeTag:l,showKeyList:u=!0,onNewNameChange:d,onCreate:f,onDismissNewKey:p,onCopyKey:m,onConfirmDelete:h,onCancelDelete:g,onDelete:_}){let{t:v}=s();return(0,Q.jsxs)(Q.Fragment,{children:[a&&(0,Q.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:v(`api.newKeyTitle`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:v(`api.newKeyNote`)}),(0,Q.jsxs)(`div`,{className:`api-form-row`,children:[(0,Q.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:a}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:m,children:o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(st,{}),` `,v(`api.copied`)]}):v(`api.copy`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:p,children:v(`api.dismiss`)})]}),(0,Q.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:v(`api.generateTitle`)}),(0,Q.jsxs)(`div`,{className:`api-form-row`,children:[(0,Q.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:v(`api.keyNamePlaceholder`),"aria-label":v(`api.keyNamePlaceholder`),value:r,maxLength:64,onChange:e=>d(e.target.value),className:`input`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:[(0,Q.jsx)(Vt,{}),` `,v(i?`api.generating`:`api.generate`)]})]})]}),u&&(0,Q.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:t?v(`api.activeKeysLoading`):v(`api.activeKeys`,{count:e.length})}),t?(0,Q.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":v(`common.loading`)}):e.length>0?(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:v(`api.colName`)}),(0,Q.jsx)(`th`,{children:v(`api.colKey`)}),(0,Q.jsx)(`th`,{children:v(`api.colCreated`)}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:e.name}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.prefix})}),(0,Q.jsx)(`td`,{children:nU(e.createdAt,l)}),(0,Q.jsx)(`td`,{children:c===e.id?(0,Q.jsxs)(`span`,{className:`api-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>_(e.id),children:v(`api.confirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,children:v(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":v(`api.deleteAria`),onClick:()=>h(e.id),children:(0,Q.jsx)(Ie,{})})})]},e.id))})]})}):n?(0,Q.jsx)(`p`,{className:`muted`,children:v(`api.keysLoadFailed`)}):(0,Q.jsx)(`p`,{className:`muted`,children:v(`api.noKeys`)})]})]})}function pU({filteredModels:e,modelsLoading:t,modelsRefreshing:n=!1,modelsLoadFailed:r,modelCount:i,hasModelData:a,modelQuery:o,copiedModelId:c,modelTests:l,claudeCodeEnabled:u,onModelQueryChange:d,onCopyModelId:f,onTestModel:p,onRetryModels:m,canTestModels:h,sourceLabel:g,protocolLabel:_}){let{t:v}=s();return(0,Q.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,Q.jsxs)(`div`,{className:`api-panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:v(`api.modelsTitle`)}),(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:v(`api.modelsCount`,{count:e.length})})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:v(`api.modelsSubtitle`)}),(0,Q.jsx)(`input`,{type:`search`,className:`input`,value:o,onChange:e=>d(e.target.value),placeholder:v(`api.modelsSearch`),"aria-label":v(`api.modelsSearch`)}),r&&(0,Q.jsxs)(`div`,{className:`api-models-error`,children:[(0,Q.jsx)(`p`,{className:`muted small`,role:`alert`,children:v(`api.modelsLoadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:v(`common.retry`)})]}),n&&!t&&(0,Q.jsx)(`p`,{className:`muted small`,"aria-live":`polite`,children:v(`api.modelsLoading`)}),t?(0,Q.jsx)(ck,{label:v(`api.modelsLoading`),rows:3}):a?e.length===0?(0,Q.jsx)(`p`,{className:`muted small api-models-empty`,children:i===0?v(`api.modelsEmpty`):v(`api.modelsNoMatch`,{query:o.trim()})}):(0,Q.jsx)(`div`,{className:`api-models-scroll`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:v(`api.colModel`)}),(0,Q.jsx)(`th`,{children:v(`api.colSource`)}),(0,Q.jsx)(`th`,{children:v(`api.colProtocols`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=GH(e),n=UH(u);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`api-model-cell`,children:[(0,Q.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,Q.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,Q.jsx)(`td`,{children:g(e)}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`api-model-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{f(t)},children:v(c===t?`api.modelCopied`:`api.copyModelId`)}),n.map(n=>{let r=l[t]?.[n],i=r?.state??`idle`;return(0,Q.jsxs)(`span`,{className:`api-model-test-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:i===`testing`||!h,title:h?void 0:v(`api.auth.testNeedsFreshKey`),onClick:()=>{p(e,n)},children:v(`api.auth.testProtocol`,{protocol:_(n)})}),i!==`idle`&&(0,Q.jsx)(`span`,{className:`api-test-note api-test-note--${i}`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:i===`testing`?v(`api.testingModel`):i===`ok`?v(`api.testSucceeded`):r?.detail??v(`api.testFailed`)})]},n)})]})})]},t)})})]})}):null]})}function mU({endpoints:e,claudeCodeEnabled:t}){let{t:n}=s(),r=JSON.stringify(n(`api.usageSampleInput`)),i=`curl ${e.chatCompletions} \\
23
- -H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
24
- -H "Content-Type: application/json" \\
25
- -d '{
26
- "model": "gpt-5.6-luna",
27
- "messages": [{"role": "user", "content": ${r}}]
28
- }'`,a=`curl ${e.responses} \\
29
- -H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
30
- -H "Content-Type: application/json" \\
31
- -d '{
32
- "model": "gpt-5.6-luna",
33
- "input": ${r}
34
- }'`,o=`curl ${e.messages} \\
35
- -H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
36
- -H "Content-Type: application/json" \\
37
- -d '{
38
- "model": "claude-sonnet-4-6",
39
- "max_tokens": 64,
40
- "messages": [{"role": "user", "content": ${r}}]
41
- }'`;return(0,Q.jsxs)(`section`,{className:`panel api-panel awi-usage-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:n(`api.workspace.usageExamples`)}),(0,Q.jsxs)(`div`,{className:`awi-usage-panel-body`,children:[(0,Q.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Q.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageChatTitle`)}),(0,Q.jsx)(aU,{text:i})]}),(0,Q.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Q.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageResponsesTitle`)}),(0,Q.jsx)(aU,{text:a})]}),t&&(0,Q.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Q.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageMessagesTitle`)}),(0,Q.jsx)(aU,{text:o})]})]})]})}function hU({client:e,apiBase:t,onOpenDetails:n,onCopy:r,onDownload:i}){let a=b(),[o,s]=(0,Z.useState)(0),c=[t,e,String(o)].join(`|`),[l,u]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let n=new AbortController,r=!1;return(async()=>{try{let i=await fetch(`${t}/api/client-config?client=${encodeURIComponent(e)}`,{signal:n.signal});if(!i.ok)throw Error(String(i.status));let a=await i.json();if(r)return;u({key:c,data:a,failed:!1})}catch{if(r)return;u({key:c,data:null,failed:!0})}})(),()=>{r=!0,n.abort()}},[t,e,c]);let d=l!==null&&l.key===c?l:null,f=d?.data??null,p=d?.failed??!1,m=d===null,h=a(PH[e]),g=FH[e],_=f?.text??``,v=(0,Z.useCallback)(t=>{f&&n(e,f,_,t.currentTarget)},[e,f,_,n]);return(0,Q.jsxs)(`li`,{className:`awi-clientconfig-row`,children:[(0,Q.jsx)(`span`,{className:`awi-clientconfig-mark`,children:(0,Q.jsx)(HH,{src:g??null,label:h,size:20})}),(0,Q.jsxs)(`span`,{className:`awi-clientconfig-identity`,children:[(0,Q.jsx)(`span`,{className:`awi-clientconfig-name`,children:h}),(0,Q.jsx)(`span`,{className:`muted text-label awi-clientconfig-meta`,children:m?a(`api.clientConfig.loading`):p||!f?(0,Q.jsx)(`span`,{role:`alert`,children:a(`api.clientConfig.rowError`,{client:h})}):a(`api.clientConfig.rowMeta`,{destination:f.destination,count:f.modelCount})})]}),(0,Q.jsx)(`span`,{className:`awi-clientconfig-row-actions`,children:p&&!m?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e=>e+1),children:a(`common.retry`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":a(`api.clientConfig.copyAria`,{client:h}),disabled:!f,onClick:()=>{f&&r(e,_)},children:a(`api.clientConfig.copy`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"aria-label":a(`api.clientConfig.downloadAria`,{client:h}),disabled:!f,onClick:()=>{f&&i(e,f,_)},children:a(`api.clientConfig.download`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":a(`api.clientConfig.detailsAria`,{client:h}),disabled:!f,onClick:v,children:a(`api.clientConfig.details`)})]})})]})}function gU({client:e,envelope:t,json:n,hasKeys:r,onClose:i,onCopy:a,onDownload:o}){let s=b(),c=(0,Z.useRef)(null),l=`awi-clientconfig-dialog-${e}`;(0,Z.useEffect)(()=>{let e=c.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]);let u=(0,Z.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,Q.jsxs)(`div`,{className:`modal-card awi-clientconfig-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:l,children:s(PH[e])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:s(`common.close`)})]}),(0,Q.jsx)(`pre`,{className:`api-code api-example-pre awi-clientconfig-json`,tabIndex:0,role:`group`,"aria-label":s(`api.clientConfig.jsonLabel`,{client:s(PH[e])}),children:n}),(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-count`,children:s(`api.clientConfig.modelCount`,{count:t.modelCount})}),t.modelsWithoutLimits>0&&(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-degraded`,children:s(`api.clientConfig.missingLimits`,{count:t.modelsWithoutLimits,total:t.modelCount})}),!r&&e!==`cline`&&t.apiKeyEnv!==``&&(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-nokey`,children:s(`api.clientConfig.noKeyYet`,{env:t.apiKeyEnv})}),(0,Q.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.destination`)}),(0,Q.jsx)(aU,{text:t.destination})]}),(0,Q.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[e!==`cline`&&t.apiKeyEnv!==``&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.envHint`)}),(0,Q.jsx)(aU,{text:t.exportHint})]}),(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-merge`,children:s(e===`cline`?`api.clientConfig.clineBundle`:`api.clientConfig.mergeWarning`)}),(e===`cline`||t.apiKeyEnv!==``)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label awi-clientconfig-where-title`,children:s(`api.clientConfig.whereDisclosure`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:s(e===`cline`?`integrations.semantics.cline`:`api.clientConfig.whereBody`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:s(`api.clientConfig.copy`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:o,children:s(`api.clientConfig.download`)})]})]})]})}function _U({apiBase:e,baseUrl:t,hasKeys:n}){let r=b(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(``),c=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(i!==null)return;let e=c.current;e&&(c.current=null,e.isConnected&&e.focus())},[i]);let l=(0,Z.useCallback)(async(e,t,n)=>{try{await navigator.clipboard.writeText(t),s(n?r(`api.clientConfig.copiedAnnounceClient`,{client:r(PH[e])}):r(`api.clientConfig.copiedAnnounce`))}catch{s(r(`api.clientConfig.copyFailed`))}},[r]),u=(0,Z.useCallback)((e,t,n)=>{let i=URL.createObjectURL(new Blob([n],{type:t.mediaType})),a=document.createElement(`a`);a.href=i,a.download=t.filename,a.click(),URL.revokeObjectURL(i),s(r(e===`cline`?`api.clientConfig.clineDownloaded`:`api.clientConfig.downloadedAnnounce`,{filename:t.filename,destination:t.destination}))},[r]),d=(0,Z.useCallback)(()=>a(null),[]),f=(0,Z.useCallback)((e,t,n,r)=>{c.current=r,a({client:e,envelope:t,json:n})},[]);return(0,Q.jsxs)(`section`,{className:`panel api-panel awi-clientconfig-panel`,children:[(0,Q.jsx)(`div`,{className:`api-panel-head awi-clientconfig-head`,children:(0,Q.jsx)(`h3`,{className:`panel-title`,children:r(`api.clientConfig.title`)})}),(0,Q.jsx)(`ul`,{className:`awi-clientconfig-rows`,"aria-label":r(`api.clientConfig.rowsLabel`),children:NH.map(t=>(0,Q.jsx)(hU,{client:t,apiBase:e,onOpenDetails:f,onCopy:(e,t)=>{l(e,t,!0)},onDownload:u},t))}),(0,Q.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:r(`api.baseUrl`)}),(0,Q.jsx)(aU,{text:t})]}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:o}),i&&(0,Q.jsx)(gU,{client:i.client,envelope:i.envelope,json:i.json,hasKeys:n,onClose:d,onCopy:()=>{l(i.client,i.json,!1)},onDownload:()=>u(i.client,i.envelope,i.json)})]})}function vU({keys:e,keysLoading:t,keysLoadFailed:n,attributionSince:r,usageMetadata:i,localeTag:a,apiBase:o,active:s=!0,onPairingStart:l,busy:u,onSelect:d,onDelete:f,onReveal:p}){let m=b(),[g,_]=(0,Z.useState)({}),[v,y]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(null),k=(0,Z.useRef)(null),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),R=(0,Z.useRef)(null),z=KH(o,s,(0,Z.useCallback)(e=>{let t=R.current;R.current=null,_({}),y(null),S(null),w(n=>e===`session`?t??n:e===`pairing`?n:null),E(null),O(null),k.current!==null&&window.clearTimeout(k.current),k.current=null},[]));(0,Z.useEffect)(()=>{if(!A)return;let e=window.setTimeout(()=>N(!0),300);return()=>window.clearTimeout(e)},[A]);let B=(0,Z.useRef)(new Set),V=e=>{let t=g[e.id];return t!==void 0&&t.startsWith(e.prefix.replace(/\.\.\.$/,``))?t:void 0},H=u||P!==null,U=c(o).shared,W=h()&&window.location.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(window.location.hostname)&&U.serverOrigin===window.location.origin,ee=async e=>{let t=z.generation.current;if(!z.current(t))return;let n=e.id;if(S(null),w(null),V(e)!==void 0)_(({[n]:e,...t})=>t);else if(p&&!v){R.current=n,y(n);try{let e=await p(n);if(!z.current(t)||B.current.has(n))return;e.ok?_(t=>({...t,[n]:e.key})):e.kind===`denied`?(z.invalidate(),l?.(),w(n)):S(n)}catch{z.current(t)&&S(n)}finally{z.current(t)&&(R.current=null,y(null))}}},G=e=>{E(t=>t===e?null:t),O(e)},te=(e,t)=>{let n=z.generation.current;if(!z.current(n))return;O(null);let r;try{r=navigator.clipboard?.writeText?.(t)}catch{r=void 0}r?r.then(()=>{z.current(n)&&!B.current.has(e)&&(E(e),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{E(t=>t===e?null:t),k.current=null},2e3))},()=>{z.current(n)&&G(e)}):G(e)};(0,Z.useEffect)(()=>()=>{k.current!==null&&window.clearTimeout(k.current)},[]);let ne=async e=>{if(f&&M&&!P){F(e),L(null);try{await f(e)?(B.current.add(e),j(null),N(!1),_(({[e]:t,...n})=>n)):L(e)}finally{F(null)}}};return(0,Q.jsxs)(`div`,{className:`panel api-panel awi-keylist-panel`,"aria-busy":t,children:[(0,Q.jsx)(`div`,{className:`api-panel-head`,children:(0,Q.jsx)(`h3`,{className:`panel-title`,children:t?m(`api.activeKeysLoading`):m(`api.activeKeys`,{count:e.length})})}),(0,Q.jsx)(ni,{data:i}),C!==null&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`warn`,children:m(`api.key.revealDenied`)}),W&&(0,Q.jsx)(eH,{local:!0,target:U,onPairingStart:()=>{z.invalidate(),l?.()},onConnected:()=>{z.invalidate(),l?.(),w(null)}})]}),t?(0,Q.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":m(`common.loading`)}):e.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:m(n?`api.keysLoadFailed`:`api.noKeys`)}):(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl awi-keylist-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:m(`api.colName`)}),(0,Q.jsx)(`th`,{children:m(`api.colKey`)}),(0,Q.jsx)(`th`,{children:m(`api.attribution.requests7d`)}),(0,Q.jsx)(`th`,{children:m(`api.attribution.lastUsed`)}),f&&(0,Q.jsx)(`th`,{className:`awi-keylist-actions-col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:m(`api.colActions`)})})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=V(e),n=A===e.id;return(0,Q.jsxs)(`tr`,{className:n?`awi-keylist-row is-confirming`:`awi-keylist-row`,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`awi-keylist-name`,disabled:H,onClick:()=>d(e.id),children:e.name})}),(0,Q.jsx)(`td`,{className:`awi-keylist-keycell`,children:p?(0,Q.jsxs)(`span`,{className:`awi-keylist-keywrap`,children:[(0,Q.jsx)(`button`,{type:`button`,className:t?`awi-keylist-key is-revealed`:`awi-keylist-key`,"aria-expanded":t!==void 0,"aria-label":m(t?`api.key.hideAria`:`api.key.revealAria`,{name:e.name}),title:m(t?`api.key.hideHint`:`api.key.revealHint`),disabled:v===e.id,onClick:()=>{ee(e)},children:(0,Q.jsx)(`code`,{children:t??e.prefix})}),t&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm awi-keylist-copy`,onClick:()=>te(e.id,t),children:T===e.id?m(`api.copied`):m(`api.copy`)}),D===e.id&&(0,Q.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:m(`api.key.copyFailedShort`)}),x===e.id&&(0,Q.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:m(`api.key.revealFailed`)})]}):(0,Q.jsx)(`code`,{children:e.prefix})}),(0,Q.jsx)(`td`,{children:r?e.usage.ambiguous?m(`api.attribution.railAmbiguous`):e.usage.requests7d.toLocaleString(a):m(`api.attribution.unavailable`)}),(0,Q.jsx)(`td`,{children:!r||e.usage.ambiguous?`—`:e.usage.lastUsedAt?nU(e.usage.lastUsedAt,a):m(i?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)}),f&&(0,Q.jsxs)(`td`,{className:`awi-keylist-actions`,children:[n?(0,Q.jsxs)(`span`,{className:`awi-keylist-confirm`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,"aria-label":m(`api.key.deleteRowAria`,{name:e.name}),disabled:!M||P!==null,onClick:()=>{ne(e.id)},children:P===e.id?m(`api.key.deleting`):m(`api.key.deleteShort`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P!==null,onClick:()=>{j(null),N(!1),L(null)},children:m(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`awi-keylist-delete`,"aria-label":m(`api.key.deleteRowAria`,{name:e.name}),title:m(`api.workspace.deleteKey`),disabled:H,onClick:()=>{L(null),N(!1),j(e.id)},children:(0,Q.jsx)(et,{width:16,height:16,"aria-hidden":`true`})}),I===e.id&&(0,Q.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:m(`api.deleteFailed`)})]})]},e.id)})})]})})]})}var yU=class extends Error{code;constructor(e){super(e),this.code=e}},bU=2097152;async function xU(e,t,n,r,i){if(!r.size||r.size>25e6)throw new yU(`size`);if(!n.trim())throw new yU(`auth`);i.throwIfAborted();let a=d(13e4),o=()=>a.controller.abort(i.reason);i.addEventListener(`abort`,o,{once:!0});try{let i=new FormData;i.set(`file`,r),i.set(`model`,t),i.set(`response_format`,`json`);let o=await E(e,{method:`POST`,headers:{"X-OpenCodex-API-Key":n.trim()},body:i,signal:a.signal});if(!o.ok)throw o.body?.cancel().catch(()=>{}),new yU(o.status===401||o.status===403?`auth`:o.status===429?`rateLimit`:o.status===413?`size`:o.status>=500?`unavailable`:`invalid`);let s=o.body?.getReader();if(!s)throw new yU(`protocol`);let c=()=>{s.cancel().catch(()=>{})};a.signal.addEventListener(`abort`,c,{once:!0});let l=``,u=0,d=new TextDecoder;try{for(a.signal.throwIfAborted();;){let e=await s.read();if(a.signal.throwIfAborted(),e.done)break;if(u+=e.value.byteLength,u>bU)throw new yU(`protocol`);l+=d.decode(e.value,{stream:!0})}l+=d.decode()}finally{a.signal.removeEventListener(`abort`,c),s.cancel().catch(()=>{}),s.releaseLock()}let f;try{f=JSON.parse(l)}catch{throw new yU(`protocol`)}if(!f||typeof f!=`object`||typeof f.text!=`string`)throw new yU(`protocol`);return f.text}catch(e){throw i.aborted?i.reason:a.signal.aborted?new yU(`timeout`):e instanceof yU?e:new yU(`network`)}finally{i.removeEventListener(`abort`,o),a.clear()}}function SU(e){let t=new TextEncoder().encode(e.trim());if(!t.length||t.length>4096)throw new yU(`auth`);let n=``;for(let e of t)n+=String.fromCharCode(e);return[`opencodex-audio`,`opencodex-key.${btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}`]}var CU={type:`session.update`,session:{instructions:``,audio:{output:{voice:`cove`}},delegation:{type:`client`}}},wU=new Set([`session.started`,`session.updated`,`delegation.created`,`output_audio.delta`]);function TU(e){let t=new URL(e.endpoint);if(![`ws:`,`wss:`].includes(t.protocol)||t.pathname!==`/v1/live`||t.username||t.password||t.search||t.hash)throw new yU(`invalid`);t.searchParams.set(`model`,e.model);let n=new WebSocket(t.href,SU(e.key)),r=!1,i=!1,a,o=setTimeout(()=>c(`failed`,`timeout`),e.readyTimeoutMs??15e3),s=()=>{clearTimeout(o),clearTimeout(a),n.onopen=n.onmessage=n.onerror=n.onclose=null;try{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({type:`session.close`})),n.close()}catch{}};function c(t,n){r||(r=!0,s(),e.onState(t,n))}return n.onopen=()=>{try{n.send(JSON.stringify(CU))}catch{c(`failed`,`network`)}},n.onmessage=t=>{if(r)return;if(typeof t.data!=`string`||t.data.length>65536){c(`failed`,`protocol`);return}let n;try{n=JSON.parse(t.data)}catch{c(`failed`,`protocol`);return}if(!n||typeof n!=`object`||typeof n.type!=`string`)c(`failed`,`protocol`);else if(n.type===`error`||n.type===`protocol.error`)c(`failed`,`protocol`);else{if(n.type===`session.started`||n.type===`session.updated`){let t=n.session;if(t?.status===`error`||t?.status===`failed`){c(`failed`,`protocol`);return}if(t?.status===`closed`){c(i?`disconnected`:`failed`,i?void 0:`protocol`);return}!i&&typeof t?.id==`string`&&t.id.trim()&&(i=!0,clearTimeout(o),a=setTimeout(()=>c(`disconnected`),e.maxSessionMs??6e4),e.onState(`connected`))}wU.has(n.type)&&e.onEvent(n.type)}},n.onerror=()=>c(`failed`,`network`),n.onclose=e=>c(i&&e.code===1e3?`disconnected`:`failed`,i&&e.code===1e3?void 0:`network`),e.onState(`connecting`),()=>{r||(r=!0,s())}}function EU(e,t,n,r){let i=new URL(e);t&&i.searchParams.set(`model`,n);let a=t?CU:{type:`session.start`,config:{input_audio_format:`pcm16`,sample_rate_hz:48e3,num_channels:1,max_buffer_size_bytes:4194304,max_utterance_duration_ms:3e4,session_ttl_ms:3e5,provider_mode:`streaming_sse`,transcript_delivery_mode:`segment`,vad:{type:`server_vad`,threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}}};return`const key = prompt(${JSON.stringify(r)})?.trim();
42
- if (!key) throw new Error("missing_data_key");
43
- const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(key)))
44
- .replace(/\\+/g, "-").replace(/\\//g, "_").replace(/=+$/, "");
45
- const ws = new WebSocket(${JSON.stringify(i.href)},
46
- ["opencodex-audio", "opencodex-key." + encoded]);
47
- ws.onopen = () => ws.send(JSON.stringify(${JSON.stringify(a)}));
48
- ws.onmessage = ({ data }) => console.log(JSON.parse(data).type);
49
- // After session.started, send your protocol's audio frames.
50
- // Dictation: mono PCM16 at the declared sample_rate_hz (48000 here).
51
- // Live Voice: input_audio.append / output_audio.delta, 24 kHz mono.
52
- const closeSession = () => ws.send(JSON.stringify({ type: "session.close" }));`}function DU(e,t){return[`curl ${JSON.stringify(e)}`,` -H "X-OpenCodex-API-Key: $OPENCODEX_API_KEY"`,` -F "file=@recording.wav" -F "model=${t}"`].join(` \\
53
- `)}function OU({value:e,onChange:t}){let n=b(),r=(0,Z.useId)();return(0,Q.jsxs)(`label`,{className:`audio-api-field`,htmlFor:r,children:[(0,Q.jsx)(`span`,{children:n(`audio.key`)}),(0,Q.jsx)(`input`,{id:r,className:`input`,type:`password`,autoComplete:`off`,spellCheck:!1,maxLength:4096,value:e,onChange:e=>t(e.target.value)})]})}function kU({code:e}){let t=b();return e?(0,Q.jsx)(`p`,{className:`audio-api-error`,role:`alert`,children:t(`audio.error.${e}`)}):null}function AU({audio:e}){let t=b(),[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useId)(),m=(0,Z.useId)();(0,Z.useEffect)(()=>()=>{f.current?.abort(),f.current=null},[]);let h=()=>{f.current?.abort(),f.current=null,s(!1)},g=async()=>{if(!e?.transcriptionConfigured||!i||!n.trim()||f.current)return;let t=new AbortController;f.current=t,s(!0),d(null),l(null);try{let r=await xU(e.transcriptionEndpoint,e.transcriptionModel,n,i,t.signal);f.current===t&&l(r)}catch(e){f.current===t&&!t.signal.aborted&&d(e instanceof yU?e.code:`network`)}finally{f.current===t&&(f.current=null,s(!1))}};return(0,Q.jsxs)(`section`,{className:`audio-api-section`,"aria-labelledby":m,children:[(0,Q.jsxs)(`header`,{className:`audio-api-head`,children:[(0,Q.jsx)(`h3`,{id:m,children:t(`audio.dictation`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:t(e?.transcriptionConfigured?`audio.configured`:e?`audio.notConfigured`:`audio.unknown`)})]}),e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`audio-api-endpoints`,children:[(0,Q.jsx)(`code`,{children:e.transcriptionModel}),(0,Q.jsx)(rU,{url:e.transcriptionEndpoint})]}),(0,Q.jsxs)(`form`,{className:`audio-api-form`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,Q.jsx)(OU,{value:n,onChange:e=>{h(),d(null),r(e)}}),(0,Q.jsxs)(`label`,{className:`audio-api-field`,htmlFor:p,children:[(0,Q.jsx)(`span`,{children:t(`audio.file`)}),(0,Q.jsx)(`input`,{id:p,className:`input`,type:`file`,accept:`audio/*,.mp4,.webm`,onChange:e=>{h(),d(null),l(null),a(e.target.files?.[0]??null)}})]}),(0,Q.jsxs)(`div`,{className:`audio-api-actions`,children:[(0,Q.jsxs)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:o||!e.transcriptionConfigured||!i||!n.trim(),children:[(0,Q.jsx)(Ee,{width:16,height:16,"aria-hidden":`true`}),t(o?`audio.transcribing`:`audio.transcribe`)]}),o&&(0,Q.jsxs)(`button`,{className:`btn`,type:`button`,onClick:h,children:[(0,Q.jsx)(Ie,{width:16,height:16,"aria-hidden":`true`}),t(`common.cancel`)]})]})]}),(0,Q.jsx)(kU,{code:u}),c!==null&&(0,Q.jsxs)(`div`,{className:`audio-api-result`,"aria-live":`polite`,children:[(0,Q.jsx)(`h4`,{children:t(`audio.transcript`)}),c?(0,Q.jsx)(aU,{text:c}):(0,Q.jsx)(`p`,{className:`muted small`,children:t(`audio.emptyTranscript`)})]}),(0,Q.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Q.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Q.jsx)(aU,{text:DU(e.transcriptionEndpoint,e.transcriptionModel)}),(0,Q.jsxs)(`div`,{className:`audio-api-head`,children:[(0,Q.jsx)(`h4`,{children:t(`audio.streaming`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:t(e.dictationConfigured?`audio.configured`:`audio.notConfigured`)})]}),(0,Q.jsx)(rU,{url:e.dictationStreamEndpoint}),(0,Q.jsx)(aU,{text:EU(e.dictationStreamEndpoint,!1,e.transcriptionModel,t(`audio.key`))})]})]})]})}function jU({audio:e}){let t=b(),[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)(`idle`),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)([]),u=(0,Z.useRef)(null),d=(0,Z.useId)();(0,Z.useEffect)(()=>()=>{u.current?.dispose?.(),u.current=null},[]);let f=()=>{u.current&&(u.current?.dispose?.(),u.current=null,a(`disconnected`))},p=()=>{if(!e?.liveConfigured||!n.trim()||u.current)return;s(null),l([]);let t={};u.current=t;try{t.dispose=TU({endpoint:e.liveEndpoint,model:e.liveModel,key:n,onState:(e,n)=>{u.current===t&&(a(e),s(n??null),(e===`failed`||e===`disconnected`)&&(u.current=null))},onEvent:e=>{u.current===t&&l(t=>[...t.slice(-7),e])}})}catch(e){u.current=null,a(`failed`),s(e instanceof yU?e.code:`network`)}},m=i===`connecting`||i===`connected`;return(0,Q.jsxs)(`section`,{className:`audio-api-section`,"aria-labelledby":d,children:[(0,Q.jsxs)(`header`,{className:`audio-api-head`,children:[(0,Q.jsx)(`h3`,{id:d,children:t(`audio.liveVoice`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:t(e?.liveConfigured?`audio.configured`:e?`audio.notConfigured`:`audio.unknown`)})]}),e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`audio-api-endpoints`,children:[(0,Q.jsx)(`code`,{children:e.liveModel}),(0,Q.jsx)(rU,{url:e.liveEndpoint}),(0,Q.jsx)(rU,{url:e.realtimeCallsEndpoint})]}),(0,Q.jsxs)(`form`,{className:`audio-api-form`,onSubmit:e=>{e.preventDefault(),p()},children:[(0,Q.jsx)(OU,{value:n,onChange:e=>{f(),s(null),l([]),r(e)}}),(0,Q.jsxs)(`div`,{className:`audio-api-actions`,children:[(0,Q.jsxs)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:m||!e.liveConfigured||!n.trim(),children:[(0,Q.jsx)(ue,{width:16,height:16,"aria-hidden":`true`}),t(`audio.connect`)]}),m&&(0,Q.jsxs)(`button`,{className:`btn`,type:`button`,onClick:f,children:[(0,Q.jsx)(Ie,{width:16,height:16,"aria-hidden":`true`}),t(`audio.disconnect`)]}),(0,Q.jsx)(`span`,{className:`audio-api-status`,role:`status`,children:t(`audio.state.${i}`)})]})]}),(0,Q.jsx)(kU,{code:o}),c.length>0&&(0,Q.jsx)(`pre`,{className:`audio-api-events`,"aria-label":t(`audio.events`),children:c.join(`
54
- `)}),(0,Q.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Q.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Q.jsx)(aU,{text:EU(e.liveEndpoint,!0,e.liveModel,t(`audio.key`))})]})]})]})}function MU({keys:e,apiBase:t,active:n=!0,onPairingStart:r,attributionSince:i,historyTruncated:a,usageMetadata:o,authMatrix:s,keysLoading:c,keysLoadFailed:l,endpoints:u,claudeCodeEnabled:d,surfaces:f,onSurfacesChanged:p,localeTag:m,newName:h,creating:g,newKey:_,copied:v,rotationSecret:y=null,rotationCopied:x=!1,filteredModels:S,planModels:C,modelsLoading:w,modelsRefreshing:T=!1,modelsLoadFailed:E,modelCount:D,hasModelData:O,modelQuery:k,copiedModelId:A,modelTests:j,canTestModels:M,onNewNameChange:N,onCreate:P,onDismissNewKey:F,onCopyKey:I,onDelete:L,onRevealKey:R,onRename:z,onRotationStart:B,onRotationCommit:V,onRotationAbort:H,onCopyRotationSecret:U,onDismissRotationSecret:W,onModelQueryChange:ee,onCopyModelId:G,onTestModel:te,onRetryModels:ne,sourceLabel:K,protocolLabel:q}){let J=b(),[re,Y]=(0,Z.useState)(null),[ie,ae]=(0,Z.useState)(!1),[oe,se]=(0,Z.useState)(!1),[ce,le]=(0,Z.useState)(!1),[ue,de]=(0,Z.useState)(!1),[fe,pe]=(0,Z.useState)(``),[me,he]=(0,Z.useState)(!1),[ge,_e]=(0,Z.useState)(!1),[ve,ye]=(0,Z.useState)(!1),[be,xe]=(0,Z.useState)(!1),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(!1),[Ee,De]=(0,Z.useState)(null),Oe=re?e.find(e=>e.id===re)??null:null,ke=Oe?y?.id===Oe.id?y.rotationId:Oe.pendingRotation?.id:void 0,Ae=ke!==void 0||!!B,je=ce||me||be,Me=()=>{let e=y;if(!e)return;let t=navigator.clipboard?.writeText?.(e.key);t?t.then(()=>{Te(!1),De(e.rotationId),window.setTimeout(()=>De(null),2e3)}).catch(()=>{Te(!0)}):Te(!0)},Ne=async e=>{if(Oe&&!be){xe(!0),Ce(!1);try{let t=ke;(e===`start`?await B?.(Oe.id)??!1:t&&(await(e===`commit`?V:H)?.(Oe.id,t)??!1))||Ce(!0)}finally{xe(!1)}}},Pe=(0,Z.useMemo)(()=>[{id:`keys`,label:J(`api.section.keys`),meta:c?void 0:String(e.length)},{id:`connect`,label:J(`api.section.connect`)},{id:`endpoints`,label:J(`api.section.endpoints`)},{id:`plan`,label:J(`api.section.plan`)},{id:`dictation`,label:J(`audio.dictation`)},{id:`live-voice`,label:J(`audio.liveVoice`)},{id:`models`,label:J(`api.section.models`),meta:String(D)},{id:`examples`,label:J(`api.section.examples`)}],[J,e.length,c,D]),Fe=()=>{ae(!1),se(!1)},Ie=()=>{Y(null),Fe(),de(!1),_e(!1),ye(!1)};(0,Z.useEffect)(()=>{if(!ie)return;let e=window.setTimeout(()=>se(!0),300);return()=>window.clearTimeout(e)},[ie]);let Le=()=>{Oe&&ae(!0)},Re=async()=>{if(Oe&&oe&&!ce){le(!0),ye(!1);try{await L(Oe.id)?(Fe(),Y(null)):ye(!0)}finally{le(!1)}}},ze=()=>{Oe&&(pe(Oe.name),_e(!1),de(!0))},Be=async()=>{if(!Oe||me)return;let e=fe.trim();if(!e||e===Oe.name)de(!1);else{he(!0),_e(!1);try{await z(Oe.id,e)?de(!1):_e(!0)}finally{he(!1)}}};return(0,Q.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!Oe&&(0,Q.jsx)(LN,{scope:`api`,items:Pe,ariaLabel:J(`api.workspace.sections`),mobileReadingLine:108}),(0,Q.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,Q.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":J(`api.workspace.details`),children:Oe?(0,Q.jsxs)(`div`,{className:`awi-detail`,children:[(0,Q.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:Ie,disabled:je,children:[(0,Q.jsx)(lt,{className:`awi-back-chevron`,"aria-hidden":`true`}),J(`modal.back`)]})}),(0,Q.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,Q.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,Q.jsx)(`h2`,{className:`awi-detail-title`,children:Oe.name}),(0,Q.jsx)(`span`,{className:`awi-detail-actions`,children:ie?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{Re()},disabled:!oe||ce,children:[(0,Q.jsx)(et,{}),` `,J(ce?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Fe,disabled:ce,children:J(`common.cancel`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ze,disabled:ue,children:J(`api.key.rename`)},`rename`),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:Le,"aria-label":J(`api.deleteAria`),children:[(0,Q.jsx)(et,{}),` `,J(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),ie&&(0,Q.jsx)(`p`,{className:`muted awi-delete-hint`,children:J(`api.workspace.deleteConfirm`)}),ve&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:J(`api.deleteFailed`)}),ue&&(0,Q.jsxs)(`div`,{className:`awi-rename`,children:[(0,Q.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:J(`api.key.name`)}),(0,Q.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:fe,maxLength:64,disabled:me,onChange:e=>pe(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Be())}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{Be()},disabled:me,children:J(me?`api.key.renaming`:`api.key.saveName`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>de(!1),disabled:me,children:J(`common.cancel`)}),ge&&(0,Q.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:J(`api.key.renameFailed`)})]}),(0,Q.jsxs)(`div`,{className:`awi-section`,children:[(0,Q.jsx)(`h3`,{className:`awi-section-title`,children:J(`api.workspace.keyDetails`)}),(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:J(`api.workspace.keyPrefix`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:Oe.prefix})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:J(`api.colCreated`)}),(0,Q.jsx)(`dd`,{children:nU(Oe.createdAt,m)})]})]})]}),Ae&&(0,Q.jsxs)(`div`,{className:`awi-section`,"aria-live":`polite`,children:[(0,Q.jsx)(`h3`,{className:`awi-section-title`,children:J(`api.rotation.title`)}),ke?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:J(`api.rotation.pending`)}),Oe.pendingRotation&&(0,Q.jsxs)(`p`,{className:`muted`,children:[J(`api.rotation.expires`),` `,nU(Oe.pendingRotation.expiresAt,m)]}),y?.id===Oe.id&&(0,Q.jsxs)(`div`,{className:`api-key-reveal`,role:`status`,children:[(0,Q.jsx)(`p`,{children:J(`api.rotation.secretOnce`)}),(0,Q.jsx)(`code`,{children:y.key}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:U??Me,children:x||Ee===y.rotationId?J(`api.copied`):J(`api.copy`)}),W&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:W,children:J(`common.close`)})]}),we&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:J(`api.key.copyFailed`)})]}),(V||H)&&(0,Q.jsxs)(`div`,{className:`awi-detail-actions`,children:[V&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:be,onClick:()=>{Ne(`commit`)},children:J(`api.rotation.commit`)}),H&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:be,onClick:()=>{Ne(`abort`)},children:J(`api.rotation.abort`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:J(`api.rotation.description`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:be,onClick:()=>{Ne(`start`)},children:J(be?`api.rotation.starting`:`api.rotation.start`)})]}),Se&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:J(`api.rotation.failed`)})]}),(0,Q.jsxs)(`div`,{className:`awi-section`,children:[(0,Q.jsx)(`h3`,{className:`awi-section-title`,children:J(`api.attribution.title`)}),(0,Q.jsx)(ni,{data:o}),i?Oe.usage.ambiguous?(0,Q.jsx)(`p`,{className:`muted`,children:J(`api.attribution.ambiguous`)}):(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:J(`api.attribution.requests7d`)}),(0,Q.jsx)(`dd`,{children:Oe.usage.requests7d.toLocaleString(m)})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a||o?.usageIncomplete?J(`api.attribution.totalRequestsAvailable`):J(`api.attribution.totalRequests`)}),(0,Q.jsx)(`dd`,{children:Oe.usage.totalRequests.toLocaleString(m)})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:J(`api.attribution.lastUsed`)}),(0,Q.jsx)(`dd`,{children:Oe.usage.lastUsedAt?nU(Oe.usage.lastUsedAt,m):J(o?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a||o?.usageIncomplete?J(`api.attribution.sinceAvailable`):J(`api.attribution.since`)}),(0,Q.jsx)(`dd`,{children:nU(i,m)})]})]}):(0,Q.jsx)(`p`,{className:`muted`,children:J(`api.attribution.unavailableDetail`)})]})]})]}):(0,Q.jsx)(`div`,{className:`awi-overview`,children:(0,Q.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,Q.jsxs)(`div`,{id:PN(`api`,`keys`),className:`awi-section-anchor`,children:[(0,Q.jsx)(fU,{keys:e,keysLoading:c,keysLoadFailed:l,newName:h,creating:g,newKey:_,copied:v,confirmDelete:null,localeTag:m,showKeyList:!1,onNewNameChange:N,onCreate:P,onDismissNewKey:F,onCopyKey:I,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,Q.jsx)(vU,{keys:e,keysLoading:c,keysLoadFailed:l,attributionSince:i,usageMetadata:o,localeTag:m,apiBase:t,active:n,onPairingStart:r,busy:je,onDelete:L,onReveal:R,onSelect:e=>{Y(e),Fe(),de(!1),_e(!1),ye(!1)}})]}),(0,Q.jsx)(`div`,{id:PN(`api`,`connect`),className:`awi-section-anchor`,children:(0,Q.jsx)(_U,{apiBase:t,baseUrl:u.baseUrl,hasKeys:e.length>0})}),(0,Q.jsx)(`div`,{id:PN(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,Q.jsx)(dU,{endpoints:u,claudeCodeEnabled:d,authMatrix:s,surfaces:f,apiBase:t,onSurfacesChanged:p})}),(0,Q.jsx)(`div`,{id:PN(`api`,`plan`),className:`awi-section-anchor`,children:(0,Q.jsx)(Gk,{apiBase:t,models:C??S,protocolLabel:q},t)}),(0,Q.jsx)(`div`,{id:PN(`api`,`dictation`),className:`awi-section-anchor`,children:n&&(0,Q.jsx)(AU,{audio:u.audio},`${t}:${JSON.stringify(u.audio)}`)}),(0,Q.jsx)(`div`,{id:PN(`api`,`live-voice`),className:`awi-section-anchor`,children:n&&(0,Q.jsx)(jU,{audio:u.audio},`${t}:${JSON.stringify(u.audio)}`)}),(0,Q.jsx)(`div`,{id:PN(`api`,`models`),className:`awi-section-anchor`,children:(0,Q.jsx)(pU,{filteredModels:S,modelsLoading:w,modelsRefreshing:T,modelsLoadFailed:E,modelCount:D,hasModelData:O,modelQuery:k,copiedModelId:A,modelTests:j,claudeCodeEnabled:d,onModelQueryChange:ee,onCopyModelId:G,onTestModel:te,onRetryModels:ne,canTestModels:M,sourceLabel:K,protocolLabel:q})}),(0,Q.jsx)(`div`,{id:PN(`api`,`examples`),className:`awi-section-anchor`,children:(0,Q.jsx)(mU,{endpoints:u,claudeCodeEnabled:d})})]})})})})]})}var NU=[],PU=15e3;function FU(e){let t=e.replace(/\/$/,``);if(!t)return eU;try{return new URL(t).host?tU(`${t}/v1/responses`):eU}catch{return eU}}function IU(e){if(!e||!YH(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!qH(e.usage)||!LU(e.pendingRotation)))return null;if(e.surfaces!==void 0&&!QH(e.surfaces)){let{surfaces:t,...n}=e;e=n}if(e.endpoints?.audio!==void 0&&!$H(e.endpoints.audio,e.endpoints.baseUrl)){let{audio:t,...n}=e.endpoints;return{...e,endpoints:n}}return e}function LU(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.id==`string`&&!!t.id&&typeof t.createdAt==`string`&&!Number.isNaN(Date.parse(t.createdAt))&&typeof t.expiresAt==`string`&&!Number.isNaN(Date.parse(t.expiresAt))}function RU({apiBase:e,active:n=!0}){let{t:r,locale:i}=s(),a=t.find(e=>e.code===i)?.htmlLang,o=`ocx.apikeys.list.v2:${e}`,c=`ocx.apikeys.models.v1:${e}`,l=`api-keys:${e}`,u=`api-models:${e}`,f=lf(o),m=lf(c),h=IU(f?.data??null),g=m?.data??null,_=(0,Z.useRef)(e);(0,Z.useLayoutEffect)(()=>{_.current=e},[e]);let[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(``),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)({}),[O,k]=(0,Z.useState)(``),[A,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!1),B=(0,Z.useRef)(!1),V=KH(e,n,(0,Z.useCallback)(()=>{N(null),F(!1),L(null),z(!1)},[])),H=(0,Z.useCallback)(async t=>{let n=await Xn(await fetch(`${e}/api/keys`,{signal:t}));if(!n||!YH(n.authMatrix))throw Error(r(`api.keysLoadFailed`));let i=n.keys??[];if(i.some(e=>!qH(e.usage)||!LU(e.pendingRotation)))throw Error(r(`api.keysLoadFailed`));let a=i,s=tU(n.endpoint??``),c=QH(n.surfaces),l={keys:a,endpoints:{baseUrl:n.baseUrl??s.baseUrl,responses:n.responsesEndpoint??n.endpoint??eU.responses,chatCompletions:n.chatCompletionsEndpoint??s.chatCompletions,messages:n.messagesEndpoint??s.messages,models:n.modelsEndpoint??s.models,...$H(n.audio,n.baseUrl??s.baseUrl)?{audio:n.audio}:{}},claudeCodeEnabled:n.claudeCodeEnabled!==!1,...c?{surfaces:c}:{},...n.attributionSince?{attributionSince:n.attributionSince}:{},...n.historyTruncated===!0?{historyTruncated:!0}:{},...Zr(n),authMatrix:n.authMatrix};return t.aborted||uf(o,l),l},[e,o,r]),U=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/v1/models`,{signal:t});if(!n.ok)throw Error(r(`api.modelsLoadFailed`));let i=await n.json(),a=Array.isArray(i)?i:typeof i==`object`&&i&&Array.isArray(i.data)?i.data:null;if(!a)throw Error(r(`api.modelsLoadFailed`));let o=a.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`).map(e=>WH(e)).sort((e,t)=>GH(e).localeCompare(GH(t)));return uf(c,o),o},[e,c,r]),W=mf(l,[e],H,{isEmpty:e=>e.keys.length===0,initialData:h??void 0,initialDataCachedAt:f?.cachedAt??null,staleAfterMs:6e4,enabled:n}),ee=mf(u,[e],U,{isEmpty:e=>e.length===0,initialData:g??void 0,initialDataCachedAt:m?.cachedAt??null,staleAfterMs:6e4,enabled:n}),G=W.state,te=ee.state,ne=G.data??h,K=te.data??g??NU,q=ne?.keys??[],J=ne?.endpoints??FU(e),Y=ne?.claudeCodeEnabled??!0,ie=ne?.surfaces,ae=ne?.attributionSince,oe=ne?.historyTruncated===!0,se=ne?.authMatrix??[],ce=W.refresh,le=ee.refresh,ue=(0,Z.useMemo)(()=>{let e=S.trim().toLowerCase();return e?K.filter(t=>GH(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):K},[S,K]),de=async t=>{let n=V.generation.current;if(B.current)return!1;B.current=!0,j(!0),x(null),y(null);try{let i=t??O,a=await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:i||`default`})});a.ok&&(_.current===e?ce():xn(l));let o=await Yn(a,r(`api.createFailed`));return V.current(n)?typeof o?.key!=`string`||o.key.length===0?(x(r(`api.createFailed`)),!1):(N(o.key),k(``),!0):(y(e),!0)}catch{return x(r(`api.createFailed`)),!1}finally{B.current=!1,j(!1)}},fe=async t=>{x(null);let n=d(PU);try{return(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal})).ok?(ce(),!0):!1}catch{return!1}finally{n.clear()}},pe=async t=>{let n=d(PU);try{let r=await fetch(`${e}/api/keys/reveal`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal,cache:`no-store`});if(r.status===401||r.status===403)return{ok:!1,kind:`denied`};if(!r.ok)return{ok:!1,kind:`failed`};let i=await r.json();return typeof i.key==`string`&&i.key?{ok:!0,key:i.key}:{ok:!1,kind:`failed`}}catch{return{ok:!1,kind:`failed`}}finally{n.clear()}},me=async(t,n)=>{x(null);let r=d(PU);try{return(await fetch(`${e}/api/keys`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,name:n}),signal:r.signal})).ok?(ce(),!0):!1}catch{return!1}finally{r.clear()}},he=async t=>{let n=V.generation.current;x(null),y(null);let i=d(PU);try{let a=await fetch(`${e}/api/keys/rotate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:i.signal});a.ok&&(_.current===e?ce():xn(l));let o=await Yn(a,r(`api.rotation.startFailed`));return V.current(n)?!o||typeof o.key!=`string`||!o.key||typeof o.rotationId!=`string`||!o.rotationId?!1:(L({id:t,key:o.key,rotationId:o.rotationId}),!0):(y(e),!0)}catch{return!1}finally{i.clear()}},ge=async(t,n,r)=>{x(null);let i=d(PU);try{return(await fetch(`${e}${r===`commit`?`/api/keys/rotate/commit`:`/api/keys/rotate`}`,{method:r===`commit`?`POST`:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,rotationId:n}),signal:i.signal})).ok?(L(e=>e?.id===t?null:e),ce(),!0):!1}catch{return!1}finally{i.clear()}},_e=async()=>{if(!I)return;let e=V.generation.current;try{if(await navigator.clipboard.writeText(I.key),!V.current(e))return;z(!0),window.setTimeout(()=>{V.current(e)&&z(!1)},2e3)}catch{V.current(e)&&x(r(`api.key.copyFailed`))}},ve=async()=>{if(!M)return;let e=V.generation.current;x(null);try{if(await navigator.clipboard.writeText(M),!V.current(e))return;F(!0),window.setTimeout(()=>{V.current(e)&&F(!1)},2e3)}catch{if(!V.current(e))return;F(!1),x(r(`api.key.copyFailed`))}},ye=async e=>{try{await navigator.clipboard.writeText(e),T(e),window.setTimeout(()=>T(t=>t===e?null:t),2e3)}catch{}},be=e=>e.native?r(`api.sourceNative`):e.provider===`combo`?r(`api.sourceCombo`):e.custom?r(`api.sourceCustom`):re(e.provider,r),xe=e=>r(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),Se=(e,t)=>e===`responses`?{url:J.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:J.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:J.chatCompletions,body:{model:t,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1}},Ce=(e,t,n)=>D(r=>({...r,[e]:{...r[e],[t]:n}})),we=async(e,t)=>{if(!M)return;let n=GH(e),i=Se(t,n);Ce(n,t,{state:`testing`});try{let e=await fetch(i.url,{method:`POST`,headers:{"Content-Type":`application/json`,"x-opencodex-api-key":M},body:JSON.stringify(i.body)});if(!e.ok){let r=await e.text();Ce(n,t,{state:`error`,detail:r.slice(0,160)||String(e.status)});return}Ce(n,t,{state:`ok`})}catch(e){Ce(n,t,{state:`error`,detail:e instanceof Error?e.message:r(`api.testFailed`)})}},Te=r(`api.subtitle`).split(`{authHeader}`);return(0,Q.jsxs)(`section`,{className:`api-page`,"aria-busy":G.refreshing||te.refreshing||void 0,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`api.title`)})}),(0,Q.jsxs)(`p`,{className:`page-sub`,children:[Te[0],(0,Q.jsx)(`code`,{children:`x-opencodex-api-key`}),Te[1]]}),v===e&&(0,Q.jsx)($,{tone:`warn`,children:r(`api.key.mutationHidden`)}),b&&(0,Q.jsx)($,{tone:`err`,children:b}),G.showError&&ne&&(0,Q.jsx)($,{tone:`err`,children:r(`api.keysLoadFailed`)}),G.showSkeleton&&!ne?(0,Q.jsx)(ck,{label:r(`api.activeKeysLoading`),rows:4}):G.kind===`failed-cold`&&!ne?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:G.error instanceof Error?G.error.message:r(`api.keysLoadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ce(),children:r(`common.retry`)})]}):(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(MU,{active:n,onPairingStart:()=>V.invalidate(),keys:q,apiBase:e,attributionSince:ae,historyTruncated:oe,usageMetadata:Zr(ne),authMatrix:se,keysLoading:!1,keysLoadFailed:G.showError,endpoints:J,claudeCodeEnabled:Y,surfaces:ie,onSurfacesChanged:()=>{ce()},localeTag:a,newName:O,creating:A,newKey:M,copied:P,rotationSecret:I,rotationCopied:R,filteredModels:ue,planModels:K,modelsLoading:te.showSkeleton&&!te.data&&!g,modelsRefreshing:te.refreshing&&te.showError&&(te.data!==void 0||g!==null),modelsLoadFailed:te.showError,modelCount:K.length,hasModelData:te.data!==void 0||g!==null,modelQuery:S,copiedModelId:w,modelTests:E,onNewNameChange:k,onCreate:()=>{de()},onDismissNewKey:()=>N(null),onCopyKey:()=>{ve()},onDelete:fe,onRevealKey:pe,onRename:me,...p()?{onRotationStart:he,onRotationCommit:(e,t)=>ge(e,t,`commit`),onRotationAbort:(e,t)=>ge(e,t,`abort`),onCopyRotationSecret:()=>{_e()},onDismissRotationSecret:()=>L(null)}:{},onModelQueryChange:C,onCopyModelId:e=>{ye(e)},onTestModel:(e,t)=>{we(e,t)},onRetryModels:()=>{le({forceLoading:!0})},canTestModels:M!==null,sourceLabel:be,protocolLabel:xe},e)})]})}var zU=[`none`,`live`,`stopped`,`disabled`,`broken`,`foreign`,`local`,`unknown`];function BU(e){return e===void 0?`none`:zU.find(t=>t===e)??`unknown`}function VU(e){return e.sharedProxy===`unknown`?`unknown`:e.sharedProxy===`foreign`?`foreign`:e.sharedProxy===`local`?`local`:!e.desktopFirstParty&&!e.cliFirstParty&&e.sharedProxy!==`none`?`residual`:e.sharedProxy===`disabled`?`disabled`:(e.sharedProxy===`stopped`||e.sharedProxy===`broken`)&&!e.interceptEligible?`routingOff`:e.sharedProxy===`stopped`?`stopped`:e.sharedProxy===`broken`?`broken`:e.sharedProxy===`none`&&e.cliFirstParty?`notApplied`:e.sharedProxy===`live`&&e.desktopFirstParty!==e.cliFirstParty?`shared`:null}function HU(e){switch(e){case`disabled`:return`claude.intercept.reason.disabled`;case`client_role`:return`claude.intercept.reason.client_role`;case`ephemeral_port`:return`claude.intercept.reason.ephemeral_port`;case`port_in_use`:return`claude.intercept.reason.port_in_use`;case`port_mismatch`:return`claude.intercept.reason.port_mismatch`;case`stopped`:return`claude.intercept.reason.stopped`;default:return`claude.intercept.reason.failed`}}var UU=`failed`;function WU({apiBase:e,reason:t,port:n,onStarted:r}){let i=b(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=async()=>{if(!a){o(!0),c(null);try{let t=await fetch(`${e}/api/claude-intercept/start`,{method:`POST`}),n=await t.json();!t.ok||!n.ok?c({reason:n.reason??UU,port:n.port}):r()}catch{c({reason:UU})}finally{o(!1)}}};return(0,Q.jsxs)(`span`,{role:`status`,children:[i(HU(s?.reason??t),{port:s?.port??n??``}),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:a,onClick:()=>void l(),children:i(a?`claude.intercept.starting`:`claude.intercept.start`)})]})}function GU(e){let[t,n]=(0,Z.useState)(!1),r=(0,Z.useRef)(!1);return{pending:t,change:async(t,i,a)=>{if(!r.current){r.current=!0,n(!0);try{i((await JO(e,`claude`,t)).desiredEnabled)}catch(e){a(e)}finally{r.current=!1,n(!1)}}}}}function KU(e,t){let n=(e??[]).map(e=>({value:e,label:RD(e)}));return[{value:``,label:t},...n]}function qU(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}function JU(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return crypto.randomUUID()}catch{}let e=new Uint8Array(16);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var YU=829800;function XU(e,t=`en`){if(e>=1e6){let n=e/1e6,r=n.toFixed(1).replace(/\.0$/,``);return Number.isInteger(n)||Number(r)*1e6===e?new Intl.NumberFormat(t,{notation:`compact`,compactDisplay:`short`,maximumFractionDigits:+!Number.isInteger(n)}).format(e):`${Math.round(e/1e3)}k`}return`${Math.round(e/1e3)}k`}function ZU(e){return e===`200k`?`200k`:`1m`}var QU=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`],$U=/\[1m\]$/i,eW={ANTHROPIC_DEFAULT_OPUS_MODEL:`claude-opus-5-5`,ANTHROPIC_DEFAULT_SONNET_MODEL:`claude-sonnet-5`,ANTHROPIC_DEFAULT_FABLE_MODEL:`claude-fable-5-1`};function tW(e){return e.replace($U,``)}function nW(e,t){let n=e.tierModels?.haiku?.trim()||e.smallFastModel?.trim()||``;return((t===`ANTHROPIC_MODEL`?e.model:t===`ANTHROPIC_DEFAULT_OPUS_MODEL`?e.tierModels?.opus:t===`ANTHROPIC_DEFAULT_SONNET_MODEL`?e.tierModels?.sonnet:t===`ANTHROPIC_DEFAULT_HAIKU_MODEL`?n:t===`ANTHROPIC_DEFAULT_FABLE_MODEL`?e.tierModels?.fable:``)??``).trim()}function rW(e){let t=e.contextAccounting??`1m`,n=e.servedContextAccounting??t;if(t!==`200k`||n===`200k`)return e.effectiveModelEnv;let r=e.model!==void 0||e.smallFastModel!==void 0||e.tierModels!==void 0,i={};for(let t of QU){let n=e.effectiveModelEnv[t];if(!n)continue;if(!r){if(eW[t]===tW(n))continue;i[t]=tW(n);continue}let a=nW(e,t);a&&(i[t]=$U.test(a)?n:tW(n))}return i}function iW(e){let t=`http://127.0.0.1:${e.port}`,n=e.authMode===`auto`?e.markerMode??`subscription`:e.authMode,r=e.contextAccounting??`1m`,i=e.servedContextAccounting??r,a=r!==`200k`&&i!==`200k`&&e.autoContext&&e.maxContextTokens===null,o=rW(e),s=QU.filter(e=>o[e]).map(e=>`export ${e}=${o[e]}`);return[`export ANTHROPIC_BASE_URL=${t}`,...n===`proxy`?[`export ANTHROPIC_AUTH_TOKEN=opencodex-proxy`]:[`# no ANTHROPIC_AUTH_TOKEN: your claude.ai login (and connectors) stay active`],`export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`,...n===`proxy`?['[ -z "${CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST+x}" ] && export CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1']:[],...a?[`export CLAUDE_CODE_AUTO_COMPACT_WINDOW=${e.autoCompactWindow??829800}`]:[],...s,`claude`].join(`
55
- `)}function aW({code:e,className:t,size:n=`md`}){let r=b(),[i,a]=(0,Z.useState)(`idle`),o=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let s=async()=>{try{await navigator.clipboard.writeText(e),a(`copied`)}catch{a(`failed`)}o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>a(`idle`),1600)},c=r(i===`copied`?`api.copied`:`api.copy`);return(0,Q.jsxs)(`div`,{className:X(`ui-v2 relative min-w-0 rounded-[8px] bg-surface ring-1 ring-inset ring-line`,t),children:[(0,Q.jsx)(`pre`,{className:X(`m-0 overflow-x-auto py-2.5 pr-11 pl-3.5 font-mono whitespace-pre text-fg`,n===`sm`?`text-[12px] leading-5`:`text-[13px] leading-5`),children:(0,Q.jsx)(`code`,{children:e})}),(0,Q.jsx)(`button`,{type:`button`,className:X(Nm,`absolute top-1 right-1`,i===`copied`&&`text-success hover:text-success`),"aria-label":c,title:c,onClick:()=>{s()},children:(0,Q.jsx)(Pc,{icon:i===`copied`?qc:zc,strokeWidth:1.8,"aria-hidden":`true`})}),(0,Q.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:i===`copied`?r(`api.copied`):i===`failed`?r(`api.key.copyFailedShort`):``})]})}var oW=Symbol(`modelEditStartedDisabled`);function sW(e){if(!e||!e[oW])return e;let t={...e};return delete t[oW],t}function cW(e){return e?e.backend??`auto`:`inherit`}function lW(e,t){if(t===`inherit`)return;let n={...e,backend:t===`auto`?void 0:t};return t!==`anthropic`&&n.anthropicInstance!==void 0&&(n.anthropicInstance=null),n}function uW(e,t){let n={...e};return t===`anthropic`||t===`anthropic2`?n.anthropicInstance=t:n.anthropicInstance!==void 0&&(n.anthropicInstance=null),n}function dW(e,t){let n=e?.enabled===!1||e?.[oW];return{...e,model:t,...n?{enabled:t.trim().length>0,[oW]:!0}:{}}}function fW(e){if(!e)return null;let t=(e.model??``).trim(),n=e.enabled===void 0?{}:{enabled:e.enabled};return e.backend?{...n,backend:e.backend,model:t,...e.anthropicInstance===void 0?{}:{anthropicInstance:e.anthropicInstance}}:!t&&e.anthropicInstance===void 0?e.enabled===void 0?null:{...n,backend:null,model:``}:{...n,backend:null,model:t,...e.anthropicInstance===void 0?{}:{anthropicInstance:e.anthropicInstance}}}function pW({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function mW({supported:e,checked:t,onChange:n}){let r=b(),i=e?void 0:`claude-system-env-unsupported`;return(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,Q.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,Q.jsx)(`span`,{className:`desc`,id:i,children:(0,Q.jsx)(z,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,Q.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,Q.jsx)(pW,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function hW({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=b(),a=t??e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,Q.jsx)(Vn,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,Q.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function gW(e,t){return e&&[`claude-json-oauth`,`claude-credentials-file`,`macos-keychain`,`exported-env`].includes(e)?t(`claude.authSource.${e}`):t(`claude.authSource.unknown`)}function _W({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=b();return(0,Q.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(Vn,{value:e.authMode,options:[{value:`auto`,label:i(`claude.authModeAuto`)},{value:`subscription`,label:i(`claude.authModeSubscription`)},{value:`proxy`,label:i(`claude.authModeProxy`)}],onChange:t=>r({...e,authMode:t}),label:i(`claude.authMode`),style:{minWidth:220},align:`right`,portal:!0})})]}),e.authModeOrigin&&(0,Q.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,Q.jsxs)(`span`,{children:[e.authModeOrigin===`manual`?i(`claude.effectiveMode.manual`,{mode:e.markerMode===`proxy`?i(`claude.authModeProxy`):i(`claude.authModeSubscription`)}):e.authModeOrigin===`auto-present`?i(`claude.effectiveMode.autoPresent`,{source:gW(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,Q.jsx)(mW,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(Vn,{value:e.fastMode===null?`auto`:e.fastMode?`on`:`off`,options:[{value:`auto`,label:i(`claude.fastAuto`)},{value:`on`,label:i(`claude.fastOn`)},{value:`off`,label:i(`claude.fastOff`)}],onChange:t=>r({...e,fastMode:t===`auto`?null:t===`on`}),label:i(`claude.fastMode`),style:{minWidth:140},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.contextAccounting`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.contextAccountingDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(Vn,{value:e.contextAccounting,options:[{value:`1m`,label:i(`claude.contextAccounting1m`)},{value:`200k`,label:i(`claude.contextAccounting200k`)}],onChange:t=>r({...e,contextAccounting:t===`200k`?`200k`:`1m`}),label:i(`claude.contextAccounting`),style:{minWidth:140},align:`right`,portal:!0})})]}),e.contextAccounting===`1m`&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,Q.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,Q.jsx)(pW,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.contextAccounting===`1m`&&e.autoContext&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,Q.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(Vn,{value:e.autoCompactWindow===null?``:String(e.autoCompactWindow),options:t,onChange:t=>r({...e,autoCompactWindow:t===``?null:Number(t)}),label:i(`claude.autoCompactWindow`),style:{minWidth:130},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,Q.jsx)(pW,{label:i(`claude.injectAgents`),checked:e.injectAgents,onChange:t=>r({...e,injectAgents:t})})]}),[`webSearchSidecar`,`visionSidecar`].map(t=>{let a=e[t],o=t===`webSearchSidecar`?`claude.webSearchSidecar`:`claude.visionSidecar`,s=t===`webSearchSidecar`?`claude.webSearchSidecarHint`:`claude.visionSidecarHint`,c=`claude-sidecar-models-${t}`,l=a?.backend??e.sidecarPools?.[t]?.backend;return(0,Q.jsxs)(`div`,{className:`setting-row claudecode-sidecar-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label setting-copy`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(o)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,Q.jsxs)(`div`,{className:`setting-controls`,children:[(0,Q.jsx)(Vn,{value:cW(a),options:[{value:`inherit`,label:i(`claude.useMainSetting`)},{value:`auto`,label:i(`dash.backendAuto`)},{value:`openai`,label:i(`dash.backendOpenAI`)},{value:`anthropic`,label:i(`dash.backendAnthropic`)}],onChange:n=>{r({...e,[t]:lW(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,Q.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:dW(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),autoComplete:`off`}),a&&(0,Q.jsx)(`datalist`,{id:c,children:n.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),l===`anthropic`&&(0,Q.jsx)(Vn,{value:a?.anthropicInstance??``,label:i(`sidecar.pool`),options:[{value:``,label:i(`sidecar.poolCurrent`)},{value:`anthropic`,label:i(`sidecar.poolA`)},{value:`anthropic2`,label:i(`sidecar.poolB`)}],onChange:n=>r({...e,[t]:uW(a,n)}),portal:!0}),l===`anthropic`&&a?.anthropicInstance&&e.sidecarPools?.[t]?.parent&&a.anthropicInstance!==e.sidecarPools[t].parent&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:i(`sidecar.poolMixed`)})]})]},t)})]})}function vW({manualEnv:e}){let t=b();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label claude-quickstart-hint`,children:(0,Q.jsx)(z,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,Q.jsx)(aW,{code:`ocx claude`}),(0,Q.jsxs)(`details`,{className:`claude-quickstart-manual`,children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,children:t(`claude.manualEnv`)}),(0,Q.jsx)(aW,{code:e,size:`sm`})]})]})}function yW({rows:e,onRowsChange:t}){let n=b();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),e.length>0&&(0,Q.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,Q.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,Q.jsx)(`input`,{className:`input mono`,value:r.from,placeholder:n(`claude.mapFrom`),"aria-label":n(`claude.mapFrom`),onChange:n=>t(e.map((e,t)=>t===i?{...e,from:n.target.value}:e)),style:{flex:1}}),(0,Q.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,Q.jsx)(`input`,{className:`input mono`,value:r.to,placeholder:n(`claude.mapTo`),"aria-label":n(`claude.mapTo`),onChange:n=>t(e.map((e,t)=>t===i?{...e,to:n.target.value}:e)),style:{flex:1}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>t(e.filter((e,t)=>t!==i)),"aria-label":n(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,Q.jsx)(Ie,{})})]},r.id))}),(0,Q.jsx)(`div`,{style:{marginTop:e.length>0?8:0},children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:JU(),from:``,to:``}]),children:[(0,Q.jsx)(Vt,{}),` `,n(`claude.addMapping`)]})})]})}var bW=`etc`;function xW(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:bW,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function SW({aliases:e}){let t=b();return(0,Q.jsxs)(`div`,{className:`claude-aliases`,children:[(0,Q.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,Q.jsx)(`div`,{className:`claude-aliases-scroll`,children:xW(e).map(([e,n])=>(0,Q.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,Q.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===bW?t(`claude.aliasProviderOther`):e,(0,Q.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,Q.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,Q.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,Q.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,Q.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}var CW=[`opus`,`sonnet`,`haiku`,`fable`];function wW({state:e,options:t,onChange:n,apiBase:r,dirty:i}){let a=b(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(``),g=t.map(e=>e.value===``?{...e,label:a(`claude.tierDefaults.unset`)}:e);async function _(e){l(!0),d(``),p(!1),h(``);try{let t=await fetch(`${r}/api/claude-code/model-defaults`,e?{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({fingerprint:o?.fingerprint})}:void 0);if(!t.ok){let e=await t.json();if(e.code===`settings_recovery_required`){s(null),p(!0),d(a(`claude.tierDefaults.recovery`)),typeof e.backupPath==`string`&&h(e.backupPath);return}throw Error(`apply_refused`)}let n=await Yn(t);e?(s(null),d(a(`claude.tierDefaults.applied`))):s(n)}catch{s(null),p(!0),d(a(`claude.tierDefaults.failed`))}finally{l(!1)}}return(0,Q.jsxs)(Q.Fragment,{children:[CW.map(t=>{let r=e.tierModels?.[t]??``,i=r&&!g.some(e=>e.value===r)?[...g,{value:r,label:r}]:g;return(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsx)(`span`,{className:`setting-label`,children:a(`claudeDesktop.family.${t}`)}),(0,Q.jsx)(Vn,{value:r,options:i,label:a(`claudeDesktop.family.${t}`),onChange:r=>{s(null),n({...e,tierModels:{...e.tierModels,[t]:r}})}})]},t)}),(0,Q.jsxs)(`div`,{className:`btn-row`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:c||i,onClick:()=>void _(!1),children:[(0,Q.jsx)(Me,{}),` `,a(`claude.tierDefaults.preview`)]}),o&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:c||i||!o.changes.length,onClick:()=>void _(!0),children:[(0,Q.jsx)(st,{}),` `,a(`claude.tierDefaults.apply`)]})]}),o&&(0,Q.jsx)(`pre`,{children:o.changes.length?o.changes.map(e=>`${e.key}\n${e.before??`-`} -> ${e.after}`).join(`
56
-
57
- `):a(`claude.tierDefaults.applied`)}),u&&(0,Q.jsx)(`p`,{role:f?`alert`:`status`,children:u}),m&&(0,Q.jsx)(`pre`,{children:m})]})}var TW=[`authMode`,`systemEnv`,`fastMode`,`autoContext`,`autoCompactWindow`,`contextAccounting`,`injectAgents`,`smallFastModel`,`tierModels`,`webSearchSidecar`,`visionSidecar`];function EW(e){let t=new Map;for(let n of e){let e=n.from.trim(),r=n.to.trim();e&&r&&t.set(e,r)}return Object.fromEntries([...t.entries()].sort(([e],[t])=>e.localeCompare(t)))}function DW(e,t){return{authMode:e.authMode,systemEnv:e.systemEnv,fastMode:e.fastMode,autoContext:e.autoContext,autoCompactWindow:e.autoCompactWindow,contextAccounting:e.contextAccounting,injectAgents:e.injectAgents,smallFastModel:e.smallFastModel,tierModels:e.tierModels??null,modelMap:EW(t),webSearchSidecar:fW(e.webSearchSidecar),visionSidecar:fW(e.visionSidecar)}}function OW(e){return JSON.stringify([DW(e.state,e.rows),e.rows.map(e=>[e.from,e.to])])}function kW(e,t){return OW(e)!==OW(t)}function AW(e){return Object.fromEntries(TW.map(t=>[t,e[t]]))}function jW(e,t){return{...t,...AW(e)}}function MW(e,t){return{...e,...AW(t)}}function NW(e,t){return!e||e.adoptNextRead||!e.savePending&&!kW(e.draft,e.baseline)?{draft:t,baseline:t,adoptNextRead:!1,savePending:e?.savePending}:{draft:{state:jW(e.draft.state,t.state),rows:e.draft.rows},baseline:t,adoptNextRead:!1,savePending:e.savePending}}function PW(e,t){return{state:{...e,...AW(t.state),visionSidecar:sW(t.state.visionSidecar),webSearchSidecar:sW(t.state.webSearchSidecar)},rows:Object.entries(EW(t.rows)).map(([e,t])=>({id:JU(),from:e,to:t}))}}function FW(e,t){if(!e)return e;let n=PW(e.baseline.state,t),r=n.rows;if(OW(e.draft)===OW(t))return{draft:{state:{...e.draft.state,visionSidecar:n.state.visionSidecar,webSearchSidecar:n.state.webSearchSidecar},rows:r},baseline:n,adoptNextRead:!0};let i=e.draft;for(let e of[`visionSidecar`,`webSearchSidecar`]){let n=JSON.stringify(fW(t.state[e]));if(JSON.stringify(fW(i.state[e]))!==n)continue;let r=sW(i.state[e]);r!==i.state[e]&&(i={...i,state:{...i.state,[e]:r}})}return{draft:i,baseline:n,adoptNextRead:!1}}function IW(e){return{...e,cliFirstParty:e.cliFirstParty===!0,cliFirstPartyApplied:e.cliFirstPartyApplied===!0,desktopFirstParty:e.desktopFirstParty===!0,interceptRunning:e.interceptRunning===!0,interceptEligible:e.interceptEligible===void 0||e.interceptEligible===!0,sharedProxy:BU(e.sharedProxy),contextAccounting:ZU(e.contextAccounting),servedContextAccounting:ZU(e.servedContextAccounting??e.contextAccounting)}}var LW=new Map,RW=e=>LW.get(e)??0,zW=e=>{LW.set(e,RW(e)+1)},BW=Symbol(`claude-code-live`),VW=new Map;function HW(e,t,n){for(let r of VW.get(e)??[])r(t,n)}var UW={unknown:`claude.firstParty.unknown`,foreign:`claude.firstParty.foreign`,local:`claude.firstParty.local`,residual:`claude.firstParty.residual`,disabled:`claude.firstParty.disabled`,routingOff:`claude.firstParty.routingOff`,stopped:`claude.firstParty.deadProxy`,broken:`claude.firstParty.brokenProxy`,notApplied:`claude.firstParty.notApplied`,shared:`claude.firstParty.shared`};function WW({title:e,count:t,children:n}){let r=(0,Z.useId)();return(0,Q.jsxs)(`section`,{className:`ccw-section`,"aria-labelledby":r,children:[(0,Q.jsxs)(`h3`,{className:`ccw-section-title`,id:r,children:[e,t==null?null:(0,Q.jsx)(`span`,{className:`count`,children:t})]}),n]})}function GW({apiBase:e,active:n=!0}){let r=b(),{locale:i}=s(),a=t.find(e=>e.code===i)?.htmlLang??`en`,o=`ocx.claude-code.v1:${e}`,c=`claude-code:${e}`,l=(0,Z.useMemo)(()=>lf(o),[o]),u=(0,Z.useMemo)(()=>l?.data?{...l.data,state:IW(l.data.state)}:null,[l]),[d,f]=(0,Z.useState)(()=>u?{draft:u,baseline:u,adoptNextRead:!1}:null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(``),[y,x]=(0,Z.useState)(!1),{pending:S,change:C}=GU(e),[w,T]=(0,Z.useState)(!1),E=(0,Z.useRef)(!1),D=(0,Z.useCallback)(async t=>{let n=RW(o),i=await Yn(await fetch(`${e}/api/claude-code`,{signal:t}),r(`claude.loadFail`));if(!i)throw Error(r(`claude.loadFail`));let a={state:IW({...i,authMode:i.authMode===`proxy`||i.authMode===`subscription`?i.authMode:`auto`,...qU(i),fastMode:i.fastMode??null,maxContextTokens:i.maxContextTokens??null,autoContext:i.autoContext!==!1,autoCompactWindow:i.autoCompactWindow??null,injectAgents:i.injectAgents!==!1,effectiveModelEnv:i.effectiveModelEnv??{}}),rows:Object.entries(i.modelMap??{}).map(([e,t])=>({id:JU(),from:e,to:String(t)}))};if(t.aborted)throw Error(`Claude Code request aborted`);return n===RW(o)?(uf(o,a),a):{...a,superseded:!0}},[e,o,r]),O=mf(c,[e],D,{isEmpty:()=>!1,enabled:n,initialData:u??void 0,initialDataCachedAt:l?.cachedAt??null,staleAfterMs:6e4}),k=O.state,[A,j]=(0,Z.useState)(k.data);if(k.data!==A){j(k.data);let e=k.data;e&&!e.superseded&&f(t=>NW(t,{state:e.state,rows:e.rows}))}let M=k.data??u,N=d?.draft.state??M?.state??null,P=d?.draft.rows??M?.rows??[],F=d!==null&&kW(d.draft,d.baseline),I=e=>{f(t=>t&&{...t,draft:{...t.draft,state:e},adoptNextRead:!1})},L=e=>{f(t=>t&&{...t,draft:{...t.draft,rows:e},adoptNextRead:!1})},R=e=>{let t=lf(o)?.data;t&&uf(o,{...t,state:{...t.state,...e}}),HW(o,{kind:`live`,fields:e},BW)},[z]=(0,Z.useState)(()=>Symbol(`claude-code-page`));(0,Z.useEffect)(()=>{let e=(e,t)=>{if(e.kind===`live`){let{fields:t}=e;f(e=>e&&{...e,draft:{...e.draft,state:{...e.draft.state,...t}},baseline:{...e.baseline,state:{...e.baseline.state,...t}}})}else if(t!==z){let{copy:t}=e;f(e=>NW(e,t))}},t=VW.get(o)??new Set;return t.add(e),VW.set(o,t),()=>{t.delete(e)}},[o,z]);let B=(0,Z.useMemo)(()=>KU(N?.available,r(`claude.smallFastModelUnsetOption`)),[N?.available,r]),V=(0,Z.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,YU,9e5,1e6].sort((e,t)=>e-t),t=N?.autoCompactWindow??null,n=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:r(`claude.autoCompactDefault`,{value:XU(YU,a)})},...n.map(e=>({value:String(e),label:XU(e,a)}))]},[N?.autoCompactWindow,r,a]),H=async()=>{N&&(v(``),await C(!N.enabled,e=>{zW(o),R({enabled:e}),O.refresh()},e=>{x(!1),v(e instanceof Error&&e.message?e.message:r(`claude.networkError`))}))},U=async()=>{if(!N||E.current)return;E.current=!0,T(!0),v(``);let t=!N.cliFirstParty;try{let n=await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cliFirstParty:t})});if(!n.ok){let e=await n.json().catch(()=>null),t={intercept_disabled:`claude.firstParty.refusal.interceptDisabled`,intercept_unavailable:`claude.firstParty.refusal.interceptUnavailable`,foreign_env:`claude.firstParty.refusal.foreignEnv`,ca_unavailable:`claude.firstParty.refusal.caUnavailable`,unreadable:`claude.firstParty.refusal.unreadable`,write_failed:`claude.firstParty.refusal.writeFailed`},i=e?.code&&e.code in t?t[e.code]:`claude.saveFailed`;throw Error(e?.code&&[`disabled`,`client_role`,`ephemeral_port`,`port_in_use`,`port_mismatch`,`stopped`,`failed`].includes(e.code)?r(HU(e.code),{port:e.port??``,bound:e.bound??``,configured:e.configured??``}):r(i))}await Yn(n,r(`claude.saveFailed`)),zW(o),R({cliFirstParty:t}),O.refresh()}catch(e){x(!1),v(e instanceof Error&&e.message?e.message:r(`claude.networkError`))}finally{E.current=!1,T(!1)}},W=async()=>{if(!N||!d||p)return;let t=d.draft;v(``),g(``),m(!0),f(e=>e&&{...e,savePending:!0}),zW(o);try{await Yn(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(DW(t.state,t.rows))}),r(`claude.saveFailed`)),zW(o);let n=lf(o)?.data,i=PW(n?.state??t.state,t);uf(o,i),HW(o,{kind:`saved`,copy:i},z),f(e=>FW(e,t)),x(!0),g(``),v(r(`claude.saved`)),O.refresh()}catch(e){f(e=>e&&{...e,savePending:!1}),x(!1),g(e instanceof Error&&e.message?e.message:r(`claude.networkError`))}finally{m(!1)}},ee=()=>{v(``),g(``),f(e=>e&&{draft:{state:MW(e.draft.state,e.baseline.state),rows:e.baseline.rows},baseline:e.baseline,adoptNextRead:!1})};if(k.kind===`disabled`&&!M)return null;if(k.showSkeleton&&!M)return(0,Q.jsx)(ck,{label:r(`claude.loading`),rows:3});if(k.kind===`failed-cold`){let e=k.error instanceof Error?k.error.message:r(`claude.loadFail`);return(0,Q.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>O.refresh(),children:r(`common.retry`)})]})}if(!N)return null;let G=(0,Q.jsxs)(`div`,{className:`setting-row claudecode-connection-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`claudecode-connection-label`,children:r(`claude.enabledLabel`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claude.subtitle`)})]}),(0,Q.jsx)(Rn,{on:N.enabled,onClick:()=>void H(),disabled:S,label:r(`claude.toggleAria`)})]});return(0,Q.jsxs)(`div`,{className:`claudecode-workspace-shell claudecode-doc`,children:[_&&(0,Q.jsx)($,{tone:y?`ok`:`err`,children:_}),k.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`claude.loadFail`)}),(0,Q.jsx)(`div`,{className:`card claudecode-connection-card`,children:(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`claudecode-first-party-label`,children:r(`claude.firstParty.label`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claude.firstParty.desc`)})]}),(0,Q.jsx)(Rn,{on:N.cliFirstParty,onClick:()=>void U(),disabled:w,label:r(`claude.firstParty.aria`)})]})}),!N.interceptRunning&&(0,Q.jsx)(WU,{apiBase:e,reason:N.interceptReason,port:N.interceptFailurePort,onStarted:()=>O.refresh()}),N.cliFirstParty&&(0,Q.jsx)($,{tone:`warn`,children:r(`claude.firstParty.risk`)}),(()=>{let e=VU(N),t=e&&UW[e];return t?(0,Q.jsx)($,{tone:`warn`,children:r(t)}):null})(),(0,Q.jsx)(WW,{title:r(`claude.quickstart`),children:(0,Q.jsx)(vW,{manualEnv:iW(N)})}),(0,Q.jsx)(WW,{title:r(`claude.workspace.settings`),children:(0,Q.jsx)(_W,{state:N,autoCompactOptions:V,availableModels:N.available??[],onStateChange:I})}),(0,Q.jsx)(WW,{title:r(`claude.tierDefaults.title`),children:(0,Q.jsx)(wW,{state:N,options:B,onChange:I,apiBase:e,dirty:!!d&&kW(d.draft,d.baseline)})}),(0,Q.jsx)(WW,{title:r(`claude.smallFastModel`),children:(0,Q.jsx)(hW,{value:N.smallFastModel,tierHaikuModel:N.tierModels?.haiku,options:B,onChange:e=>I({...N,smallFastModel:e})})}),(0,Q.jsx)(WW,{title:r(`claude.modelMap`),count:P.length,children:(0,Q.jsx)(yW,{rows:P,onRowsChange:L})}),(0,Q.jsx)(WW,{title:r(`claude.aliases`),count:N.aliases.length,children:(0,Q.jsx)(SW,{aliases:N.aliases})}),(0,Q.jsx)(`div`,{className:`card claudecode-master-card`,children:G}),(0,Q.jsxs)(`div`,{className:`ccw-savebar`,role:`region`,"aria-label":r(`claude.saveBar.label`),children:[h&&(0,Q.jsx)(`span`,{className:`ccw-savebar-error`,role:`alert`,children:h}),(0,Q.jsx)(`span`,{className:`ccw-savebar-state${F?` dirty`:``}`,"aria-live":`polite`,"aria-atomic":`true`,children:r(F?`claude.saveBar.dirty`:`claude.saveBar.clean`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!F||p,onClick:ee,children:r(`claude.saveBar.revert`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:p,onClick:()=>{W()},children:r(`common.save`)})]})]})}function KW({apiBase:e,active:t=!0,embedded:n=!1}){let r=b();return(0,Q.jsxs)(`section`,{className:`claude-page${n?` claude-page--embedded`:``}`,children:[!n&&(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`nav.claude`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`claude.pageSub`)}),(0,Q.jsx)(GW,{apiBase:e,active:t},e)]})}function qW(e,t,n){let r=t.trim().toLowerCase(),i=(r?e.filter(e=>e.label.toLowerCase().includes(r)||e.route.toLowerCase().includes(r)):e).toSorted((e,t)=>Number(!e.available)-Number(!t.available)),a=i.slice(0,n);return{total:e.length,showSearch:e.length>4,shown:a,hidden:i.length-a.length,noMatch:e.length>0&&i.length===0}}function JW(e){return new Set(Object.keys(e))}function YW(e,t){return t!==null&&e===t}function XW(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function ZW(e){return{read(t){let n=XW(t);if(!n)return null;try{let t=n.getItem(e);if(t===null)return null;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(e=>typeof e==`string`)):null}catch{return null}},write(t,n){let r=XW(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function QW(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function $W(e){return e.label||e.route}function eG({apiBase:e,bindings:t,suggestions:n,models:r,onSaved:i}){let{t:a}=s(),[o,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),h=(0,Z.useMemo)(()=>r.filter(e=>e.available),[r]),g=(0,Z.useMemo)(()=>new Set(Object.keys(t)),[t]),_=(0,Z.useMemo)(()=>n.filter(e=>!g.has(e)),[n,g]),v=(0,Z.useMemo)(()=>Object.entries(t).sort(([e],[t])=>e.localeCompare(t)),[t]),y=o.trim(),b=y.startsWith(`claude-`)&&l!==``&&d===null,x=async(t,n)=>{if(d===null){f(n),m(null);try{let n=await Yn(await fetch(`${e}/api/claude-desktop/first-party-bindings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),a(`claudeDesktop.firstParty.bindings.saveFailed`));if(!n||n.ok!==!0||typeof n.modelBindings!=`object`||n.modelBindings===null)throw Error(a(`claudeDesktop.firstParty.bindings.saveFailed`));c(``),u(``),i(n.modelBindings)}catch(e){m(e instanceof Error?e.message:a(`claudeDesktop.firstParty.bindings.saveFailed`))}finally{f(null)}}};return(0,Q.jsxs)(`section`,{className:`claude-bindings`,"aria-labelledby":`claude-bindings-title`,children:[(0,Q.jsx)(`h3`,{id:`claude-bindings-title`,className:`claude-bindings-title`,children:a(`claudeDesktop.firstParty.bindings.title`)}),(0,Q.jsx)(`p`,{className:`claude-bindings-hint`,children:a(`claudeDesktop.firstParty.bindings.hint`)}),p&&(0,Q.jsx)($,{tone:`err`,children:p}),v.length===0?(0,Q.jsx)(`p`,{className:`claude-bindings-empty`,children:a(`claudeDesktop.firstParty.bindings.empty`)}):(0,Q.jsx)(`ul`,{className:`claude-bindings-list`,children:v.map(([e,t])=>{let n=h.some(e=>e.route===t);return(0,Q.jsxs)(`li`,{className:`claude-bindings-row`,children:[(0,Q.jsx)(`code`,{className:`claude-bindings-id`,title:e,children:e}),(0,Q.jsx)(lt,{className:`claude-bindings-arrow`,width:12,height:12,"aria-hidden":`true`}),(0,Q.jsx)(Vn,{fullWidth:!0,className:`claude-bindings-select`,label:a(`claudeDesktop.firstParty.bindings.routeLabel`),value:t,disabled:d!==null,onChange:n=>{n!==t&&x({set:{[e]:n}},e)},options:[...n?[]:[{value:t,label:t}],...h.map(e=>({value:e.route,label:$W(e)}))]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-bindings-remove`,"aria-label":a(`claudeDesktop.firstParty.bindings.remove`,{id:e}),disabled:d!==null,onClick:()=>void x({remove:[e]},e),children:(0,Q.jsx)(Ie,{width:12,height:12,"aria-hidden":`true`})})]},e)})}),(0,Q.jsxs)(`div`,{className:`claude-bindings-add`,children:[(0,Q.jsx)(`input`,{className:`input claude-bindings-input`,type:`text`,list:`claude-bindings-suggestions`,"aria-label":a(`claudeDesktop.firstParty.bindings.pickerLabel`),placeholder:a(`claudeDesktop.firstParty.bindings.pickerPlaceholder`),value:o,disabled:d!==null,onChange:e=>c(e.target.value)}),(0,Q.jsx)(`datalist`,{id:`claude-bindings-suggestions`,children:_.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),(0,Q.jsx)(Vn,{fullWidth:!0,className:`claude-bindings-select`,label:a(`claudeDesktop.firstParty.bindings.routeLabel`),value:l,disabled:d!==null,onChange:u,options:[{value:``,label:a(`claudeDesktop.firstParty.bindings.routePlaceholder`)},...h.map(e=>({value:e.route,label:$W(e)}))]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!b,onClick:()=>void x({set:{[y]:l}},y),children:a(d!==null&&d===y?`common.saving`:`claudeDesktop.firstParty.bindings.add`)})]})]})}function tG(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.desired==`boolean`&&typeof t.supported==`boolean`&&[`trusted`,`untrusted`,`unsupported`,`unknown`].includes(t.trust)&&[`absent`,`applied`,`not_selected`,`unsafe`].includes(t.profile)&&typeof t.listenerReady==`boolean`&&typeof t.effective==`boolean`&&[`active`,`restart_required`,`unsupported_platform`,`not_first_party`,`integration_off`,`disabled`,`proxy_unavailable`,`mode_not_committed`,`trust_pending`,`trust_declined`,`profile_failed`].includes(t.reason)&&typeof t.models==`number`&&Number.isFinite(t.models)&&t.models>=0&&(t.snapshotAt===null||typeof t.snapshotAt==`number`)&&(t.lastBootstrapAt===null||typeof t.lastBootstrapAt==`number`)&&(t.hint===void 0||typeof t.hint==`string`)&&(t.residual===void 0||Array.isArray(t.residual)&&t.residual.every(e=>typeof e==`string`))}function nG(e){switch(e){case`active`:return`claudeDesktop.picker.state.active`;case`restart_required`:return`claudeDesktop.picker.state.restart`;case`trust_pending`:return`claudeDesktop.picker.state.trustPending`;case`trust_declined`:return`claudeDesktop.picker.state.trustDeclined`;case`proxy_unavailable`:return`claudeDesktop.picker.state.proxyUnavailable`;case`unsupported_platform`:return`claudeDesktop.picker.state.unsupported`;case`profile_failed`:return`claudeDesktop.picker.state.profileFailed`;case`not_first_party`:case`integration_off`:case`disabled`:case`mode_not_committed`:return`claudeDesktop.picker.state.notFirstParty`}}function rG({apiBase:e,picker:t,onUpdated:n,pickerReason:r,pickerFailurePort:i}){let{t:a}=s(),[o,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=o??t,m=async()=>{if(!l){u(!0),f(null);try{let t=await fetch(`${e}/api/claude-desktop/picker`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:!p.desired,persist:!0})}),r;if(t.ok)r=await Yn(t,a(`claudeDesktop.updateFailed`));else{try{r=await t.json()}catch{throw Error(a(`claudeDesktop.updateFailed`))}if(!r.picker)throw Error(a(HU(r.reason),{port:r.port??``}))}if(!r||r.ok!==!0&&!r.picker||!r.picker||!tG(r.picker))throw Error(a(`claudeDesktop.updateFailed`));c(r.picker),n?.(r.picker)}catch(e){f(e instanceof Error?e.message:a(`claudeDesktop.updateFailed`))}finally{u(!1)}}};return(0,Q.jsxs)(`section`,{className:`claude-picker`,"aria-labelledby":`claude-picker-title`,children:[!p.listenerReady&&r&&(0,Q.jsx)(`span`,{role:`status`,children:a(HU(r===`port_in_use`&&!i?`failed`:r),{port:i??``})}),!p.listenerReady&&!r&&(0,Q.jsx)(WU,{apiBase:e,onStarted:()=>{c(null),n?.(p)}}),(0,Q.jsxs)(`div`,{className:`claude-picker-header`,children:[(0,Q.jsxs)(`div`,{className:`claude-picker-copy`,children:[(0,Q.jsx)(`h3`,{id:`claude-picker-title`,className:`claude-picker-title`,children:a(`claudeDesktop.picker.title`)}),(0,Q.jsx)(`p`,{className:`claude-picker-hint`,children:a(`claudeDesktop.picker.hint`)})]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${p.desired?`on`:``}`,"aria-checked":p.desired,"aria-label":a(`claudeDesktop.picker.toggle`),disabled:l,onClick:()=>void m(),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),(0,Q.jsxs)(`p`,{className:`claude-picker-state claude-picker-state-${p.reason}`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`claude-picker-state-dot`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:a(nG(p.reason))}),p.reason===`trust_pending`&&p.hint&&(0,Q.jsx)(`code`,{children:p.hint})]}),(0,Q.jsx)(`p`,{className:`claude-picker-models`,children:a(`claudeDesktop.picker.models`,{count:p.models})}),(0,Q.jsx)(`p`,{className:`claude-picker-offline-note`,role:`note`,children:a(`claudeDesktop.picker.offlineNote`)})]})}function iG(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.mode===`include`||t.mode===`exclude`)&&Array.isArray(t.routes)&&t.routes.every(e=>typeof e==`string`)}function aG(e){if(!e)return null;let t=[...new Set(e.routes)].sort();return e.mode===`exclude`&&t.length===0?null:{mode:e.mode,routes:t}}function oG(e,t){return JSON.stringify(aG(e))===JSON.stringify(aG(t))}function sG(e,t){if(!e)return!0;let n=e.routes.includes(t);return e.mode===`include`?n:!n}function cG(e,t,n){let r=e??{mode:`exclude`,routes:[]},i=new Set(r.routes),a=r.mode===`include`?n:!n;for(let e of t)a?i.add(e):i.delete(e);return aG({mode:r.mode,routes:[...i]})}function lG(e,t,n){if((e?.mode??`exclude`)===n)return e;let r=t.filter(t=>sG(e,t)===(n===`include`));return n===`include`?{mode:n,routes:[...new Set(r)].sort()}:aG({mode:n,routes:r})}function uG(e){let t=e.indexOf(`/`);return t>0?e.slice(0,t):e}function dG(e){return[...new Set(e.map(e=>uG(e.route)))].sort()}function fG(e,t,n){let r=t.trim().toLowerCase();return e.filter(e=>(!n||uG(e.route)===n)&&(!r||e.route.toLowerCase().includes(r)||e.label.toLowerCase().includes(r)))}function pG(e,t){let n=0,r=0,i=0;for(let a of e){let e=sG(t,a.route);a.available?(r+=1,e&&(n+=1)):e&&t?.mode===`include`&&(i+=1)}return{selected:n,available:r,selectedUnavailable:i}}function mG(e,t){let n=e.filter(e=>sG(t,e.route));return n.length>0?n:[...e]}function hG(e,t){if(!t)return null;let n=new Set(t.map(e=>e.name)),r=new Set(e.map(e=>e.name));return{added:e.filter(e=>!n.has(e.name)).map(e=>e.label),removed:t.filter(e=>!r.has(e.name)).map(e=>e.label)}}var gG=6;function _G(e){let t=e.slice(0,gG).join(`, `);return e.length>gG?`${t} +${e.length-gG}`:t}function vG({models:e,visibility:t,onChange:n,rendered:r,appliedModels:i,disabled:a,badges:o}){let{t:c}=s(),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(``),[p,m]=(0,Z.useState)(6),h=(0,Z.useMemo)(()=>dG(e),[e]),g=(0,Z.useMemo)(()=>fG(e,l,d),[e,l,d]),_=pG(e,t),v=hG(mG(r,t),i),y=g.map(e=>e.route),b=t?.mode??`exclude`;return(0,Q.jsxs)(`div`,{className:`claude-visibility`,children:[(0,Q.jsxs)(`div`,{className:`claude-visibility-counts`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`claude-visibility-count`,children:c(`claudeDesktop.visibility.selected`,{n:_.selected})}),(0,Q.jsx)(`span`,{className:`claude-visibility-count`,children:c(`claudeDesktop.visibility.available`,{n:_.available})}),(0,Q.jsx)(`span`,{className:`claude-visibility-count`,children:i?c(`claudeDesktop.visibility.applied`,{n:i.length}):c(`claudeDesktop.visibility.appliedUnknown`)}),_.selectedUnavailable>0&&(0,Q.jsx)(`span`,{className:`claude-visibility-count muted`,children:c(`claudeDesktop.visibility.selectedUnavailable`,{n:_.selectedUnavailable})})]}),(0,Q.jsxs)(`fieldset`,{className:`claude-visibility-policy`,disabled:a,children:[(0,Q.jsx)(`legend`,{children:c(`claudeDesktop.visibility.newModels`)}),[`exclude`,`include`].map(r=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`radio`,name:`claude-desktop-new-models`,value:r,checked:b===r,onChange:()=>n(lG(t,e.map(e=>e.route),r))}),c(r===`exclude`?`claudeDesktop.visibility.newShow`:`claudeDesktop.visibility.newHide`)]},r))]}),(0,Q.jsxs)(`div`,{className:`claude-visibility-filters`,children:[(0,Q.jsx)(`input`,{className:`input`,type:`search`,placeholder:c(`claudeDesktop.visibility.search`),"aria-label":c(`claudeDesktop.visibility.search`),value:l,onChange:e=>{u(e.target.value),m(6)}}),(0,Q.jsx)(Vn,{label:c(`claudeDesktop.visibility.provider`),triggerClassName:`min-w-[10rem] justify-between`,value:d,onChange:e=>{f(e),m(6)},options:[{value:``,label:c(`claudeDesktop.visibility.allProviders`)},...h.map(e=>({value:e,label:e}))]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:a||g.length===0,onClick:()=>n(cG(t,y,!0)),children:c(`claudeDesktop.visibility.selectShown`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:a||g.length===0,onClick:()=>n(cG(t,y,!1)),children:c(`claudeDesktop.visibility.clearShown`)})]}),_.selected===0&&_.available>0&&(0,Q.jsx)($,{tone:`warn`,children:c(`claudeDesktop.visibility.noneSelected`)}),g.length===0?(0,Q.jsx)(`p`,{className:`claude-desktop-list-hint`,children:c(`claudeDesktop.visibility.noMatch`)}):(0,Q.jsx)(`ul`,{className:`card claude-desktop-list-rows`,children:g.slice(0,p).map(e=>{let r=sG(t,e.route);return(0,Q.jsxs)(`li`,{className:`claude-desktop-list-row${r?``:` hidden-row`}`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r,disabled:a,"aria-label":c(`claudeDesktop.visibility.toggle`,{model:e.label}),onChange:r=>n(cG(t,[e.route],r.target.checked))}),(0,Q.jsxs)(`span`,{className:`claude-desktop-list-names`,children:[(0,Q.jsx)(`strong`,{title:e.label,children:e.label}),e.label!==e.route&&(0,Q.jsx)(`code`,{title:e.route,children:e.route})]}),(0,Q.jsx)(`span`,{className:`badge badge-muted claude-visibility-provider`,children:uG(e.route)}),o(e)]},e.route)})}),g.length>p&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>m(e=>e+6),children:c(`models.showMore`,{n:g.length-p})}),v&&(0,Q.jsxs)(`div`,{className:`claude-visibility-preview`,children:[(0,Q.jsx)(`span`,{className:`claude-visibility-preview-title`,children:c(`claudeDesktop.visibility.previewTitle`)}),v.added.length===0&&v.removed.length===0?(0,Q.jsx)(`span`,{children:c(`claudeDesktop.visibility.previewSame`)}):(0,Q.jsxs)(Q.Fragment,{children:[v.added.length>0&&(0,Q.jsx)(`span`,{className:`claude-visibility-added`,children:c(`claudeDesktop.visibility.previewAdds`,{models:_G(v.added)})}),v.removed.length>0&&(0,Q.jsx)(`span`,{className:`claude-visibility-removed`,children:c(`claudeDesktop.visibility.previewRemoves`,{models:_G(v.removed)})})]})]}),(0,Q.jsx)(`p`,{className:`claude-desktop-list-hint`,children:c(`claudeDesktop.visibility.replaceNote`)})]})}var yG=[`opus`,`fable`,`sonnet`,`haiku`];function bG(e,t,n,r){let i=e.assignments[t];if(!i)return e;if(i.family===n)return!r||e.defaults[n]===t?e:{...e,defaults:{...e.defaults,[n]:t}};let a={...e.assignments,[t]:{...i,family:n}},o={...e.defaults};return o[i.family]===t&&(o[i.family]=Object.keys(a).filter(e=>e!==t&&a[e].family===i.family).sort()[0]??null),(r||o[n]===null)&&(o[n]=t),{...e,assignments:a,defaults:o}}function xG(e,t){let n=Object.fromEntries(yG.map(e=>[e,[]]));for(let r of e)r.available&&n[t.assignments[r.route]?.family??`opus`].push(r.route);let r={};for(let e of yG){let i=n[e].toSorted(),a=t.defaults[e];r[e]=a&&i.includes(a)?a:i[0]??null}return r}function SG(e,t,n){return e.filter(e=>(t.assignments[e.route]?.family??`opus`)===n).length}function CG(e,t,n){return e.defaults[n]??t[n]??``}function wG(e,t){return e.filter(e=>e.available&&e.route!==t).sort((e,t)=>e.label.localeCompare(t.label)||e.route.localeCompare(t.route))}function TG(e,t,n){let r=e=>e===t?0:e===n?1:2;return e.toSorted((e,t)=>r(e.route)-r(t.route)||e.label.localeCompare(t.label)||e.route.localeCompare(t.route))}function EG(e,t){return e.filter(e=>!e.available&&t.assignments[e.route]).map(e=>e.route)}function DG(e,t,n){let r=new Set(n.filter(e=>e.available).map(e=>e.route)),i=new Set(t.filter(t=>e.assignments[t]&&!r.has(t)));for(let t of yG){let n=e.defaults[t];if(n===null||!i.has(n))continue;let a=Object.keys(e.assignments).filter(n=>e.assignments[n].family===t&&!i.has(n));if(!a.some(e=>r.has(e)))for(let e of a)i.add(e)}return[...i].sort()}function OG(e,t,n){let r=new Set((n??[]).filter(e=>e.available).map(e=>e.route)),i=new Set(n?DG(e,t,n):t.filter(t=>e.assignments[t]));if(i.size===0)return e;let a=Object.fromEntries(Object.entries(e.assignments).filter(([e])=>!i.has(e))),o={...e.defaults};for(let e of yG){let t=o[e];if(t===null||!i.has(t))continue;let n=Object.keys(a).filter(t=>a[t].family===e).sort();o[e]=n.find(e=>r.has(e))??n[0]??null}return{...e,assignments:a,defaults:o}}function kG(e,t){return e.filter(e=>e.available||t.assignments[e.route])}var AG=ZW(`ocx.claudeDesktop.collapsedFamilies.v2`),jG=[`first-party`,`gateway`];function MG(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.desired==`boolean`&&typeof t.supported==`boolean`&&[`trusted`,`untrusted`,`unsupported`,`unknown`].includes(t.trust)&&[`absent`,`applied`,`not_selected`,`unsafe`].includes(t.profile)&&typeof t.listenerReady==`boolean`&&typeof t.effective==`boolean`&&[`active`,`restart_required`,`unsupported_platform`,`not_first_party`,`integration_off`,`disabled`,`proxy_unavailable`,`mode_not_committed`,`trust_pending`,`trust_declined`,`profile_failed`].includes(t.reason)&&typeof t.models==`number`&&Number.isFinite(t.models)&&t.models>=0&&(t.snapshotAt===null||typeof t.snapshotAt==`number`)&&(t.lastBootstrapAt===null||typeof t.lastBootstrapAt==`number`)&&(t.hint===void 0||typeof t.hint==`string`)&&(t.residual===void 0||Array.isArray(t.residual)&&t.residual.every(e=>typeof e==`string`))}function NG(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.health;if(t.mode!==void 0&&!jG.includes(t.mode))return!1;if(t.riskWarning!==void 0&&t.riskWarning!==null){let e=t.riskWarning;if(typeof e!=`object`||typeof e.code!=`string`||typeof e.message!=`string`)return!1}if(t.firstParty!==void 0){let e=t.firstParty;if(typeof e!=`object`||!e||typeof e.applied!=`boolean`||typeof e.stale!=`boolean`||typeof e.interceptEnabled!=`boolean`||typeof e.interceptRunning!=`boolean`||typeof e.proxyPort!=`number`||typeof e.caCertPath!=`string`||e.picker!==void 0&&!MG(e.picker))return!1;if(e.modelBindings!==void 0){let t=e.modelBindings;if(typeof t!=`object`||!t||Array.isArray(t)||Object.values(t).some(e=>typeof e!=`string`))return!1}if(e.pickerSuggestions!==void 0&&(!Array.isArray(e.pickerSuggestions)||e.pickerSuggestions.some(e=>typeof e!=`string`)))return!1}return t.appliedModels!==void 0&&t.appliedModels!==null&&(!Array.isArray(t.appliedModels)||t.appliedModels.some(e=>typeof e?.name!=`string`||typeof e?.label!=`string`))?!1:typeof t.desiredEnabled==`boolean`&&typeof t.applied==`boolean`&&(t.appliedAt===null||typeof t.appliedAt==`string`)&&typeof t.stale==`boolean`&&typeof n==`object`&&!!n&&(n.lastRequestAt===null||typeof n.lastRequestAt==`string`)&&typeof n.requestCount==`number`&&typeof n.errorCount==`number`}var PG={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function FG(e){return{version:1,assignments:Object.fromEntries(Object.entries(e.assignments).map(([e,t])=>[e,{...t}])),defaults:{...e.defaults},...e.appliedFingerprint===void 0?{}:{appliedFingerprint:e.appliedFingerprint},...e.appliedAt===void 0?{}:{appliedAt:e.appliedAt}}}function IG(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:yG.includes(e?.family)?e.family:`opus`,alias:typeof e?.alias==`string`?e.alias:``}}return{version:1,assignments:t,defaults:{opus:e.profile.defaults.opus??null,fable:e.profile.defaults.fable??null,sonnet:e.profile.defaults.sonnet??null,haiku:e.profile.defaults.haiku??null}}}function LG(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}var RG=`⁣route⁣`;function zG({route:e,t}){let[n=``,r=``]=t(`claudeDesktop.roles.unavailableOption`,{route:RG}).split(RG);return(0,Q.jsxs)(`span`,{className:`claude-role-option`,children:[n&&(0,Q.jsx)(`span`,{className:`claude-role-option__status`,children:n}),(0,Q.jsx)(`span`,{className:`claude-role-option__route`,children:e}),r&&(0,Q.jsx)(`span`,{className:`claude-role-option__status`,children:r})]})}function BG(e,t){return e?e>=1048576?t(`claudeDesktop.contextM`,{n:Math.round(e/1048576)}):e>=1e6?t(`claudeDesktop.contextM`,{n:e/1e6}):t(`claudeDesktop.contextK`,{n:Math.round(e/1e3)}):null}function VG(e){return iG(e?.visibility)?aG(e.visibility):null}function HG(e){return lf(e)?.data??null}function UG(e){return lf(e)?.cachedAt??null}function WG(e){let t=HG(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?FG(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function GG({apiBase:e,active:n=!0}){let{t:r,locale:i}=s(),a=t.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,c=`claude-desktop:${e}`,l=(0,Z.useMemo)(()=>WG(o),[o]),[u,d]=(0,Z.useState)(()=>l.profile),[f,p]=(0,Z.useState)(()=>l.savedProfile),[m,h]=(0,Z.useState)(()=>l.destinations),[g,_]=(0,Z.useState)(void 0),[v,y]=(0,Z.useState)(void 0),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(``),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)({}),[O,k]=(0,Z.useState)({}),[A,j]=(0,Z.useState)(()=>AG.read()??new Set(yG)),[M,N]=(0,Z.useState)({}),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(null),R=(0,Z.useRef)(null),z=(0,Z.useCallback)(async t=>{let n=await Yn(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(LG(n,r(`claudeDesktop.loadFail`)));let i=IG(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(d(i),p(FG(i)),_(VG(n)),y(VG(n)),h(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),AG.read()===null){let e=Object.fromEntries(yG.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;j(JW(e))}return uf(o,a),a},[e,o,r,h,d,p,_,y]),B=mf(c,[e],z,{isEmpty:()=>!1,enabled:n,initialData:l.held??void 0,initialDataCachedAt:UG(o),staleAfterMs:6e4}),V=B.state,H=V.data??(l.data&&l.profile?{data:l.data,profile:l.profile}:null),U=H?.data??null,W=u??H?.profile??null,ee=f??H?.profile??null,G=H?Object.fromEntries(H.data.models.map(e=>[e.route,H.profile.assignments[e.route]?.family??`opus`])):{},te=Object.keys(m).length>0?m:G,ne=g===void 0?VG(U):g,K=v===void 0?VG(U):v,q=(0,Z.useMemo)(()=>W!==null&&ee!==null&&JSON.stringify(W)!==JSON.stringify(ee)||!oG(ne,K),[W,ee,ne,K]),J=(0,Z.useMemo)(()=>U&&W?kG(U.models,W):[],[U,W]),re=(0,Z.useMemo)(()=>{let e=Object.fromEntries(yG.map(e=>[e,[]]));if(!W)return e;for(let t of J)e[W.assignments[t.route]?.family??`opus`].push(t);return e},[J,W]),Y=(0,Z.useMemo)(()=>W?xG(J,W):{opus:null,fable:null,sonnet:null,haiku:null},[J,W]),ie=`ocx.claude-desktop.status.v1:${e}`,ae=`claude-desktop-status:${e}`,oe=lf(ie),se=oe&&NG(oe.data)?oe.data:null,ce=mf(ae,[e],async t=>{let n=await Xn(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!NG(n))throw Error(`Claude Desktop status unavailable`);return uf(ie,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:n,initialData:se??void 0}),le=ce.state,ue=le.data??se,de=le.showError,fe=ue!==null,pe=fe||de,me=ue?.mode??`gateway`,he=I??me,ge=fe&&he!==me,_e=ue?.firstParty?.modelBindings,ve=_e?JSON.stringify(_e):null,[ye,be]=(0,Z.useState)(null),[xe,Se]=(0,Z.useState)(ve);xe!==ve&&(Se(ve),be(null));let Ce=ye??_e??{},we=(0,Z.useMemo)(()=>ue?.firstParty?.pickerSuggestions??[],[ue]),Te=e=>{if(!W||e.length===0)return;let t=DG(W,e,U?.models??[]);d(t=>t&&OG(t,e,U?.models??[])),C(r(`claudeDesktop.removedUnavailable`,{n:t.length}))},Ee=(e,t,n=!1)=>{W&&(n||W.assignments[e]?.family!==t)&&(d(r=>r&&bG(r,e,t,n)),h(n=>({...n,[e]:t})),C(r(`claudeDesktop.moved`,{route:e,family:r(PG[t])})))},De=e=>{let t=QW(A,e);AG.write(t),j(t)},Oe=async t=>{if(W&&!w){T(`save`),x(null);try{await Yn(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:W,visibility:aG(ne)})}),r(`claudeDesktop.saveFailed`)),p(FG(W)),y(aG(ne)),t?(T(`apply`),(await Yn(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:he})}),r(`claudeDesktop.applyFailed`)))?.saved===!1?(x({tone:`warn`,text:r(`claudeDesktop.appliedMarkerUnsaved`)}),C(r(`claudeDesktop.appliedMarkerUnsaved`))):(x({tone:`ok`,text:r(`claudeDesktop.savedApplied`)}),C(r(`claudeDesktop.savedAppliedAnnounce`))),L(null)):(x({tone:`ok`,text:r(`claudeDesktop.saved`)}),C(r(`claudeDesktop.savedAnnounce`))),ce.refresh()}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.updateFailed`);x({tone:`err`,text:t}),C(t)}finally{T(null)}}},ke=()=>{if(!W)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(W,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),C(r(`claudeDesktop.exported`))},Ae=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(r(`claudeDesktop.importExpected`));let n=IG({...U,profile:e});d(n),x({tone:`ok`,text:r(`claudeDesktop.importReady`)}),C(r(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.importInvalid`);x({tone:`err`,text:t}),C(r(`claudeDesktop.importFailed`,{error:t}))}},je=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&Ee(n,t)};if(V.kind===`disabled`&&!H)return null;if(V.showSkeleton&&!H)return(0,Q.jsx)(ck,{label:r(`claudeDesktop.loading`),rows:4});if(V.kind===`failed-cold`){let e=V.error instanceof Error?V.error.message:r(`claudeDesktop.loadFail`);return(0,Q.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>B.refresh(),children:r(`claudeDesktop.retry`)})]})}if(!U||!W)return null;let Me=CG(W,Y,`opus`),Ne=CG(W,Y,`haiku`),Pe=new Map(J.map(e=>[e.route,e])),Fe=(e,t,n)=>{let i=wG(J,t||null).map(e=>({value:e.route,label:e.label}));if(e&&!i.some(t=>t.value===e)){let t=Pe.get(e);i.unshift({value:e,label:t?.available===!1||!t?(0,Q.jsx)(zG,{route:e,t:r}):e})}return n?i.unshift({value:``,label:r(`claudeDesktop.roles.unset`)}):e||i.unshift({value:``,label:r(`claudeDesktop.roles.pick`)}),i},Ie=e=>{if(!e)return;let t=Pe.get(e);return t?.available?t.label:r(`claudeDesktop.roles.unavailableOption`,{route:e})},Le=TG(J,Me||null,Ne||null),Re=EG(J,W),ze=SG(J,W,`haiku`)===0,Be=pG(J,ne).selected===0&&J.some(e=>e.available),Ve=Array.isArray(U.rendered)?hG(mG(U.rendered,K),ue?.appliedModels??null):null,He=me===`gateway`&&!!Ve&&(Ve.added.length>0||Ve.removed.length>0);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,Q.jsx)(`p`,{className:`claude-panel-lead`,children:r(`claudeDesktop.subtitle`,{port:U.port})})}),(0,Q.jsxs)(`fieldset`,{className:`claude-mode-picker`,disabled:w!==null||!pe,children:[(0,Q.jsx)(`legend`,{children:r(`claudeDesktop.mode.legend`)}),jG.map(e=>(0,Q.jsxs)(`label`,{className:`claude-mode-option${pe&&he===e?` active`:``}`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`claude-desktop-mode`,value:e,checked:pe&&he===e,onChange:()=>L(e)}),(0,Q.jsxs)(`span`,{className:`claude-mode-title`,children:[r(e===`first-party`?`claudeDesktop.mode.firstParty`:`claudeDesktop.mode.gateway`),e===`gateway`&&(0,Q.jsx)(`span`,{className:`claude-mode-default`,children:r(`claudeDesktop.mode.defaultBadge`)}),fe&&me===e&&(0,Q.jsx)(`span`,{className:`claude-mode-current`,children:r(`claudeDesktop.mode.current`)})]}),(0,Q.jsx)(`span`,{className:`claude-mode-hint`,children:r(e===`first-party`?`claudeDesktop.mode.firstPartyHint`:`claudeDesktop.mode.gatewayHint`)})]},e)),he===`first-party`&&(0,Q.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:r(`claudeDesktop.mode.firstPartyRisk`)}),ge&&(0,Q.jsx)(`span`,{className:`claude-mode-switch-note`,children:r(`claudeDesktop.mode.switchNote`)})]}),(0,Q.jsxs)(`div`,{className:`claude-status-bar ${de&&!ue?`not-applied`:ue?ue.desiredEnabled?me===`gateway`&&ue.activeProfile===!1?`not-applied`:ue.stale||ue.applied&&He?`stale`:ue.applied?`applied`:`not-applied`:`not-applied`:`pending`}`,"aria-busy":!ue&&!de||void 0,children:[(0,Q.jsx)(`span`,{className:`claude-status-dot`}),(0,Q.jsx)(`span`,{children:de&&!ue?r(`claudeDesktop.loadFail`):ue?ue.desiredEnabled?me===`gateway`&&ue.activeProfile===!1?r(`claudeDesktop.status.notActiveProfile`):ue.stale?r(`claudeDesktop.status.stale`):ue.applied&&He?r(`claudeDesktop.status.pendingApply`):ue.applied?r(me===`first-party`?`claudeDesktop.status.appliedFirstParty`:`claudeDesktop.status.applied`):r(`claudeDesktop.status.notApplied`):r(`claudeDesktop.status.disabled`):r(`claudeDesktop.loading`)}),ue?.firstParty&&me===`first-party`&&ue.desiredEnabled&&(0,Q.jsx)(`span`,{className:`claude-status-health`,children:ue.firstParty.interceptRunning?r(`claudeDesktop.firstParty.proxyRunning`,{port:ue.firstParty.proxyPort}):(0,Q.jsx)(WU,{apiBase:e,reason:ue.firstParty.interceptReason,port:ue.firstParty.proxyPort,onStarted:()=>ce.refresh()})}),ue?.health.lastRequestAt&&(0,Q.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(ue.health.lastRequestAt).toLocaleTimeString(a)]}),ue&&ue.health.requestCount>0&&(0,Q.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:ue.health.requestCount,errors:ue.health.errorCount})}),(0,Q.jsxs)(`span`,{className:`claude-status-actions`,children:[(0,Q.jsx)(`span`,{className:`claude-dirty${q?` active`:``}`,children:r(q?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,Q.jsxs)(`span`,{className:`claude-save-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!q||Be||w!==null,onClick:()=>void Oe(!1),children:r(w===`save`?`claudeDesktop.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:Be||w!==null,onClick:()=>void Oe(!0),children:w===`apply`?r(`claudeDesktop.applying`):w===`save`?r(`claudeDesktop.saving`):ue?.desiredEnabled===!1?r(`claudeDesktop.enableApply`):r(ge?`claudeDesktop.switchModeApply`:`claudeDesktop.saveApply`)})]})]})]}),ue?.riskWarning&&he!==`first-party`&&(0,Q.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:r(`claudeDesktop.mode.firstPartyRisk`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:S}),b&&(0,Q.jsx)($,{tone:b.tone,children:b.text}),V.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),de&&ue&&(0,Q.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),me===`first-party`&&ue?.firstParty?.picker&&(0,Q.jsx)(rG,{apiBase:e,picker:ue.firstParty.picker,pickerReason:ue.firstParty.pickerReason,pickerFailurePort:ue.firstParty.pickerFailurePort,onUpdated:()=>void ce.refresh()},`${ue.firstParty.picker.reason}:${ue.firstParty.picker.desired}:${ue.firstParty.picker.effective}:${ue.firstParty.picker.models}:${ue.firstParty.picker.hint??``}`),me===`first-party`&&(0,Q.jsx)(eG,{apiBase:e,bindings:Ce,suggestions:we,models:J,onSaved:e=>{be(e),ce.refresh()}}),J.length===0&&(0,Q.jsx)(Un,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),J.length>0&&(0,Q.jsxs)(`section`,{className:`card claude-desktop-roles`,"aria-labelledby":`claude-desktop-roles-title`,children:[(0,Q.jsx)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-roles-title`,children:r(`claudeDesktop.roles.title`)}),me===`first-party`&&(0,Q.jsx)(`p`,{className:`claude-desktop-roles-scope`,children:r(`claudeDesktop.roles.gatewayScope`)}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:r(`claudeDesktop.roles.default`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claudeDesktop.roles.defaultDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(Vn,{value:Me,options:Fe(Me,Ne,!1),onChange:e=>{e&&Ee(e,`opus`,!0)},label:r(`claudeDesktop.roles.default`),title:Ie(Me),disabled:w!==null,style:{minWidth:240},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:r(`claudeDesktop.roles.quick`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claudeDesktop.roles.quickDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(Vn,{value:Ne,options:Fe(Ne,Me,ze),onChange:e=>{e&&Ee(e,`haiku`,!0)},label:r(`claudeDesktop.roles.quick`),title:Ie(Ne),disabled:w!==null,style:{minWidth:240},align:`right`,portal:!0})})]})]}),(0,Q.jsxs)(`section`,{className:`claude-desktop-list`,"aria-labelledby":`claude-desktop-list-title`,children:[(0,Q.jsxs)(`div`,{className:`claude-desktop-list-head`,children:[(0,Q.jsxs)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-list-title`,children:[r(`claudeDesktop.roles.listTitle`),(0,Q.jsx)(`span`,{className:`count`,children:J.length})]}),(0,Q.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,Q.jsx)(`input`,{ref:R,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void Ae(e)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ke,children:r(`claudeDesktop.exportJson`)}),Re.length>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w!==null,onClick:()=>Te(Re),children:r(`claudeDesktop.removeAllUnavailable`,{n:Re.length})})]})]}),J.length>0&&(0,Q.jsx)(`p`,{className:`claude-desktop-list-hint`,children:r(`claudeDesktop.roles.listHint`)}),J.length>0&&(0,Q.jsx)(vG,{models:Le,visibility:ne,onChange:_,rendered:Array.isArray(U.rendered)?U.rendered:[],appliedModels:me===`gateway`?ue?.appliedModels??null:null,disabled:w!==null,badges:e=>{let t=BG(e.contextWindow,r);return(0,Q.jsxs)(Q.Fragment,{children:[e.route===Me&&(0,Q.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),e.route===Ne&&(0,Q.jsx)(`span`,{className:`claude-row-default claude-row-quick`,children:r(`claudeDesktop.roles.quickBadge`)}),t&&(0,Q.jsx)(`span`,{className:`claude-model-context`,children:t}),e.supports1m===!0&&(0,Q.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),!e.available&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:r(`claudeDesktop.unavailable`)})]})}})]}),(0,Q.jsxs)(`details`,{className:`claude-desktop-advanced`,open:P,onToggle:e=>F(e.currentTarget.open),children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsxs)(`span`,{className:`claude-desktop-advanced-title`,children:[(0,Q.jsx)(lt,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:P?`rotate(90deg)`:`none`}}),r(`claudeDesktop.advanced.title`)]}),(0,Q.jsx)(`span`,{className:`claude-desktop-advanced-chips`,children:yG.map(e=>{let t=re[e].length,n=W.defaults[e],i=Y[e];return(0,Q.jsxs)(`span`,{className:`claude-desktop-advanced-chip`,children:[(0,Q.jsx)(`b`,{children:r(PG[e])}),i?(0,Q.jsx)(`code`,{title:i,children:i}):(0,Q.jsx)(`span`,{children:r(`claudeDesktop.advanced.empty`)}),t>0&&(0,Q.jsx)(`span`,{className:`claude-desktop-advanced-count`,children:t}),t>0&&n===null&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),i&&n!==null&&i!==n&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.temporaryDefault`)})]},e)})})]}),(0,Q.jsx)(`p`,{className:`claude-desktop-advanced-desc`,children:r(`claudeDesktop.advanced.desc`)}),(0,Q.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:yG.map(e=>{let t=re[e],n=qW(t,E[e]??``,O[e]??6),i=A.has(e),a=Y[e];return(0,Q.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>je(t,e),children:[(0,Q.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,Q.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>De(e),children:[(0,Q.jsx)(lt,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,Q.jsx)(`span`,{className:`ocx-group-name`,children:r(PG[e])}),(0,Q.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,Q.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&W.defaults[e]===null&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==W.defaults[e]&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,Q.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,Q.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:E[e]??``,onChange:t=>{let n=t.target.value;D(t=>({...t,[e]:n})),k(t=>({...t,[e]:6}))}}),(0,Q.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,Q.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,Q.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=W.assignments[t.route],i=BG(t.contextWindow,r),a=te[t.route]??`opus`,o=M[t.route]??YW(t.route,Y[e]);return(0,Q.jsxs)(`article`,{className:`claude-model-card${o?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>N(e=>({...e,[t.route]:!o})),children:[(0,Q.jsx)(lt,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,Q.jsxs)(`span`,{className:`claude-model-names`,children:[(0,Q.jsx)(`strong`,{title:t.label,children:t.label}),(0,Q.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,Q.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,Q.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,Q.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,Q.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,Q.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),W.defaults[e]===t.route&&(0,Q.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,Q.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,Q.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[Y[e]===t.route&&W.defaults[e]!==t.route&&(0,Q.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,Q.jsxs)(`div`,{className:`claude-field`,children:[(0,Q.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,Q.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,Q.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:W.defaults[e]===t.route,disabled:!t.available,onChange:()=>d(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(PG[e])})]}),!t.available&&n&&(0,Q.jsxs)(`div`,{className:`claude-remove-row`,children:[(0,Q.jsx)(`span`,{className:`claude-remove-hint`,children:(()=>{let e=DG(W,[t.route],J).length-1;return e>0?r(`claudeDesktop.removeUnavailableTierHint`,{n:e}):r(`claudeDesktop.removeUnavailableHint`)})()}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w!==null,onClick:()=>Te([t.route]),children:r(`claudeDesktop.removeUnavailable`)})]}),(0,Q.jsxs)(`div`,{className:`claude-move-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,Q.jsx)(Vn,{id:`move-${t.route}`,fullWidth:!0,triggerClassName:`h-[34px] py-1`,value:a,disabled:!t.available,onChange:e=>h(n=>({...n,[t.route]:e})),options:yG.map(e=>({value:e,label:r(PG[e])}))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>Ee(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>k(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})]})}function KG(e,t,n,r){let i=e.filter(e=>r===`native`===e.native).map(e=>({...e,alias:t.get(e.id)??null,enabled:!n.has(e.id)})).toSorted((e,t)=>Number(!e.enabled)-Number(!t.enabled));return{rows:i,total:i.length,enabled:i.filter(e=>e.enabled).length}}var qG=ZW(`ocx.grok.collapsedGroups.v2`),JG=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],YG=new Set(JG.map(e=>e.id));function XG(e,t){return e?e>=1048576?t(`claudeDesktop.contextM`,{n:Math.round(e/1048576)}):e>=1e6?t(`claudeDesktop.contextM`,{n:e/1e6}):t(`claudeDesktop.contextK`,{n:Math.round(e/1e3)}):`—`}function ZG({apiBase:e,active:t=!0}){let n=b(),r=`ocx.grok.status.v1:${e}`,i=lf(r),a=i?.data??null,[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(()=>qG.read()??new Set(YG)),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(``),g=(0,Z.useCallback)(async t=>{let i=await Yn(await fetch(`${e}/api/grok`,{signal:t}),n(`grok.loadFail`));if(!i)throw Error(n(`grok.loadFail`));let a={...i,candidates:i.candidates??[],excluded:i.excluded??[]};return uf(r,a),a},[e,r,n]),_=`grok-status:${e}`,v=mf(_,[e],g,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:i?.cachedAt??null,staleAfterMs:6e4,enabled:t}),{state:y}=v,x=v.refresh,S=y.data??a,C=(0,Z.useMemo)(()=>new Set(S?.excluded??[]),[S]),w=o??C,T=(0,Z.useMemo)(()=>o!==null&&(o.size!==C.size||[...o].some(e=>!C.has(e))),[o,C]),E=(0,Z.useMemo)(()=>new Map((S?.models??[]).map(e=>[e.id,e.alias])),[S]),D=e=>{let t=QW(c,e);qG.write(t),l(t)},O=e=>{let t=e?new Set(JG.map(e=>e.id)):new Set;qG.write(t),l(t)},k=(e,t)=>{s(n=>{let r=new Set(n??C);return t?r.delete(e):r.add(e),r})},A=async t=>{if(!u){d(`save`),p(null);try{await Yn(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...w]})}),n(`grok.saveFailed`));let i=[...w];if(S&&Sn(_,{...S,excluded:i}),s(null),t){d(`apply`);let t=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.message??e.error??n(`grok.applyFailed`))}let r=await t.json().catch(()=>({}));r.skippedReason?(p({tone:`err`,text:r.message??n(`grok.applySkipped`)}),h(r.message??n(`grok.applySkipped`))):(p({tone:`ok`,text:n(`grok.savedApplied`)}),h(n(`grok.savedApplied`))),await x()}else p({tone:`ok`,text:n(`grok.saved`)}),h(n(`grok.saved`)),S&&uf(r,{...S,excluded:i})}catch(e){let t=e instanceof Error?e.message:n(`grok.saveFailed`);p({tone:`err`,text:t}),h(t)}finally{d(null)}}};if(y.showSkeleton&&!S)return(0,Q.jsx)(`section`,{className:`grok-page`,children:(0,Q.jsx)(ck,{label:n(`grok.loading`),rows:4})});if(y.kind===`failed-cold`){let e=y.error instanceof Error?y.error.message:n(`grok.loadFail`);return(0,Q.jsxs)(`section`,{className:`grok-page`,children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x(),children:n(`common.retry`)})]})}return(0,Q.jsxs)(`section`,{className:`grok-page`,"aria-busy":y.refreshing||void 0,children:[(0,Q.jsx)(`h2`,{className:`page-title`,children:n(`grok.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`grok.subtitle`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:m}),f&&(0,Q.jsx)($,{tone:f.tone,children:f.text}),y.showError&&(0,Q.jsx)($,{tone:`err`,children:n(`grok.loadFail`)}),S&&S.candidates.length>0&&(0,Q.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,Q.jsx)(`span`,{className:`claude-dirty${T?` active`:``}`,children:n(T?`grok.unsaved`:`grok.upToDate`)}),(0,Q.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!T||u!==null,onClick:()=>void A(!1),children:n(u===`save`?`grok.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!T||u!==null,onClick:()=>void A(!0),children:n(u===`apply`?`grok.applying`:u===`save`?`grok.saving`:`grok.saveApply`)})]})]}),S?.present?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,Q.jsx)(`span`,{children:n(`grok.endpoint`)}),(0,Q.jsx)(`code`,{children:S.baseUrl??`—`})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:(0,Q.jsx)(`code`,{children:S.configPath})})]}):(0,Q.jsxs)(Un,{title:n(`grok.notConfiguredTitle`),children:[n(`grok.notConfiguredHint`),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`code`,{children:S?.configPath})]}),S&&S.candidates.length>0&&(0,Q.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,Q.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!0),disabled:u!==null,children:[(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`}),` `,n(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!1),disabled:u!==null,children:[(0,Q.jsx)(lt,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,n(`models.expandAll`)]})]}),JG.map(e=>{let t=KG(S.candidates,E,w,e.id);if(t.total===0)return null;let r=c.has(e.id);return(0,Q.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,Q.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,Q.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>D(e.id),children:[(0,Q.jsx)(lt,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,Q.jsx)(`span`,{className:`ocx-group-name`,children:n(e.tkey)}),(0,Q.jsx)(`span`,{className:`ocx-group-count`,children:n(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!r&&(0,Q.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,Q.jsxs)(`div`,{className:`grok-model-row`,children:[(0,Q.jsx)(Rn,{on:e.enabled,onClick:()=>k(e.id,!e.enabled),disabled:u!==null,label:n(`grok.toggleModel`,{id:e.id})}),(0,Q.jsxs)(`span`,{className:`grok-model-names`,children:[(0,Q.jsx)(`strong`,{title:e.id,children:e.id}),(0,Q.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,Q.jsx)(`span`,{className:`claude-model-context`,children:XG(e.contextWindow,n)})]},e.id))})]},e.id)})]})]})}async function QG(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor`,{signal:t});if(!n.ok)return null;let r=await Xn(n);return!r||typeof r!=`object`||!r.gateway||!r.privateInference?null:r}catch{return null}}async function $G(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor/local-installer`,{signal:t});if(!n.ok)return null;let r=await Xn(n);return!r||typeof r!=`object`||typeof r.available!=`boolean`?null:r}catch{return null}}function eK({value:e,label:t}){let n=b(),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);let o=async()=>{try{await navigator.clipboard.writeText(e),i(!0),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>i(!1),1500)}catch{i(!1)}};return(0,Q.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Q.jsx)(`span`,{className:`cursor-gateway-label`,children:t}),(0,Q.jsx)(`code`,{className:`cursor-gateway-value`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void o(),"aria-label":`${n(`integrations.cursor.copy`)} ${t}`,children:n(r?`integrations.cursor.copied`:`integrations.cursor.copy`)})]})}function tK({labelKey:e,installed:t,path:n,version:r}){let i=b();return(0,Q.jsxs)(`div`,{className:`cursor-detect-row`,"data-installed":t?`true`:`false`,children:[(0,Q.jsx)(`span`,{className:`cursor-detect-name`,children:i(e)}),(0,Q.jsx)(`span`,{className:`badge ${t?`badge-green`:`badge-muted`}`,children:i(t?`integrations.cursor.detected`:`integrations.cursor.notFound`)}),t&&n&&(0,Q.jsxs)(`span`,{className:`cursor-detect-path muted`,children:[r?`${r} · `:``,n]})]})}function nK({apiBase:e}){let t=b(),[n,r]=(0,Z.useState)(`idle`),[i,a]=(0,Z.useState)(null),o=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>o.current?.abort(),[]);let s=async()=>{o.current?.abort();let t=new AbortController;o.current=t,r(`checking`);let n=await $G(e,t.signal);t.signal.aborted||(a(n),r(`done`))};return n===`done`&&i?.available&&i.url!==null?(0,Q.jsxs)(`span`,{"data-cursor-installer-hint":!0,children:[t(`integrations.cursor.installerIntro`,{version:i.version??t(`integrations.cursor.unknownVersion`)}),` `,(0,Q.jsx)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,"data-cursor-installer-url":!0,children:t(`integrations.cursor.installerOpen`)}),`.`]}):(0,Q.jsxs)(Q.Fragment,{children:[n===`done`&&(0,Q.jsxs)(`span`,{"data-cursor-installer-unavailable":!0,children:[t(`integrations.cursor.installerUnavailable`),` `]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void s(),disabled:n===`checking`,"data-cursor-installer-check":!0,children:t(n===`checking`?`integrations.cursor.installerChecking`:`integrations.cursor.installerCheck`)})]})}function rK({apiBase:e,active:t}){let{t:n,locale:r}=s(),[i,a]=(0,Z.useState)(()=>Date.now()),o=(0,Z.useCallback)(async t=>{let n=await QG(e,t);if(!n)throw Error(`cursor status unavailable`);return a(Date.now()),n},[e]),c=mf(`integration-cursor-page:${e}`,[e],o,{isEmpty:()=>!1,enabled:t,pollMs:15e3,pauseWhenHidden:!0}),l=c.state.data??null,u=Jm(n);return(0,Q.jsxs)(`section`,{className:`integration-native-page cursor-page`,"aria-labelledby":`cursor-integration-title`,children:[(0,Q.jsx)(`h3`,{id:`cursor-integration-title`,children:n(`integrations.cursor.title`)}),(0,Q.jsx)(`p`,{children:n(`integrations.cursor.intro`)}),c.state.showError&&(0,Q.jsx)($,{tone:`err`,children:n(`integrations.cursor.unavailable`)}),!l&&!c.state.showError&&(0,Q.jsx)(ck,{label:n(`integrations.cursor.loading`),rows:4}),l&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.detection`)}),(0,Q.jsx)(tK,{labelKey:`integrations.cursor.privateInference`,installed:l.privateInference.installed,path:l.privateInference.path,version:l.privateInference.version}),(0,Q.jsx)(tK,{labelKey:`integrations.cursor.regular`,installed:l.regularCursor.installed,path:l.regularCursor.path,version:null}),!l.privateInference.installed&&(0,Q.jsxs)($,{tone:`warn`,children:[n(l.regularCursor.installed?`integrations.cursor.regularOnly`:`integrations.cursor.nothingFound`),` `,(0,Q.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,"data-cursor-guide":`notice`,children:n(`integrations.cursor.guide`)}),l.regularCursor.installed&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`span`,{"data-cursor-installer":!0,children:(0,Q.jsx)(nK,{apiBase:e})})]})]})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.gateway`)}),(0,Q.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.gatewayHint`)}),(0,Q.jsx)(eK,{label:n(`integrations.cursor.baseUrl`),value:l.gateway.baseUrl}),l.gateway.apiKeyMode===`placeholder`?(0,Q.jsx)(eK,{label:n(`integrations.cursor.apiKey`),value:l.gateway.placeholder}):(0,Q.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Q.jsx)(`span`,{className:`cursor-gateway-label`,children:n(`integrations.cursor.apiKey`)}),(0,Q.jsx)(`span`,{className:`cursor-gateway-value`,children:n(`integrations.cursor.apiKeyCredential`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>En(`integrations/keys`),children:n(`integrations.tab.keys`)})]})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,"data-seen":l.lastSeen?`true`:`false`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.connection`)}),l.lastSeen?(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`span`,{className:`badge ${i-l.lastSeen.at<864e5?`badge-green`:`badge-muted`}`,children:n(`integrations.cursor.seen`,{time:qm(l.lastSeen.at,u,i),ua:l.lastSeen.userAgent})})}):(0,Q.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.neverSeen`)})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.models`)}),(0,Q.jsx)(`p`,{className:`muted`,children:l.effortTable.source===`bundle`?n(`integrations.cursor.ladderFromBundle`,{version:l.effortTable.version??n(`integrations.cursor.unknownVersion`)}):n(`integrations.cursor.ladderFromStatic`)}),(0,Q.jsxs)(`table`,{className:`cursor-model-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`integrations.cursor.colModel`)}),(0,Q.jsx)(`th`,{children:n(`integrations.cursor.colReasoning`)}),(0,Q.jsx)(`th`,{children:n(`integrations.cursor.colContext`)})]})}),(0,Q.jsx)(`tbody`,{children:l.models.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.id})}),(0,Q.jsx)(`td`,{children:e.reasoning?e.reasoning.join(` · `):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`cursor-no-control`,title:n(`integrations.cursor.noControlTitle`),"aria-label":n(`integrations.cursor.noControlTitle`),children:n(`integrations.cursor.noControl`)}),e.effortRows.length>0?(0,Q.jsx)(`span`,{className:`cursor-effort-rows`,children:n(e.effortRows.length===1?`integrations.cursor.effortRowsOne`:`integrations.cursor.effortRowsMany`,{n:e.effortRows.length})}):(0,Q.jsx)(`span`,{className:`cursor-effort-rows muted`,children:n(`integrations.cursor.effortRowsOff`)})]})}),(0,Q.jsx)(`td`,{children:e.context?`${$e(e.context.defaultWindow,r)} · ${$e(e.context.longWindow,r)}`:n(`integrations.cursor.singleWindow`)})]},e.id))})]}),l.models.some(e=>e.tableLess)&&(0,Q.jsx)(`p`,{className:`muted`,"data-cursor-tableless-hint":!0,children:n(`integrations.cursor.tableLessHint`)})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,children:n(`integrations.cursor.guide`)})})]})]})}function iK(e){let t=b(),[n,r]=(0,Z.useState)(!1),i=(0,Z.useId)();return{open:n,button:(0,Q.jsx)(`button`,{type:`button`,className:X(Nm,n&&`bg-surface-2 text-fg`),"aria-expanded":n,"aria-controls":i,"aria-label":t(`connectV2.moreAbout`,{label:e}),onClick:()=>r(e=>!e),children:(0,Q.jsx)(Pc,{icon:Bc,strokeWidth:1.8,"aria-hidden":`true`})}),panel:(e,t)=>(0,Q.jsx)(`div`,{id:i,hidden:!n,className:X(`ui-v2 rounded-[8px] bg-surface px-3.5 py-3 text-[13px] leading-5 text-fg-muted [&_p]:m-0 [&_p+p]:mt-2`,t),children:e})}}var aK={"not-installed":`integrations.state.notInstalled`,unknown:`integrations.state.unknown`,absent:`integrations.state.absent`,current:`integrations.state.current`,stale:`integrations.state.stale`,conflict:`integrations.state.conflict`,unsafe:`integrations.state.unsafe`},oK={"not-installed":`badge badge-muted`,unknown:`badge badge-muted`,absent:`badge badge-muted`,current:`badge badge-green`,stale:`badge badge-amber`,conflict:`badge integration-badge--danger`,unsafe:`badge integration-badge--danger-outline`};function sK({state:e,installed:t,id:n}){let r=b(),i=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,Q.jsx)(`span`,{id:n,className:oK[i],"data-integration-state":i,children:r(aK[i])})}var cK={apply:`integrations.plan.operation.apply`,overwrite:`integrations.plan.operation.overwrite`,disable:`integrations.plan.operation.disable`,restore:`integrations.plan.operation.restore`},lK={add:`integrations.plan.change.add`,replace:`integrations.plan.change.replace`,remove:`integrations.plan.change.remove`,snapshot:`integrations.plan.change.snapshot`,ownership:`integrations.plan.change.ownership`,journal:`integrations.plan.change.journal`},uK={none:`integrations.plan.foreign.none`,unowned:`integrations.plan.foreign.unowned`,"foreign-edit":`integrations.plan.foreign.foreignEdit`,drift:`integrations.plan.foreign.drift`},dK={not_installed:`integrations.plan.refusal.notInstalled`,conflict:`integrations.plan.refusal.conflict`,unsafe:`integrations.plan.refusal.unsafe`,non_loopback:`integrations.plan.refusal.nonLoopback`,superseded_store:`integrations.plan.refusal.supersededStore`,drift_requires_confirm:`integrations.plan.refusal.driftRequiresConfirm`,snapshot_expired:`integrations.plan.refusal.snapshotExpired`,write_failed:`integrations.plan.refusal.writeFailed`};function fK({plan:e,missingStorePath:t}){let n=b(),r=e.refusalReason?dK[e.refusalReason]:void 0,i=e.supersededReason===`missing-store`?e.missingStoreDocument:void 0,a=i===void 0?n(r??`integrations.plan.refused`):t===void 0?n(`integrations.plan.refusal.missingStore`,{document:i}):n(`integrations.status.missingStore`,{path:t,document:i});return(0,Q.jsxs)(`div`,{className:`integration-plan-details`,children:[(0,Q.jsx)(`p`,{className:`integration-plan-operation`,children:n(`integrations.plan.operation`,{operation:n(cK[e.operation])})}),e.foreignEdit!==`none`&&(0,Q.jsx)(`p`,{children:n(uK[e.foreignEdit])}),!e.willChange&&e.canApply&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:n(e.operation===`disable`?`integrations.plan.noop.disabled`:`integrations.plan.noop.applied`)}),e.profileId!==void 0&&(0,Q.jsx)(`p`,{children:n(`integrations.plan.noop.profilePreference`)})]}),!e.canApply&&(0,Q.jsx)(`p`,{children:a}),e.changes.length>0&&(0,Q.jsx)(`ul`,{className:`integration-plan-changes`,children:e.changes.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:n(lK[e.kind])}),` `,(0,Q.jsx)(`code`,{children:e.path})]},`${e.kind}:${e.path}`))})]})}function pK({plan:e,plans:t,missingStorePath:n}){let r=b();return!e&&(!t||t.length===0)?null:(0,Q.jsxs)(`section`,{className:`integration-plan`,"aria-labelledby":`integration-plan-heading`,children:[(0,Q.jsx)(`h4`,{id:`integration-plan-heading`,children:r(`integrations.plan.heading`)}),e&&(0,Q.jsx)(fK,{plan:e,missingStorePath:n}),t?.map(e=>(0,Q.jsxs)(`section`,{className:`integration-plan-group`,children:[(0,Q.jsx)(`h5`,{children:e.label}),(0,Q.jsx)(fK,{plan:e.plan})]},`${e.clientId}:${e.plan.fingerprint}`))]})}function mK({copyKey:e,vars:t}){let n=b()(e,t),r=t?.path;if(!r||!n.includes(r))return(0,Q.jsx)(`p`,{children:n});let[i,...a]=n.split(r);return(0,Q.jsxs)(`p`,{children:[i,(0,Q.jsx)(`code`,{children:r}),a.join(r)]})}function hK(e){return e.changes.some(e=>e.kind===`snapshot`||e.kind===`journal`)}function gK({copy:e,plan:t=null,plans:n,hasUnboundAction:r=!1,planStale:i=!1,planLoading:a=!1,planFailure:o=null,previewRecovery:s=null,onPreviewRecovery:c,missingStorePath:l,onConfirm:u,onClose:d}){let f=b(),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(null),T=`integration-consequence-dialog-title`,E=t!==null||a||o!==null||n!==void 0,D=C?.sourceFingerprint===(t?.fingerprint??null)?C.plan:t,O=C?.sourceFingerprint===(t?.fingerprint??null),k=n!==void 0&&!r&&!n.some(e=>e.plan.canApply),A=!E||(D?hK(D):n?.some(e=>hK(e.plan))===!0),j=(0,Z.useCallback)(()=>{g||d()},[d,g]);(0,Z.useEffect)(()=>{let e=p.current,t=document.activeElement;return m.current=t?.tagName===`BUTTON`?t:null,e&&!e.open&&e.showModal(),h.current?.focus(),()=>{e?.open&&e.close(),m.current?.isConnected&&m.current.focus?.()}},[]);let M=(0,Z.useCallback)(e=>{e.preventDefault(),j()},[j]),N=(0,Z.useCallback)(async()=>{if(!g){_(!0),y(null);try{await u(D??void 0)}catch(e){if(e instanceof pO&&e.stalePlan){w({sourceFingerprint:t?.fingerprint??null,plan:e.stalePlan});return}y(e instanceof Error?e.message:f(`integrations.error.generic`))}finally{_(!1)}}},[D,u,g,t?.fingerprint,f]),P=(0,Z.useCallback)(async()=>{if(c&&!x){S(!0);try{await c()}finally{S(!1)}}},[c,x]),F=[(0,Q.jsx)(mK,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,Q.jsx)(mK,{copyKey:e.breakageKey,vars:e.vars},`breakage`)];return A&&F.push((0,Q.jsx)(mK,{copyKey:e.undoKey,vars:e.vars},`undo`)),e.sideEffectKey&&F.push((0,Q.jsx)(mK,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,Q.jsxs)(`dialog`,{ref:p,className:`modal-overlay`,"aria-labelledby":T,"aria-busy":g,onCancel:M,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":f(`common.close`),tabIndex:-1,onClick:j}),(0,Q.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:T,children:f(e.titleKey,e.vars)}),(0,Q.jsx)(`button`,{ref:h,type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:g,children:f(`common.close`)})]}),(0,Q.jsx)(`div`,{className:`integration-consequence-body`,children:F}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[a&&(0,Q.jsx)(`p`,{children:f(`integrations.preview.loading`)}),g&&(0,Q.jsx)(`p`,{children:f(`integrations.mutation.pending`)}),(O||i)&&(0,Q.jsx)($,{tone:`err`,children:f(`integrations.preview.stale`)}),s===`catalog-unavailable`&&(0,Q.jsx)($,{tone:`err`,children:f(`integrations.preview.catalogUnavailable`)}),o&&(0,Q.jsx)($,{tone:`err`,children:o})]}),(0,Q.jsx)(pK,{plan:D,plans:n,missingStorePath:l}),v&&(0,Q.jsx)($,{tone:`err`,children:v}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[s!==null&&c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void P(),disabled:g||x||a,children:f(x?`integrations.preview.recovering`:`integrations.preview.loadCatalogRetry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void N(),disabled:g||a||s!==null||!!o||E&&!D&&n===void 0||k||D?.canApply===!1,children:f(e.confirmKey)})]})]})]})}function _K({apiBase:e,row:t,onClose:n,onRestored:r,profileId:i,onReconcile:a,hermesProfile:o}){let s=b(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(!1),f=(0,Z.useRef)(n),p=(0,Z.useRef)(r),m=(0,Z.useRef)(a),h=(0,Z.useRef)(s),g=(0,Z.useRef)(null),_=(0,Z.useRef)(0),[v,y]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!0),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),j=t.clientId===`aside`?i??t.profileId:void 0,M=t.clientId===`hermes`?o:void 0,N=v?.plan??null,P=N?.foreignEdit===`drift`;(0,Z.useEffect)(()=>{f.current=n,p.current=r,m.current=a,h.current=s},[n,a,r,s]);let F=(0,Z.useCallback)(()=>{T||(_.current+=1,g.current?.abort(),g.current=null,f.current())},[T]);(0,Z.useEffect)(()=>{let e=c.current,t=document.activeElement;return l.current=t?.tagName===`BUTTON`?t:null,u.current=t?.closest?.(`section, [role='region'], main`)??null,e&&!e.open&&e.showModal(),()=>{e?.open&&e.close();let t=u.current;if(d.current&&t?.isConnected){t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.();return}let n=l.current;n?.isConnected?n.focus?.():t?.isConnected&&(t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.())}},[]);let I=(0,Z.useCallback)(async()=>{let n=new AbortController,r=_.current+1;_.current=r,g.current?.abort(),g.current=n,S(!0),O(null),A(null),y(null),w(!1);try{let i=!1,a=await OO(e,t.opId,i,n.signal,j,M);if(a.refusalReason===`drift_requires_confirm`&&(i=!0,a=await OO(e,t.opId,i,n.signal,j,M)),n.signal.aborted||r!==_.current)return;y({plan:a,confirmDrift:i})}catch(e){if(n.signal.aborted||r!==_.current)return;if(_O(e)){m.current?.(),f.current();return}O(h.current(`integrations.preview.failed`))}finally{!n.signal.aborted&&r===_.current&&(g.current=null,S(!1))}},[e,t.opId,j,M]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{I()},0);return()=>{window.clearTimeout(e),_.current+=1,g.current?.abort(),g.current=null}},[I]);let L=(0,Z.useCallback)(e=>{e.preventDefault(),F()},[F]),R=async()=>{if(T||x||!v||!v.plan.canApply)return;let n=v.confirmDrift;E(!0),A(null);try{await AO(e,{opId:t.opId,confirmDrift:n,profileId:j,hermesProfile:M,binding:vO(v.plan)}),d.current=!0,p.current(),f.current()}catch(r){if(t.clientId===`aside`&&m.current?.(),r instanceof pO&&r.stalePlan){let i=r.stalePlan,a=n;E(!1);try{if(i.refusalReason===`drift_requires_confirm`){let n=new AbortController,r=_.current+1;_.current=r,g.current?.abort(),g.current=n,S(!0),a=!0;try{i=await OO(e,t.opId,a,n.signal,j,M)}finally{!n.signal.aborted&&r===_.current&&(g.current=null,S(!1))}if(n.signal.aborted||r!==_.current)return}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;if(_O(e)){m.current?.(),f.current();return}O(h.current(`integrations.preview.failed`));return}y({plan:i,confirmDrift:a}),w(!0);return}A(tk(s,r)),E(!1)}};return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`integration-restore-title`,"aria-busy":T,onCancel:L,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:F}),(0,Q.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,role:`document`,children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h3`,{id:`integration-restore-title`,children:s(P?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:s(P?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[x&&(0,Q.jsx)(`p`,{children:s(`integrations.preview.loading`)}),T&&(0,Q.jsx)(`p`,{children:s(`integrations.mutation.pending`)}),C&&(0,Q.jsx)($,{tone:`err`,children:s(`integrations.preview.stale`)})]}),(0,Q.jsx)(pK,{plan:N}),D&&(0,Q.jsx)($,{tone:`err`,children:D}),k&&(0,Q.jsx)($,{tone:`err`,children:k}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:F,disabled:T,children:s(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void R(),disabled:T||x||!N?.canApply||!!D,children:s(T?`integrations.restore.pending`:P?`integrations.restore.confirmDrift`:`integrations.restore.confirm`)})]})]})]})}var vK={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,"gentle-shell":`integrations.tab.gentleShell`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,commandcode:`integrations.tab.commandcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`,kilo:`integrations.tab.kilo`,droid:`integrations.tab.droid`,qoder:`integrations.tab.qoder`,"qoder-cn":`integrations.tab.qoderCn`,workbuddy:`integrations.tab.workbuddy`,"workbuddy-ai":`integrations.tab.workbuddyAi`,t3code:`integrations.tab.t3code`},yK={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`,overwrite:`integrations.kind.overwrite`};function bK(e){return e===`current`||e===`stale`}function xK(e,t,n){let r={id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`,toggle:`codex`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null};if(n===void 0)return e?e.routingInjected===!0?{...r,state:e.status===`error`?`stale`:`current`,installed:!0,applied:!0,detailKey:`integrations.detail.codexRouted`}:{...r,state:`absent`,installed:!0,applied:!1,detail:e.recommendedCommand??null,detailKey:e.recommendedCommand?null:`integrations.detail.codexAbsent`}:{...r,state:`unknown`,installed:!1,applied:!1,detailKey:null};if(!n)return{...r,state:`unknown`,installed:!1,applied:!1,detailKey:null};if(!t)return{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:null};let i=t.desiredEnabled;return e?e.routingInjected===!0?{...r,state:e.status===`error`?`stale`:`current`,installed:t.installed,applied:!0,toggleOn:i,detailKey:`integrations.detail.codexRouted`}:{...r,state:`absent`,installed:t.installed,applied:!1,toggleOn:i,detail:e.recommendedCommand??null,detailKey:e.recommendedCommand?null:`integrations.detail.codexAbsent`}:{...r,state:`unknown`,installed:t.installed,applied:!1,toggleOn:i,detailKey:null}}function SK(e,t){let n={hash:`integrations/keys`,labelKey:`integrations.tab.keys`};return e===`checking`?{...n,state:`checking`,detailKey:`integrations.detail.keyChecking`,detailVars:null}:e===`unavailable`||t===null?{...n,state:`unavailable`,detailKey:`integrations.detail.keyUnavailable`,detailVars:null}:{...n,state:t>0?`issued`:`none-issued`,detailKey:t>0?`integrations.detail.keyCount`:`integrations.detail.keyNone`,detailVars:t>0?{count:String(t)}:null}}function CK(e){return e?e.enabled===!0?e.authMode===`subscription`?`claude.authModeSubscription`:e.authMode===`proxy`?`claude.authModeProxy`:e.authMode===`auto`?`claude.authModeAuto`:null:`integrations.detail.claudeOff`:null}function wK(e,t,n){let r={id:`claude`,hash:`claude/code`,labelKey:`integrations.tab.claude`,toggle:`claude`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null},i=CK(e);if(n===void 0){if(!e)return{...r,state:`unknown`,installed:!1,applied:!1,detailKey:i};let t=e.enabled===!0;return{...r,state:t?`current`:`absent`,installed:!0,applied:t,detailKey:i}}return n?t?{...r,state:t.state,installed:t.installed,applied:t.state===`current`,detailKey:i}:{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:i}:{...r,state:`unknown`,installed:!1,applied:!1,detailKey:i}}function TK(e,t,n){let r={id:`claudeDesktop`,hash:`claude/desktop`,labelKey:`claudeDesktop.title`,toggle:`claude-desktop`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null};if(!e||!n||!t||typeof e.desiredEnabled!=`boolean`)return{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:null};let i=e.desiredEnabled;if(!i)return e.applied===!0||e.driftReason===`desired_off_gateway_selected`?{...r,state:`stale`,installed:e.installed===!0,applied:!0,toggleOn:!1,detailKey:`integrations.detail.desktopDesiredOffCleanupPending`}:{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:!1,detailKey:`integrations.detail.desktopDesiredOff`};if(e.applied!==!0)return{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:i,detailKey:`integrations.detail.desktopDesiredOnNotApplied`};let a=e.stale===!0||e.activeProfile===!1;return{...r,state:a?`stale`:`current`,installed:!0,applied:!0,toggleOn:i,detailKey:e.activeProfile===!1?`integrations.detail.desktopNotServed`:a?`integrations.detail.desktopStale`:`integrations.detail.desktopCurrent`}}function EK(e){if(!e)return{detailKey:null,detailVars:null};let t=e.present===!0;return{detailKey:t?`integrations.detail.grokModels`:`integrations.detail.grokAbsent`,detailVars:t?{count:String(e.models?.length??0)}:null}}function DK(e,t,n){let r={id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`,toggle:`grok`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null},i=EK(e);if(n===void 0){if(!e)return{...r,state:`unknown`,installed:!1,applied:!1,...i};let t=e.present===!0;return{...r,state:t?`current`:`absent`,installed:t,applied:t,...i}}return n?t?{...r,state:t.state,installed:t.installed,applied:t.state===`current`,...i}:{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,...i}:{...r,state:`unknown`,installed:!1,applied:!1,...i}}function OK(e,t=Date.now()){let n={id:`cursor`,hash:`integrations/cursor`,labelKey:`integrations.tab.cursor`,toggle:null,toggleBlocked:null,togglePath:null,status:null,detail:null,detailVars:null};if(!e)return{...n,state:`unknown`,installed:!1,applied:!1,detailKey:null};if(!e.privateInference.installed)return{...n,state:`not-installed`,installed:!1,applied:!1,detailKey:`integrations.detail.cursorAbsent`};let r=e.lastSeen!==null&&t-e.lastSeen.at<864e5;return{...n,state:r?`current`:`absent`,installed:!0,applied:r,detailKey:r?`integrations.detail.cursorSeen`:`integrations.detail.cursorNeverSeen`}}function kK(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:vK[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&(bK(e.state)||qD(e)),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function AK(e){let t=e.native?.find(e=>e.clientId===`codex`),n=e.native?.find(e=>e.clientId===`claude`),r=e.native?.find(e=>e.clientId===`grok`),i=new Map(e.clients.map(e=>[e.clientId,e])),a=[xK(e.codex,t,e.nativeSettled),wK(e.claude,n,e.nativeSettled),TK(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),DK(e.grok,r,e.nativeSettled),OK(e.cursor)];for(let t of KD){let n=i.get(t);n?a.push(kK(n)):e.clientsSettled||a.push({id:t,hash:`integrations/${t}`,labelKey:vK[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:SK(e.keyPhase,e.keyCount),rows:a}}function jK(e){return{detected:e.filter(e=>e.installed).length,applied:e.filter(e=>e.applied).length,stale:e.filter(e=>e.state===`stale`).length,unknown:e.filter(e=>e.state===`unknown`).length}}var MK=6;function NK({row:e,showClient:t,onRestore:n,onDelete:r}){let i=b();return(0,Q.jsxs)(`li`,{className:`integration-history-row`,children:[(0,Q.jsx)(`span`,{className:`integration-history-kind`,children:i(yK[e.kind])}),t&&(0,Q.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,Q.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:i(`integrations.action.snapshotExpired`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e),children:e.undoable?i(`integrations.action.undo`):i(`integrations.action.restorePoint`)}),e.deletable&&r&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e),"aria-label":i(`integrations.rollback.deleteAria`,{at:new Date(e.at).toLocaleString()}),children:i(`integrations.rollback.delete`)})]})}function PK({rows:e,showClient:t,onRestore:n,onDelete:r}){let i=b(),[a,o]=(0,Z.useState)(MK),[s,...c]=e;if(!s)return null;let l=c.slice(0,a),u=c.length-l.length;return(0,Q.jsxs)(`div`,{className:`integration-history`,children:[(0,Q.jsx)(`ul`,{className:`integration-history-list`,children:(0,Q.jsx)(NK,{row:s,showClient:t,onRestore:n,onDelete:r})}),c.length>0&&(0,Q.jsxs)(`details`,{className:`integration-history-older`,children:[(0,Q.jsx)(`summary`,{children:i(`integrations.rollback.older`)}),(0,Q.jsx)(`ul`,{className:`integration-history-list`,children:l.map(e=>(0,Q.jsx)(NK,{row:e,showClient:t,onRestore:n,onDelete:r},e.opId))}),u>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm integration-history-more`,onClick:()=>o(e=>e+MK),children:i(`integrations.rollback.showMore`,{n:String(Math.min(u,MK))})})]})]})}function FK(e){return _O(e)?`catalog-unavailable`:null}var IK={titleKey:`integrations.dialog.grok.title`,changesKey:`integrations.dialog.grok.changes`,breakageKey:`integrations.dialog.grok.breakage`,undoKey:`integrations.dialog.grok.undo`,confirmKey:`integrations.dialog.grok.confirm`},LK={titleKey:`integrations.dialog.codex.title`,changesKey:`integrations.dialog.codex.changes`,breakageKey:`integrations.dialog.codex.breakage`,undoKey:`integrations.dialog.codex.undo`,sideEffectKey:`integrations.dialog.codex.sideEffect`,confirmKey:`integrations.dialog.codex.confirm`},RK={titleKey:`integrations.dialog.desktop.title`,changesKey:`integrations.dialog.desktop.changes`,breakageKey:`integrations.dialog.desktop.breakage`,undoKey:`integrations.dialog.desktop.undo`,sideEffectKey:`integrations.dialog.desktop.restart`,confirmKey:`integrations.dialog.desktop.confirm`},zK={titleKey:`integrations.dialog.apply.title`,changesKey:`integrations.dialog.apply.changes`,breakageKey:`integrations.dialog.apply.breakage`,undoKey:`integrations.dialog.apply.undo`,confirmKey:`integrations.dialog.apply.confirm`},BK={titleKey:`integrations.dialog.disable.title`,changesKey:`integrations.dialog.disable.changes`,breakageKey:`integrations.dialog.disable.breakage`,undoKey:`integrations.dialog.disable.undo`,confirmKey:`integrations.dialog.disable.confirm`},VK={titleKey:`integrations.bulk.title`,changesKey:`integrations.bulk.body`,breakageKey:`integrations.bulk.breakage`,undoKey:`integrations.bulk.undo`,confirmKey:`integrations.bulk.confirm`};function HK(e){return e.flatMap(e=>e.plan?[{clientId:e.clientId,label:e.label,plan:e.plan}]:[])}function UK(e){return e.state===`current`||e.state===`stale`||qD(e)}function WK({row:e,pending:t,result:n,onOpen:r,onToggle:i,onOverwrite:a,onChooseProfile:o}){let s=b(),c=e.detail??(e.detailKey?s(e.detailKey,e.detailVars??void 0):null),l=e.toggleBlocked!==null&&(e.applied||e.toggleBlocked.reason===`orphaned_marker`),u=l&&e.toggleBlocked&&(e.toggle===`claude`||e.toggle===`grok`||e.toggle===`codex`)?tk(s,new UO(409,{error:`native integration change refused`,code:`native_integration_refused`,clientId:e.toggle,reason:e.toggleBlocked.reason,message:e.toggleBlocked.message}),void 0,e.togglePath??void 0):null,d=e.toggleOn??e.applied,f=e.status!==null&&qD(e.status),p=!e.installed&&e.state!==`unknown`?`idle`:e.state===`current`?`on`:e.state===`stale`||e.state===`conflict`||e.state===`unsafe`?`attention`:e.state===`absent`?`off`:`idle`;return(0,Q.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,"data-tone":p,children:[(0,Q.jsxs)(`div`,{className:`integration-card-head`,children:[(0,Q.jsx)(HH,{src:VH(e.id),label:s(e.labelKey),size:20}),(0,Q.jsx)(`h4`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:r,children:s(e.labelKey)})}),(0,Q.jsx)(sK,{state:e.state,installed:e.installed})]}),c&&(0,Q.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:c}),e.status?.reason===`candidate-conflict`&&e.status.conflictPaths?.map(e=>(0,Q.jsx)($,{tone:`err`,children:s(`integrations.status.candidateConflict`,{path:e})},e)),n?.tone===`err`&&(0,Q.jsx)($,{tone:`err`,children:n.text}),n?.tone===`ok`&&(0,Q.jsx)($,{tone:`ok`,children:n.text}),(0,Q.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&i&&(0,Q.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,Q.jsx)(Rn,{on:d,onClick:i,disabled:e.state===`unknown`||!e.installed||(e.state===`conflict`||e.state===`unsafe`)&&!f||l||t,label:s(d?`integrations.action.disable`:`integrations.action.apply`)}),u&&(0,Q.jsx)(`p`,{className:`integration-toggle-blocked`,children:u})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,tabIndex:-1,children:s(`integrations.action.settings`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:a,disabled:t,children:s(`integrations.action.overwrite`)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:o,disabled:t,children:s(`integrations.action.chooseProfile`)})]})]})}function GK(e){return e.state!==`unknown`&&(e.state===`not-installed`||!e.installed)&&!(e.toggleOn??e.applied)}function KK({apiBase:e,active:t=!0}){let n=b(),r=iK(n(`integrations.catalog.title`)),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)({}),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),x=(0,Z.useRef)(null),S=(0,Z.useRef)(0),C=(0,Z.useRef)(null),w=(0,Z.useRef)(0),T=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(m!==null)return;let e=T.current;e&&(T.current=null,e.isConnected&&e.focus())},[m]),(0,Z.useEffect)(()=>()=>{S.current+=1,w.current+=1,x.current?.abort(),C.current?.abort()},[]);let E=(0,Z.useCallback)(async t=>(await wO(e,t)).clients,[e]),D=(0,Z.useCallback)(async t=>(await EO(e,void 0,t)).operations,[e]),O=(0,Z.useCallback)(t=>NO(e,t),[e]),k=(0,Z.useCallback)(t=>PO(e,t),[e]),A=(0,Z.useCallback)(t=>FO(e,t),[e]),j=(0,Z.useCallback)(t=>IO(e,t),[e]),M=(0,Z.useCallback)(t=>LO(e,t),[e]),N=(0,Z.useCallback)(t=>QG(e,t),[e]),P=(0,Z.useCallback)(async t=>(await qO(e,t))?.clients??null,[e]),F=mf(`integration-states:${e}`,[e],E,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.states.v1:${e}`}),I=mf(`integration-journal-all:${e}`,[e],D,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.journal.v1:${e}`}),L=mf(`integration-codex:${e}`,[e],O,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.codex.v1:${e}`}),R=mf(`integration-keys:${e}`,[e],k,{isEmpty:()=>!1,enabled:t,sessionCacheKey:`ocx.integrations.keys.v1:${e}`}),z=mf(`integration-claude:${e}`,[e],A,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude.v1:${e}`}),B=mf(`integration-claude-desktop:${e}`,[e],j,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude-desktop.v1:${e}`}),V=mf(`integration-grok:${e}`,[e],M,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.grok.v1:${e}`}),H=mf(`integration-cursor:${e}`,[e],N,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.cursor.v1:${e}`}),U=mf(`integration-native:${e}`,[e],P,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.native.v1:${e}`}),W=F.state.data??[],ee=I.state.data??[],G=W.filter(UK),te=W.filter(e=>e.installed),ne=F.state.data!==void 0,K=U.state.data??null,q=K!==null,J=R.state.kind===`cold`||R.state.kind===`retrying-cold`?`checking`:R.state.kind===`failed-cold`||R.state.kind===`failed-with-stale`?`unavailable`:`settled`,{keysRow:re,rows:Y}=AK({clients:W,clientsSettled:ne,codex:L.state.data??null,keyCount:R.state.data??null,keyPhase:J,claude:z.state.data??null,claudeDesktop:B.state.data??null,grok:V.state.data??null,cursor:H.state.data??null,native:K,nativeSettled:q}),ie=jK(Y),ae=()=>{F.refresh(),I.refresh(),L.refresh(),R.refresh(),z.refresh(),B.refresh(),V.refresh(),U.refresh()},oe=async(t=!1)=>{if(i||v&&!t||G.length===0)return;let r=new AbortController,a=w.current+1;w.current=a,C.current?.abort(),C.current=r,y({actions:[],loading:!0,failure:null,recovery:null,stale:!1,failures:[]});try{let t=await Promise.all(G.map(async t=>{let i=Y.find(e=>e.status?.clientId===t.clientId);if(t.clientId===`aside`)return{clientId:t.clientId,label:i?n(i.labelKey):t.clientId,plan:null};let a=await DO(e,t.clientId,`disable`,r.signal);return{clientId:t.clientId,label:i?n(i.labelKey):t.clientId,plan:a}}));if(r.signal.aborted||a!==w.current)return;C.current=null,y({actions:t,loading:!1,failure:null,recovery:null,stale:!1,failures:[]})}catch(e){if(r.signal.aborted||a!==w.current)return;C.current=null;let t=FK(e);y({actions:[],loading:!1,recovery:t,stale:!1,failures:[],failure:t===null?n(`integrations.preview.failed`):null})}},se=async()=>{let t=w.current;try{await wO(e)}catch{}t===w.current&&(ae(),await oe(!0))},ce=()=>{w.current+=1,C.current?.abort(),C.current=null,y(null)},le=async t=>{if(i||t.actions.length===0)return;a(!0),s(null);let r=[...t.failures],o=[];for(let i of t.actions)if(i.plan&&!i.plan.canApply)r.push(`${i.clientId}: ${n(`integrations.plan.refused`)}`);else try{await kO(e,i.clientId,{enabled:!1,...i.plan?{binding:vO(i.plan)}:{}})}catch(e){if(i.plan&&e instanceof pO&&e.stalePlan){o.push({...i,plan:e.stalePlan});continue}r.push(`${i.clientId}: ${tk(n,e)}`)}if(o.length>0){ae(),a(!1),y({actions:o,loading:!1,failure:null,recovery:null,stale:!0,failures:r}),s(r.length===0?null:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:r.join(`; `)})});return}let c=!1;try{c=(await wO(e)).clients.some(UK)}catch{r.push(n(`integrations.error.stale`))}c&&r.length===0&&r.push(n(`integrations.error.stale`)),ae(),a(!1),y(null),s(r.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:r.join(`; `)})})},ue=ee[0]?.at,[de,fe]=(0,Z.useState)(null),pe=()=>{U.refresh(),L.refresh(),z.refresh(),V.refresh()},me=(e,t)=>{p(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},he=async(t,r,i)=>{if(!de&&t.toggle){fe(t.id),me(t.id,null);try{if(t.status){if(!i&&t.status.clientId!==`aside`)return;await kO(e,t.status.clientId,{enabled:r,...i?{overwriteConflict:i.operation===`overwrite`,binding:vO(i)}:{}}),ae()}else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await JO(e,t.toggle,r);i.reason===`non_loopback_removed`?me(t.id,{tone:`ok`,text:n(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&me(t.id,{tone:`ok`,text:n(`integrations.native.msg.nonLoopbackSuperseded`)}),pe()}}catch(e){if(t.status&&e instanceof pO&&e.stalePlan)throw e;if(me(t.id,{tone:`err`,text:tk(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&pe(),t.status)throw Error(tk(n,e,void 0,t.togglePath??void 0),{cause:e})}finally{fe(null)}}},ge=async(t,r,i=!1)=>{if(!t.status||g&&!i)return;let a=new AbortController,o=S.current+1;S.current=o,x.current?.abort(),x.current=a,_({row:t,operation:r,plan:null,loading:!0,failure:null,recovery:null});try{let n=await DO(e,t.status.clientId,r,a.signal);if(a.signal.aborted||o!==S.current)return;x.current=null,_({row:t,operation:r,plan:n,loading:!1,failure:null,recovery:null})}catch(e){if(a.signal.aborted||o!==S.current)return;x.current=null;let i=FK(e);_({row:t,operation:r,plan:null,loading:!1,recovery:i,failure:i===null?n(`integrations.preview.failed`):null})}},_e=async()=>{let t=g;if(!t)return;let n=S.current;try{await wO(e)}catch{}n===S.current&&(ae(),await ge(t.row,t.operation,!0))},ve=()=>{S.current+=1,x.current?.abort(),x.current=null,_(null)},ye=(e,t)=>{if(e.status&&e.status.clientId!==`aside`){ge(e,t?`apply`:`disable`);return}if(e.status?.clientId===`aside`){he(e,t).catch(()=>{});return}if(t||e.id===`claude`||e.toggle===null){he(e,t);return}let n=document.activeElement;T.current=n?.tagName===`BUTTON`?n:null,h(e)},be=Y.filter(e=>!GK(e)),xe=Y.filter(GK),Se=e=>(0,Q.jsx)(WK,{row:e,pending:de!==null,result:f[e.id]??null,onOpen:()=>En(e.hash),onToggle:e.toggle?()=>ye(e,!(e.toggleOn??e.applied)):null,onOverwrite:e.status!==null&&e.status.clientId!==`aside`&&e.status.state===`conflict`&&e.status.reason!==`candidate-conflict`&&e.installed?()=>void ge(e,`overwrite`):null,onChooseProfile:e.status?.clientId===`aside`&&e.status.state===`conflict`&&e.status.reason!==`candidate-conflict`&&e.installed?()=>En(e.hash):null},e.id);return(0,Q.jsxs)(`section`,{className:`integrations-overview`,children:[(0,Q.jsxs)(`div`,{className:`integration-summary`,children:[(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,Q.jsx)(`strong`,{children:ie.detected})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,"data-tone":ie.applied>0?`ok`:void 0,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,Q.jsx)(`strong`,{children:ie.applied})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,"data-tone":ie.stale>0?`warn`:void 0,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,Q.jsx)(`strong`,{children:ie.stale})]}),ie.unknown>0&&(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,Q.jsx)(`strong`,{children:ie.unknown})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,Q.jsx)(`strong`,{className:`integration-summary-when`,children:ue?new Date(ue).toLocaleString():n(`integrations.status.unknown`)})]})]}),(0,Q.jsxs)(`div`,{className:`connect-catalog-head`,children:[(0,Q.jsx)(`h3`,{children:n(`integrations.catalog.title`)}),r.button,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm connect-disable-all`,onClick:()=>void oe(),disabled:i||!!v||G.length===0,children:n(`integrations.summary.disableAll`)})]}),r.panel((0,Q.jsx)(`p`,{children:n(`integrations.onboarding`)}),`connect-help-panel`),(0,Q.jsx)(qK,{row:re}),F.state.kind===`failed-cold`&&(0,Q.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),F.state.kind===`failed-with-stale`&&(0,Q.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),o&&(0,Q.jsx)($,{tone:o.tone,children:o.text}),Y.length===0?F.state.kind===`failed-cold`?null:(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,Q.jsxs)(Q.Fragment,{children:[be.length>0&&(0,Q.jsx)(`ul`,{className:`integration-cards`,children:be.map(Se)}),xe.length>0&&(0,Q.jsxs)(`details`,{className:`connect-elsewhere`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`connect-elsewhere-title`,children:n(`connectV2.elsewhereTitle`,{count:String(xe.length)})}),(0,Q.jsx)(`span`,{className:`connect-elsewhere-hint`,children:n(`connectV2.elsewhereHint`)})]}),(0,Q.jsx)(`ul`,{className:`integration-cards integration-cards--elsewhere`,children:xe.map(Se)})]})]}),ne&&te.length===0&&(0,Q.jsxs)(`div`,{className:`integration-empty`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,Q.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,Q.jsx)(`h3`,{children:n(`integrations.rollback.title`)}),I.state.showSkeleton?(0,Q.jsx)(ck,{label:n(`integrations.rollback.title`),rows:2}):I.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[n(`integrations.rollback.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void I.refresh(),children:n(`common.retry`)})]}):ee.length===0?(0,Q.jsxs)(`div`,{className:`integration-empty`,children:[(0,Q.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,Q.jsx)(PK,{rows:ee,showClient:!0,onRestore:l,onDelete:d}),c&&(0,Q.jsx)(_K,{apiBase:e,row:c,onClose:()=>l(null),onRestored:ae,onReconcile:ae}),u&&(0,Q.jsx)(gK,{copy:{titleKey:`integrations.dialog.deleteEntry.title`,changesKey:`integrations.dialog.deleteEntry.changes`,breakageKey:`integrations.dialog.deleteEntry.breakage`,undoKey:`integrations.dialog.deleteEntry.undo`,confirmKey:`integrations.dialog.deleteEntry.confirm`,vars:{path:u.configPath}},onClose:()=>d(null),onConfirm:async()=>{try{await jO(e,u.opId,void 0,u.clientId===`aside`?u.profileId:void 0)}catch(e){if(mO(e)){d(null),await I.refresh();return}throw Error(tk(n,e),{cause:e})}d(null),await I.refresh()}}),m&&(0,Q.jsx)(gK,{copy:{...m.toggle===`claude-desktop`?RK:m.id===`codex`?LK:IK,vars:{path:m.togglePath??``}},onClose:()=>h(null),onConfirm:async()=>{await he(m,!1),h(null)}}),g&&g.row.status&&(0,Q.jsx)(gK,{copy:g.operation===`overwrite`?{titleKey:`integrations.dialog.overwrite.title`,changesKey:g.row.status.reason===`foreign-edit`?`integrations.dialog.overwrite.changesForeign`:`integrations.dialog.overwrite.changesUnowned`,breakageKey:`integrations.dialog.overwrite.breakage`,undoKey:`integrations.dialog.overwrite.undo`,confirmKey:`integrations.dialog.overwrite.confirm`,vars:{path:g.row.status.configPath}}:g.operation===`disable`?BK:zK,plan:g.plan,planLoading:g.loading,planFailure:g.failure,previewRecovery:g.recovery,onPreviewRecovery:_e,onClose:ve,onConfirm:async e=>{e&&(await he(g.row,e.operation!==`disable`,e),_(null))}}),v&&(0,Q.jsx)(gK,{copy:VK,plans:HK(v.actions),hasUnboundAction:v.actions.some(e=>e.plan===null),planStale:v.stale,planLoading:v.loading,planFailure:v.failure,previewRecovery:v.recovery,onPreviewRecovery:se,onClose:ce,onConfirm:async()=>{await le(v)}})]})}function qK({row:e}){let t=b(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,Q.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,Q.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,Q.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>En(e.hash),children:t(`integrations.action.manageKeys`)})]})}function JK({install:e}){let t=b();return(0,Q.jsxs)(Q.Fragment,{children:[e.plan===`free`&&(0,Q.jsx)($,{tone:`warn`,children:t(`integrations.raycast.proRequired`)}),e.plan===`unknown`&&(0,Q.jsx)(`p`,{className:`page-sub`,"data-raycast-plan":`unknown`,children:t(`integrations.raycast.planUnknown`)}),!e.aiDirPresent&&(0,Q.jsx)(`p`,{className:`page-sub`,"data-raycast-ai-dir":`absent`,children:t(`integrations.raycast.revealConfig`)})]})}function YK({reasoning:e,defaults:t,disabled:n,onChange:r,onReview:i}){let a=b(),o=new Map(e.models.map(e=>[e.model,new Set(e.efforts)])),s=Object.entries(t).filter(([e,t])=>!o.get(e)?.has(t)),c=(e,n)=>{let i={...t};n?i[e]=n:delete i[e],r(i)};return(0,Q.jsxs)(`section`,{className:`droid-reasoning-panel`,"aria-labelledby":`droid-reasoning-title`,children:[(0,Q.jsxs)(`div`,{className:`droid-reasoning-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{id:`droid-reasoning-title`,children:a(`integrations.droidReasoning.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`integrations.droidReasoning.description`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:i,disabled:n,children:a(`integrations.droidReasoning.saveReview`)})]}),e.models.length>0?(0,Q.jsx)(`ul`,{className:`droid-reasoning-list`,children:e.models.map(e=>{let r=t[e.model]??``,i=e.efforts.includes(r),o=[{value:``,label:a(`integrations.droidReasoning.noDefault`)},...!i&&r?[{value:r,label:a(`integrations.droidReasoning.unsupportedEffort`,{effort:r})}]:[],...e.efforts.map(e=>({value:e,label:e}))];return(0,Q.jsxs)(`li`,{className:`droid-reasoning-row`,children:[(0,Q.jsxs)(`div`,{className:`droid-reasoning-model`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`code`,{children:e.model})]}),e.efforts.length>0?(0,Q.jsx)(Vn,{value:r,options:o,onChange:t=>c(e.model,t),disabled:n,label:a(`integrations.droidReasoning.modelDefault`,{model:e.label})}):(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`integrations.droidReasoning.noEfforts`)})]},e.model)})}):(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`integrations.droidReasoning.noModels`)}),s.length>0&&(0,Q.jsxs)(`div`,{className:`droid-reasoning-unsupported`,role:`status`,children:[(0,Q.jsx)(`p`,{children:a(`integrations.droidReasoning.unsupportedTitle`)}),(0,Q.jsx)(`ul`,{children:s.map(([e,t])=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e}),` `,a(`integrations.droidReasoning.unsupportedEffort`,{effort:t}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:()=>c(e,``),children:a(`integrations.droidReasoning.clear`)})]},e))})]})]})}function XK(e,t){return{titleKey:`integrations.dialog.overwrite.title`,changesKey:e===`foreign-edit`?`integrations.dialog.overwrite.changesForeign`:`integrations.dialog.overwrite.changesUnowned`,breakageKey:`integrations.dialog.overwrite.breakage`,undoKey:`integrations.dialog.overwrite.undo`,confirmKey:`integrations.dialog.overwrite.confirm`,vars:{path:t}}}var ZK={titleKey:`integrations.dialog.apply.title`,changesKey:`integrations.dialog.apply.changes`,breakageKey:`integrations.dialog.apply.breakage`,undoKey:`integrations.dialog.apply.undo`,confirmKey:`integrations.dialog.apply.confirm`},QK={titleKey:`integrations.dialog.disable.title`,changesKey:`integrations.dialog.disable.changes`,breakageKey:`integrations.dialog.disable.breakage`,undoKey:`integrations.dialog.disable.undo`,confirmKey:`integrations.dialog.disable.confirm`},$K={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,"gentle-shell":`integrations.semantics.gentleShell`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`,zcode:`integrations.semantics.zcode`,commandcode:`integrations.semantics.commandcode`,prime:`integrations.semantics.prime`,aside:`integrations.semantics.aside`,raycast:`integrations.semantics.raycast`,omo:`integrations.semantics.omo`,cline:`integrations.semantics.cline`,kilo:`integrations.semantics.kilo`,droid:`integrations.semantics.droid`,qoder:`integrations.semantics.qoder`,"qoder-cn":`integrations.semantics.qoderCn`,workbuddy:`integrations.semantics.workbuddy`,"workbuddy-ai":`integrations.semantics.workbuddyAi`,t3code:`integrations.semantics.t3code`},eq={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,"gentle-shell":`integrations.tab.gentleShell`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,commandcode:`integrations.tab.commandcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`,kilo:`integrations.tab.kilo`,droid:`integrations.tab.droid`,qoder:`integrations.tab.qoder`,"qoder-cn":`integrations.tab.qoderCn`,workbuddy:`integrations.tab.workbuddy`,"workbuddy-ai":`integrations.tab.workbuddyAi`,t3code:`integrations.tab.t3code`};function tq(e){return(0,Q.jsx)(nq,{...e},JSON.stringify([e.apiBase,e.client,e.profileId,e.hermesProfile]))}function nq({apiBase:e,client:t,active:n=!0,profileId:r,profileLabel:i,hermesProfile:a,onRefresh:o}){let s=b(),c=r===void 0?a===void 0?t:`${t}/${a}`:`${t}:${r}`,[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,x]=(0,Z.useState)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(0);(0,Z.useEffect)(()=>()=>{C.current+=1,S.current?.abort()},[]);let w=(0,Z.useCallback)(n=>TO(e,t,n,r,a),[e,t,r,a]),T=(0,Z.useCallback)(async n=>(await EO(e,t,n,r,a)).operations,[e,t,r,a]),E=mf(`integration-state:${e}:${c}`,[e,t,r,a],w,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${c}`}),D=mf(`integration-journal:${e}:${c}`,[e,t,r,a],T,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${c}`}),O=E.state.data??null,k=O&&(r===void 0||O.profileId===r&&typeof O.enabled==`boolean`)&&O.hermesProfile===a?O:null,A=D.state.data??[],j=()=>{E.refresh(),D.refresh(),o?.()},M=()=>{f(null),j()},N=async(n,i=t===`droid`&&n!==`disable`&&d?.scopeKey===c?d.values:void 0,o=!1)=>{if(!k||l||y&&!o)return;let u=i===void 0?void 0:{...i},f=new AbortController,p=C.current+1;C.current=p,S.current?.abort(),S.current=f,x({operation:n,plan:null,loading:!0,failure:null,recovery:null});try{let i=await DO(e,t,n,f.signal,r,u,a);if(f.signal.aborted||p!==C.current)return;S.current=null,x({operation:n,plan:i,loading:!1,failure:null,recovery:null,droidReasoningDefaults:u})}catch(e){if(f.signal.aborted||p!==C.current)return;S.current=null;let t=FK(e);x({operation:n,plan:null,loading:!1,recovery:t,failure:t===null?s(`integrations.preview.failed`):null})}},P=async()=>{let n=y;if(!n)return;let i=C.current,o=n.droidReasoningDefaults;try{await TO(e,t,void 0,r,a)}catch{}i===C.current&&(j(),await N(n.operation,o,!0))},F=()=>{C.current+=1,S.current?.abort(),S.current=null,x(null)},I=async n=>{if(k&&!l){u(!0),m(null);try{await kO(e,t,{enabled:n.operation!==`disable`,overwriteConflict:n.operation===`overwrite`,profileId:r,hermesProfile:a,binding:vO(n),...n.operation!==`disable`&&y?.droidReasoningDefaults!==void 0?{droidReasoningDefaults:y.droidReasoningDefaults}:{}}),x(null),t===`droid`&&f(null)}catch(e){throw j(),e instanceof pO&&e.stalePlan?e:Error(tk(s,e),{cause:e})}finally{j(),u(!1)}}},L=()=>void N(B?`disable`:`apply`);if(!k)return(0,Q.jsx)(`section`,{className:`integration-client-page`,children:E.state.showError?(0,Q.jsxs)($,{tone:`err`,children:[s(`integrations.error.load`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:E.state.refreshing,children:s(`common.retry`)})]}):(0,Q.jsx)(`p`,{className:`page-sub`,children:s(`common.loading`)})});let R=qD(k),z=k.state===`current`||k.state===`stale`||R,B=r===void 0?z:k.enabled===!0,V=r!==void 0&&(E.state.showError||E.state.refreshing),H=(!k.installed||(k.state===`conflict`||k.state===`unsafe`)&&!R)&&!(r!==void 0&&B);return(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Q.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Q.jsx)(HH,{src:VH(t),label:s(eq[t]),size:24}),(0,Q.jsx)(`h3`,{children:i??s(eq[t])}),(0,Q.jsx)(sK,{state:k.state,installed:k.installed,id:`integration-state-${t}${r===void 0?``:`-${r}`}${a===void 0?``:`-${a}`}`}),(0,Q.jsx)(Rn,{on:B,onClick:L,disabled:H||l||V,label:s(B?`integrations.action.disable`:`integrations.action.apply`)})]}),r!==void 0&&E.state.showError&&(0,Q.jsxs)($,{tone:`err`,children:[s(`integrations.aside.loadError`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:l||E.state.refreshing,children:s(`common.retry`)})]}),k.state===`stale`&&B&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void N(`apply`),disabled:l,children:s(`integrations.action.refresh`)}),t===`droid`&&k.droidReasoning&&(0,Q.jsx)(YK,{reasoning:k.droidReasoning,defaults:d?.scopeKey===c?d.values:k.droidReasoning.defaults,disabled:l||y!==null,onChange:e=>f({scopeKey:c,values:e}),onReview:()=>void N(`apply`)}),k.installed&&k.state===`conflict`&&k.reason!==`candidate-conflict`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void N(`overwrite`),disabled:l,children:s(`integrations.action.overwrite`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:s($K[t])}),(0,Q.jsx)(`p`,{className:`integration-path`,children:k.configPath}),k.reason===`candidate-conflict`&&k.conflictPaths?.map(e=>(0,Q.jsx)($,{tone:`err`,children:s(`integrations.status.candidateConflict`,{path:e})},e)),k.raycast&&(0,Q.jsx)(JK,{install:k.raycast}),k.supersededBy&&(0,Q.jsx)($,{tone:`err`,children:k.supersededReason===`missing-store`&&k.missingStoreDocument!==void 0?s(`integrations.status.missingStore`,{path:k.supersededBy,document:k.missingStoreDocument}):s(`integrations.status.supersededStore`,{path:k.supersededBy})}),k.appliedAt&&(0,Q.jsxs)(`p`,{className:`integration-meta`,children:[s(`integrations.status.appliedAt`),`: `,new Date(k.appliedAt).toLocaleString()]}),k.retentionDegraded&&(0,Q.jsx)($,{tone:`err`,children:s(`integrations.retention.degraded`)}),p&&(0,Q.jsx)($,{tone:`err`,children:p}),(0,Q.jsx)(`h4`,{children:s(`integrations.rollback.title`)}),D.state.showSkeleton?(0,Q.jsx)(ck,{label:s(`integrations.rollback.title`),rows:2}):D.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[s(`integrations.rollback.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void D.refresh(),children:s(`common.retry`)})]}):A.length===0?(0,Q.jsx)(`p`,{className:`page-sub`,children:s(`integrations.rollback.empty`)}):(0,Q.jsx)(PK,{rows:A,onRestore:g,onDelete:v}),h&&(0,Q.jsx)(_K,{apiBase:e,row:h,profileId:r,hermesProfile:a,onClose:()=>g(null),onRestored:()=>{t===`droid`?M():j()},onReconcile:j}),_&&(0,Q.jsx)(gK,{copy:{titleKey:`integrations.dialog.deleteEntry.title`,changesKey:`integrations.dialog.deleteEntry.changes`,breakageKey:`integrations.dialog.deleteEntry.breakage`,undoKey:`integrations.dialog.deleteEntry.undo`,confirmKey:`integrations.dialog.deleteEntry.confirm`,vars:{path:_.configPath}},onClose:()=>v(null),onConfirm:async()=>{try{await jO(e,_.opId,void 0,r,a)}catch(e){if(mO(e)){v(null),await D.refresh();return}throw Error(tk(s,e),{cause:e})}v(null),await D.refresh()}}),y&&(0,Q.jsx)(gK,{copy:y.operation===`overwrite`?XK(k.reason,k.configPath):y.operation===`disable`?QK:ZK,plan:y.plan,planLoading:y.loading,planFailure:y.failure,previewRecovery:y.recovery,onPreviewRecovery:P,missingStorePath:k.supersededReason===`missing-store`?k.supersededBy:void 0,onClose:F,onConfirm:async e=>{e&&await I(e)}})]})}function rq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iq(){throw new pO(502,{code:`invalid_aside_profile_response`})}async function aq(e,t){let n=await gO(await fetch(`${e}/api/client-integrations/aside/profiles`,{signal:t}));(!rq(n)||!Array.isArray(n.profiles)||typeof n.allEnabled!=`boolean`)&&iq();let r=n.profiles.map(e=>WD(e)??iq());new Set(r.map(e=>e.profileId)).size!==r.length&&iq();let i=r.filter(e=>e.enabled).length,a=r.filter(e=>e.state===`current`||e.state===`stale`).length;return(n.total!==r.length||n.enabledCount!==i||n.appliedCount!==a||n.allEnabled!==(r.length>0&&i===r.length))&&iq(),{profiles:r,allEnabled:n.allEnabled,enabledCount:i,appliedCount:a,total:r.length,...typeof n.error==`string`?{error:n.error}:{}}}async function oq(e,t){let n=await gO(await fetch(`${e}/api/client-integrations/aside/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,signal:t}));(!rq(n)||typeof n.ok!=`boolean`||!Array.isArray(n.results))&&iq(),n.results.some(e=>!rq(e)||e.client!==`aside`)&&iq();let r=GD(n.results)??iq();return n.ok!==r.every(e=>e.ok)&&iq(),{ok:n.ok,results:r}}var sq={titleKey:`integrations.dialog.apply.title`,changesKey:`integrations.dialog.apply.changes`,breakageKey:`integrations.dialog.apply.breakage`,undoKey:`integrations.dialog.apply.undo`,confirmKey:`integrations.dialog.apply.confirm`},cq={titleKey:`integrations.dialog.disable.title`,changesKey:`integrations.dialog.disable.changes`,breakageKey:`integrations.dialog.disable.breakage`,undoKey:`integrations.dialog.disable.undo`,confirmKey:`integrations.dialog.disable.confirm`};function lq({apiBase:e,active:t=!0}){let n=b(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),s=(0,Z.useRef)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(new Map),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(0);(0,Z.useEffect)(()=>()=>{h.current+=1,m.current?.abort()},[]);let g=(0,Z.useCallback)(t=>aq(e,t),[e]),_=mf(`aside-profiles:${e}`,[e],g,{enabled:t,isEmpty:e=>!e.error&&e.profiles.length===0,sessionCacheKey:`ocx.integrations.aside-profiles.v1:${e}`}),v=_.state.data,y=v?.profiles??[],x=_.state.showError||!!v?.error,S=a!==null||_.state.refreshing||f!==null,C=e=>e.name||n(`integrations.aside.profile`,{id:e.profileId}),w=e=>d(t=>{let r=new Map(t);for(let t of e)t.ok?r.delete(t.profileId):r.set(t.profileId,nk(n,t));return r}),T=(e,t)=>{e instanceof pO&&`results`in e.body&&e.body.results?.length?(w(e.body.results),l(n(`integrations.aside.partial`))):t===void 0?l(tk(n,e)):d(r=>new Map(r).set(t,tk(n,e)))},E=async(t,r,i)=>{if(!s.current){s.current=!0,o(r??`all`),l(null);try{let n=await kO(e,`aside`,{enabled:t,profileId:r,...i?{binding:vO(i)}:{}});w(n.results??(r===void 0?y.map(e=>e.profileId):[r]).map(e=>({profileId:e,ok:!0})))}catch(e){if(i&&e instanceof pO&&e.stalePlan)throw e;if(T(e,r),i)throw Error(tk(n,e),{cause:e})}finally{_.refresh(),s.current=!1,o(null)}}},D=async(t,r,i=!1)=>{if(s.current||f&&!i)return;let a=new AbortController,o=h.current+1;h.current=o,m.current?.abort(),m.current=a,p({profile:t,enabled:r,plan:null,loading:!0,failure:null,recovery:null});try{let n=await DO(e,`aside`,r?`apply`:`disable`,a.signal,t.profileId);if(a.signal.aborted||o!==h.current)return;m.current=null,p({profile:t,enabled:r,plan:n,loading:!1,failure:null,recovery:null})}catch(e){if(a.signal.aborted||o!==h.current)return;m.current=null;let i=FK(e);p({profile:t,enabled:r,plan:null,loading:!1,recovery:i,failure:i===null?n(`integrations.preview.failed`):null})}},O=async()=>{let t=f;if(!t)return;let n=h.current;try{await TO(e,`aside`,void 0,t.profile.profileId)}catch{}n===h.current&&(_.refresh(),await D(t.profile,t.enabled,!0))},k=()=>{h.current+=1,m.current?.abort(),m.current=null,p(null)},A=async()=>{if(!s.current){s.current=!0,o(`sync`),l(null);try{let t=await oq(e);w(t.results),t.ok||l(n(`integrations.aside.partial`))}catch(e){T(e)}finally{_.refresh(),s.current=!1,o(null)}}};return r?(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,autoFocus:!0,onClick:()=>{i(null),_.refresh()},children:n(`integrations.aside.back`)}),u.has(r.profileId)&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(r.profileId)})}),(0,Q.jsx)(tq,{apiBase:e,client:`aside`,active:t,profileId:r.profileId,profileLabel:C(r)},r.profileId)]}):(0,Q.jsxs)(`section`,{className:`integration-client-page`,"aria-busy":S,children:[(0,Q.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Q.jsx)(HH,{src:VH(`aside`),label:n(`integrations.tab.aside`),size:24}),(0,Q.jsx)(`h3`,{children:n(`integrations.aside.profilesTitle`)})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.profilesHint`)}),(0,Q.jsxs)(`div`,{className:`aside-profile-toolbar`,children:[(0,Q.jsx)(Rn,{on:v?.allEnabled??!1,mixed:!!(v&&v.enabledCount>0&&v.enabledCount<v.total),onClick:()=>void E(!v?.allEnabled),disabled:S||x||y.length===0,label:n(`integrations.aside.all`),showLabel:!0}),(0,Q.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.applied`,{count:v?.appliedCount??0,total:v?.total??0})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:S||x||!v?.enabledCount,onClick:()=>void A(),children:n(`integrations.aside.syncNow`)})]}),c&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:c})}),[...u].filter(([e])=>!y.some(t=>t.profileId===e)).map(([e,t])=>(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsxs)(`span`,{className:`aside-profile-failure`,children:[n(`integrations.aside.profile`,{id:e}),`: `,t]})},e)),x&&(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{children:n(`integrations.aside.loadError`)}),v?.error&&(0,Q.jsx)(`span`,{className:`text-caption`,children:v.error}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>_.refresh(),disabled:S,children:n(`common.retry`)})]}),_.state.showSkeleton&&(0,Q.jsx)(ck,{label:n(`common.loading`),rows:3}),!_.state.showSkeleton&&!x&&v&&y.length===0&&(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.empty`)}),y.length>0&&(0,Q.jsx)(`div`,{className:`aside-profile-list`,children:y.map(e=>{let t=C(e),r=e.state===`current`||e.state===`stale`,o=e.enabled!==r||e.enabled&&e.state===`stale`,s=(!e.installed||e.state===`unsafe`||e.state===`conflict`)&&!e.enabled;return(0,Q.jsxs)(`div`,{className:`aside-profile-row`,"aria-busy":a===e.profileId,children:[(0,Q.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-label":n(`integrations.aside.details`,{name:t}),onClick:()=>i(e),disabled:S||x,children:t}),(0,Q.jsxs)(`div`,{className:`aside-profile-meta`,children:[(0,Q.jsx)(`code`,{children:e.profileId}),e.current&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.current`)})]}),o&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.pending`)}),e.error&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:e.error}),u.has(e.profileId)&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(e.profileId)})})]}),(0,Q.jsxs)(`div`,{className:`aside-profile-controls`,children:[(0,Q.jsx)(sK,{state:e.state,installed:e.installed,id:`aside-profile-state-${e.profileId}`}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S||x,"aria-label":n(`integrations.aside.retry`,{name:t}),onClick:()=>void D(e,e.enabled),children:n(`common.retry`)}),(0,Q.jsx)(Rn,{on:e.enabled,onClick:()=>void D(e,!e.enabled),disabled:S||x||s,label:n(`integrations.aside.toggle`,{name:t})})]})]},e.profileId)})}),f&&(0,Q.jsx)(gK,{copy:f.enabled?sq:cq,plan:f.plan,planLoading:f.loading,planFailure:f.failure,previewRecovery:f.recovery,onPreviewRecovery:O,onClose:k,onConfirm:async e=>{e&&(await E(f.enabled,f.profile.profileId,e),p(null))}})]})}var uq=[`absent`,`current`,`stale`,`conflict`,`unsafe`];function dq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fq(){throw new pO(502,{code:`invalid_hermes_profile_response`})}async function pq(e,t){let n=await gO(await fetch(e+`/api/client-integrations/hermes/profiles`,{signal:t}));(!dq(n)||!Array.isArray(n.profiles))&&fq();let r=n.profiles.map(e=>((!dq(e)||typeof e.hermesProfile!=`string`||typeof e.configPath!=`string`||typeof e.installed!=`boolean`||!uq.includes(e.state))&&fq(),{hermesProfile:e.hermesProfile,configPath:e.configPath,state:e.state,installed:e.installed,...typeof e.error==`string`?{error:e.error}:{}}));return(r[0]?.hermesProfile!=="default"||new Set(r.map(e=>e.hermesProfile)).size!==r.length)&&fq(),r}function mq({apiBase:e,active:t=!0}){let n=b(),[r,i]=(0,Z.useState)(`default`),a=(0,Z.useCallback)(t=>pq(e,t),[e]),o=mf(`hermes-profiles:${e}`,[e],a,{enabled:t,isEmpty:e=>e.length===0,sessionCacheKey:`ocx.integrations.hermes-profiles.v1:${e}`}),s=o.state.data??[],c=s.some(e=>e.hermesProfile===r)?r:`default`,l=e=>e==="default"?n(`integrations.hermes.defaultProfile`):e,u=c==="default"?void 0:c;return(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[s.length>1&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{children:n(`integrations.hermes.profilesTitle`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.hermes.profilesHint`)}),(0,Q.jsx)(`ul`,{className:`aside-profile-list hermes-profile-list`,children:s.map(e=>(0,Q.jsxs)(`li`,{className:`aside-profile-row`,children:[(0,Q.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-pressed":e.hermesProfile===c,"aria-label":n(`integrations.hermes.select`,{name:l(e.hermesProfile)}),onClick:()=>i(e.hermesProfile),children:l(e.hermesProfile)}),(0,Q.jsx)(`div`,{className:`aside-profile-meta`,children:(0,Q.jsx)(`code`,{children:e.configPath})}),e.error&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:e.error})]}),(0,Q.jsx)(`div`,{className:`aside-profile-controls`,children:(0,Q.jsx)(sK,{state:e.state,installed:e.installed,id:`hermes-profile-state-${e.hermesProfile}`})})]},e.hermesProfile))})]}),o.state.showError&&(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{children:n(`integrations.hermes.loadError`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void o.refresh(),disabled:o.state.refreshing,children:n(`common.retry`)})]}),(0,Q.jsx)(tq,{apiBase:e,client:`hermes`,active:t,hermesProfile:u,profileLabel:u===void 0?void 0:n(`integrations.hermes.profileTitle`,{name:u}),onRefresh:()=>void o.refresh()})]})}function hq(e){return e.proposedModel===e.model&&(e.proposedEffort==null||e.proposedEffort===e.effort)}function gq({apiBase:e,busy:t,apply:n}){let r=b(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)({}),[m,h]=(0,Z.useState)(null),g=async()=>{a(!0),l(null),h(null);try{let t=await Yn(await fetch(`${e}/api/codex-agent-roles/auto-assign`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),r(`integrations.lazycodexRoles.auto.failed`));d(t??null),p({})}catch(e){d(null),l(e instanceof Error&&e.message?e.message:r(`integrations.lazycodexRoles.auto.failed`))}finally{a(!1)}},_=(u?.proposals??[]).filter(e=>e.status===`proposed`&&e.proposedModel&&!f[e.role]&&!hq(e)),v=async(e,t)=>{let r=await n(e.role,e.proposedModel,e.proposedEffort??void 0,t);return r&&p(t=>({...t,[e.role]:!0})),r},y=async()=>{s(!0);try{let e=0,t=_.length,n;for(let t of _){let r=await v(t,n);r&&(n??=r.batch,e+=1)}h(r(`integrations.lazycodexRoles.auto.appliedCount`,{count:String(e),total:String(t)}))}finally{s(!1)}},x=i||o||t;return(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign`,children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.lazycodexRoles.auto.hint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:x,onClick:()=>void g(),children:r(i?`integrations.lazycodexRoles.auto.running`:`integrations.lazycodexRoles.auto.button`)})]}),c&&(0,Q.jsx)($,{tone:`err`,children:c}),u&&(0,Q.jsxs)(`section`,{className:`lazycodex-auto-assign-panel`,"aria-labelledby":`lazycodex-auto-assign-title`,children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Q.jsx)(`h5`,{id:`lazycodex-auto-assign-title`,children:r(`integrations.lazycodexRoles.auto.title`)}),(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.sizedWith`,{model:u.sizingModel})}),(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:x||_.length===0,onClick:()=>void y(),children:r(`integrations.lazycodexRoles.auto.applyAll`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:o,onClick:()=>{d(null),h(null)},children:r(`integrations.lazycodexRoles.auto.discard`)})]})]}),u.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:r(`integrations.lazycodexRoles.auto.sizingFailed`,{error:u.sizingError})}),m&&(0,Q.jsx)($,{tone:`ok`,children:m}),(0,Q.jsx)(`ul`,{className:`lazycodex-auto-assign-list`,children:u.proposals.map(e=>(0,Q.jsxs)(`li`,{"aria-label":r(`integrations.lazycodexRoles.auto.proposalFor`,{role:e.role}),children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-head`,children:[(0,Q.jsx)(`code`,{children:e.role}),e.tier&&e.effortIntent&&(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.tierEffort`,{tier:r(zN[e.tier]),effort:r(BN[e.effortIntent])})})]}),e.status===`unsized`?(0,Q.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.unsized`,{reason:e.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-change`,children:[(0,Q.jsx)(`span`,{children:e.model?(0,Q.jsx)(`code`,{children:e.model}):r(`integrations.lazycodexRoles.none`)}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),e.proposedModel?(0,Q.jsxs)(`code`,{children:[e.proposedModel,e.proposedEffort?` · ${e.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.unassigned`,{reason:e.reason??``})}),e.status===`proposed`&&(f[e.role]||hq(e)?(0,Q.jsx)(`span`,{className:`lazycodex-auto-assign-done`,children:f[e.role]?r(`integrations.lazycodexRoles.auto.applied`):r(`integrations.lazycodexRoles.auto.alreadySet`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:x,onClick:()=>void v(e),children:r(`integrations.lazycodexRoles.auto.apply`)}))]}),e.rationale&&(0,Q.jsx)(`p`,{children:e.rationale}),e.moveUpIf&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.moveUp`,{text:e.moveUpIf})}),e.moveDownIf&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.moveDown`,{text:e.moveDownIf})})]})]},e.role))})]})]})}function _q(e){let t=new Map;for(let n of e)t.set(n.batch,[...t.get(n.batch)??[],n]);return[...t.values()]}function vq(e){let t=new Map;for(let n of e)t.set(n.role,n.before);return t}function yq({history:e,unavailable:t,busy:n,restore:r}){let{locale:i,t:a}=s(),[o,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null);if(t)return(0,Q.jsx)($,{tone:`warn`,children:a(`integrations.lazycodexRoles.history.unavailable`)});if(e.length===0)return null;let d=e=>{let t=e.model??a(`integrations.lazycodexRoles.none`);return e.effort?`${t} · ${e.effort}`:t},f=async e=>{c(e[0].batch),u(null);try{let t,n=[...vq(e)],o=0;for(let[i,a]of n){let n=await r(i,a.model??void 0,a.effort,t,e[0].batch);if(!n)break;t??=n.batch,o+=1}let s=new Date(e[0].at).toLocaleString(i);u(o===n.length?{tone:`ok`,text:a(`integrations.lazycodexRoles.history.restored`,{count:String(o),time:s})}:{tone:`warn`,text:a(`integrations.lazycodexRoles.history.partial`,{count:String(o),total:String(n.length),role:n[o][0]})})}finally{c(null)}};return(0,Q.jsxs)(`div`,{className:`lazycodex-role-history`,children:[(0,Q.jsx)(`h5`,{children:a(`integrations.lazycodexRoles.history.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`integrations.lazycodexRoles.history.hint`)}),l&&(0,Q.jsx)($,{tone:l.tone,children:l.text}),(0,Q.jsx)(`ul`,{children:_q(e).map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`integration-meta`,children:new Date(e[0].at).toLocaleString(i)}),(0,Q.jsx)(`ul`,{children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e.role}),`: `,(0,Q.jsx)(`code`,{children:d(e.before)}),` → `,(0,Q.jsx)(`code`,{children:d(e.after)})]},`${e.at}-${e.role}`))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:n||o!==null,onClick:()=>void f(e),children:o===e[0].batch?a(`common.saving`):a(`integrations.lazycodexRoles.history.restore`)})]},e[0].batch))})]})}var bq={absent:`integrations.lazycodexRoles.omoAbsent`,skipped_comments:`integrations.lazycodexRoles.omoComments`,invalid:`integrations.lazycodexRoles.omoInvalid`,write_failed:`integrations.lazycodexRoles.omoFailed`};function xq({apiBase:e,active:t}){let n=b(),[r,i]=(0,Z.useState)({}),[a,o]=(0,Z.useState)({}),[s,c]=(0,Z.useState)({}),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=(0,Z.useCallback)(async t=>{let r=await Yn(await fetch(`${e}/api/codex-agent-roles`,{signal:t}),n(`integrations.lazycodexRoles.loadFailed`));if(r?.lazycodex?.detected!==!0)return{detected:!1,roles:[],history:[],historyUnavailable:!1,omoJsonc:null,available:[],efforts:[]};let[i,a]=await Promise.all([fetch(`${e}/api/subagent-models`,{signal:t}).then(e=>Yn(e,n(`integrations.lazycodexRoles.loadFailed`))),fetch(`${e}/api/injection-model`,{signal:t}).then(e=>Yn(e,n(`integrations.lazycodexRoles.loadFailed`))).catch(()=>null)]);return{detected:!0,roles:r.roles??[],history:r.history??[],historyUnavailable:r.historyUnavailable===!0,omoJsonc:r.omoJsonc??null,available:i?.available??[],efforts:a?.efforts??[]}},[e,n]),m=`lazycodex-role-models:${e}`,h=mf(m,[e],p,{isEmpty:e=>e.roles.length===0,enabled:t}),g=h.state.data,_=(0,Z.useRef)(g);(0,Z.useLayoutEffect)(()=>{_.current=g},[g]);let v=async(t,r,a=void 0,d,p,g)=>{if(l!==null)return null;let v=a===void 0?s[t]?.sent:a;if(r===void 0&&v===void 0)return null;u(t),f(null);try{let a=await Yn(await fetch(`${e}/api/codex-agent-roles/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...r===void 0?{}:{model:r},...v===void 0?{}:{effort:v},...p===void 0?{}:{batch:p},...g===void 0?{}:{restores:g}})}),n(`integrations.lazycodexRoles.saveFailed`,{role:t})),s=a?.omoJsonc?.status,l=_.current,u=l?.roles.find(e=>e.role===t),y=v===void 0?u?u.effort??null:d||null:v,b=y??``,x=r??u?.model??null;if(l){let e={...l,roles:l.roles.map(e=>e.role===t?{...e,model:r??e.model,effort:y,omoJsoncModel:r!==void 0&&(s===`written`||s===`unchanged`)?r:e.omoJsoncModel}:e)};_.current=e,Sn(m,e)}let S=s?bq[s]:void 0,C=x??n(`integrations.lazycodexRoles.none`),w=b?`${C} · ${b}`:C;f(S?{tone:`warn`,text:n(S,{role:t,model:w})}:{tone:`ok`,text:n(`integrations.lazycodexRoles.saved`,{role:t,model:w})});let T=s===`write_failed`,E=(e,n)=>{let{[t]:r,...i}=e;return T?{...i,[t]:n}:i};return i(e=>E(e,r??``)),o(e=>E(e,b)),c(e=>E(e,{sent:v})),await h.refresh(),{batch:a?.batch}}catch{return f({tone:`err`,text:n(`integrations.lazycodexRoles.saveFailed`,{role:t})}),null}finally{u(null)}},y=(e,t)=>{let r=[...new Set([...e.model?[e.model]:[],...g?.available??[]])];return[...t===``?[{value:``,label:n(`integrations.lazycodexRoles.choose`)}]:[],...r.map(e=>({value:e,label:e}))]};return h.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[n(`integrations.lazycodexRoles.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h.refresh(),children:n(`common.retry`)})]}):g?.detected?(0,Q.jsxs)(`section`,{id:`lazycodex-role-models`,className:`lazycodex-role-models`,"aria-labelledby":`lazycodex-role-models-title`,children:[(0,Q.jsx)(`h4`,{id:`lazycodex-role-models-title`,children:n(`integrations.lazycodexRoles.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.lazycodexRoles.hint`)}),g.omoJsonc?.state===`comments`&&(0,Q.jsx)($,{tone:`warn`,children:n(`integrations.lazycodexRoles.omoCommentsState`)}),d&&(0,Q.jsx)($,{tone:d.tone,children:d.text}),g.roles.length===0?(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.lazycodexRoles.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(gq,{apiBase:e,busy:l!==null,apply:(e,t,n,r)=>v(e,t,n,void 0,r)}),(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`integrations.lazycodexRoles.role`)}),(0,Q.jsx)(`th`,{children:n(`integrations.lazycodexRoles.current`)}),(0,Q.jsxs)(`th`,{children:[n(`integrations.lazycodexRoles.model`),` · `,n(`integrations.lazycodexRoles.effort`)]})]})}),(0,Q.jsx)(`tbody`,{children:g.roles.map(e=>{let t=r[e.role]??e.model??``,c=a[e.role]??e.effort??``,u=c!==(e.effort??``),d=t!==``&&t!==e.model||u,f=s[e.role],p=f!==void 0&&(t!==``||f.sent!==void 0);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.role})}),(0,Q.jsx)(`td`,{children:e.model?(0,Q.jsx)(`code`,{children:e.effort?`${e.model} · ${e.effort}`:e.model}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`integration-meta`,children:n(`integrations.lazycodexRoles.none`)}),e.effort&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,(0,Q.jsx)(`code`,{children:e.effort})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`lazycodex-role-models-edit`,children:[(0,Q.jsx)(Vn,{value:t,options:y(e,t),label:n(`integrations.lazycodexRoles.modelFor`,{role:e.role}),disabled:l!==null,onChange:t=>i(n=>({...n,[e.role]:t}))}),(0,Q.jsx)(Vn,{value:c,options:[{value:``,label:n(`integrations.lazycodexRoles.effortDefault`)},...[...new Set([...e.effort?[e.effort]:[],...g.efforts])].map(e=>({value:e,label:e}))],label:n(`integrations.lazycodexRoles.effortFor`,{role:e.role}),disabled:l!==null,onChange:t=>o(n=>({...n,[e.role]:t}))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!(d||p)||l!==null,onClick:()=>void v(e.role,t||void 0,u?c||null:void 0,e.effort??``),children:l===e.role?n(`common.saving`):n(p&&!d?`integrations.lazycodexRoles.retryMirror`:`common.save`)})]})})]},e.role)})})]})}),(0,Q.jsx)(yq,{history:g.history,unavailable:g.historyUnavailable,busy:l!==null,restore:(e,t,n,r,i)=>v(e,t,n,void 0,r,i)})]})]}):null}var Sq=[{id:`overview`,hash:`integrations`,labelKey:`integrations.tab.overview`},{id:`keys`,hash:`integrations/keys`,labelKey:`integrations.tab.keys`},{id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`},{id:`claude`,hash:`claude`,labelKey:`nav.claude`},{id:`claudeDesktop`,hash:`claude/desktop`,labelKey:`claudeDesktop.title`},{id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`},{id:`cursor`,hash:`integrations/cursor`,labelKey:`integrations.tab.cursor`},{id:`opencode`,hash:`integrations/opencode`,labelKey:`integrations.tab.opencode`},{id:`pi`,hash:`integrations/pi`,labelKey:`integrations.tab.pi`},{id:`gentle-shell`,hash:`integrations/gentle-shell`,labelKey:`integrations.tab.gentleShell`},{id:`omp`,hash:`integrations/omp`,labelKey:`integrations.tab.omp`},{id:`hermes`,hash:`integrations/hermes`,labelKey:`integrations.tab.hermes`},{id:`openclaw`,hash:`integrations/openclaw`,labelKey:`integrations.tab.openclaw`},{id:`kimi`,hash:`integrations/kimi`,labelKey:`integrations.tab.kimi`},{id:`gajae`,hash:`integrations/gajae`,labelKey:`integrations.tab.gajae`},{id:`dsh`,hash:`integrations/dsh`,labelKey:`integrations.tab.dsh`},{id:`mcode`,hash:`integrations/mcode`,labelKey:`integrations.tab.mcode`},{id:`zcode`,hash:`integrations/zcode`,labelKey:`integrations.tab.zcode`},{id:`commandcode`,hash:`integrations/commandcode`,labelKey:`integrations.tab.commandcode`},{id:`prime`,hash:`integrations/prime`,labelKey:`integrations.tab.prime`},{id:`aside`,hash:`integrations/aside`,labelKey:`integrations.tab.aside`},{id:`raycast`,hash:`integrations/raycast`,labelKey:`integrations.tab.raycast`},{id:`omo`,hash:`integrations/omo`,labelKey:`integrations.tab.omo`},{id:`qoder`,hash:`integrations/qoder`,labelKey:`integrations.tab.qoder`},{id:`qoder-cn`,hash:`integrations/qoder-cn`,labelKey:`integrations.tab.qoderCn`},{id:`workbuddy`,hash:`integrations/workbuddy`,labelKey:`integrations.tab.workbuddy`},{id:`workbuddy-ai`,hash:`integrations/workbuddy-ai`,labelKey:`integrations.tab.workbuddyAi`},{id:`cline`,hash:`integrations/cline`,labelKey:`integrations.tab.cline`},{id:`kilo`,hash:`integrations/kilo`,labelKey:`integrations.tab.kilo`},{id:`droid`,hash:`integrations/droid`,labelKey:`integrations.tab.droid`},{id:`t3code`,hash:`integrations/t3code`,labelKey:`integrations.tab.t3code`}],Cq=new Set([`opencode`,`pi`,`gentle-shell`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`,`qoder`,`qoder-cn`,`workbuddy`,`workbuddy-ai`,`t3code`]);function wq(e=window.location.hash){let t=BT(e);return t===`claude/desktop`?`claudeDesktop`:t===`claude`||t.startsWith(`claude/`)?`claude`:Sq.find(e=>e.hash===t)?.id??`overview`}function Tq(e){return`integrations-tab-${e}`}function Eq(e){return`integrations-panel-${e}`}function Dq(e){return e===`overview`||e===`keys`?null:RH[e]??null}function Oq({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=b(),[i,a]=(0,Z.useState)(wq),[o,s]=(0,Z.useState)(()=>new Set([wq()])),c=(0,Z.useRef)(null),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)(!1);c.current===null&&(c.current=new Map),(0,Z.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/clients`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{!e.signal.aborted&&Array.isArray(t?.selectedClients)&&u(t.selectedClients.filter(e=>typeof e==`string`))}).catch(()=>{}),()=>e.abort()},[n,t]);let p=async()=>{f(!0);try{await fetch(`${t}/api/machine/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`})}finally{f(!1)}},m=e=>{a(e),s(t=>t.has(e)?t:new Set([...t,e]))};(0,Z.useEffect)(()=>{let e=()=>m(wq());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let h=(e,t)=>{let n=Sq.find(t=>t.id===e);n&&(En(n.hash),m(e),t&&window.requestAnimationFrame(()=>{c.current.get(e)?.focus({preventScroll:!0})}))},g=e=>{let t=Sq.findIndex(e=>e.id===i),n=null;e.key===`ArrowLeft`?n=(t-1+Sq.length)%Sq.length:e.key===`ArrowRight`?n=(t+1)%Sq.length:e.key===`Home`?n=0:e.key===`End`&&(n=Sq.length-1),n!==null&&(e.preventDefault(),h(Sq[n].id,!0))};return(0,Q.jsxs)(`section`,{className:`integrations-page`,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`nav.connect`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`connectV2.subtitle`)}),n&&(0,Q.jsxs)(`section`,{className:`notice`,"aria-label":r(`connection.clients.title`),children:[(0,Q.jsx)(`strong`,{children:r(`connection.clients.title`)}),(0,Q.jsx)(`span`,{children:l.length>0?l.join(`, `):r(`connection.clients.none`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d,onClick:()=>void p(),children:r(d?`connection.clients.syncing`:`connection.clients.sync`)})]}),(0,Q.jsx)(`div`,{className:`page-tabs connect-tabs`,role:`tablist`,"aria-label":r(`integrations.tabsLabel`),children:Sq.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`button`,{ref:t=>{t?c.current.set(e.id,t):c.current.delete(e.id)},type:`button`,role:`tab`,id:Tq(e.id),"aria-selected":i===e.id,"aria-controls":Eq(e.id),tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>h(e.id,!0),onKeyDown:g,children:[e.id!==`overview`&&e.id!==`keys`&&(0,Q.jsx)(HH,{src:Dq(e.id),label:r(e.labelKey),size:14}),r(e.labelKey)]}),e.id===`keys`&&(0,Q.jsx)(`span`,{className:`connect-tabs-divider`,role:`presentation`})]},e.id))}),Sq.map(t=>{if(!o.has(t.id))return null;let n=i===t.id;return(0,Q.jsxs)(`div`,{role:`tabpanel`,id:Eq(t.id),"aria-labelledby":Tq(t.id),hidden:!n,children:[t.id===`overview`&&(0,Q.jsx)(KK,{apiBase:e,active:n}),t.id===`keys`&&(0,Q.jsx)(RU,{apiBase:e,active:n}),t.id===`codex`&&(0,Q.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,Q.jsx)(`h3`,{id:`codex-integration-title`,children:r(`integrations.codex.title`)}),(0,Q.jsx)(`p`,{children:r(`integrations.codex.body`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>En(`startup`),children:r(`integrations.codex.openService`)})]}),t.id===`grok`&&(0,Q.jsx)(ZG,{apiBase:e,active:n}),t.id===`claude`&&(0,Q.jsx)(KW,{apiBase:e,active:n,embedded:!0}),t.id===`claudeDesktop`&&(0,Q.jsx)(`div`,{className:`claude-page claude-page--embedded`,children:(0,Q.jsx)(GG,{apiBase:e,active:n},e)}),t.id===`cursor`&&(0,Q.jsx)(rK,{apiBase:e,active:n}),Cq.has(t.id)&&(t.id===`aside`?(0,Q.jsx)(lq,{apiBase:e,active:n}):t.id===`hermes`?(0,Q.jsx)(mq,{apiBase:e,active:n}):(0,Q.jsx)(tq,{apiBase:e,client:t.id,active:n})),t.id===`omo`&&(0,Q.jsx)(xq,{apiBase:e,active:n})]},t.id)})]})}var kq={ok:`bg-success-soft text-success`,warn:`bg-warning-soft text-warning`,err:`bg-danger-soft text-danger`,neutral:`bg-surface-2 text-fg-muted`};function Aq({tone:e,children:t,className:n}){return(0,Q.jsxs)(`span`,{className:X(`startup-badge inline-flex h-[22px] max-w-full shrink-0 items-center gap-1.5 rounded-full px-2 text-[12px] leading-4 font-semibold whitespace-nowrap`,kq[e],n),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`size-1.5 shrink-0 rounded-full bg-current`}),(0,Q.jsx)(`span`,{className:`truncate`,children:t})]})}function jq({children:e}){return(0,Q.jsx)(`span`,{className:`inline-flex h-5 items-center rounded-[6px] px-1.5 text-[11px] font-medium text-fg-muted ring-1 ring-line-strong ring-inset`,children:e})}function Mq({title:e,meta:t,description:n,actions:r,icon:i,children:a,className:o,bodyClassName:s,id:c}){let l=(0,Z.useId)(),u=c??l;return(0,Q.jsxs)(`section`,{"aria-labelledby":e?u:void 0,className:X(`flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,o),children:[(e||r)&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-2 px-4 pt-3 pb-3`,children:[i&&(0,Q.jsx)(Nq,{children:i}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[e&&(0,Q.jsxs)(`h3`,{id:u,className:`m-0 flex min-w-0 flex-wrap items-baseline gap-x-2 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:[e,t!=null&&(0,Q.jsx)(`span`,{className:`text-[12px] font-normal text-fg-subtle tabular-nums`,children:t})]}),n&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:n})]}),r&&(0,Q.jsx)(`div`,{className:`ml-auto flex flex-wrap items-center justify-end gap-1.5`,children:r})]}),a!=null&&a!==!1&&(0,Q.jsx)(`div`,{className:X(`flex min-w-0 flex-col rounded-[8px] bg-bg ring-1 ring-line`,s),children:a})]})}function Nq({children:e,className:t}){return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`grid size-9 shrink-0 place-items-center rounded-[10px] bg-raised text-fg shadow-sm ring-1 ring-line [&_svg]:size-[18px]`,t),children:e})}var Pq={ok:`text-success`,warn:`text-warning`,err:`text-danger`};function Fq({tone:e,children:t,action:n,role:r=`status`,className:i}){let a=e===`ok`?st:e===`info`?He:St;return(0,Q.jsxs)(`div`,{role:r,className:X(`flex min-w-0 items-start gap-2.5 rounded-[10px] bg-raised px-3 py-2.5 text-[13px] leading-[19px] text-fg ring-1 ring-line`,e===`warn`&&`bg-warning-soft ring-warning/25`,e===`err`&&`bg-danger-soft ring-danger/25`,i),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`mt-px shrink-0 [&_svg]:size-4`,e===`info`?`text-fg-muted`:Pq[e]),children:(0,Q.jsx)(a,{})}),(0,Q.jsx)(`div`,{className:`min-w-0 flex-1 [overflow-wrap:anywhere]`,children:t}),n&&(0,Q.jsx)(`div`,{className:`-my-1 flex shrink-0 flex-wrap items-center gap-1.5`,children:n})]})}function Iq({label:e,onClick:t,children:n,disabled:r,tone:i=`neutral`,className:a}){return(0,Q.jsx)(`button`,{type:`button`,"aria-label":e,title:e,onClick:t,disabled:r,className:X(`ui-v2 inline-grid size-[var(--ocx-control-h-sm)] shrink-0 cursor-pointer place-items-center rounded-[8px] text-fg-muted transition-colors`,`hover:bg-surface-2 hover:text-fg focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-40 [&_svg]:size-4`,i===`danger`&&`hover:bg-danger-soft hover:text-danger`,a),children:n})}function Lq({copied:e,onCopy:t,className:n}){let r=b();return(0,Q.jsx)(Iq,{label:r(e?`startup.copied`:`startup.copy`),onClick:t,className:n,children:(0,Q.jsx)(Pc,{icon:e?qc:zc,size:16,strokeWidth:1.8,"aria-hidden":`true`,className:e?`text-success`:void 0})})}function Rq({label:e,command:t,copied:n,onCopy:r}){return(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[e&&(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 font-medium text-fg`,children:e}),(0,Q.jsx)(`code`,{className:`block min-w-0 font-mono text-[12.5px] leading-5 text-fg-muted [overflow-wrap:anywhere]`,children:t})]}),(0,Q.jsx)(Lq,{copied:n,onCopy:r})]})}function zq({open:e,controls:t,name:n,onToggle:r}){let i=b()(`startupV2.about`,{name:n});return(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":e,"aria-controls":t,"aria-label":i,title:i,onClick:r,className:X(`ui-v2 inline-grid size-6 shrink-0 cursor-pointer place-items-center rounded-full text-fg-subtle transition-colors`,`hover:bg-surface-2 hover:text-fg focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight [&_svg]:size-[15px]`,e&&`bg-surface-2 text-fg`),children:(0,Q.jsx)(He,{"aria-hidden":`true`})})}function Bq({id:e,open:t,children:n,className:r}){return(0,Q.jsx)(`div`,{id:e,hidden:!t,className:X(`rounded-[8px] bg-surface-2/60 px-3 py-2.5 text-[13px] leading-[19px] text-fg-muted`,r),children:n})}function Vq({title:e,subtitle:t,actions:n}){return(0,Q.jsxs)(`header`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Q.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:e}),t&&(0,Q.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[14px] leading-5 text-fg-muted`,children:t})]}),n&&(0,Q.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:n})]})}function Hq(){return typeof window<`u`&&BT(window.location.hash)===`startup/desktop`}function Uq(e){let[t,n]=(0,Z.useState)(()=>+!!Hq()),r=(0,Z.useRef)(0);(0,Z.useEffect)(()=>{let e=()=>{Hq()&&n(e=>e+1)};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>{if(t===0||r.current===t||!e)return;let n=document.querySelector(`[data-option="desktop"]`);if(!n)return;r.current=t;let i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;n.scrollIntoView?.({behavior:i?`auto`:`smooth`,block:`start`}),n.hasAttribute(`tabindex`)||(n.tabIndex=-1),n.focus({preventScroll:!0})},[t,e])}function Wq({icon:e,title:t,term:n,tag:r,badge:i,children:a,actions:o,option:s}){return(0,Q.jsxs)(`article`,{"data-option":s,className:`startup-option flex min-w-0 flex-col gap-3 rounded-[12px] bg-surface p-4 ring-1 ring-line`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Q.jsx)(Nq,{children:e}),(0,Q.jsx)(Aq,{tone:i.tone,children:i.label})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Q.jsxs)(`h4`,{className:`m-0 flex flex-wrap items-center gap-2 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:[t,r&&(0,Q.jsx)(jq,{children:r})]}),n&&(0,Q.jsx)(`span`,{className:`text-[12px] leading-4 text-fg-subtle`,children:n})]}),(0,Q.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2 text-[13px] leading-5 text-fg-muted`,children:a}),o&&(0,Q.jsx)(`div`,{className:X(`mt-auto flex flex-wrap items-center gap-2 pt-1`),children:o})]})}function Gq(){let[e,t]=(0,Z.useState)(!1);return{open:e,id:(0,Z.useId)(),toggle:()=>t(e=>!e)}}function Kq(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.supported==`boolean`&&typeof t.installed==`boolean`&&typeof t.running==`boolean`&&typeof t.stale==`boolean`&&typeof t.summary==`string`}var qq={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},Jq={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},Yq={desktop:`startup.protection.desktop`,service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`},Xq=e=>(0,Q.jsx)(Pc,{icon:e,size:18,strokeWidth:1.8,"aria-hidden":`true`});function Zq({failed:e,data:t}){let{t:n}=s(),r=Gq(),i=kf(t,e),a=i===`unverified`,o=i===`error`||i===`at-risk`,c=a?He:o?St:st,l=[[`startup.routing`,n(t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`)],[`startup.restartProtection`,n(a?`startup.unverified`:Yq[t.protection])],[`startup.preference`,n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)]];return(0,Q.jsxs)(`section`,{className:`startup-status flex min-w-0 gap-4 rounded-[12px] bg-surface p-5 ring-1 ring-line`,"aria-live":`polite`,"data-status":e?`error`:t.status,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`grid size-11 shrink-0 place-items-center rounded-full [&_svg]:size-[22px]`,a?`bg-surface-2 text-fg-muted`:o?`bg-warning-soft text-warning`:`bg-success-soft text-success`),children:(0,Q.jsx)(c,{})}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,children:[(0,Q.jsx)(Aq,{tone:a?`neutral`:o?`warn`:`ok`,className:`self-start`,children:n(a?`startup.unverified`:e?`startup.status.atRisk`:qq[t.status])}),(0,Q.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`m-0 text-[20px] leading-7 font-semibold tracking-[-0.02em] text-fg`,children:n(a?Df(t)?`startup.loginUnverifiedTitle`:`startup.unverified`:e?`startup.error`:Jq[t.status])}),(0,Q.jsx)(`span`,{className:`mt-0.5`,children:(0,Q.jsx)(zq,{open:r.open,controls:r.id,name:n(`startup.title`),onToggle:r.toggle})})]}),(0,Q.jsx)(`p`,{className:`m-0 max-w-[72ch] text-[14px] leading-[21px] text-fg-muted`,children:a?n(Df(t)?`startup.loginUnverifiedAction`:`startup.subtitle`):t.status===`at-risk`&&t.routingKind===`opencodex-local`&&Df(t)&&!Of(t)?n(`startup.loginUnverifiedAction`):e?n(`startup.staleData`):t.status===`at-risk`?n(Nf(t)):n(`startup.safeDetail`)}),(0,Q.jsx)(`p`,{className:`startup-status-line m-0 mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[13px] leading-5`,children:l.map(([e,t],r)=>(0,Q.jsxs)(Z.Fragment,{children:[r>0&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-fg-subtle`,children:`·`}),(0,Q.jsxs)(`span`,{className:`inline-flex flex-wrap gap-x-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-fg-subtle`,children:n(e)}),(0,Q.jsx)(`span`,{className:`font-medium text-fg`,children:t})]})]},e))}),(0,Q.jsx)(Bq,{id:r.id,open:r.open,className:`mt-1 max-w-[72ch]`,children:n(`startup.subtitle`)})]})]})}function Qq({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a,tray:o}){let{t:c}=s(),l=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,u=e.shimInstalled&&!e.shimHealthy&&e.shimActivationPending===!0,d=e.shimInstalled&&!e.shimHealthy&&!u,f=r!==null||t||n,p=Df(e),m=f||p,h=e.serviceViable?{tone:`ok`,label:c(`startup.viable`)}:{tone:e.serviceInstalled?`warn`:`neutral`,label:c(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)},g=e.shimHealthy&&e.autostartEnabled?{tone:`ok`,label:c(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`)}:{tone:e.shimInstalled?`warn`:`neutral`,label:c(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:u?`startup.shimActivationPending`:`startup.stale`:`startup.notInstalled`)},_=!!(e.desktop&&!t&&e.desktop.viable),v=+!!e.desktop+2+ +!!o,y=(e,t,n,i)=>(0,Q.jsx)(Jp,{variant:`primary`,size:`sm`,"aria-label":`${t} - ${c(n?`startup.repair`:`startup.install`)}`,disabled:i,onClick:()=>a(e,n?{repair:!0}:void 0),children:c(r===e?n?`startup.repairing`:`startup.installing`:n?`startup.repair`:`startup.install`)});return(0,Q.jsxs)(`section`,{className:`startup-options flex min-w-0 flex-col gap-3`,"aria-labelledby":`startup-options-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-x-4 gap-y-1 px-1`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Q.jsx)(`h3`,{id:`startup-options-title`,className:`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:c(`startupV2.optionsTitle`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:c(`startupV2.optionsHint`)})]}),(0,Q.jsx)(`span`,{className:`font-mono text-[12px] text-fg-subtle`,title:c(`startup.details`),children:e.platform})]}),(0,Q.jsxs)(`div`,{className:X(`grid gap-3 sm:grid-cols-2`,v===3&&`lg:grid-cols-3`),children:[e.desktop&&(0,Q.jsx)(Wq,{option:`desktop`,icon:Xq(Uc),title:c(`startup.protection.desktop`),badge:{tone:_?`ok`:kf(e,t)===`unverified`?`neutral`:`warn`,label:c(kf(e,t)===`unverified`?`startup.loginUnverifiedTitle`:Mf(e.desktop,t))},children:_?(0,Q.jsx)(`p`,{className:`m-0`,children:c(`startup.desktopHint`)}):t?null:e.desktop.running?(0,Q.jsx)(`p`,{className:`m-0`,children:c(`startup.desktopRunning`)}):(0,Q.jsx)(`p`,{className:`m-0`,children:c(`startup.desktopReopenRecovery`)})}),(0,Q.jsx)(Wq,{option:`service`,icon:Xq(Kc),title:c(`startup.service`),tag:e.serviceSupported&&!p?c(`startupV2.recommended`):void 0,badge:h,actions:e.serviceSupported&&!e.serviceInstalled?y(`install-service`,c(`startup.service`),!1,m):l?y(`install-service`,c(`startup.service`),!0,m):void 0,children:(0,Q.jsx)(`p`,{className:`m-0`,children:c(`startup.serviceHint`)})}),(0,Q.jsx)(Wq,{option:`shim`,icon:Xq(Lc),title:c(`startupV2.shimPlain`),term:c(`startup.shim`),badge:g,actions:e.shimInstalled?d?y(`install-shim`,c(`startup.shim`),!0,f):void 0:y(`install-shim`,c(`startup.shim`),!1,f),children:(0,Q.jsx)(`p`,{className:`m-0`,children:c(u?`startup.shimActivationHint`:`startup.shimHint`)})}),o]}),i&&(0,Q.jsx)(Fq,{tone:i.kind===`success`?`ok`:`warn`,className:`startup-action-result`,children:i.kind===`success`?i.action===`install-service`?c(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):c(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${c(`startup.installFailed`)} ${i.detail??``}`})]})}function $q({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=s(),o=async()=>{await Ju({message:a(`startup.tray.uninstall`),tone:`danger`})&&i(`uninstall`)},c=!t&&!n&&e!==null,l=c?e.running&&!e.stale?{tone:`ok`,label:a(`startup.tray.running`)}:{tone:e.stale?`warn`:`neutral`,label:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)}:{tone:t?`neutral`:`warn`,label:a(t?`startup.tray.loading`:`startup.tray.unavailable`)},u=c?(0,Q.jsxs)(Q.Fragment,{children:[!e.installed&&!e.stale&&(0,Q.jsx)(Jp,{variant:`primary`,size:`sm`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),e.installed&&!e.stale&&!e.running&&(0,Q.jsx)(Jp,{variant:`primary`,size:`sm`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),e.running&&!e.stale&&(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),(e.installed||e.stale)&&(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,className:`hover:bg-danger-soft hover:text-danger`,disabled:r,onClick:()=>{o()},children:a(`startup.tray.uninstall`)})]}):void 0;return(0,Q.jsxs)(Wq,{option:`tray`,icon:Xq(Rc),title:a(`startup.tray.title`),term:a(`startup.tray.login`),tag:a(`startupV2.optional`),badge:l,actions:u,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:a(`startup.tray.hint`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[12px] leading-[18px] text-fg-subtle`,children:a(`startup.tray.notProtection`)}),(n||e?.stale)&&(0,Q.jsx)(Fq,{tone:`warn`,role:`alert`,children:a(`startup.tray.error`)})]})}function eJ({data:e,copied:t,onCopy:n}){let{t:r}=s(),i=Df(e),a=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService,o=[...e.serviceSupported&&!i?[[`startup.command.service`,a]]:[],[`startup.command.shim`,e.commands.installShim],[`startup.command.native`,e.commands.restoreNative]];return(0,Q.jsx)(`section`,{className:`startup-recovery-panel rounded-[12px] bg-surface p-1 ring-1 ring-line`,"aria-label":r(`startup.recovery`),children:(0,Q.jsxs)(`details`,{className:`startup-recovery group`,open:kf(e)===`at-risk`,children:[(0,Q.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center gap-3 rounded-[10px] px-3 py-2.5 transition-colors hover:bg-surface-2/50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(Nq,{className:`size-8 rounded-[8px] [&_svg]:size-4`,children:(0,Q.jsx)(Qe,{})}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,Q.jsx)(`span`,{className:`text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:r(`startup.recovery`)}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:r(i?`startup.protection.desktop`:`startupV2.recoveryMeta`)})]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-fg-subtle transition-transform duration-200 group-open:rotate-90 [&_svg]:size-4`,children:(0,Q.jsx)(lt,{})})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-3 px-3 pt-1 pb-3`,children:[!i&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:r(`startup.recoveryHint`)}),(0,Q.jsx)(`div`,{className:`flex flex-col divide-y divide-line rounded-[8px] bg-bg ring-1 ring-line`,children:o.map(([e,i])=>(0,Q.jsx)(Rq,{label:r(e),command:i,copied:t===i,onCopy:()=>n(i)},e))}),e.status===`at-risk`&&e.recommendedCommand&&!i&&(0,Q.jsx)(Fq,{tone:`warn`,role:`alert`,children:r(`startup.recommended`,{cmd:e.recommendedCommand})})]})]})})}var tJ=`ocx.startup.page.v1:`;function nJ(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function rJ(e,t,n){if(!e)return{warning:null,fix:null};let r=!!e.catalogClamp?.active,i=!!e.newerAvailable,a=(r?e.catalogClamp?.runtimeVersion:e.version)??e.version??`unknown`,o=(e.catalogClamp?.removedEfforts??[]).join(`, `),s=nJ([`ocx doctor --fix-codex-runtime`,`ocx sync`],n);return r?{warning:o?t(`startup.codexRuntime.clampHiddenWithEfforts`,{version:a,efforts:o}):t(`startup.codexRuntime.clampHidden`,{version:a}),fix:i?s:`ocx sync`}:i?{warning:t(`startup.codexRuntime.olderBinary`,{version:a}),fix:s}:{warning:null,fix:null}}function iJ({apiBase:e,machineApiBase:t=e,connected:n=!1}){let{t:r}=s(),i=`${tJ}${e}`,a=(0,Z.useMemo)(()=>sf(i),[i]),o=`startup-page:${e}`,[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(()=>a?.tray??null),[f,p]=(0,Z.useState)(()=>!a?.data),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(()=>a?.warning??null),[w,T]=(0,Z.useState)(()=>a?.fix??null),[E,D]=(0,Z.useState)(()=>!a?.data),O=(0,Z.useRef)(!!a?.data),k=(0,Z.useRef)(0),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/shim`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{e.signal.aborted||j(t)}).catch(()=>{e.signal.aborted||j(null)}),()=>e.abort()},[n,t]);let P=async e=>{N(!0);try{let n=await fetch(`${t}/api/machine/shim`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:e})});if(n.ok){let e=await n.json();j(e.shim??null)}}finally{N(!1)}};(0,Z.useEffect)(()=>()=>{k.current+=1},[e]);let F=(0,Z.useCallback)(async t=>{let n=++k.current,a=O.current;a||(p(!0),D(!0));try{let a=fetch(`${e}/api/settings`,{signal:t}).then(async e=>e.ok?await e.json():null).catch(()=>null),o=await fetch(`${e}/api/startup-health`,{signal:t});if(!o.ok)throw Error(`fetch failed`);let s=await o.json();x(e=>e?.kind===`error`&&(s.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?s.serviceViable:s.shimInstalled&&(s.shimHealthy||s.shimActivationPending===!0)))?null:e),O.current=!0;let c=sf(i);df(i,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:c?.tray??null});let l=s.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:t}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!Kq(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([a,l]).then(([e,a])=>{if(t.aborted||n!==k.current)return;let o=s.platform===`win32`?a.tray:null;if(s.platform===`win32`?(d(o),_(a.error)):(d(null),_(!1)),p(!1),D(!1),e){let t=rJ(e.codexRuntime,r,s.platform);C(t.warning),T(t.fix),df(i,{data:s,warning:t.warning,fix:t.fix,tray:o});return}let c=sf(i);df(i,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:o})}),s}catch(e){throw t.aborted||(a||(d(null),_(!0),C(null),T(null)),D(!1),p(!1)),e}},[e,i,r]),I=mf(o,[e],F,{isEmpty:()=>!1,initialData:a?.data??void 0}),L=I.state,R=I.refresh,z=L.data??a?.data??null,B=L.refreshing,V=!!z?.diagnosticStale||L.showError,H=z!==null&&kf(z,V)===`unverified`;Uq(!!z?.desktop),(0,Z.useEffect)(()=>{if(!z?.diagnosticStale)return;let e=window.setTimeout(R,2e3);return()=>window.clearTimeout(e)},[z,R]);let U=async e=>{try{await navigator.clipboard.writeText(e),l(e),window.setTimeout(()=>l(t=>t===e?null:t),1600)}catch{l(null)}},W=async t=>{h(!0),_(!1);try{let n=await fetch(`${e}/api/windows-tray`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t})});if(!n.ok)throw Error(`tray action failed`);let r=await n.json();if(!Kq(r.status))throw Error(`invalid tray action status`);d(r.status),_(!1)}catch{d(null),_(!0)}finally{h(!1)}},ee=async(t,n)=>{y(t),x(null);try{let r=await fetch(`${e}/api/startup-action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t,repair:n?.repair===!0})});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(typeof e?.error==`string`?e.error:`installation failed`)}x({kind:`success`,action:t,repair:n?.repair===!0}),R()}catch(e){x({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:z?.localRoutingDependency===!0})}finally{y(null)}};return(0,Q.jsxs)(`div`,{className:`startup-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Q.jsx)(Vq,{title:r(`startup.title`),actions:(0,Q.jsxs)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>R(),disabled:B,children:[(0,Q.jsx)(Ke,{}),` `,r(`startup.refresh`)]})}),n&&(0,Q.jsxs)(Fq,{tone:A?.healthy?`ok`:`warn`,className:`startup-machine`,action:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,disabled:M,onClick:()=>void P(`repair`),children:r(`connection.machine.repairShim`)}),A?.installed&&(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,disabled:M,onClick:()=>void P(`uninstall`),children:r(`connection.machine.removeShim`)})]}),children:[(0,Q.jsx)(`strong`,{className:`font-semibold`,children:r(`connection.machine.title`)}),` `,(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:A?.healthy?r(`connection.machine.shimHealthy`):r(`connection.machine.shimNeedsAttention`)})]}),L.showSkeleton&&!z?(0,Q.jsx)(ck,{label:r(`startup.loading`),rows:5}):L.kind===`failed-cold`?(0,Q.jsx)(Fq,{tone:`err`,action:(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:()=>R(),children:r(`common.retry`)}),children:L.error instanceof Error?L.error.message:r(`startup.error`)}):z?(0,Q.jsxs)(Q.Fragment,{children:[L.showError&&!H&&(0,Q.jsx)(Fq,{tone:`err`,children:r(`startup.error`)}),V&&!H&&(0,Q.jsx)(Fq,{tone:`warn`,role:`alert`,children:r(`startup.staleData`)}),(E||S)&&(0,Q.jsx)(`div`,{className:X(`startup-runtime-slot`,E&&!S&&`min-h-[60px]`),"aria-hidden":E&&!S?!0:void 0,children:S&&(0,Q.jsxs)(Fq,{tone:`warn`,className:`startup-runtime-notice`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:S}),w&&(0,Q.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 rounded-[8px] bg-bg py-1 pr-1 pl-3 ring-1 ring-line`,children:[(0,Q.jsx)(`code`,{className:`min-w-0 flex-1 font-mono text-[12.5px] text-fg-muted [overflow-wrap:anywhere]`,children:w}),(0,Q.jsx)(Lq,{copied:c===w,onCopy:()=>void U(w)})]})]})}),(0,Q.jsx)(Zq,{failed:V,data:z}),(0,Q.jsx)(Qq,{data:z,failed:V,loading:B,installBusy:v,installResult:b,onInstall:(e,t)=>{ee(e,t)},tray:z.platform===`win32`?(0,Q.jsx)($q,{tray:u,trayLoading:f,trayError:g,trayBusy:m,onTrayAction:e=>{W(e)}}):null}),(0,Q.jsx)(eJ,{data:z,copied:c,onCopy:e=>{U(e)}})]}):null]})}function aJ(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function oJ(e){return`'${e.replace(/'/g,`''`)}'`}function sJ(e,t){return{posix:`printf '%s\\n' ${aJ(e)} | ocx remote-workspace pair ${aJ(t)} --pairing-code-stdin --root "$PWD" && ocx remote-workspace agent`,powershell:`$pairingCode = ${oJ(e)}; $pairingCode | ocx remote-workspace pair ${oJ(t)} --pairing-code-stdin --root (Get-Location).Path; if ($LASTEXITCODE -eq 0) { ocx remote-workspace agent }`}}var cJ=[`codex`,`claude`,`pi`],lJ={codex:`Codex`,claude:`Claude Code`,pi:`Pi`},uJ={starting:`remote.status.starting`,ready:`remote.status.ready`,running:`remote.status.running`,waiting_for_executor:`remote.status.waiting`,failed:`remote.status.failed`,stopped:`remote.status.stopped`},dJ={status:`remote.event.status`,tool:`remote.event.tool`,error:`remote.event.error`},fJ=8,pJ=e=>e?e.type===`pane`?[e.sessionId]:[...pJ(e.first),...pJ(e.second)]:[],mJ=e=>({type:`pane`,sessionId:e});function hJ(e){if(e.type===`pane`)return 260;let t=hJ(e.first),n=hJ(e.second);return e.axis===`row`?t+fJ+n:Math.max(t,n)}function gJ(e,t){if(!e)return null;if(e.type===`pane`)return e.sessionId===t?null:e;let n=gJ(e.first,t),r=gJ(e.second,t);return n?r?n===e.first&&r===e.second?e:{...e,first:n,second:r}:n:r}function _J(e,t,n){return e.type===`pane`?e.sessionId===t?n:e:{...e,first:_J(e.first,t,n),second:_J(e.second,t,n)}}function vJ(e,t,n){return e?pJ(e).includes(t)?e:_J(e,pJ(e).includes(n)?n:pJ(e)[0],mJ(t)):mJ(t)}function yJ(e,t,n,r){if(!e)return mJ(t);let i=pJ(e);if(t===n||!i.includes(n)||i.length>=4&&!i.includes(t))return e;let a=gJ(e,t),o=r===`left`||r===`up`,s=new Set,c=e=>{e.type!==`pane`&&(s.add(e.id),c(e.first),c(e.second))};c(a);let l=1;for(;s.has(`split-${l}`);)l++;return _J(a,n,{type:`split`,id:`split-${l}`,axis:r===`left`||r===`right`?`row`:`column`,ratio:.5,first:mJ(o?t:n),second:mJ(o?n:t)})}function bJ(e,t,n){return e.type===`pane`?e:e.id===t?{...e,ratio:Math.min(.8,Math.max(.2,n))}:{...e,first:bJ(e.first,t,n),second:bJ(e.second,t,n)}}function xJ(e,t,n){let r=new Set(t),i=e;for(let t of pJ(e))r.has(t)||(i=gJ(i,t));return i??(n&&r.has(n)?mJ(n):t.length?mJ(t[t.length-1]):null)}function SJ(e){if(!e||e.length>8192)return null;let t=new Set,n=new Set;function r(e,i){if(!e||typeof e!=`object`||i>4)return null;let a=e;if(a.type===`pane`&&typeof a.sessionId==`string`&&a.sessionId.length>0&&a.sessionId.length<200&&!t.has(a.sessionId))return t.add(a.sessionId),t.size<=4?mJ(a.sessionId):null;if(a.type!==`split`||typeof a.id!=`string`||a.id.length>400||a.axis!==`row`&&a.axis!==`column`||typeof a.ratio!=`number`||!Number.isFinite(a.ratio)||n.has(a.id))return null;n.add(a.id);let o=r(a.first,i+1),s=r(a.second,i+1);return o&&s?{type:`split`,id:a.id,axis:a.axis,ratio:Math.min(.8,Math.max(.2,a.ratio)),first:o,second:s}:null}try{return r(JSON.parse(e),0)}catch{return null}}function CJ(e,t,n,r,i){let a=b(),[o,s]=(0,Z.useState)({}),[c,l]=(0,Z.useState)({}),[u,d]=(0,Z.useState)({}),[f,p]=(0,Z.useState)({}),m=(0,Z.useRef)(new Set),h=(0,Z.useRef)(new Set),g=(0,Z.useRef)(new Set),_=t.map(e=>{let t=c[e.id];return t?.status===`stopped`?{...e,status:`stopped`}:t&&(t.events.at(-1)?.sequence??0)>(e.events.at(-1)?.sequence??0)?t:e}),v=(e,t)=>s(n=>({...n,[e]:t})),y=(e,t)=>p(n=>({...n,[e]:t})),x=(e,t,n)=>d(r=>({...r,[e]:{...r[e],[t]:n}})),S=e=>!(!(o[e.id]??``).trim()||u[e.id]?.prompt||u[e.id]?.stop||r||e.status===`running`||e.status===`starting`||e.status===`stopped`||e.status===`failed`&&e.resumable===!1||e.status===`waiting_for_executor`&&!n.find(t=>t.id===e.deviceId)?.online);return{sessions:_,drafts:o,setDraft:v,pending:u,errors:f,canSend:S,send:async t=>{let n=t.id;if(!S(t)||h.current.has(n)||g.current.has(n))return;let r=o[n]??``;h.current.add(n),x(n,`prompt`,!0),y(n,``);let c;try{let t=await fetch(`${e}/api/remote-workspace/sessions/${n}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({prompt:r})});c=t.status;let o=await Yn(t,a(`remote.requestFailed`));if(!o)throw Error(a(`remote.requestFailed`));s(e=>e[n]===r?{...e,[n]:``}:e),m.current.has(n)||l(e=>({...e,[n]:o})),i()}catch(e){m.current.has(n)||(y(n,c!==void 0&&c>=400&&c<500?e instanceof Error?e.message:a(`remote.requestFailed`):a(`remote.submissionUnknown`)),i())}finally{h.current.delete(n),x(n,`prompt`,!1)}},stop:async t=>{let n=t.id;if(!(g.current.has(n)||t.status===`stopped`)){g.current.add(n),x(n,`stop`,!0);try{await Yn(await fetch(`${e}/api/remote-workspace/sessions/${n}`,{method:`DELETE`}),a(`remote.requestFailed`)),m.current.add(n),l(e=>({...e,[n]:{...t,status:`stopped`}})),i()}catch(e){y(n,e instanceof Error?e.message:a(`remote.requestFailed`))}finally{g.current.delete(n),x(n,`stop`,!1)}}}}}var wJ=`application/x-opencodex-session`,TJ=[`left`,`right`,`up`,`down`],EJ=e=>e.type===`split`?hJ(e):0;function DJ({node:e,renderPane:t,resize:n}){let r=b(),i=(0,Z.useRef)(null),a=(0,Z.useRef)(!1);if(e.type===`pane`)return t(e.sessionId);let o={"--split-ratio":e.ratio,"--split-min-width":hJ(e),"--split-first-min":EJ(e.first),"--split-second-min":EJ(e.second)};return(0,Q.jsxs)(`div`,{ref:i,className:`remote-split-branch remote-split-branch--${e.axis}`,style:o,children:[(0,Q.jsx)(`div`,{className:`remote-split-child`,children:(0,Q.jsx)(DJ,{node:e.first,renderPane:t,resize:n})}),(0,Q.jsx)(`div`,{role:`separator`,tabIndex:0,className:`remote-split-divider`,"aria-label":r(`remote.split.resize`),"aria-orientation":e.axis===`row`?`vertical`:`horizontal`,"aria-valuemin":20,"aria-valuemax":80,"aria-valuenow":Math.round(e.ratio*100),onPointerDown:e=>{e.button===0&&(e.preventDefault(),e.currentTarget.focus(),a.current=!0,e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:t=>{if(!a.current||!i.current)return;let r=i.current.getBoundingClientRect(),o=e.axis===`row`?r.width:r.height;o>0&&n(e.id,(e.axis===`row`?t.clientX-r.left:t.clientY-r.top)/o)},onPointerUp:e=>{a.current=!1,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{a.current=!1},onLostPointerCapture:()=>{a.current=!1},onKeyDown:t=>{let r=e.axis===`row`?`ArrowLeft`:`ArrowUp`;[r,e.axis===`row`?`ArrowRight`:`ArrowDown`,`Home`,`End`].includes(t.key)&&(t.preventDefault(),n(e.id,t.key===`Home`?.2:t.key===`End`?.8:e.ratio+(t.key===r?-.05:.05)))}}),(0,Q.jsx)(`div`,{className:`remote-split-child`,children:(0,Q.jsx)(DJ,{node:e.second,renderPane:t,resize:n})})]})}function OJ({apiBase:e,sessions:t,devices:n,selectedSessionId:r,stale:i,refresh:a}){let o=b(),s=`ocx-remote-workspace-layout:${e}`,[c,l]=(0,Z.useState)(()=>{try{return SJ(localStorage.getItem(s))}catch{return null}}),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(r),x=(0,Z.useRef)(null),S=CJ(e,t,n,i,a),C=S.sessions.map(e=>e.id),w=xJ(c,C,[...S.sessions].reverse().find(e=>e.status!==`stopped`)?.id??C.at(-1)),T=pJ(w),E=T.includes(u)?u:T[0]??``;v===r?c!==w&&l(w):(y(r),r&&C.includes(r)&&(l(vJ(w,r,E)),d(r))),(0,Z.useEffect)(()=>{try{localStorage.setItem(s,JSON.stringify(w))}catch{}},[w,s]),(0,Z.useEffect)(()=>{g&&[...x.current?.querySelectorAll(`[data-pane-heading]`)??[]].find(e=>e.dataset.paneHeading===g.id)?.focus()},[g]);let D=e=>{l(vJ(w,e,E)),d(e)},O=(e,t,n)=>{if(!C.includes(e))return;let r=yJ(w,e,t,n);l(r),pJ(r).includes(e)&&d(e),p(null),h(null)},k=e=>{let t=gJ(w,e),n=pJ(t)[0]??``;l(t),d(n),_({id:n})},A=(e,t)=>{e.dataTransfer.setData(wJ,t),e.dataTransfer.effectAllowed=`move`,p(t)},j=()=>{p(null),h(null)},M=(e,t)=>e!==t&&(T.includes(e)||T.length<4);return(0,Q.jsxs)(`section`,{ref:x,className:`remote-chats-workspace`,"aria-label":o(`remote.split.title`),children:[(0,Q.jsxs)(`div`,{className:`remote-chats-toolbar`,children:[(0,Q.jsx)(`h3`,{children:o(`remote.sessions`)}),(0,Q.jsx)(`p`,{children:o(`remote.split.hint`)})]}),(0,Q.jsxs)(`div`,{className:`remote-chats-layout`,children:[(0,Q.jsxs)(`aside`,{className:`remote-session-rail`,"aria-label":o(`remote.sessions`),children:[S.sessions.map(e=>(0,Q.jsxs)(`div`,{className:`remote-session-row${E===e.id?` is-active`:``}`,draggable:!0,onDragStart:t=>A(t,e.id),onDragEnd:j,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`remote-session-open`,"data-session-open":e.id,"aria-pressed":E===e.id,title:o(`remote.split.open`),onClick:()=>D(e.id),children:[(0,Q.jsx)(Be,{}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[lJ[e.profile],` · `,e.rootLabel]}),(0,Q.jsxs)(`small`,{children:[e.deviceName,` · `,o(uJ[e.status])]})]})]}),(0,Q.jsxs)(`div`,{className:`remote-session-split-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,title:o(`remote.split.right`),"aria-label":o(`remote.split.right`),disabled:!E||!M(e.id,E),onClick:()=>O(e.id,E,`right`),children:(0,Q.jsx)(lt,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,title:o(`remote.split.down`),"aria-label":o(`remote.split.down`),disabled:!E||!M(e.id,E),onClick:()=>O(e.id,E,`down`),children:(0,Q.jsx)(Ot,{})})]})]},e.id)),T.length>=4?(0,Q.jsx)(`p`,{className:`remote-split-limit`,children:o(`remote.split.limit`)}):null]}),(0,Q.jsx)(`div`,{className:`remote-pane-surface`,children:w?(0,Q.jsx)(DJ,{node:w,renderPane:e=>{let t=S.sessions.find(t=>t.id===e);if(!t)return null;let n=t.status===`stopped`||t.status===`failed`&&t.resumable===!1;return(0,Q.jsxs)(`section`,{className:`remote-chat-pane remote-console-panel${e===E?` is-active`:``}`,"data-session-id":e,"aria-label":`${lJ[t.profile]} · ${t.deviceName}/${t.rootLabel}`,onFocusCapture:()=>d(e),onPointerDown:()=>d(e),children:[(0,Q.jsxs)(`header`,{className:`remote-chat-pane-head`,children:[(0,Q.jsxs)(`div`,{tabIndex:-1,"data-pane-heading":e,className:`remote-chat-pane-name`,draggable:!0,onDragStart:t=>A(t,e),onDragEnd:j,children:[(0,Q.jsx)(Be,{}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:lJ[t.profile]}),(0,Q.jsxs)(`small`,{children:[t.deviceName,`/`,t.rootLabel]})]})]}),(0,Q.jsx)(`span`,{className:`remote-status remote-status--${t.status}`,children:o(uJ[t.status])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm remote-pane-close`,"aria-label":o(`remote.split.close`),title:o(`remote.split.close`),disabled:T.length===1,onClick:()=>k(e),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`small`,{className:`remote-chat-access`,children:t.accessMode===`read-only`?o(`remote.access.readOnly`):t.capabilities.includes(`workspace.exec`)?o(`remote.access.workspace`):o(`remote.access.workspaceFilesOnly`)}),(0,Q.jsx)(`div`,{className:`remote-events`,"aria-live":`polite`,"aria-label":o(`remote.events`),children:t.events.length===0?(0,Q.jsx)(`p`,{className:`remote-empty`,children:o(`remote.noEvents`)}):t.events.map(e=>(0,Q.jsxs)(`div`,{className:`remote-event remote-event--${e.type}`,children:[(0,Q.jsx)(`span`,{children:e.type===`assistant`?lJ[t.profile]:o(dJ[e.type])}),(0,Q.jsx)(`p`,{children:e.text})]},e.sequence))}),t.status===`failed`&&t.resumable===!1?(0,Q.jsx)($,{tone:`err`,children:o(`remote.notResumable`)}):null,S.errors[e]?(0,Q.jsx)($,{tone:`err`,children:S.errors[e]}):null,(0,Q.jsxs)(`label`,{className:`remote-composer`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:o(`remote.prompt`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:3,value:S.drafts[e]??``,onChange:t=>S.setDraft(e,t.target.value),placeholder:o(`remote.promptPlaceholder`),disabled:n,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),S.send(t))}})]}),(0,Q.jsxs)(`div`,{className:`remote-console-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!S.canSend(t),onClick:()=>void S.send(t),children:o(`remote.send`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:S.pending[e]?.stop||t.status===`stopped`,onClick:()=>void S.stop(t),children:o(`remote.stop`)})]}),f&&M(f,e)?(0,Q.jsx)(`div`,{className:`remote-pane-drop-targets`,children:TJ.map(t=>(0,Q.jsx)(`div`,{className:`remote-pane-drop remote-pane-drop--${t}${m?.id===e&&m.edge===t?` is-over`:``}`,onDragOver:n=>{n.preventDefault(),n.dataTransfer.dropEffect=`move`,h({id:e,edge:t})},onDrop:n=>{n.preventDefault();let r=n.dataTransfer.getData(wJ);r===f?O(r,e,t):j()},children:o(`remote.split.${t}`)},t))}):null]},e)},resize:(e,t)=>l(bJ(w,e,t))}):(0,Q.jsx)(`p`,{className:`remote-empty remote-empty--console`,children:o(`remote.noSessions`)})})]})]})}function kJ(e){return e===`codex`||e===`claude`||e===`pi`}function AJ(e){return e===`read-only`||e===`workspace`}async function jJ(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function MJ(e,t){return(0,Q.jsxs)(`label`,{className:`flex min-w-0 flex-col gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-[12px] leading-4 font-medium text-fg-muted`,children:e}),t]})}function NJ({apiBase:e,hubOrigin:t}){let n=b(),r=bn(`remote-workspace:${e}`,[e],async t=>await Yn(await fetch(`${e}/api/remote-workspace`,{signal:t,cache:`no-store`}),n(`remote.loadFailed`)),{pollMs:3e3,deadlineMs:1e4}),i=r.data,[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(`codex`),[d,f]=(0,Z.useState)(`read-only`),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),E=i?.devices??[],D=E.find(e=>e.id===a)??E.find(e=>e.online)??E[0]??null,O=D?.roots.find(e=>e.id===s)??D?.roots[0]??null,k=d===`workspace`&&(D?.capabilities.includes(`workspace.exec`)??!1),A=D&&!D.capabilities.includes(`workspace.exec`)?n(`remote.access.workspaceFilesOnly`):n(`remote.access.workspace`),j=cJ.filter(e=>i?.runtimes?.[e]?.available),M=j.includes(l)?l:j[0]??l,N=i?.sessions??[],P=h&&!N.some(e=>e.id===h.id)?[...N,h]:N;h&&i?.sessions.some(e=>e.id===h.id)&&g(null);let F=!(!i||r.lastAttemptOk),I=(0,Z.useMemo)(()=>_?sJ(_.code,t):{posix:``,powershell:``},[_,t]),L=async(t,n,r)=>{let i=await Yn(await fetch(`${e}${t}`,n),r);if(i===void 0)throw Error(r);return i},R=async()=>{x(`pair`),C(null);try{let e=await L(`/api/remote-workspace/pairing`,{method:`POST`},n(`remote.requestFailed`));v(e),T(null)}catch(e){C({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{x(null)}},z=async()=>{if(D&&O){x(`session`),C(null);try{let e=await L(`/api/remote-workspace/sessions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:M,deviceId:D.id,rootId:O.id,accessMode:d})},n(`remote.requestFailed`));g(e),m(e.id),C({tone:`ok`,text:n(`remote.sessionStarted`)}),r.refresh()}catch(e){C({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{x(null)}}},B=async e=>{if(await Ju({message:n(`remote.revokeConfirm`,{name:e.name}),confirmLabel:n(`common.remove`),tone:`danger`})){x(`revoke`);try{await L(`/api/remote-workspace/devices/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),a===e.id&&o(``),r.refresh()}catch(e){C({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{x(null)}}},V=async(e,t)=>{T(await jJ(t)?e:null)};return!i&&!r.error?(0,Q.jsx)(Fq,{tone:`info`,children:n(`remote.loading`)}):r.error&&!i?(0,Q.jsx)(Fq,{tone:`err`,action:(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:()=>void r.refresh(),children:n(`common.retry`)}),children:n(`remote.loadFailed`)}):i?.available===!1?(0,Q.jsx)(Fq,{tone:`err`,children:n(`remote.hubRequired`)}):(0,Q.jsxs)(`section`,{className:`remote-workspace-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Q.jsx)(Vq,{title:n(`remote.title`),subtitle:n(`remote.subtitle`),actions:(0,Q.jsxs)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>void r.refresh(),disabled:r.refreshing,children:[(0,Q.jsx)(Ke,{}),` `,n(`remote.refresh`)]})}),F?(0,Q.jsx)(Fq,{tone:`err`,children:n(`remote.loadFailed`)}):null,S?(0,Q.jsx)(Fq,{tone:S.tone,children:S.text}):null,(0,Q.jsxs)(`div`,{className:`grid min-w-0 items-start gap-4 lg:grid-cols-[minmax(280px,0.85fr)_minmax(0,1.3fr)]`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,Q.jsx)(Mq,{icon:(0,Q.jsx)(ue,{}),title:n(`remote.addComputer`),description:n(`remote.addComputerHint`),children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(Jp,{variant:`outline`,className:`self-start`,onClick:()=>void R(),disabled:y!==null,children:[(0,Q.jsx)(Vt,{}),` `,n(`remote.createPairing`)]}),_?(0,Q.jsxs)(`div`,{className:`remote-pairing-result flex flex-col gap-3 border-t border-line pt-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Q.jsx)(`span`,{className:`text-[12px] font-medium text-fg-muted`,children:n(`remote.pairingCode`)}),(0,Q.jsx)(`span`,{className:`font-mono text-[24px] leading-8 font-semibold tracking-[0.1em] text-fg`,children:_.code}),(0,Q.jsx)(`span`,{className:`text-[12px] text-fg-subtle`,children:n(`remote.pairingExpires`,{time:new Date(_.expiresAt).toLocaleTimeString()})})]}),[[`posix`,n(`remote.pairingCommandPosix`),I.posix],[`powershell`,n(`remote.pairingCommandWindows`),I.powershell]].map(([e,t,r])=>(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-[12px] font-medium text-fg-muted`,children:t}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-start gap-1 rounded-[8px] bg-surface py-1 pr-1 pl-3 ring-1 ring-line`,children:[(0,Q.jsx)(`pre`,{className:`m-0 min-w-0 flex-1 py-1.5 font-mono text-[12px] leading-[18px] whitespace-pre-wrap text-fg [overflow-wrap:anywhere]`,children:(0,Q.jsx)(`code`,{children:r})}),(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>void V(e,r),children:n(w===e?`remote.copied`:`remote.copyCommand`)})]})]},e))]}):null]})}),(0,Q.jsx)(Mq,{title:n(`remote.devices`),meta:E.length,children:E.length===0?(0,Q.jsx)(`p`,{className:`m-0 px-4 py-6 text-center text-[13px] text-fg-muted`,children:n(`remote.noDevices`)}):(0,Q.jsx)(`ul`,{className:`m-0 flex list-none flex-col gap-1 p-1`,children:E.map(e=>{let t=D?.id===e.id;return(0,Q.jsxs)(`li`,{className:X(`remote-device flex min-w-0 items-center gap-1 rounded-[8px] pr-1 transition-colors hover:bg-surface`,t&&`bg-surface ring-1 ring-line-strong`),children:[(0,Q.jsxs)(`button`,{type:`button`,"aria-pressed":t,onClick:()=>{o(e.id),c(e.roots[0]?.id??``)},className:`ui-v2 flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-[8px] px-3 py-2.5 text-left focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-highlight`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`size-2 shrink-0 rounded-full`,e.online?`bg-success`:`bg-fg-subtle`)}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-col`,children:[(0,Q.jsx)(`strong`,{className:`truncate text-[14px] font-semibold`,children:e.name}),(0,Q.jsxs)(`small`,{className:`truncate text-[12px] text-fg-muted`,children:[e.platform,` · `,e.online?n(`remote.online`):n(`remote.offline`),` · `,e.capabilities.includes(`workspace.exec`)?n(`remote.capability.full`):n(`remote.capability.files`)]})]}),t&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`ml-auto text-fg [&_svg]:size-4`,children:(0,Q.jsx)(st,{})})]}),(0,Q.jsx)(Iq,{label:n(`remote.revoke`),tone:`danger`,disabled:y!==null,onClick:()=>void B(e),children:(0,Q.jsx)(et,{})})]},e.id)})})})]}),(0,Q.jsx)(Mq,{icon:(0,Q.jsx)(Oe,{}),title:n(`remote.newSession`),children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[MJ(n(`remote.device`),(0,Q.jsx)(Vn,{fullWidth:!0,value:D?.id??``,options:E.map(e=>({value:e.id,label:e.name})),onChange:e=>{o(e),c(E.find(t=>t.id===e)?.roots[0]?.id??``)},label:n(`remote.device`),disabled:E.length===0})),MJ(n(`remote.folder`),(0,Q.jsx)(Vn,{fullWidth:!0,value:O?.id??``,options:(D?.roots??[]).map(e=>({value:e.id,label:e.label})),onChange:c,label:n(`remote.folder`),disabled:!D})),MJ(n(`remote.runtime`),(0,Q.jsx)(Vn,{fullWidth:!0,value:M,options:cJ.map(e=>({value:e,label:i?.runtimes?.[e]?.available?lJ[e]:`${lJ[e]} · ${n(`remote.unavailable`)}`})),onChange:e=>{kJ(e)&&u(e)},label:n(`remote.runtime`)})),MJ(n(`remote.access`),(0,Q.jsx)(Vn,{fullWidth:!0,value:d,options:[{value:`read-only`,label:n(`remote.access.readOnly`)},{value:`workspace`,label:A}],onChange:e=>{AJ(e)&&f(e)},label:n(`remote.access`)}))]}),D?(0,Q.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[[lJ[M],n(`remote.runsOnHub`)],[D.name,n(d===`read-only`?`remote.runsReadOnly`:k?`remote.runsFilesCommands`:`remote.runsFilesOnly`)]].map(([e,t])=>(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-0.5 rounded-[8px] bg-surface px-3 py-2.5 text-[12px] text-fg-muted ring-1 ring-line`,children:[(0,Q.jsx)(`strong`,{className:`truncate text-[13px] font-semibold text-fg`,children:e}),t]},t))}):null,d===`workspace`&&!k&&D?(0,Q.jsx)(Fq,{tone:`err`,children:n(`remote.execUnavailable`)}):null,!i?.runtimes?.[M]?.available&&i?.runtimes?.[M]?.reason?(0,Q.jsx)(`p`,{className:`m-0 text-[12px] leading-[18px] text-danger`,children:i.runtimes[M].reason}):null,(0,Q.jsxs)(Jp,{variant:`primary`,className:`w-full`,onClick:()=>void z(),disabled:!D?.online||!O||!i?.runtimes?.[M]?.available||y!==null,children:[(0,Q.jsx)(Qe,{}),` `,n(`remote.startSession`)]})]})})]}),(0,Q.jsx)(OJ,{apiBase:e,sessions:P,devices:E,selectedSessionId:p,stale:F,refresh:r.refresh},e)]})}var PJ=(0,Q.jsx)(Pc,{icon:Vc,size:18,strokeWidth:1.8,"aria-hidden":`true`}),FJ=(0,Q.jsx)(Pc,{icon:Uc,size:18,strokeWidth:1.8,"aria-hidden":`true`});function IJ({on:e,onToggle:t,disabled:n}){let r=b();return(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`remote-link-switch shrink-0`,"aria-checked":e,"aria-label":r(`link.switch`),onClick:t,disabled:n})}function LJ({on:e,onToggle:t,hint:n}){let r=b();return(0,Q.jsxs)(`div`,{className:`flex items-center gap-4 px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-2 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:[r(`link.switch`),(0,Q.jsx)(`span`,{className:X(`rounded-full px-1.5 text-[11px] leading-[18px] font-semibold`,e?`bg-accent text-on-accent`:`bg-surface-2 text-fg-muted`),children:r(e?`startupV2.on`:`startupV2.off`)})]}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:n})]}),(0,Q.jsx)(IJ,{on:e,onToggle:t})]})}function RJ(e,t,n){return(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-start gap-3 rounded-[10px] bg-surface px-3.5 py-3 ring-1 ring-line`,children:[(0,Q.jsx)(Nq,{children:e}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Q.jsx)(`span`,{className:`text-[14px] leading-5 font-semibold text-fg`,children:t}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:n})]})]})}function zJ({onTurnOn:e}){let t=b();return(0,Q.jsxs)(`section`,{className:`remote-link-intro flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,"aria-label":t(`link.switch`),children:[(0,Q.jsx)(LJ,{on:!1,onToggle:e,hint:t(`link.switchOffHint`)}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-5 rounded-[8px] bg-bg p-5 ring-1 ring-line`,children:[(0,Q.jsxs)(`div`,{className:`flex max-w-[68ch] flex-col gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`m-0 text-[17px] leading-6 font-semibold tracking-[-0.015em] text-fg`,children:t(`startupV2.linkIntroTitle`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[14px] leading-[21px] text-fg-muted`,children:t(`startupV2.linkIntroBody`)})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col items-stretch gap-2 sm:flex-row sm:items-center`,children:[RJ(PJ,t(`link.role.home`),t(`link.role.homeHint`)),(0,Q.jsxs)(`div`,{"aria-hidden":`true`,className:`flex shrink-0 items-center justify-center gap-2 px-1 text-[11px] font-medium text-fg-subtle sm:flex-col sm:gap-1`,children:[(0,Q.jsx)(`span`,{className:`hidden h-px w-10 bg-line-strong sm:block`}),t(`startupV2.sshTunnel`),(0,Q.jsx)(`span`,{className:`hidden h-px w-10 bg-line-strong sm:block`})]}),RJ(FJ,t(`link.role.child`),t(`link.role.childHint`))]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1 border-t border-line pt-4 text-[13px] leading-5 text-fg-muted`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 flex-1`,children:t(`link.setup.requirements`)}),(0,Q.jsxs)(`a`,{href:`https://opencodex.me/guides/remote-link/`,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 font-medium text-highlight hover:underline [&_svg]:size-3.5`,children:[t(`link.setup.guide`),(0,Q.jsx)(dt,{"aria-hidden":`true`})]})]})]})]})}function BJ({role:e,checked:t,disabled:n,tabIndex:r,onSelect:i,onKeyDown:a,buttonRef:o}){let s=b();return(0,Q.jsxs)(`button`,{ref:o,type:`button`,role:`radio`,tabIndex:r,"aria-checked":t,"aria-disabled":n,onClick:i,onKeyDown:a,className:X(`remote-link-role-card ui-v2 group flex min-w-0 cursor-pointer items-start gap-3 rounded-[10px] bg-surface p-4 text-left ring-1 ring-line transition-[box-shadow,background-color]`,`hover:bg-raised focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,t&&`bg-raised ring-2 ring-fg`,n&&`cursor-not-allowed opacity-60 hover:bg-surface`),children:[(0,Q.jsx)(Nq,{children:e===`home`?PJ:FJ}),(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsx)(`span`,{className:`text-[14px] leading-5 font-semibold text-fg`,children:s(e===`home`?`link.role.home`:`link.role.child`)}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:s(e===`home`?`link.role.homeHint`:`link.role.childHint`)})]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`mt-0.5 grid size-[18px] shrink-0 place-items-center rounded-full ring-1 ring-line-strong [&_svg]:size-3`,t&&`bg-fg text-bg ring-fg`),children:t&&(0,Q.jsx)(st,{})})]})}var VJ={connected:`bg-success`,reconnecting:`bg-warning`,connecting:`bg-warning`,failed:`bg-danger`,idle:`bg-fg-subtle`};function HJ({state:e,children:t}){return(0,Q.jsxs)(`span`,{className:X(`remote-link-status inline-flex items-center gap-1.5 text-[13px] leading-5 font-medium`,e===`failed`?`text-danger`:`text-fg`),"data-state":e,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:X(`size-2 shrink-0 rounded-full`,VJ[e]??VJ.idle)}),t]})}function UJ({name:e}){let t=e.replace(/[^\p{L}\p{N}]/gu,``).slice(0,2).toUpperCase()||`?`;return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`grid size-8 shrink-0 place-items-center rounded-[8px] bg-raised font-mono text-[12px] font-medium text-fg ring-1 ring-line-strong`,children:t})}function WJ({step:e}){let t=b(),n=[t(`startupV2.stepHost`),t(`startupV2.stepVerify`),t(`startupV2.stepConnect`)];return(0,Q.jsx)(`ol`,{"aria-label":t(`startupV2.steps`),className:`m-0 flex list-none flex-wrap items-center gap-x-2 gap-y-1 p-0 text-[12px] leading-4`,children:n.map((t,n)=>(0,Q.jsxs)(`li`,{"aria-current":n===e?`step`:void 0,className:`flex items-center gap-2`,children:[n>0&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`h-px w-5 bg-line-strong`}),(0,Q.jsx)(`span`,{className:X(`grid size-5 place-items-center rounded-full text-[11px] font-semibold tabular-nums [&_svg]:size-3`,n<e?`bg-success-soft text-success`:n===e?`bg-accent text-on-accent`:`bg-surface-2 text-fg-muted`),children:n<e?(0,Q.jsx)(st,{"aria-hidden":`true`}):n+1}),(0,Q.jsx)(`span`,{className:X(n===e?`font-medium text-fg`:`text-fg-muted`),children:t})]},t))})}var GJ={child_link_mismatch:`remoteLink.forceRemove.refusal.child_link_mismatch`,child_residual:`remoteLink.forceRemove.refusal.child_residual`,child_disconnect_pending:`remoteLink.forceRemove.refusal.child_disconnect_pending`,expect_link_unsupported:`remoteLink.forceRemove.refusal.expect_link_unsupported`},KJ=`~/.cache/opencodex/bin/ocx-child`;function qJ({removed:e,onDismiss:t}){let n=b(),r={alias:e.alias,linkId:e.id};return(0,Q.jsx)(Fq,{tone:`warn`,className:`remote-link-force-removed`,action:(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:t,children:n(`api.dismiss`)}),children:e.kind===`ephemeral`?(0,Q.jsx)(`span`,{className:`block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.ephemeral`,cmd:`ocx link recover --link-id ${e.id}`,vars:r})}):e.kind===`unknown`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.unknownCheck`,cmd:`ocx disconnect --expect-link ${e.id}`,vars:r})}),(0,Q.jsx)(`span`,{className:`mt-1 block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.unknownLocate`,cmd:`command -v ocx-child`,vars:r})}),(0,Q.jsx)(`span`,{className:`mt-1 block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.unknownLightweight`,cmd:`${KJ} detach --expect-link ${e.id}`,vars:r})}),(0,Q.jsx)(`span`,{className:`mt-1 block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.unknownFallback`,cmd:`ocx connect status --json`,vars:r})}),(0,Q.jsx)(`span`,{className:`mt-1 block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.unknownDisconnect`,cmd:`ocx disconnect`,vars:r})})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.fullBound`,cmd:`ocx disconnect --expect-link ${e.id}`,vars:r})}),(0,Q.jsx)(`span`,{className:`mt-1 block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.fullCheck`,cmd:`ocx connect status`,vars:r})}),(0,Q.jsx)(`span`,{className:`mt-1 block`,children:(0,Q.jsx)(z,{k:`remoteLink.forceRemoved.fullDisconnect`,cmd:`ocx disconnect`,vars:r})})]})})}function JJ({confirmRef:e,confirming:t,purge:n,onPurgeChange:r,forceError:i,busy:a,onClose:o,onConfirm:s}){let c=b(),l=t?.row.childKind===`ephemeral`,u=t!==null&&(t.row.childKind??null)===null,d=l?`ocx link recover --link-id ${t?.row.id??``}`:`ocx disconnect --expect-link ${t?.row.id??``}`,f=t?.force?t.refusal??null:null;return(0,Q.jsx)(`dialog`,{ref:e,"aria-labelledby":`remote-link-confirm-title`,onCancel:e=>{e.preventDefault(),o()},className:`remote-link-confirm-dialog m-auto w-[min(440px,calc(100vw-24px))] rounded-[14px] border-0 bg-surface p-1 text-fg shadow-lg ring-1 ring-line backdrop:bg-black/40`,children:t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-[10px] bg-bg px-5 py-4 ring-1 ring-line`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-confirm-title`,className:`m-0 text-[16px] leading-6 font-semibold tracking-[-0.015em]`,children:t.force?c(f?`remoteLink.forceRemove.refusedTitle`:`remoteLink.forceRemove.title`,{alias:t.row.alias}):c(`link.disconnect`)}),f&&(0,Q.jsx)(`p`,{className:`remote-link-refusal m-0 text-[13px] leading-5 text-fg`,children:c(GJ[f])}),(0,Q.jsx)(`p`,{className:`m-0 text-[14px] leading-[21px] text-fg-muted`,children:t.force?u?c(`remoteLink.forceRemove.unknownBody`,{alias:t.row.alias}):(0,Q.jsx)(z,{k:l?`remoteLink.forceRemove.ephemeralBody`:`remoteLink.forceRemove.body`,cmd:d,vars:{alias:t.row.alias}}):c(l?`remoteLink.disconnect.ephemeralBody`:`link.disconnectConfirm`,{alias:t.row.alias})}),t.force&&!l&&(0,Q.jsx)(`p`,{className:`remote-link-note-id m-0 text-[13px] leading-5 text-fg-muted`,children:c(`remoteLink.forceRemove.noteId`,{linkId:t.row.id})}),!t.force&&l&&(0,Q.jsxs)(`label`,{className:`remote-link-purge-option mt-1 flex cursor-pointer items-start gap-2 rounded-[8px] bg-surface px-3 py-2.5 text-[13px] leading-5 ring-1 ring-line`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`mt-0.5 shrink-0`,checked:n,onChange:e=>r(e.target.checked)}),(0,Q.jsx)(`span`,{children:c(`remoteLink.disconnect.purgeLabel`)})]}),i&&(0,Q.jsx)(`p`,{className:`remote-link-error m-0 text-[13px] text-danger`,role:`alert`,children:c(i)})]}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2 px-2 py-2`,children:[(0,Q.jsx)(Jp,{variant:`ghost`,"data-action":`cancel`,onClick:o,children:c(`link.cancel`)}),(0,Q.jsx)(Jp,{variant:`danger`,"data-action":`confirm`,onClick:s,disabled:a,children:t.force?c(`remoteLink.forceRemove.confirm`):c(l&&n?`remoteLink.disconnect.purgeConfirm`:`link.disconnect`)})]})]})})}var YJ=[`owner_lookup`,`relay_retry`,`relay_failure`,`relay_recovered`,`tunnel_transition`],XJ=`match.mismatch.lookup_error.deadline.stale.unavailable.identity_unknown.identity_mismatch.auth_timeout.auth_failed.transport_error.client_abort.header_timeout.recovered.connected.spawned.stopped.auth.hostkey.forward.remote_forward_conflict.timeout.network.unknown.spawn_failed.listener_unavailable`.split(`.`),ZJ=[`idle`,`connecting`,`connected`,`reconnecting`,`failed`],QJ=864e13;function $J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eY(e,t){return typeof t==`string`&&e.includes(t)}function tY(e,t=0){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=t}function nY(e,t){if(!$J(e)||!eY(YJ,e.event)||!eY(XJ,e.outcome))return null;let n={rowKey:`r`+t,event:e.event,outcome:e.outcome};return eY(ZJ,e.previousState)&&(n.previousState=e.previousState),eY(ZJ,e.state)&&(n.state=e.state),tY(e.attempt)&&(n.attempt=e.attempt),tY(e.tunnelPort,1)&&e.tunnelPort<=65535&&(n.tunnelPort=e.tunnelPort),tY(e.timestamp)&&e.timestamp<=QJ&&(n.timestamp=e.timestamp),tY(e.suppressed,1)&&(n.suppressed=e.suppressed),n}function rY(e){if(!$J(e)||!Array.isArray(e.records)||!tY(e.matched)||!tY(e.skipped))throw Error(`invalid link diagnostics response`);let t=Array.isArray(e.files)?e.files.filter($J):[];return{records:e.records.map((e,t)=>nY(e,t)).filter(e=>e!==null),matched:e.matched,skipped:e.skipped,truncated:t.some(e=>e.truncated===!0),refused:t.some(e=>e.state===`refused`),unreadable:t.some(e=>e.state===`unreadable`)}}async function iY(e,t){return rY(await gV(e,`/api/link/diagnostics?limit=100`,{signal:t}))}var aY=(0,Q.jsx)(`span`,{className:`text-fg-subtle`,children:`—`}),oY=new Map;function sY(e,t){let n=oY.get(e);return n||(n=new Intl.DateTimeFormat(e,{dateStyle:`short`,timeStyle:`medium`}),oY.set(e,n)),n.format(new Date(t))}function cY(e){return e.previousState&&e.state?e.previousState+` → `+e.state:e.state??null}function lY({apiBase:e}){let{t,locale:n}=s(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)({kind:`idle`}),c=(0,Z.useRef)(null),l=(0,Z.useRef)(0),u=(0,Z.useCallback)(async()=>{c.current?.controller.abort();let t={controller:new AbortController,sequence:++l.current};c.current=t,o({kind:`loading`});try{let n=await iY(e,t.controller.signal);c.current===t&&o({kind:`ready`,view:n})}catch{c.current===t&&o({kind:`error`})}},[e]);return(0,Z.useEffect)(()=>()=>{c.current?.controller.abort(),c.current=null},[]),(0,Q.jsxs)(`section`,{className:`remote-link-panel flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,"aria-labelledby":`remote-link-diagnostics-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-diagnostics-title`,className:`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em]`,children:t(`remoteLinkDiagnostics.title`)}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:t(`remoteLinkDiagnostics.hint`)})]}),r&&(0,Q.jsxs)(Jp,{variant:`ghost`,size:`sm`,"data-action":`link-diagnostics-refresh`,onClick:()=>void u(),disabled:a.kind===`loading`,children:[(0,Q.jsx)(Ke,{}),t(`link.refresh`)]}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,"data-action":`link-diagnostics-toggle`,"aria-expanded":r,"aria-controls":`remote-link-diagnostics-body`,onClick:()=>{let e=!r;i(e),e&&a.kind===`idle`&&u()},children:t(r?`remoteLinkDiagnostics.hide`:`remoteLinkDiagnostics.show`)})]}),r&&(0,Q.jsxs)(`div`,{id:`remote-link-diagnostics-body`,className:`flex min-w-0 flex-col gap-2 rounded-[8px] bg-bg p-3 ring-1 ring-line`,"aria-live":`polite`,children:[a.kind===`loading`&&(0,Q.jsx)(`p`,{"data-state":`loading`,className:`m-0 text-[13px] text-fg-muted`,children:t(`remoteLinkDiagnostics.loading`)}),a.kind===`error`&&(0,Q.jsx)(`div`,{"data-state":`error`,children:(0,Q.jsx)(Fq,{tone:`err`,children:t(`remoteLinkDiagnostics.error`)})}),a.kind===`ready`&&a.view.records.length===0&&(0,Q.jsx)(`p`,{"data-state":`empty`,className:`m-0 px-1 py-3 text-center text-[13px] text-fg-muted`,children:t(`remoteLinkDiagnostics.empty`)}),a.kind===`ready`&&a.view.records.length>0&&(0,Q.jsx)(`div`,{className:`min-w-0 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`w-full border-collapse text-left text-[12px] leading-5`,children:[(0,Q.jsx)(`thead`,{className:`text-fg-muted`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-1 font-medium`,children:t(`remoteLinkDiagnostics.colTime`)}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-1 font-medium`,children:t(`remoteLinkDiagnostics.colEvent`)}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-1 font-medium`,children:t(`remoteLinkDiagnostics.colOutcome`)}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-1 font-medium`,children:t(`remoteLinkDiagnostics.colState`)}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-1 text-right font-medium`,children:t(`remoteLinkDiagnostics.colAttempt`)}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-1 text-right font-medium`,children:t(`remoteLinkDiagnostics.colPort`)})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-line`,children:a.view.records.map(e=>{let r=cY(e);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`whitespace-nowrap px-2 py-1 tabular-nums`,children:e.timestamp===void 0?aY:sY(n,e.timestamp)}),(0,Q.jsx)(`td`,{className:`px-2 py-1`,children:(0,Q.jsx)(`code`,{className:`font-mono`,children:e.event})}),(0,Q.jsxs)(`td`,{className:`px-2 py-1`,children:[(0,Q.jsx)(`code`,{className:`font-mono`,children:e.outcome}),e.suppressed!==void 0&&(0,Q.jsx)(`span`,{className:`ml-2 text-fg-muted`,children:t(`remoteLinkDiagnostics.suppressed`,{count:e.suppressed})})]}),(0,Q.jsx)(`td`,{className:`px-2 py-1`,children:r?(0,Q.jsx)(`code`,{className:`font-mono`,children:r}):aY}),(0,Q.jsx)(`td`,{className:`px-2 py-1 text-right tabular-nums`,children:e.attempt??aY}),(0,Q.jsx)(`td`,{className:`px-2 py-1 text-right tabular-nums`,children:e.tunnelPort??aY})]},e.rowKey)})})]})}),a.kind===`ready`&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-0.5 px-1 text-[12px] leading-5 text-fg-muted`,children:[a.view.records.length>0&&(0,Q.jsx)(`span`,{children:t(`remoteLinkDiagnostics.showing`,{shown:a.view.records.length,total:a.view.matched})}),a.view.skipped>0&&(0,Q.jsx)(`span`,{children:t(`remoteLinkDiagnostics.skipped`,{count:a.view.skipped})}),a.view.truncated&&(0,Q.jsx)(`span`,{children:t(`remoteLinkDiagnostics.truncated`)}),a.view.refused&&(0,Q.jsx)(`span`,{children:t(`remoteLinkDiagnostics.refused`)}),a.view.unreadable&&(0,Q.jsx)(`span`,{children:t(`remoteLinkDiagnostics.unreadable`)})]})]})]})}function uY({error:e}){let t=b();return(0,Q.jsxs)(Fq,{tone:`err`,children:[(0,Q.jsx)(`span`,{className:`remote-link-error`,children:t(e.key)}),e.childStep&&(0,Q.jsxs)(`span`,{className:`remote-link-child-step mt-1 block`,children:[e.childStep.cmd===void 0?t(e.childStep.key):(0,Q.jsx)(z,{k:e.childStep.key,cmd:e.childStep.cmd}),e.childStep.more?.map(e=>(0,Q.jsx)(`span`,{className:`mt-1 block`,children:e.cmd===void 0?t(e.key,e.vars):(0,Q.jsx)(z,{k:e.key,cmd:e.cmd,vars:e.vars})},e.key))]}),e.hint&&(0,Q.jsxs)(`span`,{className:`remote-link-hint mt-1 block text-[12px] text-fg-muted [overflow-wrap:anywhere]`,children:[t(`remoteLink.reason.generic`),` `,(0,Q.jsx)(`code`,{className:`font-mono`,children:e.hint})]})]})}function dY(e){return e.startsWith(`windows-`)?`ocx-child-`+e+`.exe`:`ocx-child-`+e}var fY=`flex flex-col gap-3 rounded-[10px] bg-surface p-4 ring-1 ring-line`;function pY({confirmation:e,isChildFlow:t,childSelectable:n,busy:r,onApplyLink:i,onJoinLink:a}){let o=b();return t?(0,Q.jsxs)(`div`,{className:fY,children:[(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:o(`link.ocxVersion`,{version:e.ocxVersion??``})}),(0,Q.jsx)(Fq,{tone:`warn`,children:o(`remoteLink.findHome.notice`)}),(0,Q.jsx)(Jp,{variant:`primary`,className:`self-start`,onClick:a,disabled:r!==null||!n,children:o(r===`join`?`remoteLink.joining`:`remoteLink.findHome.connect`)})]}):e.runtimeKind===`missing`?e.plantable?(0,Q.jsxs)(`div`,{className:X(fY,`remote-link-plant-card`),children:[(0,Q.jsx)(`h4`,{className:`m-0 text-[14px] leading-5 font-semibold`,children:o(`link.plant.title`)}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 font-mono text-[12px] text-fg`,children:[(0,Q.jsx)(`code`,{children:e.targetTriple??o(`link.plant.unknownArch`)}),(0,Q.jsx)(`code`,{children:mV(e.binarySizeBytes)}),(0,Q.jsx)(`code`,{children:`~/.cache/opencodex/bin/ocx-child`})]}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:o(`link.plant.body`)}),(0,Q.jsx)(Jp,{variant:`primary`,className:`self-start`,onClick:i,disabled:r!==null,children:o(r===`apply`?`link.plant.applying`:`link.plant.apply`)})]}):(0,Q.jsxs)(Fq,{tone:`warn`,children:[o(`link.plant.unavailable`,{arch:e.targetTriple??o(`link.plant.unknownArch`)}),e.plantUnavailableReason===`artifact_not_found`&&e.targetTriple&&(0,Q.jsx)(`span`,{className:`mt-1 block`,children:o(`link.plant.artifactHelp`,{file:dY(e.targetTriple)})})]}):(0,Q.jsxs)(`div`,{className:fY,children:[(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:e.runtimeKind===`ephemeral`?o(`link.ephemeralReady`,{version:e.ocxVersion??``}):o(`link.ocxVersion`,{version:e.ocxVersion??``})}),(0,Q.jsx)(Jp,{variant:`primary`,className:`self-start`,onClick:i,disabled:r!==null,children:o(r===`apply`?`link.applying`:`link.apply`)})]})}function mY({sheetRef:e,role:t,standaloneRuntime:n,childSelectable:r,discovery:i,candidates:a,alias:o,onAliasChange:s,probe:c,checkedFingerprint:l,onCheckedFingerprintChange:u,confirmation:d,busy:f,sheetOpen:p,actionError:m,failedAction:h,onClose:g,onRescan:_,onProbe:v,onConfirmHost:y,onApplyLink:x,onJoinLink:S,onRetryFailedAction:C}){let w=b(),T=t===`child`&&n;return(0,Q.jsxs)(`dialog`,{ref:e,"aria-labelledby":`remote-link-sheet-title`,onCancel:e=>{e.preventDefault(),g()},className:`remote-link-sheet m-auto max-h-[min(800px,calc(100dvh-24px))] w-[min(620px,calc(100vw-24px))] flex-col overflow-hidden rounded-[14px] border-0 bg-surface p-1 text-fg shadow-lg ring-1 ring-line backdrop:bg-black/40 open:flex`,children:[(0,Q.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-[10px] bg-bg ring-1 ring-line`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-col gap-3 border-b border-line px-5 pt-4 pb-3.5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-sheet-title`,className:`m-0 text-[16px] leading-6 font-semibold tracking-[-0.015em]`,children:w(T?`remoteLink.findHome.title`:`link.sheetTitle`)}),(0,Q.jsx)(Iq,{label:w(`link.close`),onClick:g,children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(WJ,{step:d?2:+!!c})]}),(0,Q.jsxs)(`div`,{className:`flex min-h-0 flex-col gap-5 overflow-y-auto px-5 py-4`,children:[t===`home`&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1 text-[13px] leading-5 text-fg-muted`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:w(`link.setup.relationship`)}),(0,Q.jsx)(`p`,{className:`m-0`,children:w(`link.setup.requirements`)})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Q.jsx)(`h4`,{className:`m-0 text-[13px] leading-5 font-semibold`,children:w(T?`remoteLink.findHome.body`:`link.candidates`)}),i===`loading`&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,role:`status`,children:w(`link.loading`)}),i===`failed`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:w(`link.discoveryFailed`)}),p&&m&&(0,Q.jsx)(uY,{error:m})]}),i===`ready`&&(a.length>0?(0,Q.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:a.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>s(e.alias),"aria-pressed":o===e.alias,className:X(`remote-link-candidate ui-v2 flex min-h-[var(--ocx-control-h)] cursor-pointer items-center justify-between gap-3 rounded-[10px] bg-surface px-3 py-2 text-left ring-1 ring-line transition-colors hover:bg-raised`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,o===e.alias&&`bg-raised ring-2 ring-fg`),children:[(0,Q.jsx)(`span`,{className:`truncate font-mono text-[13px] text-fg`,children:e.alias}),(0,Q.jsx)(`small`,{className:`shrink-0 text-[12px] text-fg-subtle`,children:e.source})]},`${e.source}:${e.alias}`))}):(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 text-[13px] leading-5 text-fg-muted`,children:[(0,Q.jsx)(`p`,{className:`m-0`,children:w(`link.noCandidates`)}),(0,Q.jsx)(`p`,{className:`m-0`,children:w(t===`home`?`link.setup.emptyHome`:`link.setup.emptyLocal`)}),(0,Q.jsx)(`pre`,{className:`m-0 rounded-[8px] bg-surface px-3 py-2.5 font-mono text-[12px] leading-5 whitespace-pre-wrap text-fg ring-1 ring-line [overflow-wrap:anywhere]`,children:(0,Q.jsx)(`code`,{children:`Host devbox
58
- HostName devbox.example.com
59
- User you
60
- IdentityFile ~/.ssh/id_ed25519`})})]})),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsx)(`a`,{href:`https://opencodex.me/guides/remote-link/`,target:`_blank`,rel:`noopener noreferrer`,className:`text-[13px] font-medium text-highlight hover:underline`,children:w(`link.setup.guide`)}),(0,Q.jsxs)(Jp,{variant:`ghost`,size:`sm`,onClick:_,disabled:f!==null,children:[(0,Q.jsx)(Ke,{}),w(i===`failed`?`link.retry`:`link.rescan`)]})]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-[13px] leading-5 font-semibold`,htmlFor:`remote-link-alias`,children:w(`link.alias`)}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`input`,{id:`remote-link-alias`,"aria-describedby":`remote-link-alias-help`,className:`input min-w-0 flex-1 font-mono`,spellCheck:!1,value:o,onChange:e=>s(e.target.value),placeholder:w(`link.aliasPlaceholder`),autoComplete:`off`}),(0,Q.jsxs)(Jp,{variant:`outline`,onClick:v,disabled:!o.trim()||f!==null,children:[(0,Q.jsx)(ue,{}),w(f===`probe`?`link.probing`:`link.probe`)]})]}),(0,Q.jsx)(`p`,{id:`remote-link-alias-help`,className:`m-0 text-[12px] leading-[18px] text-fg-subtle`,children:w(`link.aliasRequired`)})]}),c&&(0,Q.jsxs)(`div`,{className:fY,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Q.jsxs)(`span`,{className:`text-[13px] font-semibold`,children:[w(`link.hostFingerprint`),` `,(0,Q.jsx)(`span`,{className:`font-normal text-fg-subtle`,children:c.keyType})]}),(0,Q.jsx)(`p`,{className:`remote-link-fingerprint m-0 rounded-[8px] bg-bg px-3 py-2 font-mono text-[12.5px] ring-1 ring-line [overflow-wrap:anywhere]`,children:(0,Q.jsx)(`code`,{children:c.fingerprint})})]}),(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-[13px]`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),` `,w(`link.confirmFingerprint`)]}),(0,Q.jsx)(Jp,{variant:`primary`,className:`self-start`,onClick:y,disabled:!l||f!==null,children:w(f===`confirm`?`link.confirming`:`link.confirm`)})]}),d&&(0,Q.jsx)(pY,{confirmation:d,isChildFlow:T,childSelectable:r,busy:f,onApplyLink:x,onJoinLink:S}),p&&i!==`failed`&&m&&(0,Q.jsx)(uY,{error:m}),h&&m?.key!==`remoteLink.error.join_restart_failed`&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[h.phase===`probe`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:w(`link.probeHelp`)}),(0,Q.jsx)(`pre`,{className:`m-0 rounded-[8px] bg-surface px-3 py-2 font-mono text-[12px] whitespace-pre-wrap ring-1 ring-line`,children:(0,Q.jsx)(`code`,{children:`ssh -o BatchMode=yes <alias> true`})})]}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,className:`self-start`,onClick:C,disabled:f!==null,children:w(`link.retry`)})]})]})]}),(0,Q.jsx)(`footer`,{className:`flex shrink-0 justify-end gap-2 px-2 py-2`,children:(0,Q.jsx)(Jp,{variant:`ghost`,onClick:g,children:w(`link.cancel`)})})]})}var hY={invalid_job_id:`remoteLink.error.invalid_job_id`,job_not_found:`remoteLink.error.job_not_found`,link_not_home_initiated:`remoteLink.error.link_not_home_initiated`,link_operation_in_progress:`remoteLink.error.link_operation_in_progress`,no_eligible_links:`remoteLink.error.no_eligible_links`,policy_write_failed:`remoteLink.error.policy_write_failed`,runtime_role_client:`remoteLink.error.runtime_role_client`};function gY(e){return{key:e instanceof tV&&e.code in hY?hY[e.code]:`remoteLink.error.generic`,hint:e instanceof tV?e.hint:null}}var _Y={observe:`remoteLink.job.op.observe`,sync:`remoteLink.job.op.sync`,"restart-codex":`remoteLink.job.op.restartCodex`,update:`remoteLink.job.op.update`},vY={observe:`remoteLink.job.active.observe`,sync:`remoteLink.job.active.sync`,"restart-codex":`remoteLink.job.active.restartCodex`,update:`remoteLink.job.active.update`},yY={"legacy-ocx":`remoteLink.child.ownerAction.legacy-ocx`,"desktop-app-owned":`remoteLink.child.ownerAction.desktop-app-owned`,goat:`remoteLink.child.ownerAction.goat`,"launcher-node-missing":`remoteLink.child.ownerAction.launcher-node-missing`,"launcher-bypassed":`remoteLink.child.ownerAction.launcher-bypassed`,"mise-managed":`remoteLink.child.ownerAction.mise-managed`,"source-checkout":`remoteLink.child.ownerAction.source-checkout`,"installer-unknown":`remoteLink.child.ownerAction.installer-unknown`},bY={queued:`remoteLink.job.state.queued`,running:`remoteLink.job.state.running`,succeeded:`remoteLink.job.state.succeeded`,"up-to-date":`remoteLink.job.state.upToDate`,busy:`remoteLink.job.state.busy`,offline:`remoteLink.job.state.offline`,refused:`remoteLink.job.state.refused`,"owner-action":`remoteLink.job.state.ownerAction`,unsupported:`remoteLink.job.state.unsupported`,failed:`remoteLink.job.state.failed`,uncertain:`remoteLink.job.state.uncertain`},xY={synced:`remoteLink.job.sync.synced`,skipped:`remoteLink.job.sync.skipped`,failed:`remoteLink.job.sync.failed`,"timed-out":`remoteLink.job.sync.timedOut`},SY={requested:`remoteLink.job.restart.requested`,unsupported:`remoteLink.job.restart.unsupported`,"not-run":`remoteLink.job.restart.notRun`,skipped:`remoteLink.job.restart.skipped`},CY={"desktop-app":`remoteLink.child.kind.desktopApp`,goat:`remoteLink.child.kind.goat`,source:`remoteLink.child.kind.source`};function wY({children:e}){return(0,Q.jsx)(`code`,{className:`font-mono`,children:e})}var TY=e=>e.map(e=>e.id);function EY({row:e}){let t=b(),n=e.installedVersion??e.runningVersion,r=e.update.route===`owner-action`?e.update.reason:null,i=r===null?null:yY[r]??null,a=e.installKind===null?null:CY[e.installKind]??null,o=e.lastOperation?bY[e.lastOperation.state]??null:null;return(0,Q.jsxs)(`span`,{className:`remote-link-child-badges flex min-w-0 flex-wrap items-center gap-1.5`,children:[n&&(0,Q.jsxs)(Aq,{tone:`neutral`,children:[`v`,n]}),a&&(0,Q.jsx)(Aq,{tone:`neutral`,children:t(a)}),e.installKind!==null&&!a&&(0,Q.jsx)(Aq,{tone:`neutral`,children:(0,Q.jsx)(wY,{children:e.installKind})}),e.childBuild&&(0,Q.jsx)(Aq,{tone:`neutral`,children:(0,Q.jsx)(wY,{children:`ocx-child ${e.childBuild}`})}),e.versionSkew===`same`&&(0,Q.jsx)(Aq,{tone:`ok`,children:t(`remoteLink.child.skew.same`)}),e.versionSkew===`behind`&&(0,Q.jsx)(Aq,{tone:`warn`,children:t(`remoteLink.child.skew.behind`,{version:e.homeVersion})}),e.versionSkew===`ahead`&&(0,Q.jsx)(Aq,{tone:`warn`,children:t(`remoteLink.child.skew.ahead`)}),VB(e)&&(0,Q.jsx)(Aq,{tone:`warn`,children:t(`remoteLink.child.updateAvailable`,{version:e.homeVersion})}),e.catalog.state===`behind`&&(0,Q.jsx)(Aq,{tone:`warn`,children:t(`remoteLink.child.catalog.behind`)}),e.catalog.state===`current`&&(0,Q.jsx)(Aq,{tone:`ok`,children:t(`remoteLink.child.catalog.current`)}),HB(e)&&(0,Q.jsx)(Aq,{tone:`warn`,children:t(`remoteLink.child.codex.restartNeeded`,{count:e.codex?.staleCount??0})}),e.codex?.appServers===`not_running`&&(0,Q.jsx)(Aq,{tone:`neutral`,children:t(`remoteLink.child.codex.notRunning`)}),i&&(0,Q.jsx)(Aq,{tone:`neutral`,children:t(i)}),r&&!i&&(0,Q.jsx)(wY,{children:r}),e.activeJob&&(0,Q.jsx)(Aq,{tone:`neutral`,children:t(vY[e.activeJob.op])}),e.lastOperation&&(0,Q.jsxs)(`span`,{className:`text-[12px] leading-5 text-fg-muted`,children:[t(`remoteLink.job.last`,{op:t(_Y[e.lastOperation.op]),state:o?t(o):e.lastOperation.state}),!o&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(wY,{children:e.lastOperation.state})]}),e.lastOperation.reason&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(wY,{children:e.lastOperation.reason})]})]})]})}function DY(e){let t=b(),n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let t=n.current;t&&(e.open&&!t.open&&(typeof t.showModal==`function`?t.showModal():t.setAttribute(`open`,``)),!e.open&&t.open&&t.close())},[e.open]),(0,Q.jsx)(`dialog`,{ref:n,"aria-labelledby":`remote-link-child-confirm-title`,onCancel:t=>{t.preventDefault(),e.onCancel()},className:`remote-link-confirm-dialog m-auto w-[min(440px,calc(100vw-24px))] rounded-[14px] border-0 bg-surface p-1 text-fg shadow-lg ring-1 ring-line backdrop:bg-black/40`,children:e.open&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-[10px] bg-bg px-5 py-4 ring-1 ring-line`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-child-confirm-title`,className:`m-0 text-[16px] leading-6 font-semibold tracking-[-0.015em]`,children:e.title}),(0,Q.jsx)(`p`,{className:`m-0 text-[14px] leading-[21px] text-fg-muted`,children:e.body})]}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2 px-2 py-2`,children:[(0,Q.jsx)(Jp,{variant:`ghost`,onClick:e.onCancel,children:t(`link.cancel`)}),(0,Q.jsx)(Jp,{variant:`danger`,autoFocus:!0,onClick:e.onConfirm,children:e.confirm})]})]})})}function OY(e){let t=b(),[n,r]=(0,Z.useState)(`app-server`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-[10px] bg-bg px-5 py-4 ring-1 ring-line`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-restart-title`,className:`m-0 text-[16px] leading-6 font-semibold tracking-[-0.015em]`,children:t(`remoteLink.child.restartCodex`)}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2 text-[13px] leading-5`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`ocx-restart-scope`,checked:n===`app-server`,onChange:()=>r(`app-server`),className:`mt-1`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:t(`remoteLink.restart.scope.appServer`)}),(0,Q.jsx)(`span`,{className:`mt-0.5 block text-fg-muted`,children:t(`remoteLink.restart.scope.appServerBody`)})]})]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2 text-[13px] leading-5`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`ocx-restart-scope`,checked:n===`codex`,onChange:()=>r(`codex`),className:`mt-1`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:t(`remoteLink.restart.scope.codex`)}),(0,Q.jsx)(`span`,{className:`mt-0.5 block text-fg-muted`,children:t(`remoteLink.restart.scope.codexBody`,{alias:e.alias})})]})]})]}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2 px-2 py-2`,children:[(0,Q.jsx)(Jp,{variant:`ghost`,onClick:e.onCancel,children:t(`link.cancel`)}),(0,Q.jsx)(Jp,{variant:`danger`,onClick:()=>e.onConfirm(n),children:t(`remoteLink.restart.confirm`)})]})]})}function kY(e){let t=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let n=t.current;n&&(e.open&&!n.open&&(typeof n.showModal==`function`?n.showModal():n.setAttribute(`open`,``)),!e.open&&n.open&&n.close())},[e.open]),(0,Q.jsx)(`dialog`,{ref:t,"aria-labelledby":`remote-link-restart-title`,onCancel:t=>{t.preventDefault(),e.onCancel()},className:`remote-link-confirm-dialog m-auto w-[min(440px,calc(100vw-24px))] rounded-[14px] border-0 bg-surface p-1 text-fg shadow-lg ring-1 ring-line backdrop:bg-black/40`,children:e.open&&(0,Q.jsx)(OY,{alias:e.alias,onCancel:e.onCancel,onConfirm:e.onConfirm})})}function AY(e){let t=b(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),o=e.link.child??null;if(!UB(e.link.direction,o))return null;let s=e.disabled||o.activeJob!==null,c=s||o.activity.inFlight>0,l=async t=>{e.onError(null),e.onRun({linkId:e.link.id,op:t.op});try{e.onJob(await LB(e.apiBase,t))}catch(t){e.onError(gY(t))}finally{e.onRun(null)}},u=(t,n)=>void l({op:t,linkIds:[e.link.id],...n?{restart:n}:{}}),d=VB(o);return(0,Q.jsxs)(`span`,{className:`remote-link-child-actions flex shrink-0 flex-wrap items-center gap-1`,children:[(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>u(`observe`),disabled:s,children:t(`remoteLink.child.check`)}),(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>u(`sync`),disabled:s,children:t(`remoteLink.child.syncNow`)}),(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>{r(!0),e.onDialog(!0)},disabled:c,children:t(`remoteLink.child.restartCodex`)}),(0,Q.jsx)(Jp,{variant:`primary`,size:`sm`,onClick:()=>{a(!0),e.onDialog(!0)},disabled:c||!d,title:d?void 0:t(`remoteLink.child.upToDate`),children:t(`remoteLink.child.update`)}),(0,Q.jsx)(kY,{alias:e.link.alias,open:n,onCancel:()=>{r(!1),e.onDialog(!1)},onConfirm:t=>{r(!1),e.onDialog(!1),u(`restart-codex`,t)}}),(0,Q.jsx)(DY,{open:i,title:t(`remoteLink.child.update`),body:t(`remoteLink.child.updateConfirm`,{alias:e.link.alias,version:o.homeVersion}),confirm:t(`remoteLink.child.update`),onCancel:()=>{a(!1),e.onDialog(!1)},onConfirm:()=>{a(!1),e.onDialog(!1),u(`update`)}})]})}function jY(e){let t=b(),[n,r]=(0,Z.useState)(null),i=e.rows.filter(e=>UB(e.direction,e.child??null)),a=i.filter(e=>VB(e.child));if(i.length===0)return null;let o=a[0]?.child?.homeVersion??i[0]?.child?.homeVersion??``,s=async(t,n)=>{e.onError(null),e.onRun({linkId:`all`,op:t});try{let r=await Promise.allSettled(qB(n).map(n=>LB(e.apiBase,{op:t,linkIds:n})));for(let t of r)t.status===`fulfilled`&&e.onJob(t.value);let i=r.find(e=>e.status===`rejected`);i&&e.onError(gY(i.reason))}finally{e.onRun(null)}};return(0,Q.jsxs)(`div`,{className:`remote-link-child-bulk flex flex-wrap items-center gap-2 px-1 py-2`,children:[(0,Q.jsx)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>void s(`observe`,TY(i)),children:t(`remoteLink.child.checkAll`)}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,disabled:a.length===0,onClick:()=>r(`all`),children:t(`remoteLink.child.updateAll`)}),(0,Q.jsx)(DY,{open:n===`all`,title:t(`remoteLink.child.updateAll`),body:t(`remoteLink.child.updateAllConfirm`,{count:a.length,version:o}),confirm:t(`remoteLink.child.updateAll`),onCancel:()=>r(null),onConfirm:()=>{r(null),s(`update`,TY(a))}})]})}function MY(e,t,n){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),s=r?.jobId===t.jobId?r.value:t,c=a===t.jobId,l=(0,Z.useRef)(n);return(0,Z.useEffect)(()=>{l.current=n},[n]),(0,Z.useEffect)(()=>{if(t.state===`done`)return;let n=!1,r=!1,a=0,s=0,c=new AbortController,u=async(u=!1)=>{if(document.visibilityState===`hidden`||r&&!u)return;r=!0;let d=++a,f=new AbortController,p=()=>f.abort();c.signal.addEventListener(`abort`,p,{once:!0});let m=window.setTimeout(p,JB);try{let r=await YB(RB(e,t.jobId,f.signal),f.signal);!n&&d>s&&(s=d,i({jobId:t.jobId,value:r}),l.current?.(r))}catch(e){e instanceof tV&&(e.code===`job_not_found`||e.status===404)&&(n=!0,c.abort(),o(t.jobId))}finally{window.clearTimeout(m),c.signal.removeEventListener(`abort`,p),r=!1}},d=window.setInterval(()=>void u(),KB),f=()=>{document.visibilityState!==`hidden`&&u(!0)};return document.addEventListener(`visibilitychange`,f),()=>{n=!0,r=!1,c.abort(),window.clearInterval(d),document.removeEventListener(`visibilitychange`,f)}},[e,t.jobId,t.state]),{job:s,missing:c}}function NY(e){let t=b(),{job:n,missing:r}=MY(e.apiBase,e.job,e.onJobUpdate),i=n.state===`done`||r,a=(0,Z.useRef)(!1);return(0,Z.useEffect)(()=>{i&&!a.current&&(a.current=!0,e.onDone())},[i,e]),(0,Q.jsxs)(`section`,{className:`remote-link-job flex min-w-0 flex-col gap-1 rounded-[12px] bg-surface px-4 py-3 ring-1 ring-line`,"aria-live":`polite`,children:[(0,Q.jsxs)(`h4`,{className:`m-0 text-[13px] font-semibold`,children:[t(vY[n.op]),n.trigger===`auto`&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,t(`remoteLink.job.automatic`)]})]}),r&&(0,Q.jsx)(Fq,{tone:`info`,children:t(`remoteLink.job.notFound`)}),(0,Q.jsx)(`ul`,{className:`m-0 flex list-none flex-col gap-1 p-0 text-[12px] leading-5`,children:n.items.map(e=>{let n=r&&(e.state===`queued`||e.state===`running`)?`uncertain`:e.state,i=bY[n]??null,a=e.sync?xY[e.sync.state]??null:null,o=e.restart?SY[e.restart.outcome]??null:null;return(0,Q.jsxs)(`li`,{className:`flex min-w-0 flex-wrap items-center gap-x-2`,children:[(0,Q.jsx)(`span`,{className:`font-semibold`,children:e.alias}),(0,Q.jsx)(`span`,{children:i?t(i):(0,Q.jsx)(wY,{children:n})}),(e.fromVersion||e.toVersion)&&(0,Q.jsx)(wY,{children:`${e.fromVersion??`?`} → ${e.toVersion??`?`}`}),e.reason&&(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:(0,Q.jsx)(wY,{children:e.reason})}),e.hint&&(0,Q.jsx)(`span`,{className:`basis-full text-fg-muted remote-link-job-hint`,children:e.hint}),e.sync&&(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:a?t(a):(0,Q.jsx)(wY,{children:e.sync.state})}),e.restart&&(0,Q.jsx)(`span`,{className:WB(e.restart.outcome)?`text-warning`:`text-fg-muted`,children:o?t(o):(0,Q.jsx)(wY,{children:e.restart.outcome})})]},e.linkId||e.alias)})})]})}function PY(e){if(!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>=1&&t<=60?t:void 0}function FY(e){let t=b(),[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(0),{apiBase:f,reloadSignal:p}=e,m=(0,Z.useRef)(0),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(i);(0,Z.useEffect)(()=>{g.current=i},[i]);let _=(0,Z.useRef)(n);(0,Z.useEffect)(()=>{_.current=n},[n]);let v=(0,Z.useCallback)(async e=>{let t=m.current,n=g.current,i=_.current;try{let o=await zB(f,e);if(e?.aborted||m.current!==t)return;if(r(o),g.current!==n&&i){let e=XB(i.policy,g.current);a({...o.policy,...e})}else a(o.policy);l(null)}catch(t){e?.aborted||l(gY(t))}},[f]);if((0,Z.useEffect)(()=>{if(h.current)return;let e=new AbortController;return Promise.resolve().then(()=>v(e.signal)),()=>e.abort()},[v,u,p]),!i||!n)return c?(0,Q.jsxs)(`section`,{className:`remote-link-policy flex min-w-0 flex-col gap-2 rounded-[12px] bg-surface p-4 ring-1 ring-line`,"aria-labelledby":`remote-link-policy-title`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-policy-title`,className:`m-0 text-[14px] font-semibold`,children:t(`remoteLink.policy.title`)}),(0,Q.jsx)(Fq,{tone:`err`,action:(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:()=>{l(null),d(e=>e+1)},children:t(`link.retry`)}),children:t(`remoteLink.policy.loadFailed`)})]}):null;let y=XB(n.policy,i),x=n.warning===`policy-file-invalid`,S=async()=>{h.current=!0,m.current+=1,e.onBusy(!0),e.onError(null),s(!1);try{let e=await BB(f,x?i:y);r(e),a(e.policy),s(!0)}catch(t){e.onError(gY(t))}finally{h.current=!1,e.onBusy(!1)}},C=Math.round(i.idleAfterMs/6e4),w=(e,t)=>{s(!1),a({...i,[e]:t})};return(0,Q.jsxs)(`section`,{className:`remote-link-policy flex min-w-0 flex-col gap-2 rounded-[12px] bg-surface p-4 ring-1 ring-line`,"aria-labelledby":`remote-link-policy-title`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-policy-title`,className:`m-0 text-[14px] font-semibold`,children:t(`remoteLink.policy.title`)}),x&&(0,Q.jsx)(Fq,{tone:`warn`,children:t(`remoteLink.policy.invalid`)}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3 text-[13px]`,children:[(0,Q.jsx)(`span`,{children:t(`remoteLink.policy.catalogFanout`)}),(0,Q.jsx)(Vn,{value:i.catalogFanout,disabled:e.busy,onChange:e=>w(`catalogFanout`,e),label:t(`remoteLink.policy.catalogFanout`),options:[{value:`auto`,label:t(`remoteLink.policy.catalogFanout.auto`)},{value:`manual`,label:t(`remoteLink.policy.catalogFanout.manual`)}]})]}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3 text-[13px]`,children:[(0,Q.jsx)(`span`,{children:t(`remoteLink.policy.childCodexRestart`)}),(0,Q.jsx)(Vn,{value:i.childCodexRestart,disabled:e.busy,onChange:e=>w(`childCodexRestart`,e),label:t(`remoteLink.policy.childCodexRestart`),options:[{value:`never`,label:t(`remoteLink.policy.childCodexRestart.never`)},{value:`app-server-when-idle`,label:t(`remoteLink.policy.childCodexRestart.whenIdle`)}]})]}),(0,Q.jsxs)(`label`,{className:`flex flex-col gap-1 text-[13px]`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`span`,{children:t(`remoteLink.policy.updates`)}),(0,Q.jsx)(Vn,{value:i.updates,disabled:e.busy,onChange:e=>w(`updates`,e),label:t(`remoteLink.policy.updates`),options:[{value:`off`,label:t(`remoteLink.policy.updates.off`)},{value:`notify`,label:t(`remoteLink.policy.updates.notify`)},{value:`auto-when-idle`,label:t(`remoteLink.policy.updates.autoWhenIdle`)}]})]}),(0,Q.jsx)(`span`,{className:`text-[12px] leading-5 text-fg-muted`,children:t(`remoteLink.policy.updatesInactive`)})]}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3 text-[13px]`,children:[(0,Q.jsx)(`span`,{children:t(`remoteLink.policy.idleMinutes`)}),(0,Q.jsx)(`input`,{type:`number`,className:`input w-[88px]`,min:1,max:60,value:C,disabled:e.busy,"aria-label":t(`remoteLink.policy.idleMinutes`),onChange:e=>{let t=PY(e.target.value);t!==void 0&&w(`idleAfterMs`,t*6e4)}})]}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[o&&(0,Q.jsx)(`span`,{className:`text-[12px] text-success`,role:`status`,children:t(`remoteLink.policy.saved`)}),(0,Q.jsx)(Jp,{variant:`primary`,size:`sm`,disabled:e.busy||Object.keys(y).length===0&&!x,onClick:()=>void S(),children:t(`remoteLink.policy.save`)})]})]})}function IY(){window.location.reload()}var LY={connecting:`remoteLink.status.connecting`,connected:`remoteLink.status.connected`,reconnecting:`remoteLink.status.reconnecting`,failed:`remoteLink.status.failed`,idle:`remoteLink.status.idle`},RY={admission_failed:`remoteLink.error.admission_failed`,admission_timeout:`remoteLink.error.admission_timeout`,child_external_provider_conflict:`remoteLink.error.child_external_provider_conflict`,child_port_busy:`remoteLink.error.child_port_busy`,compensation_failed:`remoteLink.error.compensation_failed`,fingerprint_failed:`remoteLink.error.fingerprint_failed`,forbidden:`remoteLink.error.forbidden`,host_confirmation_expired:`remoteLink.error.host_confirmation_expired`,host_fingerprint_mismatch:`remoteLink.error.host_fingerprint_mismatch`,host_not_confirmed:`remoteLink.error.host_not_confirmed`,invalid_alias:`remoteLink.error.invalid_alias`,invalid_body:`remoteLink.error.invalid_body`,invalid_job_id:`remoteLink.error.invalid_job_id`,invalid_link_id:`remoteLink.error.invalid_link_id`,join_connect_failed:`remoteLink.error.join_connect_failed`,join_in_progress:`remoteLink.error.join_in_progress`,join_issue_failed:`remoteLink.error.join_issue_failed`,join_port_failed:`remoteLink.error.join_port_failed`,join_port_mismatch:`remoteLink.error.join_port_mismatch`,join_restart_failed:`remoteLink.error.join_restart_failed`,join_rollback_failed:`remoteLink.error.join_rollback_failed`,join_tunnel_failed:`remoteLink.error.join_tunnel_failed`,job_not_found:`remoteLink.error.job_not_found`,key_issue_failed:`remoteLink.error.key_issue_failed`,key_revoke_failed:`remoteLink.error.key_revoke_failed`,link_apply_failed:`remoteLink.error.link_apply_failed`,link_exists:`remoteLink.error.link_exists`,link_not_found:`remoteLink.error.link_not_found`,link_not_home_initiated:`remoteLink.error.link_not_home_initiated`,link_operation_in_progress:`remoteLink.error.link_operation_in_progress`,link_remove_failed:`remoteLink.error.link_remove_failed`,link_unavailable:`remoteLink.error.link_unavailable`,listener_unavailable:`remoteLink.error.listener_unavailable`,no_eligible_links:`remoteLink.error.no_eligible_links`,policy_write_failed:`remoteLink.error.policy_write_failed`,probe_failed:`remoteLink.error.probe_failed`,purge_unsupported:`remoteLink.error.purge_unsupported`,remote_connect_failed:`remoteLink.error.remote_connect_failed`,remote_disconnect_failed:`remoteLink.error.remote_disconnect_failed`,remote_ocx_missing:`remoteLink.error.remote_ocx_missing`,remote_ocx_outdated:`remoteLink.error.remote_ocx_outdated`,remote_ocx_unrecognized:`remoteLink.error.remote_ocx_unrecognized`,remote_plant_failed:`remoteLink.error.remote_plant_failed`,remote_plant_timeout:`remoteLink.error.remote_plant_timeout`,remote_plant_unavailable:`remoteLink.error.remote_plant_unavailable`,remote_port_failed:`remoteLink.error.remote_port_failed`,runtime_role_client:`remoteLink.error.runtime_role_client`,standalone_required:`remoteLink.error.standalone_required`,tailscale_session_refused:`remoteLink.error.tailscale_session_refused`,version_probe_failed:`remoteLink.error.version_probe_failed`,link_pin_conflict:`remoteLink.error.link_pin_conflict`,host_key_changed:`remoteLink.error.host_key_changed`,trust_file_unexpected:`remoteLink.error.trust_file_unexpected`,key_cleanup_failed:`remoteLink.error.key_cleanup_failed`,link_cleanup_uncertain:`remoteLink.error.link_cleanup_uncertain`},zY={auth:`remoteLink.reason.auth`,hostkey:`remoteLink.reason.hostkey`,forward:`remoteLink.reason.forward`,timeout:`remoteLink.reason.timeout`,bind:`remoteLink.reason.bind`,persist:`remoteLink.reason.persist`,compensation_failed:`remoteLink.reason.compensation_failed`,"stale tunnel may hold the port":`remoteLink.reason.staleTunnel`},BY={pairing_required:`remoteLink.joinDenied.pairing_required`,standalone_required:`remoteLink.childDisabled`,join_port_mismatch:`remoteLink.error.join_port_mismatch`};function VY(e){return typeof e==`object`&&!!e}function HY(e){return typeof e==`string`&&e.length>0}function UY(e){if(!VY(e)||!Array.isArray(e.candidates))throw Error(`invalid candidates`);return e.candidates.map(e=>{if(!VY(e)||!HY(e.alias)||!HY(e.source))throw Error(`invalid candidate`);return{alias:e.alias,source:e.source}})}function WY(e){if(!VY(e)||!HY(e.alias)||!HY(e.fingerprint)||!HY(e.keyType))throw Error(`invalid probe`);return{alias:e.alias,fingerprint:e.fingerprint,keyType:e.keyType}}function GY(e){return e instanceof tV&&e.code in RY?RY[e.code]:`remoteLink.error.generic`}function KY(e,t){return e!==null&&t!==null?e===t:null}var qY=`~/.cache/opencodex/bin/ocx-child detach --purge`,JY=`"%LOCALAPPDATA%\\opencodex\\bin\\ocx-child.exe" detach --purge`,YY=`"%USERPROFILE%\\.cache\\opencodex\\bin\\ocx-child.exe" detach --purge`;function XY(e){let t=e.linkId;if(t===null||e.step===`noLink`)return{key:`remoteLink.residual.noLink`};let n=e=>e+` --expect-link `+t,r={linkId:t},i={key:`remoteLink.residual.bound`,vars:r},a={key:`remoteLink.residual.olderFull`,cmd:`ocx connect status --json`,vars:r},o={key:`remoteLink.residual.olderLightweight`},s={key:`remoteLink.residual.purgeWindowsFallback`,cmd:n(YY)},c={key:`remoteLink.residual.purgeNotFound`},l=n(`~/.cache/opencodex/bin/ocx-child detach`),u=n(`"%LOCALAPPDATA%\\opencodex\\bin\\ocx-child.exe" detach`),d={key:`remoteLink.residual.purgeWindowsFallback`,cmd:n(`"%USERPROFILE%\\.cache\\opencodex\\bin\\ocx-child.exe" detach`)},f=e.platform===`windows`?{key:`remoteLink.residual.lightweightPlacedWindows`,cmd:`where.exe ocx-child`}:{key:`remoteLink.residual.lightweightPlaced`,cmd:`command -v ocx-child`},p=e.platform===`windows`?[d,f]:e.platform===`posix`?[f]:[{key:`remoteLink.residual.purgeAnyWindows`,cmd:u},d,f];switch(e.step){case`purge`:return{key:`remoteLink.residual.purge`,cmd:n(qY),more:[i,c]};case`purgeWindows`:return{key:`remoteLink.residual.purgeWindows`,cmd:n(JY),more:[s,i,c]};case`purgeAny`:return{key:`remoteLink.residual.purgeAny`,cmd:n(qY),more:[{key:`remoteLink.residual.purgeAnyWindows`,cmd:n(JY)},s,i,c]};case`ephemeral`:return e.platform===`windows`?{key:`remoteLink.residual.purgeWindows`,cmd:u,more:[...p,i,o]}:{key:e.platform===`posix`?`remoteLink.residual.ephemeral`:`remoteLink.residual.purgeAny`,cmd:l,more:[...p,i,o]};case`full`:return{key:`remoteLink.residual.full`,cmd:n(`ocx disconnect`),more:[i,a]};case`unknown`:return{key:`remoteLink.residual.unknown`,cmd:n(`ocx disconnect`),more:[{key:`remoteLink.residual.unknownLightweight`,cmd:e.platform===`windows`?u:l},...p,i,o,a]}}}function ZY(e){return e instanceof tV?{key:GY(e),hint:e.hint,childStep:e.residual?XY(e.residual):null}:{key:GY(e),hint:null}}function QY({apiBase:e,diagnosticsApiBase:t=e,sessionReady:n,pairingRecoveryAvailable:r=!1,onRequestPairing:i,workspaceAvailable:a=!1,onOpenWorkspace:o,onChildReady:s=IY,restartWait:l}){let u=b(),[d,f]=(0,Z.useState)(`off`),[p,m]=(0,Z.useState)(`home`),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(`idle`),[D,O]=(0,Z.useState)([]),[k,A]=(0,Z.useState)(``),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(null),[F,I]=(0,Z.useState)(!1),[L,R]=(0,Z.useState)(null),[z,B]=(0,Z.useState)(null),[V,H]=(0,Z.useState)(!1),[U,W]=(0,Z.useState)(0),[ee,G]=(0,Z.useState)([]),te=(0,Z.useRef)(new Set),[ne,K]=(0,Z.useState)(null),[q,J]=(0,Z.useState)(null),[re,Y]=(0,Z.useState)(null),[ie,ae]=(0,Z.useState)(!1),[oe,se]=(0,Z.useState)(null),[ce,le]=(0,Z.useState)([]),ue=(0,Z.useRef)(null),de=(0,Z.useRef)(null),fe=(0,Z.useRef)(null),pe=(0,Z.useRef)(null),me=(0,Z.useRef)([]),he=(0,Z.useRef)(null),ge=(0,Z.useRef)(0),_e=(0,Z.useRef)(null),ve=(0,Z.useRef)(0),ye=(0,Z.useRef)(null),be=(0,Z.useRef)(!1),[xe,Se]=(0,Z.useState)(!1),Ce=r&&i&&(!n||x)?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:i,children:u(`connection.pairing.title`)}):null,we=(0,Z.useCallback)(()=>{_e.current?.controller.abort();let e={controller:new AbortController,sequence:++ve.current};return _e.current=e,e},[]),Te=(0,Z.useCallback)(()=>{ve.current+=1,_e.current?.controller.abort(),_e.current=null},[]),Ee=e=>_e.current?.sequence===e.sequence&&!e.controller.signal.aborted,De=(0,Z.useCallback)(()=>{ge.current+=1,he.current?.controller.abort(),he.current=null},[]),Oe=(0,Z.useCallback)(async()=>{if(!n||document.visibilityState===`hidden`||be.current)return;he.current?.controller.abort();let t=new AbortController,r=++ge.current;he.current={controller:t,sequence:r};try{let n=fV(await gV(e,`/api/link/status?children=1`,{signal:t.signal}));if(t.signal.aborted||ge.current!==r)return;_(n),y(null),S(!1),q?f(`failed`):n.role===`child`?f(`connected`):n.links.length===0?f(e=>[`role-select`,`adding-child`,`confirming-host`,`applying`,`joining`,`restart-waiting`].includes(e)?e:`off`):n.links.some(e=>e.state===`failed`)?f(`failed`):n.links.some(e=>e.state===`reconnecting`)?f(`reconnecting`):n.links.some(e=>e.state===`connected`)&&f(`connected`)}catch(e){if(t.signal.aborted||ge.current!==r)return;y(GY(e)),S(e instanceof tV&&(e.status===401||e.status===403))}finally{he.current?.sequence===r&&(he.current=null)}},[e,q,n]),ke=(0,Z.useEffectEvent)(()=>{Oe()});(0,Z.useEffect)(()=>{if(!n)return;Promise.resolve().then(ke);let e=window.setInterval(ke,5e3),t=()=>{document.visibilityState===`visible`?ke():De()};return document.addEventListener(`visibilitychange`,t),()=>{window.clearInterval(e),document.removeEventListener(`visibilitychange`,t),De()}},[De,n]),(0,Z.useEffect)(()=>{if(d!==`restart-waiting`)return;let t=new AbortController;return CV(e,ye.current,t.signal,{...l,onSlow:()=>Se(!0)}).then(e=>{e===`ready`&&s()}),()=>t.abort()},[e,s,l,d]),(0,Z.useEffect)(()=>{if(!C){let e=de.current?.open;de.current?.close?.(),e&&ue.current?.focus();return}let e=de.current;e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``));let t=window.setTimeout(()=>e?.querySelector(`input, button`)?.focus(),0);return()=>window.clearTimeout(t)},[C]),(0,Z.useEffect)(()=>{let e=fe.current;re?e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``)):e?.close?.()},[re]);let Ae=()=>{Te(),w(!1),E(`idle`),O([]),M(null),P(null),I(!1),K(null),J(null),R(null),f(e=>[`failed`,`adding-child`,`confirming-host`,`applying`,`joining`].includes(e)?`adding-child`:e)},je=h(),Me=je&&g?.joinAvailable===!0,Ne=g?.joinDenied?BY[g.joinDenied]:`remoteLink.joinDenied.unavailable`,Pe=c(e).shared,Fe=je&&window.location.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(window.location.hostname)&&Pe.serverOrigin===window.location.origin,Ie=async()=>{let t=we();E(`loading`),O([]),K(null),J(null),R(`candidates`),M(null),P(null),I(!1);try{let n=await gV(e,`/api/link/candidates`,{signal:t.controller.signal});if(!Ee(t))return;O(UY(n)),E(`ready`)}catch(e){if(!Ee(t))return;E(`failed`),K(ZY(e))}finally{Ee(t)&&R(null)}},Le=async()=>{w(!0),f(`adding-child`),await Ie()},Re=async(t=k.trim(),n=_e.current??we())=>{let r=t.trim();if(r){T===`failed`&&E(`idle`),R(`probe`),K(null),M(null),P(null),I(!1),J(null),f(`adding-child`);try{let t=await gV(e,`/api/link/probe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal});if(!Ee(n))return;M(WY(t))}catch(e){if(!Ee(n))return;K(ZY(e)),J({phase:`probe`,alias:r}),f(`failed`)}finally{Ee(n)&&R(null)}}},ze=async()=>{if(!j||!F)return;let t=_e.current;if(!t)return;R(`confirm`),K(null);let n=p===`home`?{alias:j.alias,fingerprint:j.fingerprint,allowMissing:!0}:{alias:j.alias,fingerprint:j.fingerprint};try{let r=await gV(e,`/api/link/confirm-host`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n),signal:t.controller.signal});if(!Ee(t))return;P(pV(r))}catch(e){if(!Ee(t))return;K(ZY(e))}finally{Ee(t)&&R(null)}},Be=async(t=_e.current)=>{let n=N;if(!n||!t)return;R(`apply`),K(null),J(null),f(`applying`);let r=n.runtimeKind===`missing`?{alias:n.alias,plant:!0}:{alias:n.alias};try{if(await gV(e,`/api/link/apply`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r),signal:t.controller.signal}),!Ee(t))return;Ae(),Oe()}catch(e){if(!Ee(t))return;K(ZY(e)),J({phase:`apply`,alias:n.alias}),f(`failed`)}finally{Ee(t)&&R(null)}},Ve=async(t=N?.alias,n=_e.current??we())=>{let r=t?.trim();if(r&&Me){R(`join`),K(null),J(null),f(`joining`);try{if(ye.current=(await _V(e,n.controller.signal))?.pid??null,!Ee(n)||(await gV(e,`/api/link/join`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal}),!Ee(n)))return;be.current=!0,De(),Ae(),Se(!1),f(`restart-waiting`)}catch(e){if(!Ee(n))return;K(ZY(e)),J({phase:`join`,alias:r}),f(`failed`)}finally{Ee(n)&&R(null)}}},He=async()=>{let t=(g?.links??[]).filter(e=>e.direction===`hub-initiated`&&(e.state===`failed`||e.state===`reconnecting`));if(t.length===0)await Oe();else{R(`reconnect`),K(null);try{let n=(await Promise.allSettled(t.map(t=>gV(e,`/api/link/${encodeURIComponent(t.id)}/reconnect`,{method:`POST`})))).find(e=>e.status===`rejected`);n&&K(ZY(n.reason))}finally{await Oe(),R(null)}}},Ue=()=>{if(!q){He();return}let e=we();q.phase===`probe`?(A(q.alias),Re(q.alias,e)):q.phase===`join`?Ve(q.alias,e):Be(e)},We=()=>{Y(null),ae(!1),se(null),window.setTimeout(()=>pe.current?.focus(),0)},Ge=(e,t)=>{let n=t===`Home`?0:t===`End`?1:t===`ArrowRight`||t===`ArrowDown`||t===`ArrowLeft`||t===`ArrowUp`?(e+1)%2:e;(n!==1||Me)&&n!==e&&(me.current[n]?.focus(),m(n===0?`home`:`child`))},qe=async()=>{if(!re)return;let t=re;R(`remove`),se(null);let n=t.force?{method:`DELETE`,headers:{"content-type":`application/json`},body:JSON.stringify({force:!0})}:ie&&t.row.childKind===`ephemeral`?{method:`DELETE`,headers:{"content-type":`application/json`},body:JSON.stringify({purge:!0})}:{method:`DELETE`};try{await gV(e,`/api/link/${encodeURIComponent(t.row.id)}`,n),t.force&&le(e=>[...e.filter(e=>e.id!==t.row.id),{id:t.row.id,alias:t.row.alias,kind:t.row.childKind??`unknown`}]),We(),await Oe()}catch(e){!t.force&&e instanceof tV&&e.code===`remote_disconnect_failed`?Y({row:t.row,force:!0,refusal:sV(e.hint)}):se(GY(e))}finally{R(null)}},Je=g?.links??[],Ye=new Set(Je.filter(e=>GB(ee,e.id)).map(e=>e.id)),Xe=(0,Z.useCallback)(e=>{te.current.has(e.jobId)||(te.current.add(e.jobId),G(t=>[...t,e]))},[]),Ze=(0,Z.useCallback)(e=>{G(t=>t.filter(t=>t.jobId!==e)),Oe()},[Oe]),Qe=(0,Z.useCallback)(e=>{G(t=>t.map(t=>t.jobId===e.jobId?e:t))},[]);(0,Z.useEffect)(()=>{for(let t of g?.links??[]){let n=t.child?.activeJob;n&&!te.current.has(n.jobId)&&(te.current.add(n.jobId),RB(e,n.jobId).then(e=>G(t=>t.some(t=>t.jobId===e.jobId)?t:[...t,e])).catch(()=>{te.current.delete(n.jobId)}))}},[e,g]);let $e=p===`home`&&(d===`adding-child`||d===`confirming-host`||d===`applying`),tt=g?.role===`home`||$e?`remoteLink.role.home`:g?.role===`child`?`remoteLink.role.child`:`remoteLink.role.standalone`,nt=p===`child`&&!Me,rt=(0,Q.jsxs)(Jp,{variant:`ghost`,size:`sm`,onClick:()=>{W(e=>e+1),Oe()},disabled:L!==null,children:[(0,Q.jsx)(Ke,{}),u(`link.refresh`)]});if(!n)return(0,Q.jsxs)(`div`,{className:`remote-link-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Q.jsx)(Vq,{title:u(`link.title`),subtitle:u(`link.subtitle`)}),(0,Q.jsx)(Fq,{tone:`warn`,action:Ce,children:u(`link.sessionRequired`)})]});let it=p===`child`&&je,at=d===`connected`||d===`reconnecting`||d===`failed`||d===`restart-waiting`||g?.role===`child`||Je.length>0||d===`adding-child`||d===`confirming-host`||d===`applying`||d===`joining`,ot=g?.role===`home`&&Je.some(e=>e.child),st=!C&&(d===`reconnecting`||d===`failed`&&(q!==null&&ne?.key!==`remoteLink.error.join_restart_failed`||Je.some(e=>e.state===`failed`))),ct=(e,t,n)=>{n&&[`ArrowRight`,`ArrowDown`,`ArrowLeft`,`ArrowUp`,`Home`,`End`].includes(e.key)&&(e.preventDefault(),Ge(t,e.key))};return(0,Q.jsxs)(`div`,{className:`remote-link-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Q.jsx)(Vq,{title:u(`link.title`),subtitle:u(`link.subtitle`),actions:rt}),a&&(0,Q.jsxs)(Fq,{tone:`info`,className:`remote-link-workspace-card`,action:(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:o??(()=>{window.location.hash=`remote-workspace`}),children:u(`remoteLink.workspaceMoved.open`)}),children:[(0,Q.jsx)(`strong`,{className:`font-semibold`,children:u(`remoteLink.workspaceMoved.title`)}),` `,(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:u(`remoteLink.workspaceMoved.body`)})]}),v&&(0,Q.jsx)(Fq,{tone:`err`,action:Ce,children:(0,Q.jsx)(`span`,{className:`remote-link-error`,children:u(v)})}),ce.map(e=>(0,Q.jsx)(qJ,{removed:e,onDismiss:()=>le(t=>t.filter(t=>t.id!==e.id))},e.id)),Je.length===0&&d===`off`&&(0,Q.jsx)(zJ,{onTurnOn:()=>f(`role-select`)}),d===`role-select`&&(0,Q.jsxs)(`section`,{className:`remote-link-panel flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,"aria-label":u(`link.role.title`),children:[(0,Q.jsx)(LJ,{on:!0,onToggle:()=>f(`off`),hint:u(`link.role.title`)}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4 rounded-[8px] bg-bg p-4 ring-1 ring-line`,children:[(0,Q.jsx)(`p`,{className:`m-0 max-w-[72ch] text-[13px] leading-5 text-fg-muted`,children:u(`link.role.hint`)}),(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,role:`radiogroup`,"aria-label":u(`link.role.title`),children:[(0,Q.jsx)(BJ,{role:`home`,buttonRef:e=>{me.current[0]=e},tabIndex:p===`home`?0:-1,checked:p===`home`,onSelect:()=>m(`home`),onKeyDown:e=>ct(e,0,!0)}),(0,Q.jsx)(BJ,{role:`child`,buttonRef:e=>{me.current[1]=e},tabIndex:Me&&p===`child`?0:-1,checked:p===`child`,disabled:!Me,onSelect:()=>{Me&&(m(`child`),Le())},onKeyDown:e=>ct(e,1,Me)})]}),!je&&(0,Q.jsx)(Fq,{tone:`warn`,children:u(`remoteLink.childDisabled`)}),je&&g!==null&&!g.joinAvailable&&(0,Q.jsx)(Fq,{tone:`warn`,children:u(Ne)})]}),(0,Q.jsx)(`div`,{className:`flex justify-end px-3 py-2.5`,children:(0,Q.jsx)(Jp,{variant:`primary`,"data-action":`continue`,disabled:nt||g?.role===`child`,onClick:()=>void Le(),children:u(p===`child`?`remoteLink.findHome.action`:`link.continue`)})})]}),d===`role-select`&&Fe&&g?.joinAvailable===!1&&g.joinDenied===`pairing_required`&&(0,Q.jsx)(eH,{local:!0,target:Pe,onConnected:()=>{Oe()}}),at&&(0,Q.jsxs)(`section`,{className:`remote-link-panel flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,"aria-labelledby":`remote-link-list-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-list-title`,className:`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em]`,children:u(it?`remoteLink.findHome.title`:`link.children`)}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:u(d===`restart-waiting`?`remoteLink.restart.waiting`:tt)})]}),(0,Q.jsxs)(Jp,{ref:ue,variant:`primary`,size:`sm`,onClick:()=>void Le(),disabled:L!==null||d===`applying`||d===`joining`||d===`restart-waiting`||g?.role===`child`,children:[(0,Q.jsx)(Vt,{}),u(it?`remoteLink.findHome.action`:`link.addChild`)]})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col rounded-[8px] bg-bg ring-1 ring-line`,children:[ot&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(jY,{apiBase:e,rows:Je,onJob:Xe,onError:K,onRun:B}),ee.map(t=>(0,Q.jsx)(NY,{apiBase:e,job:t,onDone:()=>Ze(t.jobId),onJobUpdate:Qe},t.jobId))]}),d===`restart-waiting`?(0,Q.jsxs)(`div`,{className:`remote-link-restart flex flex-col gap-1.5 px-4 py-4`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{className:`text-[14px] font-semibold`,children:u(`remoteLink.restart.title`)}),(0,Q.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:u(`remoteLink.restart.body`)}),xe&&(0,Q.jsx)(Fq,{tone:`warn`,className:`mt-1`,children:u(`remoteLink.restart.slow`)})]}):g?.role===`child`?(0,Q.jsx)(`ul`,{className:`remote-link-children m-0 list-none p-0`,"aria-live":`polite`,children:(0,Q.jsxs)(`li`,{className:`remote-link-row flex min-w-0 items-center gap-3 px-4 py-3`,children:[(0,Q.jsx)(UJ,{name:g.child?.alias??u(`remoteLink.role.child`)}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsx)(`span`,{className:`truncate text-[14px] font-semibold`,children:g.child?.alias??u(`remoteLink.role.child`)}),g.child&&(0,Q.jsx)(HJ,{state:g.child.state,children:u(LY[g.child.state])})]})]})}):Je.length>0?(0,Q.jsx)(`ul`,{className:`remote-link-children m-0 flex list-none flex-col divide-y divide-line p-0`,"aria-live":`polite`,children:Je.map(t=>{let n=KY(g?.homeCodexSettingsDigest??null,t.appliedCodexSettingsDigest??null);return(0,Q.jsxs)(`li`,{className:`remote-link-row flex min-w-0 items-center gap-3 px-4 py-3`,children:[(0,Q.jsx)(UJ,{name:t.alias}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`truncate text-[14px] font-semibold`,children:t.alias}),t.childKind&&(0,Q.jsx)(Aq,{tone:t.childKind===`ephemeral`?`ok`:`neutral`,children:u(t.childKind===`ephemeral`?`remoteLink.badge.ephemeral`:`remoteLink.badge.full`)}),n!==null&&(0,Q.jsx)(Aq,{tone:n?`ok`:`warn`,children:u(n?`remoteLink.parity.synced`:`remoteLink.parity.outdated`)}),t.child&&(0,Q.jsx)(EY,{row:t.child})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[12px] leading-5 text-fg-muted`,children:[(0,Q.jsx)(HJ,{state:t.state,children:u(LY[t.state])}),(0,Q.jsx)(`span`,{children:t.direction===`hub-initiated`?u(`remoteLink.direction.hub`):u(`remoteLink.direction.client`)}),t.reason&&(0,Q.jsx)(`span`,{className:`remote-link-error text-danger`,children:t.reason in zY?u(zY[t.reason]):(0,Q.jsxs)(Q.Fragment,{children:[u(`remoteLink.reason.generic`),` `,(0,Q.jsx)(`code`,{className:`font-mono`,children:t.reason})]})})]})]}),t.child&&t.direction===`hub-initiated`&&(0,Q.jsx)(AY,{apiBase:e,link:t,disabled:z!==null||Ye.has(t.id),onJob:Xe,onError:K,onDialog:e=>B(e?{linkId:t.id,op:`observe`}:null),onRun:B}),(0,Q.jsxs)(Jp,{variant:`ghost`,size:`sm`,className:`hover:bg-danger-soft hover:text-danger`,onClick:e=>{pe.current=e.currentTarget,ae(!1),Y({row:t,force:!1})},disabled:L!==null||t.child?.activeJob!=null||Ye.has(t.id),title:t.child?.activeJob||Ye.has(t.id)?u(`remoteLink.child.disconnectBlocked`):void 0,children:[(0,Q.jsx)(et,{}),u(`link.disconnect`)]})]},t.id)})}):(0,Q.jsx)(`p`,{className:`m-0 px-4 py-6 text-center text-[13px] text-fg-muted`,children:u(it?`remoteLink.findHome.empty`:`link.noChildren`)})]}),(st||d===`joining`||!C&&ne)&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 px-3 py-2.5`,children:[st&&(0,Q.jsxs)(`div`,{className:`remote-link-status-message flex items-center justify-between gap-3`,"aria-live":`polite`,children:[(0,Q.jsx)(HJ,{state:d===`failed`?`failed`:`reconnecting`,children:u(LY[d===`failed`?`failed`:`reconnecting`])}),(0,Q.jsx)(Jp,{variant:`outline`,size:`sm`,onClick:Ue,disabled:L!==null,children:u(`link.retry`)})]}),d===`joining`&&(0,Q.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,"aria-live":`polite`,children:u(`remoteLink.joining`)}),!C&&ne&&(0,Q.jsx)(uY,{error:ne})]})]}),ot&&(0,Q.jsx)(FY,{apiBase:e,busy:V,reloadSignal:U,onBusy:H,onError:K}),(g?.role===`child`||Je.length>0)&&(0,Q.jsx)(wd,{apiBase:e,section:`devices`,readOnly:g?.role===`child`}),(0,Q.jsx)(lY,{apiBase:t}),(0,Q.jsx)(mY,{sheetRef:de,role:p,standaloneRuntime:je,childSelectable:Me,discovery:T,candidates:D,alias:k,onAliasChange:A,probe:j,checkedFingerprint:F,onCheckedFingerprintChange:I,confirmation:N,busy:L,sheetOpen:C,actionError:ne,failedAction:q,onClose:Ae,onRescan:()=>void Ie(),onProbe:()=>void Re(),onConfirmHost:()=>void ze(),onApplyLink:()=>void Be(),onJoinLink:()=>void Ve(),onRetryFailedAction:Ue}),(0,Q.jsx)(JJ,{confirmRef:fe,confirming:re,purge:ie,onPurgeChange:ae,forceError:oe,busy:L===`remove`,onClose:We,onConfirm:()=>void qe()})]})}var $Y=`meta-muse`,eX=`meta-muse:rate-limit-observation`,tX=6912e5;function nX(e,t=Date.now()){let n=Math.max(0,Math.ceil((e-t)/1e3));return[Math.floor(n/3600),Math.floor(n/60)%60,n%60].map(e=>String(e).padStart(2,`0`)).join(`:`)}function rX(e,t,n=Date.now()){if(!e||typeof e!=`object`||Array.isArray(e))return null;let r=e;if(r.provider!==$Y||r.accountLogLabel!==t||r.status!==429||r.errorCode!==`rate_limit_exceeded`||typeof r.timestamp!=`number`||!Number.isFinite(r.timestamp)||r.timestamp>n)return null;let i=r.rateLimitResetAt;return typeof i!=`number`||!Number.isFinite(i)||i<=n||i<=r.timestamp||i-r.timestamp>tX?null:{label:`Muse Code`,source:`meta-muse:rate-limit-observation`,observed:!0,updatedAt:r.timestamp,quota:{customWindows:[{label:`Muse Code`,percent:100,resetAt:i}],updatedAt:r.timestamp}}}function iX(e){let t=e[$Y];if(t?.source!==eX)return;let n=gt(t)?.customWindows?.[0]?.resetAt;return typeof n==`number`&&Number.isFinite(n)?n:void 0}function aX(e,t=Date.now()){let n=iX(e);if(n===void 0||n>t)return e;let{[$Y]:r,...i}=e;return i}async function oX(e,t,n,r=fetch){if(e[$Y])return e;try{let[i,a]=await Promise.all([r(`${t}/api/providers`,{signal:n}),r(`${t}/api/oauth/accounts?provider=${$Y}`,{signal:n})]);if(!i.ok||!a.ok)return e;let o=await i.json();if(!Array.isArray(o)||!o.some(e=>e?.name===$Y&&e.disabled!==!0&&e.authMode===`oauth`&&e.baseUrl===`https://api.meta.ai/v1`))return e;let s=await a.json();if(typeof s.activeAccountId!=`string`||!Array.isArray(s.accounts))return e;let c=s.accounts.find(e=>e.id===s.activeAccountId);if(!c||c.paused||c.needsReauth)return e;let l=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(`${$Y}\0${s.activeAccountId}`)),u=`o${Array.from(new Uint8Array(l),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,6)}`,d=await r(`${t}/api/logs?provider=${$Y}&account=${u}`,{signal:n});if(!d.ok)return e;let f=await d.json(),p,m=-1/0;for(let e of Array.isArray(f.logs)?f.logs:[]){if(!e||typeof e!=`object`||Array.isArray(e))continue;let t=e;t.provider===$Y&&t.accountLogLabel===u&&typeof t.timestamp==`number`&&Number.isFinite(t.timestamp)&&t.timestamp>=m&&(p=t,m=t.timestamp)}let h=rX(p,u);return h?{...e,[$Y]:h}:e}catch{return e}}var sX={requests:`usage.col.requests`,tokens:`usage.col.tokens`,"input-tokens":`usage.col.inputTokens`,"output-tokens":`usage.col.outputTokens`},cX=e=>typeof e==`object`&&!!e&&!Array.isArray(e),lX=e=>Number.isSafeInteger(e)&&e>=0&&e<=0xe677d21fdbff,uX=e=>Number.isSafeInteger(e)&&e>=0&&e<=0xe8d4a51000;function dX(e){if(!Array.isArray(e))return[];let t=[],n=new Map,r=new Set;for(let i of e){if(!cX(i)||typeof i.provider!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(i.provider)||typeof i.keyId!=`string`||!i.keyId||i.keyId.length>256||typeof i.model!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(i.model)||!Array.isArray(i.windows))continue;let e=[],a=new Set;for(let t of i.windows){if(!cX(t)||typeof t.dimension!=`string`||!Object.hasOwn(sX,t.dimension)||t.window!==void 0&&t.window!==`minute`&&t.window!==`day`&&t.window!==`month`||!lX(t.observedAt)||typeof t.stale!=`boolean`)continue;let n=`${t.dimension}:${t.window??``}`;a.has(n)||(a.add(n),e.push({dimension:t.dimension,...t.window?{window:t.window}:{},observedAt:t.observedAt,stale:t.stale,...uX(t.remaining)?{remaining:t.remaining}:{},...uX(t.limit)?{limit:t.limit}:{},...lX(t.resetAt)?{resetAt:t.resetAt}:{}}))}if(!e.length)continue;let o=JSON.stringify([i.provider,i.keyId,i.model]);if(r.has(o))continue;r.add(o);let s=n.get(i.provider);s||(s=new Map,n.set(i.provider,s)),s.has(i.keyId)||s.set(i.keyId,s.size+1),t.push({provider:i.provider,keyId:i.keyId,account:s.get(i.keyId),model:i.model,windows:e})}return t}function fX(e){let t=document.documentElement,n=()=>t.style.setProperty(`--ocx-sticky-top-h`,String(Math.ceil(e.getBoundingClientRect().height)));n();let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(e),()=>{r?.disconnect(),t.style.removeProperty(`--ocx-sticky-top-h`)}}var pX=6e4,mX=7,hX=8,gX=.8;function _X(e,t){try{return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(e)}catch{return new Date(e).toTimeString().slice(0,5)}}function vX(e,t){return e.labelKey?t(e.labelKey):e.displayLabel??e.label??e.id}function yX(e,t){return e===`critical`?t(`quotaSummary.critical`):e===`warn`?t(`quotaSummary.warn`):``}function bX(e,t){let n=t(sX[e.dimension]);return e.window?`${n} · ${t(e.window===`minute`?`quotaSummary.perMinute`:e.window===`day`?`quotaSummary.perDay`:`quotaSummary.perMonth`)}`:n}function xX(e,t,n){let r=e=>e===void 0?t(`pws.completion.unknown`):new Intl.NumberFormat(n).format(e);return`${r(e.remaining)} / ${r(e.limit)}`}function SX(e,t){return e.stale||e.resetAt!==void 0&&e.resetAt<=t}function CX(e){try{return e.matches(`:focus-visible`)}catch{return!0}}function wX(e,t,n){(0,Z.useLayoutEffect)(()=>{if(!e)return;let r=()=>{let e=t.current,r=n.current;if(!e||!r)return;let i=e.getBoundingClientRect(),a=r.offsetWidth,o=document.documentElement.clientWidth||window.innerWidth,s=Math.max(hX,o-a-hX),c=Math.min(Math.max(i.left,hX),s);r.style.setProperty(`--qs-pop-top`,String(Math.round(i.bottom+mX))),r.style.setProperty(`--qs-pop-left`,String(Math.round(c))),r.style.setProperty(`--qs-pop-gap`,String(Math.round(i.bottom+mX)-i.bottom));let l=r.getBoundingClientRect();r.style.setProperty(`--qs-bridge-left`,String(Math.min(0,Math.max(0,i.left)-l.left))),r.style.setProperty(`--qs-bridge-right`,String(Math.min(0,l.right-Math.min(o,i.right))))};return r(),window.addEventListener(`scroll`,r,{capture:!0,passive:!0}),window.addEventListener(`resize`,r),()=>{window.removeEventListener(`scroll`,r,{capture:!0}),window.removeEventListener(`resize`,r)}},[e,t,n])}function TX({row:e,t,locale:n}){let[r,i]=(0,Z.useState)(Date.now),a=Math.max(r,e.passive?e.updatedAt??0:0);(0,Z.useEffect)(()=>{let t=e.passive?.windows.flatMap(e=>e.resetAt!==void 0&&e.resetAt>Date.now()?[e.resetAt]:[])??[];if(!e.passive&&(e.provider!==`meta-muse`||e.headline.resetAt===void 0))return;let n=window.setInterval(()=>i(Date.now()),e.passive?6e4:1e3),r=t.length?Math.min(...t):void 0,a=r===void 0?void 0:window.setTimeout(()=>i(Date.now()),Math.min(2147483647,Math.max(0,r-Date.now())));return()=>{window.clearInterval(n),a!==void 0&&window.clearTimeout(a)}},[e.provider,e.headline.resetAt,e.passive,r]);let[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(null),_=(0,Z.useRef)(``),v=(0,Z.useId)(),y=!f&&(o||c||u),b=(0,Z.useCallback)(()=>{s(!1),l(!1),d(!1)},[]);(0,Z.useEffect)(()=>{if(!y)return;let e=e=>{m.current&&!m.current.contains(e.target)&&d(!1)},t=e=>{if(e.key===`Escape`){let e=g.current?.contains(document.activeElement);b(),e&&(h.current?.focus(),p(!0))}};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[y,b]),wX(y,h,g);let x=e=>{e.pointerType!==`touch`&&s(!0)},S=e=>{e.pointerType!==`touch`&&s(!1),p(!1)},C=t=>{if(t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;t.preventDefault();let n=_.current===`touch`;_.current=``,n&&!y?d(!0):(b(),n||p(!0),pE(e.provider))},{headline:w}=e,T=yX(e.severity,t);return(0,Q.jsxs)(`li`,{ref:m,className:`quota-summary-item quota-summary-item--${e.severity}`,onPointerEnter:x,onPointerLeave:S,onFocus:e=>{CX(e.target)&&(p(!1),l(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||l(!1)},children:[(0,Q.jsxs)(`a`,{ref:h,href:`#${oE(e.provider)}`,className:`quota-summary-chip${y?` quota-summary-chip--open`:``}`,"aria-expanded":y,"aria-controls":y?v:void 0,"aria-describedby":y?`${v}-table`:void 0,onPointerDown:e=>{_.current=e.pointerType},onClick:C,children:[(0,Q.jsx)(`span`,{className:`quota-summary-name`,children:e.label}),w.labelKey===`quotaSummary.creditsUnavailable`&&(0,Q.jsx)(`span`,{className:`quota-summary-name`,children:t(`quotaSummary.creditsUnavailable`)}),e.passive?e.passive.windows.map(e=>(0,Q.jsxs)(`span`,{className:`quota-summary-pct`,title:t(`quotaSummary.remainingLimit`),children:[bX(e,t),`: `,xX(e,t,n),SX(e,a)?` · ${t(`startup.stale`)}`:``,(0,Q.jsx)(`span`,{className:`sr-only`,children:t(`quotaSummary.remainingLimit`)})]},`${e.dimension}:${e.window??``}`)):e.showAllWindows?e.windows.map(e=>(0,Q.jsxs)(`span`,{className:`quota-summary-pct quota-summary-pct--${e.severity}`,title:vX(e,t),children:[vX(e,t).split(` (`)[0],`: `,Et(e.percent)]},e.id)):(0,Q.jsx)(`span`,{className:`quota-summary-pct`,children:w.unknownBudget===!0?t(`cws.quota.unknown`):Et(w.percent)}),e.provider===`meta-muse`&&w.resetAt!==void 0&&(0,Q.jsx)(`span`,{className:`quota-summary-name`,title:xh(w.resetAt,t,n),children:nX(w.resetAt,r)}),T&&(0,Q.jsx)(`span`,{className:`quota-summary-flag`,"aria-hidden":`true`,children:`!`}),T&&(0,Q.jsx)(`span`,{className:`sr-only`,children:T}),(0,Q.jsx)(`span`,{className:`sr-only`,children:t(`quotaSummary.openAccounts`)})]}),y&&(0,Q.jsxs)(`div`,{ref:g,id:v,className:`quota-summary-popover`,role:`group`,"aria-label":e.label,children:[(0,Q.jsxs)(`div`,{className:`quota-summary-popover-head`,children:[(0,Q.jsx)(`strong`,{children:e.label}),T&&(0,Q.jsx)(`span`,{className:`quota-summary-badge quota-summary-badge--${e.severity}`,children:T})]}),(0,Q.jsx)(`table`,{id:`${v}-table`,className:`quota-summary-table${e.passive?` quota-summary-table--passive`:``}`,children:(0,Q.jsx)(`tbody`,{children:e.passive?e.passive.windows.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:bX(e,t)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-pct`,children:xX(e,t,n)}),(0,Q.jsxs)(`td`,{className:`quota-summary-row-reset`,children:[e.resetAt===void 0?t(`pws.completion.unknown`):t(`quota.resetsAt`,{when:new Intl.DateTimeFormat(n,{dateStyle:`medium`,timeStyle:`short`}).format(e.resetAt)}),SX(e,a)?` · ${t(`startup.stale`)}`:``,(0,Q.jsx)(`br`,{}),ph(e.observedAt,t,a)?t(`quota.observedAgo`,{age:ph(e.observedAt,t,a)}):t(`quotaSummary.observedAt`,{time:_X(e.observedAt,n)})]})]},`${e.dimension}:${e.window??``}`)):e.windows.map(e=>(0,Q.jsxs)(`tr`,{className:`quota-summary-row--${e.severity}`,children:[(0,Q.jsx)(`th`,{scope:`row`,children:vX(e,t)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-pct`,children:e.unknownBudget===!0?t(`cws.quota.unknown`):Et(e.percent)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-reset`,children:e.resetAt===void 0?`-`:xh(e.resetAt,t,n)})]},e.id))})}),(0,Q.jsxs)(`div`,{className:`quota-summary-popover-foot`,children:[!e.passive&&e.updatedAt!==void 0&&(0,Q.jsx)(`span`,{children:t(e.observed?`quotaSummary.observedAt`:`quotaSummary.dataAt`,{time:_X(e.updatedAt,n)})}),(0,Q.jsx)(`a`,{href:`#${oE(e.provider)}`,className:`quota-summary-popover-link`,onPointerDown:e=>{_.current=e.pointerType},onClick:C,children:t(`quotaSummary.openAccounts`)})]})]})]})}var EX={overflow:!1,atStart:!0,atEnd:!0};function DX({rows:e,t,locale:n}){let r=(0,Z.useRef)(null),[i,a]=(0,Z.useState)(EX),o=(0,Z.useCallback)(()=>{let e=r.current;if(!e)return;let t=e.scrollWidth-e.clientWidth,n=t>1?{overflow:!0,atStart:e.scrollLeft<=1,atEnd:e.scrollLeft>=t-1}:EX;a(e=>e.overflow===n.overflow&&e.atStart===n.atStart&&e.atEnd===n.atEnd?e:n)},[]),s=e.map(e=>`${e.provider}:${e.label}:${Et(e.headline.percent)}:${e.severity}`).join(`|`);(0,Z.useEffect)(()=>{let e=r.current;if(!e)return;let t=requestAnimationFrame(o),n=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>o());n?.observe(e);for(let t of Array.from(e.children))n?.observe(t);return()=>{cancelAnimationFrame(t),n?.disconnect()}},[o,s]);let c=e=>{let t=r.current;if(!t)return;let n=t.scrollWidth-t.clientWidth;if(e<0?t.scrollLeft<=1:t.scrollLeft>=n-1){o();return}let i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;t.scrollBy({left:e*Math.max(t.clientWidth*gX,80),behavior:i?`auto`:`smooth`})};return(0,Q.jsxs)(`div`,{className:`quota-summary-scroller${i.overflow?` quota-summary-scroller--overflow`:``}`,children:[i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--prev`,"aria-label":t(`quotaSummary.scrollPrev`),title:t(`quotaSummary.scrollPrev`),"aria-disabled":i.atStart,onClick:()=>c(-1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`«`})}),(0,Q.jsx)(`ul`,{ref:r,className:`quota-summary-list`,onScroll:o,children:e.map(e=>(0,Q.jsx)(TX,{row:e,t,locale:n},e.passive?JSON.stringify([e.provider,e.passive.keyId,e.passive.model]):e.provider))}),i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--next`,"aria-label":t(`quotaSummary.scrollNext`),title:t(`quotaSummary.scrollNext`),"aria-disabled":i.atEnd,onClick:()=>c(1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`»`})})]})}function OX({apiBase:e}){let{t,locale:n}=s(),r=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`quota summary load failed`);let r=await n.json(),i=await oX(Ne(r?.reports),e,t);return{fetchedAt:Date.now(),reports:i,passive:dX(r?.passiveKeyLimits)}},[e]),i=mf(`ocx.quota-summary.provider-quotas.v1:${e}`,[e],r,{isEmpty:e=>Object.keys(e.reports).length===0&&(e.passive?.length??0)===0,pollMs:pX,pauseWhenHidden:!0}),a=i.data,[o,c]=(0,Z.useState)(Date.now),l=a?iX(a.reports):void 0;if((0,Z.useEffect)(()=>{if(l===void 0||o>=l)return;let e=window.setTimeout(()=>c(Date.now()),Math.max(0,l-Date.now()));return()=>window.clearTimeout(e)},[l,o]),!a)return null;let u=aX(a.reports,o),d=bt(u,e=>re(e,t));for(let e of a.passive??[])d.push({provider:e.provider,label:`${re(e.provider,t)} · ${t(`quotaSummary.account`,{n:e.account})} · ${e.model}`,headline:{id:`passive`,severity:`normal`},windows:[],updatedAt:a.fetchedAt,observed:!0,severity:`normal`,passive:e});if(d.length===0)return null;let f=!i.lastAttemptOk;return(0,Q.jsxs)(`section`,{className:`quota-summary-bar`,"aria-label":t(`quotaSummary.aria`),ref:fX,children:[(0,Q.jsx)(DX,{rows:d,t,locale:n}),(0,Q.jsx)(`span`,{className:`quota-summary-updated${f?` quota-summary-updated--stale`:``}`,title:f?t(`quotaSummary.refreshFailed`):void 0,children:t(`quotaSummary.updated`,{time:_X(a.fetchedAt,n)})}),(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,children:f?t(`quotaSummary.refreshFailed`):``})]})}var kX=3e5,AX=6e5,jX=`https://github.com/lidge-jun/opencodex`;async function MX(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function NX({apiBase:e,onOpenUpdate:t,onOpenTerminalCommand:n,version:r}){let i=b(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=bn(`sidebar-star:${e}`,[e],t=>MX(`${e}/api/github/star`,t),{pollMs:kX}),u=bf(e),d=bn(`sidebar-update-badge:`+u,[u],e=>MX(u,e),{pollMs:_f()?6e4:AX}),f=l.data?.state??null,p=s!==null&&s.basedOn===f?s.state:f??`not-starred`,m=l.data?.url??jX,h=p===`starred`,g=d.data,_=g?.updateAvailable===!0,v=g?.latestVersion??null,y=()=>window.open(m,`_blank`,`noopener,noreferrer`),x=async()=>{if(!(h||a)){if(p===`unauthenticated`)y();else{o(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){c({state:`starred`,basedOn:f});return}n?.state&&c({state:n.state,basedOn:f}),y()}catch{y()}finally{o(!1),l.refresh()}}}},S=i(h?`sidebar.starred`:p===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),C=_&&v?i(`sidebar.updateAvailable`,{version:v}):_f()?i(`sidebar.desktopUpdate`):i(`sidebar.checkUpdate`);return(0,Q.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Q.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:m,target:`_blank`,rel:`noreferrer`,children:[(0,Q.jsx)(zt,{}),` `,i(`common.github`)]}),r,(0,Q.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb${h?` sidebar-orb--starred`:``}`,onClick:()=>{x()},disabled:a||h,"aria-label":S,"aria-pressed":h,title:S,children:(0,Q.jsx)(Tt,{"aria-hidden":`true`,...h?{fill:`currentColor`}:{}})}),(0,Q.jsxs)(`button`,{type:`button`,className:`sidebar-orb${_?` sidebar-orb--update`:``}`,onClick:t,"aria-label":C,title:C,children:[(0,Q.jsx)(pt,{"aria-hidden":`true`}),_&&(0,Q.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]}),_f()&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:n,"aria-label":i(`sidebar.terminalCommand`),title:i(`sidebar.terminalCommand`),children:(0,Q.jsx)(Qe,{"aria-hidden":`true`})})]})]})}var PX=`ocx-desktop-star-onboarding`,FX=`https://github.com/lidge-jun/opencodex`,IX=1200;function LX(){try{return window.localStorage.getItem(PX)!==null}catch{return!0}}function RX(){try{window.localStorage.setItem(PX,`seen`)}catch{}}function zX(e){window.location.assign(e)}function BX({apiBase:e,enabled:t,onSettled:n}){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(LX),s=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{t&&!s.current&&(a||!_f())&&(s.current=!0,n?.())},[a,t,n]),(0,Z.useEffect)(()=>{if(!t||a||!_f())return;let n=new AbortController,r=window.setTimeout(()=>{fetch(`${e}/api/github/star`,{signal:n.signal}).then(async e=>e.ok?await e.json():{}).catch(()=>n.signal.aborted?null:{}).then(e=>{e&&(e.state===`starred`?(RX(),o(!0)):i(e))})},IX);return()=>{window.clearTimeout(r),n.abort()}},[e,t,a]);let c=(0,Z.useCallback)(()=>{RX(),o(!0)},[]);return a||!t||!r?null:(0,Q.jsx)(VX,{apiBase:e,status:r,onClose:c})}function VX({apiBase:e,status:t,onClose:n}){let r=b(),i=(0,Z.useId)(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),[s,c]=(0,Z.useState)(`prompt`),l=t.url??FX,u=t.state===`not-starred`;(0,Z.useEffect)(()=>{let e=o.current;e&&!e.open&&e.showModal()},[]);let d=(0,Z.useCallback)(e=>{e.preventDefault(),s!==`starring`&&n()},[n,s]),f=()=>{zX(l),n()},p=async()=>{c(`starring`);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`});if((t.ok?await t.json():null)?.ok===!0){Sn(`sidebar-star:${e}`,{state:`starred`,url:l}),c(`thanks`);return}}catch{}c(`failed`)},m=s===`thanks`,h=s===`failed`;return(0,Q.jsxs)(`dialog`,{ref:o,"aria-labelledby":i,"aria-describedby":a,className:`modal-overlay star-onboarding-overlay`,onCancel:d,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>{s!==`starring`&&n()}}),(0,Q.jsxs)(`div`,{className:`modal-card star-onboarding`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`span`,{className:`star-onboarding-mark${m?` star-onboarding-mark--done`:``}`,"aria-hidden":`true`,children:(0,Q.jsx)(Tt,{...m?{fill:`currentColor`}:{}})}),(0,Q.jsx)(`h3`,{id:i,className:`star-onboarding-title`,children:r(m?`onboarding.star.thanks`:`onboarding.star.title`)}),(0,Q.jsx)(`p`,{id:a,className:`star-onboarding-body`,children:r(m?`onboarding.star.thanksBody`:h?`onboarding.star.failed`:`onboarding.star.body`)}),m?(0,Q.jsx)(`div`,{className:`star-onboarding-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:n,autoFocus:!0,children:r(`onboarding.star.done`)})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`star-onboarding-actions`,children:[u&&!h?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:s===`starring`,onClick:()=>{p()},autoFocus:!0,children:[(0,Q.jsx)(Tt,{"aria-hidden":`true`}),r(s===`starring`?`onboarding.star.starring`:`onboarding.star.cta`)]}):(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,autoFocus:!0,children:[(0,Q.jsx)(zt,{"aria-hidden":`true`}),r(h?`onboarding.star.openPage`:`onboarding.star.cta`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:s===`starring`,onClick:n,children:r(`onboarding.star.later`)})]}),(0,Q.jsxs)(`p`,{className:`star-onboarding-hint`,children:[r(u&&!h?`onboarding.star.ghHint`:`onboarding.star.browserHint`),u&&!h&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`button`,{type:`button`,className:`star-onboarding-link`,disabled:s===`starring`,onClick:f,children:r(`onboarding.star.openPage`)})]})]})]})]})]})}var HX=`dialog.telemetry-consent-overlay`;function UX({apiBase:e,enabled:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(!1),[,o]=(0,Z.useState)(0),s=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=e=>{let t=e.detail;t&&(s.current=!0,r(t),Ad(t)||a(!0))};return window.addEventListener(Dd,e),()=>{window.removeEventListener(Dd,e)}},[]),(0,Z.useEffect)(()=>{if(!t||i)return;let n=new AbortController;return Fd(e,n.signal).then(e=>{n.signal.aborted||s.current||(Ad(e)?r(e):a(!0))}).catch(()=>{}),()=>n.abort()},[e,i,t]);let c=!!(t&&!i&&n&&Ad(n)),l=c&&Nd(HX);(0,Z.useEffect)(()=>{if(!c)return;let e=Nd(HX),t=()=>{let t=Nd(HX);t!==e&&(e=t,o(e=>e+1))};return t(),Pd(t)},[c]);let u=(0,Z.useCallback)(()=>{a(!0)},[]);return!c||l||!n?null:(0,Q.jsx)(WX,{apiBase:e,status:n,onClose:u})}function WX({apiBase:e,status:t,onClose:n}){let r=b(),i=(0,Z.useId)(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),[c,l]=(0,Z.useState)(!0),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=o.current;return e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``)),s.current?.focus(),()=>{e?.open&&e.close?.()}},[]);let h=(0,Z.useCallback)(async()=>{if(!m.current){m.current=!0,d(!0),p(null);try{await Id(e,c?`accepted`:`declined`,t),n()}catch(t){if(!(t instanceof Ld)&&await Fd(e).then(e=>e.decision!==null).catch(()=>!1)){n();return}m.current=!1,d(!1),p(Rd(t)?`session`:`failed`)}}},[e,c,n,t]),g=(0,Z.useCallback)(()=>{m.current||n()},[n]),_=(0,Z.useCallback)(e=>{e.preventDefault(),g()},[g]),v=(0,Z.useCallback)(e=>{e.key===`Escape`&&(e.preventDefault(),g())},[g]);return(0,Q.jsxs)(`dialog`,{ref:o,"aria-labelledby":i,"aria-describedby":a,className:`modal-overlay telemetry-consent-overlay`,onCancel:_,onKeyDown:v,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:g}),(0,Q.jsxs)(`div`,{className:`modal-card telemetry-consent-card flex flex-col gap-3`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h3`,{ref:s,id:i,className:`m-0`,tabIndex:-1,children:r(`proxyV2.telemetryConsentTitle`)})}),(0,Q.jsx)(`p`,{id:a,className:`modal-desc m-0`,children:r(`proxyV2.telemetryConsentBody`)}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-control bg-raised p-3 text-[13px] leading-[19px]`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`strong`,{className:`text-fg`,children:[r(`proxyV2.telemetrySentTitle`),`: `]}),(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:r(`proxyV2.telemetrySentItems`)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`strong`,{className:`text-fg`,children:[r(`proxyV2.telemetryNeverTitle`),`: `]}),(0,Q.jsx)(`span`,{className:`text-fg-muted`,children:r(`proxyV2.telemetryNeverItems`)})]}),(0,Q.jsx)(`a`,{className:`telemetry-policy-link w-fit font-medium text-highlight hover:underline`,href:zd,target:`_blank`,rel:`noreferrer`,children:r(`proxyV2.telemetryPolicyLink`)})]}),(0,Q.jsxs)(`label`,{className:`flex cursor-pointer items-start gap-3 rounded-control bg-raised p-3 ring-1 ring-line`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`telemetry-consent-checkbox mt-0.5 size-4 shrink-0 cursor-pointer`,checked:c,disabled:u,onChange:e=>l(e.target.checked)}),(0,Q.jsx)(`span`,{className:`text-[13px] leading-[19px] text-fg`,children:r(`proxyV2.telemetryConsentCheckbox`)})]}),(0,Q.jsxs)(`details`,{className:`telemetry-preview-details pv2-more`,children:[(0,Q.jsx)(`summary`,{children:r(`proxyV2.telemetryWhatIsSent`)}),(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-col gap-2`,children:[(0,Q.jsx)(`p`,{className:`m-0 text-[12px] text-fg-muted`,children:r(`proxyV2.telemetryPreviewHint`)}),t.previewEligible===!1&&(0,Q.jsx)(`p`,{className:`telemetry-preview-ineligible m-0 text-[12px] text-fg-muted`,children:r(`proxyV2.telemetryPreviewIneligible`)}),(0,Q.jsx)(`pre`,{className:`log-detail-json telemetry-preview-json`,children:jd(t)})]})]}),f&&(0,Q.jsx)($,{tone:`err`,children:r(f===`session`?`proxyV2.telemetrySaveNeedsHumanSession`:`proxyV2.telemetrySaveFailed`)}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary inline-flex items-center gap-2`,disabled:u,"aria-busy":u,onClick:()=>{h()},children:[u&&(0,Q.jsx)(we,{"aria-hidden":!0,width:16,height:16,className:`shrink-0 animate-spin motion-reduce:animate-none`}),r(`proxyV2.telemetryConsentContinue`)]})})]})]})}var GX=`ocx-ui`;function KX(e){try{localStorage.setItem(GX,e)}catch{}window.location.assign(e===`classic`?`/classic/`:`/`)}var qX=[{tier:`daily`,tkey:`shellV2.tierDaily`},{tier:`advanced`,tkey:`shellV2.tierAdvanced`}],JX=[{id:`home`,tier:`daily`,tkey:`shellV2.navHome`,Icon:Lt,pages:[`home`,`startup`]},{id:`connect`,tier:`daily`,tkey:`nav.connect`,Icon:ve,pages:[`integrations`,`setup`],embedded:[`claude`]},{id:`providers`,tier:`daily`,tkey:`nav.providers`,Icon:Re,pages:[`providers`]},{id:`models`,tier:`daily`,tkey:`nav.models`,Icon:jt,pages:[`models`]},{id:`accounts`,tier:`daily`,tkey:`shellV2.navAccounts`,Icon:yt,pages:[`codex-set`]},{id:`subagents`,tier:`daily`,tkey:`nav.subagents`,Icon:vt,pages:[`subagents`]},{id:`usage-logs`,tier:`daily`,tkey:`nav.usageLogs`,Icon:rt,pages:[`usage`,`logs`,`storage`]},{id:`remote`,tier:`daily`,tkey:`nav.remote`,Icon:Oe,pages:[`remote`,`remote-workspace`]},{id:`proxy`,tier:`advanced`,tkey:`shellV2.pageProxyDetails`,Icon:Je,pages:[`dashboard`]},{id:`advisor`,tier:`advanced`,tkey:`nav.advisor`,Icon:Tt,pages:[`advisor`]},{id:`advanced`,tier:`advanced`,tkey:`shellV2.pageAllSettings`,Icon:Me,pages:[`advanced`]}];function YX(e){return JX.find(t=>t.pages.includes(e)||t.embedded?.includes(e))??null}function XX(e,t){return e.pages.filter(e=>e!==`remote-workspace`||t.remoteWorkspaceAvailable)}function ZX(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function QX(e,t=typeof navigator>`u`?``:navigator.userAgent){let n=/Mac OS X|Macintosh/i.test(t);return e?n?`desktop-mac`:`desktop`:n?`browser-mac`:`browser`}function $X(e,t){switch(e){case`desktop-mac`:return`⌘${t}`;case`desktop`:return`Ctrl+${t}`;case`browser-mac`:return`⌥${t}`;default:return`Alt+${t}`}}function eZ(e){return e===`desktop-mac`||e===`browser-mac`?`⌘K`:`Ctrl+K`}function tZ(e,t){if(t.shiftKey)return!1;switch(e){case`desktop-mac`:return t.metaKey&&!t.ctrlKey&&!t.altKey;case`desktop`:return t.ctrlKey&&!t.metaKey&&!t.altKey;default:return t.altKey&&!t.metaKey&&!t.ctrlKey}}function nZ(e){return e===`desktop-mac`?`⌘,`:`Ctrl+,`}var rZ=`ocx-nav-advanced-open`,iZ=`advanced`;function aZ(){try{return localStorage.getItem(rZ)===`1`}catch{return!1}}function oZ({activeGroupId:e,pageLabel:t,pageAvailable:n,onNavigate:r,onReveal:i,desktopShell:a,t:o}){let s=(0,Z.useMemo)(()=>QX(a),[a]),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(0),[m,h]=(0,Z.useState)(aZ),g=(0,Z.useRef)(null),_=(0,Z.useRef)(null),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(!1),x=(0,Z.useId)();(0,Z.useEffect)(()=>{try{localStorage.setItem(rZ,m?`1`:`0`)}catch{}},[m]);let S=(0,Z.useMemo)(()=>JX.flatMap(e=>{let r=o(e.tkey);return[...e.pages,...e.embedded??[]].map((n,i)=>{let a=i===0?r:t(n);return{group:e,page:n,label:a,context:i===0||a===r?null:r,haystack:`${a} ${r}`.toLowerCase()}}).filter(e=>n(e.page))}),[n,t,o]),C=c.trim().toLowerCase(),w=(0,Z.useMemo)(()=>C?S.filter(e=>e.haystack.includes(C)):[],[S,C]),T=(0,Z.useCallback)((e=!1)=>{u||(y.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b.current=e||y.current===_.current,i(),d(!0))},[i,u]);(0,Z.useEffect)(()=>{if(!u)return;let e=requestAnimationFrame(()=>g.current?.focus()),t=setTimeout(()=>{v.current?.contains(document.activeElement)||g.current?.focus()},200);return()=>{cancelAnimationFrame(e),clearTimeout(t)}},[u]),(0,Z.useEffect)(()=>{let e=v.current;if(!u||!e)return;let t=[];for(let n=e;n?.parentElement;n=n.parentElement){for(let e of Array.from(n.parentElement.children))e!==n&&!e.hasAttribute(`inert`)&&(e.setAttribute(`inert`,``),t.push(e));if(n.parentElement===document.body)break}let n=t=>{e.contains(t.target)||g.current?.focus()};return document.addEventListener(`focusin`,n),()=>{document.removeEventListener(`focusin`,n),t.forEach(e=>e.removeAttribute(`inert`))}},[u,C]);let E=(0,Z.useCallback)(e=>{l(``),p(0),d(!1),e&&requestAnimationFrame(()=>{let e=b.current?_.current:y.current;e?.isConnected?e.focus():_.current?.focus()})},[]);(0,Z.useEffect)(()=>{if(!u)return;let e=e=>{e.key!==`Escape`||e.isComposing||e.metaKey||e.ctrlKey||e.altKey||(e.preventDefault(),e.stopImmediatePropagation(),E(!0))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[E,u]);let D=(0,Z.useCallback)(e=>{E(!1),r(e)},[E,r]),O=(0,Z.useMemo)(()=>JX.filter(e=>e.tier===`daily`),[]);(0,Z.useEffect)(()=>{let e=e=>{if(u||e.defaultPrevented||e.isComposing)return;if((s.endsWith(`mac`)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey)&&!e.altKey&&!e.shiftKey&&(e.key===`k`||e.key===`K`)||e.key===`/`&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!ZX(e.target)){e.preventDefault(),T();return}if(a&&(s===`desktop-mac`?e.metaKey:e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key===`,`){e.preventDefault(),r(`advanced`);return}let t=/^Digit([1-9])$/.exec(e.code)?.[1];if(!t||!tZ(s,e)||s.startsWith(`browser`)&&ZX(e.target))return;let n=O[Number(t)-1];n&&(e.preventDefault(),r(n.pages[0]))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[O,a,r,T,u,s]);let k=e=>{if(!(e.nativeEvent.isComposing||e.metaKey||e.ctrlKey||e.altKey)){if(e.key===`Escape`)e.preventDefault(),e.stopPropagation(),E(!0);else if(e.key===`Tab`){e.preventDefault();let t=v.current?.querySelector(`.nav-search-close`);(e.shiftKey?document.activeElement===g.current:document.activeElement!==t)?t?.focus():g.current?.focus()}}},A=e=>{if(!(e.nativeEvent.isComposing||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)){if(e.key===`ArrowDown`)e.preventDefault(),p(e=>w.length?(e+1)%w.length:0);else if(e.key===`ArrowUp`)e.preventDefault(),p(e=>w.length?(e-1+w.length)%w.length:0);else if(e.key===`Enter`){let t=w[Math.min(f,w.length-1)];t&&(e.preventDefault(),D(t.page))}}},j=o(`shellV2.navSearch`),M=eZ(s),N=(t,n)=>{let{id:i,tkey:a,Icon:s}=t,c=e===i,l=o(a);return(0,Q.jsx)(`div`,{className:`nav-entry`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`nav-item${c?` active`:``}`,"data-page":t.pages[0],"data-group":i,title:n?`${l} (${n})`:void 0,"aria-keyshortcuts":n?n.replace(`⌘`,`Meta+`).replace(`⌥`,`Alt+`):void 0,onClick:()=>r(t.pages[0]),"aria-current":c?`page`:void 0,children:[(0,Q.jsx)(s,{}),` `,(0,Q.jsx)(`span`,{className:`nav-item-label`,children:l}),n&&(0,Q.jsx)(`kbd`,{className:`nav-kbd`,"aria-hidden":`true`,children:n})]})},i)};return(0,Q.jsx)(Q.Fragment,{children:qX.map(({tier:t,tkey:n})=>{let r=JX.filter(e=>e.tier===t);if(t===`daily`)return(0,Q.jsxs)(`div`,{className:`nav-tier`,"data-tier":t,children:[u?(0,Q.jsxs)(`div`,{ref:v,role:`dialog`,"aria-modal":`true`,"aria-label":j,onKeyDown:k,children:[(0,Q.jsxs)(`div`,{className:`nav-search`,children:[(0,Q.jsx)(We,{"aria-hidden":`true`}),(0,Q.jsx)(`input`,{ref:g,type:`search`,className:`nav-search-input`,value:c,placeholder:o(`shellV2.navSearchPlaceholder`),"aria-label":j,role:`combobox`,"aria-expanded":`true`,"aria-autocomplete":`list`,"aria-controls":x,"aria-activedescendant":w.length?`${x}-${Math.min(f,w.length-1)}`:void 0,onChange:e=>{l(e.target.value),p(0)},onKeyDown:A}),(0,Q.jsx)(`button`,{type:`button`,className:`nav-search-close`,onClick:()=>E(!0),"aria-label":o(`common.close`),title:o(`common.close`),children:(0,Q.jsx)(Ie,{})})]}),C&&w.length===0&&(0,Q.jsx)(`div`,{className:`nav-search-empty`,role:`status`,children:o(`shellV2.navSearchEmpty`)}),(0,Q.jsx)(`div`,{id:x,className:`nav-search-results`,role:`listbox`,"aria-label":j,children:w.map((e,t)=>{let{Icon:n}=e.group;return(0,Q.jsxs)(`button`,{id:`${x}-${t}`,type:`button`,role:`option`,tabIndex:-1,"aria-selected":t===Math.min(f,w.length-1),className:`nav-item nav-search-result${t===Math.min(f,w.length-1)?` is-highlighted`:``}`,onMouseEnter:()=>p(t),onMouseDown:e=>e.preventDefault(),onClick:()=>D(e.page),children:[(0,Q.jsx)(n,{}),` `,(0,Q.jsx)(`span`,{className:`nav-item-label`,children:e.label}),e.context&&(0,Q.jsx)(`span`,{className:`nav-search-context`,children:e.context})]},e.page)})})]}):(0,Q.jsxs)(`div`,{className:`nav-tier-head`,children:[(0,Q.jsx)(`div`,{className:`nav-tier-label`,"aria-hidden":`true`,children:o(n)}),(0,Q.jsxs)(`button`,{ref:_,type:`button`,className:`nav-search-open`,onClick:()=>T(!0),"aria-label":`${j} (${M})`,title:`${j} (${M})`,"aria-keyshortcuts":M===`⌘K`?`Meta+K`:`Control+K`,children:[(0,Q.jsx)(We,{"aria-hidden":`true`}),(0,Q.jsx)(`kbd`,{className:`nav-kbd nav-kbd--search`,"aria-hidden":`true`,children:M})]})]}),!C&&r.map((e,t)=>N(e,t<9?$X(s,String(t+1)):null))]},t);if(C)return null;if(t!==iZ)return(0,Q.jsxs)(`div`,{className:`nav-tier`,"data-tier":t,children:[(0,Q.jsx)(`div`,{className:`nav-tier-label`,"aria-hidden":`true`,children:o(n)}),r.map(e=>N(e,null))]},t);let i=m?r:r.filter(t=>t.id===e);return(0,Q.jsxs)(`div`,{className:`nav-tier nav-tier--folding${m?` is-open`:``}`,"data-tier":t,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`nav-tier-toggle`,"aria-expanded":m,onClick:()=>h(e=>!e),children:[(0,Q.jsx)(`span`,{className:`nav-tier-label`,children:o(n)}),(0,Q.jsx)(lt,{"aria-hidden":`true`,className:`nav-tier-chevron`})]}),i.map(e=>N(e,a&&e.id===`advanced`?nZ(s):null))]},t)})})}function sZ({items:e,currentPage:t,onNavigate:n,ariaLabel:r,onFocusOrphaned:i}){let a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(i);(0,Z.useLayoutEffect)(()=>{s.current=i}),(0,Z.useLayoutEffect)(()=>{let e=a.current;return()=>{e&&e.contains(e.ownerDocument.activeElement)&&s.current?.()}},[]),(0,Z.useLayoutEffect)(()=>{let t=a.current,n=o.current;t&&n!==null&&(t.contains(t.ownerDocument.activeElement)||e.some(e=>e.page===n)||(t.querySelector(`[aria-current="page"]`)??t.querySelector(`button`))?.focus())},[e]);let c=()=>[...a.current?.querySelectorAll(`button`)??[]],l=e=>{let t=c(),n=t.indexOf(e.currentTarget),r=null;e.key===`ArrowRight`?r=(n+1)%t.length:e.key===`ArrowLeft`?r=(n-1+t.length)%t.length:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r]?.focus())};return(0,Q.jsx)(`nav`,{ref:a,className:`section-switcher`,"aria-label":r,onFocus:e=>{o.current=e.target.dataset.sectionPage??null},onBlur:e=>{if(a.current?.contains(e.relatedTarget))return;let t=e.target;window.setTimeout(()=>{t.isConnected&&(o.current=null)},0)},children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`section-switcher-btn`,"data-section-page":e.page,"aria-current":e.page===t?`page`:void 0,onClick:()=>{e.page!==t&&n(e.page)},onKeyDown:l,children:e.label},e.page))})}function cZ(e){let t=null,n=!1,r=!1,i=()=>{if(t)return n=!0,t;let a=(async()=>{let t=new AbortController;try{let n=await e.discover(e.initialBase,t.signal);if(r||t.signal.aborted||(e.configure(n),e.onTargets(n),n.connected&&!e.hasSession(`shared`)&&await e.bootstrap(`shared`,t.signal),r||t.signal.aborted))return;e.onSessionReady(e.hasSession(`shared`)),e.onError(null),e.onSettled(!0)}catch(n){if(r||t.signal.aborted)return;e.onError(e.isClientStateChanged(n)?`client-state-changed`:`unavailable`),e.onSettled(!0)}})().finally(()=>{t=null,n&&!r&&(n=!1,i())});return t=a,a};return{refresh:i,dispose:()=>{r=!0}}}var lZ=[`ocx-global-view`,`ocx-view`,`ocx-providers-view`,`ocx-subagents-view`,`ocx-storage-view`,`ocx-codexauth-view`,`ocx-apikeys-view`,`ocx-claudecode-view`,`ocx-usage-view`,`ocx-logs-view`,`ocx-models-view`,`ocx-dashboard-view`];function uZ(){try{for(let e of lZ)localStorage.removeItem(e)}catch{}}function dZ(){let[e,t]=(0,Z.useState)(zT);(0,Z.useEffect)(()=>{uZ()},[]);let n=(0,Z.useCallback)(e=>{let n=XT(e);n.replaceTo&&Tn(n.replaceTo),t(n.page)},[]);return(0,Z.useEffect)(()=>{let e=()=>{n(Cn(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,Z.useEffect)(()=>{let n=XT(Cn(window.location.hash));n.replaceTo&&Tn(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{En(n?`${e}/${n}`:e),t(e)}}}var fZ=15e3,pZ=3e3;function mZ(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}async function hZ(e,t,n){try{return(await t(`${e}/healthz`,{method:`GET`,cache:`no-store`,signal:AbortSignal.timeout(n)})).ok?`answering`:`undecided`}catch{return`gone`}}async function gZ(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=fZ,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`,formatStillRunning:a=()=>`The proxy is still answering, so it did not stop.`,formatUnknown:o=()=>`The proxy did not confirm the stop. Check whether it is still running.`,mode:s=`standalone`,livenessTimeoutMs:c=pZ}=t,l;try{l=await n(`${e}${s===`client`?`/api/machine/disconnect`:`/api/stop`}`,{method:`POST`,...s===`client`?{headers:{"Content-Type":`application/json`},body:`{}`}:{},signal:AbortSignal.timeout(r)})}catch{if(s===`client`)return{status:`unknown`,message:o()};let t=await hZ(e,n,c);return t===`gone`?{status:`accepted`}:t===`answering`?{status:`unknown`,message:a()}:{status:`unknown`,message:o()}}let u=null,d=!0;try{u=await l.json()}catch{d=!1}return!l.ok||u?.success===!1?{status:`rejected`,message:mZ(u,l.status,i)}:d?{status:`accepted`}:{status:`unknown`,message:o()}}var _Z=`ocx-desktop-zoom`,vZ=.5,yZ=.1;function bZ(e){return e===`macos`||e===`linux`}function xZ(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,vZ),3)*100)/100:1}function SZ(e,t){return t===`reset`?1:xZ(e+(t===`in`?yZ:-.1))}function CZ(e){return Math.round(e*100)}function wZ(e=typeof localStorage>`u`?void 0:localStorage){try{let t=e?.getItem(_Z);return t==null?1:xZ(Number(t))}catch{return 1}}function TZ(e,t=typeof localStorage>`u`?void 0:localStorage){try{t?.setItem(_Z,String(e))}catch{}}function EZ(e,t){return(t===`macos`?e.metaKey:e.ctrlKey)?e.key===`-`||e.key===`_`?`out`:e.key===`=`||e.key===`+`?`in`:e.key===`0`?`reset`:null:null}function DZ(e,t){if(!Number.isFinite(t)||t===0)return{accumulated:e,action:null};let n=(Math.sign(e)===Math.sign(t)?e:0)+t;return Math.abs(n)<50?{accumulated:n,action:null}:{accumulated:0,action:n<0?`in`:`out`}}async function OZ(e){let t=window.__TAURI_INTERNALS__?.invoke??window.__TAURI__?.core?.invoke;if(!t)return!1;try{return await t(`plugin:webview|set_webview_zoom`,{value:e}),!0}catch{return!1}}var kZ=`ocx-sidebar-collapsed`;function AZ(e=typeof localStorage>`u`?void 0:localStorage){try{return e?.getItem(kZ)===`1`}catch{return!1}}function jZ(e){try{localStorage.setItem(kZ,e?`1`:`0`)}catch{}}function MZ(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function NZ({shortcut:e=!1}={}){let[t,n]=(0,Z.useState)(AZ),r=(0,Z.useCallback)(()=>n(e=>!e),[]);return(0,Z.useEffect)(()=>{jZ(t)},[t]),(0,Z.useEffect)(()=>{if(!e)return;let t=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||(e.key===`b`||e.key===`B`)&&(MZ(e.target)||(e.preventDefault(),r()))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[r,e]),{collapsed:t,toggle:r}}function PZ({managed:e}){let[t,n]=(0,Z.useState)(wZ),r=(0,Z.useCallback)(e=>n(t=>SZ(t,e)),[]),i=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{e&&(OZ(t),TZ(t))},[e,t]),(0,Z.useEffect)(()=>{if(!e)return;let t=xf(),n=e=>{let n=EZ(e,t);n&&(e.preventDefault(),e.stopImmediatePropagation(),r(n))},a=e=>{if(!e.ctrlKey)return;e.preventDefault(),e.stopImmediatePropagation();let t=DZ(i.current,e.deltaY);i.current=t.accumulated,t.action&&r(t.action)},o=e=>{e.ctrlKey&&(e.preventDefault(),e.stopImmediatePropagation())};return window.addEventListener(`keydown`,n,{capture:!0}),window.addEventListener(`wheel`,a,{capture:!0,passive:!1}),window.addEventListener(`mousewheel`,o,{capture:!0,passive:!1}),()=>{window.removeEventListener(`keydown`,n,{capture:!0}),window.removeEventListener(`wheel`,a,{capture:!0}),window.removeEventListener(`mousewheel`,o,{capture:!0})}},[e,r]),{zoom:t,percent:CZ(t),canZoomIn:t<3,canZoomOut:t>vZ,step:r}}function FZ({percent:e,canZoomIn:t,canZoomOut:n,onStep:r}){let i=b();return(0,Q.jsxs)(`div`,{className:`zoom-control`,role:`group`,"aria-label":i(`zoom.label`),title:i(`zoom.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!n,onClick:()=>r(`out`),"aria-label":i(`zoom.out`),title:i(`zoom.out`),children:(0,Q.jsx)(ht,{"aria-hidden":!0})}),(0,Q.jsxs)(`button`,{type:`button`,className:`zoom-control__value`,onClick:()=>r(`reset`),"aria-label":i(`zoom.reset`),title:i(`zoom.reset`),children:[e,`%`]}),(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!t,onClick:()=>r(`in`),"aria-label":i(`zoom.in`),title:i(`zoom.in`),children:(0,Q.jsx)(Vt,{"aria-hidden":!0})})]})}var IZ=[{mode:`light`,tkey:`theme.light`,Icon:Se},{mode:`dark`,tkey:`theme.dark`,Icon:Ae},{mode:`system`,tkey:`theme.system`,Icon:Oe}];function LZ({theme:e,onChange:t}){let n=b(),r=Math.max(0,IZ.findIndex(t=>t.mode===e)),i=IZ[r],a=IZ[(r+1)%IZ.length],o=n(`shellV2.themeCycle`,{mode:n(i.tkey),next:n(a.tkey)});return(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-theme-toggle`,"data-mode":e,onClick:()=>t(a.mode),"aria-label":o,title:o,children:(0,Q.jsx)(i.Icon,{"aria-hidden":`true`})})}var RZ=14,zZ=26,BZ=.3,VZ=.82,HZ={stop:`340ms cubic-bezier(0.7, 0, 0.25, 1.6)`,restart:`320ms cubic-bezier(0.34, 1.7, 0.64, 1)`,rest:`260ms cubic-bezier(0.34, 1.4, 0.64, 1)`},UZ=e=>e>=VZ?`stop`:e>=BZ?`restart`:`rest`;function WZ({restartLabel:e,stopLabel:t,hint:n,restarting:r,settled:i=!1,stopping:a,onRestart:o,onStop:s,onPreview:c}){let[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(null),g=e=>{h.current!==e&&(h.current=e,c?.(e))},_=a||l,v=_?1:r?.5:0,y=d??v,b=d===null?_?`stop`:r?`restart`:`rest`:UZ(d),x=()=>{_||(u(!0),Promise.resolve(s()).finally(()=>u(!1)))},S=()=>{_||r||o()},C=e=>{let t=UZ(e);t===`stop`?x():t===`restart`&&S()};return(0,Q.jsxs)(`button`,{type:`button`,"aria-label":`${e} · ${t}`,"aria-description":n,"aria-keyshortcuts":`ArrowDown End`,title:n,disabled:a,onClick:()=>{m.current?m.current=!1:S()},onKeyDown:e=>{e.key===`End`||e.key===`PageDown`?(e.preventDefault(),x()):e.key===`ArrowDown`&&(e.preventDefault(),S())},onPointerDown:e=>{_||e.button!==0||(e.currentTarget.setPointerCapture?.(e.pointerId),p.current={y:e.clientY,from:v,moved:!1})},onPointerMove:e=>{let t=p.current;if(!t)return;let n=e.clientY-t.y;if(Math.abs(n)>3&&(t.moved=!0),!t.moved)return;let r=Math.min(1,Math.max(t.from,t.from+n/zZ));f(r),g(UZ(r))},onPointerUp:()=>{let e=p.current;if(p.current=null,!e?.moved)return;m.current=!0;let t=d??e.from;f(null),g(null),C(t)},onPointerCancel:()=>{p.current=null,f(null),g(null)},onPointerEnter:()=>{p.current||g(`hover`)},onPointerLeave:()=>{p.current||g(null)},onFocus:()=>g(`hover`),onBlur:()=>g(null),className:X(`group relative inline-flex h-[var(--ocx-control-h-sm)] w-7 shrink-0 cursor-grab touch-none justify-center rounded-[6px] bg-transparent`,`transition-[background-color] duration-150 ease-soft hover:bg-accent-soft active:cursor-grabbing`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-60`,d!==null&&b===`stop`&&`ocx-tremble`),children:[(0,Q.jsx)(`span`,{className:X(`pointer-events-none absolute top-[4px] h-5 w-[5px] rounded-full bg-line-strong`,r&&`ocx-charge`),"aria-hidden":!0}),[0,.5,1].map(e=>(0,Q.jsx)(`span`,{className:`pointer-events-none absolute left-[21px] h-px w-[3px] bg-line-strong`,style:{top:7+e*RZ},"aria-hidden":!0},e)),(0,Q.jsx)(`span`,{"aria-hidden":!0,className:X(`pointer-events-none absolute top-[5px] h-[5px] w-3 rounded-[2px] shadow-sm`,b===`stop`?`bg-danger`:b===`restart`?`bg-highlight`:i?`bg-success`:`bg-fg-muted group-hover:bg-fg`,(r&&d===null||d!==null&&b===`restart`)&&`shadow-[0_0_0_3px_var(--ocx-highlight-soft)]`),style:{transform:`translateY(${y*RZ}px)`,transition:d===null?`transform ${HZ[b]}, background-color 150ms, box-shadow 200ms`:`background-color 150ms`}})]})}function GZ({label:e,statusLabel:t,detail:n,online:r=!0,stopLabel:i,stoppingLabel:a,restartLabel:o,restartingLabel:s,leverHint:c,leverText:l,stopping:u,restarting:d,onStop:f,onRestart:p,session:m,className:h}){let g=qZ(d),_=r&&!u,v=u?a:d?s:t,y=u||d,[b,x]=(0,Z.useState)(null),S=y||b===null?null:b===`hover`?l.hover:b===`rest`?l.cancel:l[b];return(0,Q.jsxs)(`div`,{className:X(`ui-v2 relative flex h-8 items-center gap-[9px] overflow-hidden px-2.5`,h),title:n?`${v} · ${n}`:v,children:[(b===`restart`||d&&!u)&&(0,Q.jsx)(`span`,{className:X(`ocx-sweep`,b===`restart`&&`ocx-sweep-loop`),"aria-hidden":!0}),(0,Q.jsxs)(`span`,{className:X(`relative flex min-w-0 flex-1 items-center gap-[9px]`,u?`ocx-halt`:b===`stop`&&`ocx-tremble ocx-dim`),children:[(0,Q.jsx)(`span`,{className:`grid size-4 shrink-0 place-items-center`,"aria-hidden":!0,children:(0,Q.jsx)(`span`,{className:X(`size-2 rounded-full transition-colors duration-300`,u?`bg-danger ocx-lightout`:b===`stop`?`bg-danger ocx-flicker`:b===`restart`?`bg-highlight`:_?`bg-success`:`bg-fg-subtle`)})}),S===null?(0,Q.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-baseline gap-1.5 text-[13px] leading-5`,children:[(0,Q.jsx)(`span`,{className:`shrink-0 font-medium text-fg`,children:e}),(0,Q.jsx)(`span`,{className:`sr-only`,children:v}),(0,Q.jsx)(`span`,{className:X(`min-w-0 truncate text-xs tabular-nums`,u?`font-medium text-danger`:d?`ocx-shine font-medium`:`text-fg-subtle`),"aria-hidden":!y&&n?void 0:!0,children:u?(0,Q.jsx)(`span`,{className:`ocx-brake`,children:v}):y?v:n??t})]}):(0,Q.jsx)(`span`,{"aria-hidden":!0,className:X(`min-w-0 flex-1 truncate text-[13px] leading-5`,b===`stop`?`font-medium text-danger`:b===`restart`?`ocx-shine font-medium`:`text-fg-muted`),children:S})]}),m&&(0,Q.jsx)(KZ,{onClick:m.onClick,disabled:m.busy,label:m.busy?m.busyLabel:m.label,title:m.label,children:(0,Q.jsx)(Ie,{})}),(0,Q.jsx)(WZ,{restartLabel:d?s:o,stopLabel:u?a:i,hint:c,restarting:d,settled:g,stopping:u,onRestart:p,onStop:f,onPreview:x})]})}function KZ({onClick:e,disabled:t,label:n,title:r,children:i}){return(0,Q.jsx)(`button`,{type:`button`,onClick:e,disabled:t,"aria-label":n,title:r,className:X(`inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-[6px] bg-transparent text-fg-subtle`,`transition-[background-color,color] duration-150 ease-soft`,`focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-highlight`,`disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-3.5`,`hover:bg-accent-soft hover:text-fg`),children:i})}function qZ(e,t=1600){let[n,r]=(0,Z.useState)(!1),i=(0,Z.useRef)(e);return(0,Z.useEffect)(()=>{if(i.current&&!e){r(!0);let n=window.setTimeout(()=>r(!1),t);return i.current=e,()=>window.clearTimeout(n)}i.current=e},[e,t]),n}function JZ(e){try{window.__TAURI__?.core?.invoke?.(e).catch(()=>{})}catch{}}var YZ=`a, button, input, select, textarea, summary, [role='button'], [role='link'], [contenteditable]`;function XZ(e){return e instanceof Element&&e.closest(YZ)!==null}function ZZ(){return{onMouseDown:e=>{e.button!==0||XZ(e.target)||JZ(`plugin:window|start_dragging`)},onDoubleClick:e=>{XZ(e.target)||JZ(`plugin:window|toggle_maximize`)}}}function QZ(e){let t=window.__TAURI__?.core,n=window.devicePixelRatio,r=Number.isFinite(n)&&n>0?Math.max(2,n):2,i=!0,a=0,o,s=()=>{let t=window.devicePixelRatio,n=Number.isFinite(t)&&t>0?r/t:1,i=Math.max(1,n);if(e.classList.toggle(`app--reduced-zoom`,i>1),e.style.setProperty(`--titlebar-h`,`${Math.ceil(40*i)}px`),n>=1){e.style.setProperty(`--tl-inset`,`${Math.ceil(80*i)}px`),e.style.setProperty(`--chrome-clear`,`${Math.ceil(124*i)}px`);return}let a=Math.ceil(80*n);e.style.setProperty(`--tl-inset`,`${a}px`),e.style.setProperty(`--chrome-clear`,`${a+44}px`)},c=()=>{if(!t?.invoke)return;let e=++a;t.invoke(`plugin:window|scale_factor`).then(t=>{i&&e===a&&typeof t==`number`&&Number.isFinite(t)&&t>0&&(r=t,s())}).catch(()=>{})},l=()=>{s(),clearTimeout(o),o=setTimeout(c,80)};return s(),c(),window.addEventListener(`resize`,l),window.addEventListener(`focus`,c),()=>{i=!1,clearTimeout(o),window.removeEventListener(`resize`,l),window.removeEventListener(`focus`,c)}}function $Z({collapsed:e,onToggle:t,brand:n}){let r=b()(e?`nav.expandSidebar`:`nav.collapseSidebar`);return(0,Q.jsxs)(`div`,{className:`sidebar-top`,...ZZ(),children:[n,(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-collapse`,onClick:t,"aria-expanded":!e,"aria-controls":`app-sidebar`,"aria-label":r,title:r,children:(0,Q.jsx)(Pe,{})})]})}function eQ({children:e}){return(0,Q.jsx)(`div`,{className:`main-top`,...ZZ(),children:e})}var tQ=T({RemoteWorkspaceRoute:()=>oQ,default:()=>lQ}),nQ={home:`shellV2.navHome`,setup:`shellV2.pageChecklist`,advanced:`shellV2.pageAllSettings`,dashboard:`shellV2.pageProxyDetails`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,advisor:`nav.advisor`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,remote:`nav.remote`,"remote-workspace":`nav.remoteWorkspace`,"codex-set":`nav.codexSet`,integrations:`nav.connect`,claude:`nav.claude`},rQ=``,iQ=c(rQ);R(iQ),K();var aQ=`ocx-theme`;function oQ({available:e,apiBase:t,hubOrigin:n,onOpenRemoteLink:r}){let i=b();return e?(0,Q.jsx)(NJ,{apiBase:t,hubOrigin:n}):(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h2`,{children:i(`nav.remoteWorkspace`)}),(0,Q.jsxs)($,{tone:`warn`,children:[i(`link.workspaceUnavailable`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:r,children:i(`nav.remote`)})]})]})}function sQ(){let e=localStorage.getItem(aQ);return e===`light`||e===`dark`?e:`system`}function cQ(){let e=document.querySelector(`.sidebar .nav-item.active`),t=e?.getBoundingClientRect(),n=!!t&&t.width>0&&t.height>0&&t.right>0&&t.left<window.innerWidth&&t.bottom>0&&t.top<window.innerHeight;if(e&&n){e.focus({preventScroll:!0});return}let r=document.querySelector(`main.main`);r&&(r.tabIndex=-1,r.focus({preventScroll:!0}))}function lQ(){let{page:r,navigateToPage:i}=dZ(),[o,c]=(0,Z.useState)(wM);(0,Z.useEffect)(()=>{let e=()=>c(wM());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[l,d]=(0,Z.useState)(sQ),{locale:f,setLocale:h}=s(),g=b(),[_,v]=(0,Z.useState)(iQ),[y,x]=(0,Z.useState)(()=>!p()),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(()=>q(`shared`)),[E,k]=(0,Z.useState)(0),[A,M]=(0,Z.useState)(!1),[N,L]=(0,Z.useState)(!1),[z,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(!1),ee=(0,Z.useCallback)(()=>U(!0),[]),[G,te]=(0,Z.useState)(null),[ne,K]=(0,Z.useState)(0),J=(0,Z.useCallback)((e,t)=>{te({tone:t,text:e}),K(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!q(`shared`)&&T(!1)},t=e=>{e.detail?.plane===`shared`&&q(`shared`)&&T(!0)};window.addEventListener(B,e),window.addEventListener(D,t);let n=e=>{e.detail?.plane===`shared`&&k(e=>e+1)};return window.addEventListener(P,n),()=>{window.removeEventListener(B,e),window.removeEventListener(D,t),window.removeEventListener(P,n)}},[]),(0,Z.useEffect)(()=>{let e=cZ({initialBase:rQ,discover:F,configure:R,bootstrap:j,hasSession:q,onTargets:v,onSessionReady:T,onError:C,onSettled:x,isClientStateChanged:e=>e instanceof m});e.refresh();let t=()=>{e.refresh()},n=()=>{document.visibilityState===`visible`&&t()};return window.addEventListener(D,t),window.addEventListener(P,t),window.addEventListener(W,t),window.addEventListener(`focus`,t),document.addEventListener(`visibilitychange`,n),()=>{e.dispose(),window.removeEventListener(D,t),window.removeEventListener(P,t),window.removeEventListener(W,t),window.removeEventListener(`focus`,t),document.removeEventListener(`visibilitychange`,n)}},[]);let re=I(`machine`,_),Y=I(`shared`,_),ae=e(_);(0,Z.useEffect)(()=>{if(!w)return;let e=new AbortController;return fetch(`${Y}/api/remote-workspace`,{signal:e.signal,cache:`no-store`}).then(e=>e.ok?e.json():Promise.reject(Error(`unavailable`))).then(t=>{e.signal.aborted||L(t.available===!0)}).catch(()=>{e.signal.aborted||L(!1)}),()=>e.abort()},[r,w,Y]);let se=w&&N,ce=YX(r),le=ce?XX(ce,{remoteWorkspaceAvailable:se}):[],ue=r===`claude`?`integrations`:r,de=r===`remote`&&a()===`hub`,fe=de&&A,[pe,me]=(0,Z.useState)(!1),he=_f(),{collapsed:ge,toggle:_e}=NZ({shortcut:he}),ve=he&&xf()===`macos`,ye=he&&bZ(xf()),be=PZ({managed:ye}),xe=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(ve&&xe.current)return QZ(xe.current)},[ve]);let Se=(0,Z.useRef)(null),Ce=(0,Z.useCallback)(()=>{ge&&_e(),typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 760px)`).matches&&me(!0)},[ge,_e]),we=e=>{i(e),me(!1)},Te=e=>g(nQ[e]),Ee=e=>e!==`remote-workspace`||se,De=(0,Z.useRef)(null),Oe=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=()=>me(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,Z.useEffect)(()=>{if(!_f())return;let e=e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a[href]`);if(!(n instanceof HTMLAnchorElement))return;let r=n.href;Ef(r)&&(e.preventDefault(),window.location.assign(r))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[]),(0,Z.useEffect)(()=>{let e=document.documentElement;l===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(aQ)):(e.setAttribute(`data-theme`,l),localStorage.setItem(aQ,l))},[l]),(0,Z.useEffect)(()=>{if(G?.tone!==`ok`)return;let e=window.setTimeout(()=>te(null),4500);return()=>window.clearTimeout(e)},[G,ne]);let ke=Cm(_.connected||p()),Ae=bn(`app-health:${re}${ke}`,[re,ke,y],e=>Em(re,ke,e),{pollMs:3e4,enabled:y}),je=(0,Q.jsx)(LZ,{theme:l,onChange:d}),Me=Ae.data?.version??`2.100.5`,Ne=Sm(Ae.data,Ae.error),Pe=Ne?Ae.data?.uptime??null:null,Fe=Pe===null?void 0:g(`shellV2.uptimeValue`,{h:String(Math.floor(Pe/3600)),m:String(Math.floor(Pe%3600/60))}),[Le,Re]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{if(!pe)return;let e=e=>{e.key===`Escape`&&me(!1)};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[pe]),(0,Z.useEffect)(()=>{if(pe){Oe.current=!0;let e=setTimeout(()=>{De.current?.contains(document.activeElement)||De.current?.focus()},200);return()=>clearTimeout(e)}Oe.current&&(Oe.current=!1,Se.current?.focus())},[pe]),(0,Z.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&me(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[ze,Be]=(0,Z.useState)(0),{restarting:Ve,restart:He}=jD(Y,{onSettled:()=>Be(e=>e+1),report:J}),Ue=async()=>{if(!await Ju({message:g(_.connected?`connection.disconnectConfirm`:`dash.stopConfirm`),confirmLabel:g(_.connected?`connection.disconnect`:`dash.stop`),tone:`danger`}))return;Re(!0);let e=await gZ(re,{formatFailure:e=>g(`dash.stopFailed`,{status:String(e)}),formatStillRunning:()=>g(`dash.stopStillRunning`),formatUnknown:()=>g(`dash.stopUnknown`),mode:_.connected?`client`:`standalone`});e.status!==`accepted`&&(Re(!1),J(e.message,e.status===`rejected`?`err`:`warn`))},We=async()=>{if(z)return;V(!0);let e=await n(`shared`);V(!1),e?T(!1):J(g(O(`shared`)?`connection.forgetDeviceFailed`:`connection.sessionLogoutFailed`),`err`)},Ge=O(`shared`),qe=g(Ge?`connection.forgetDevice`:`connection.sessionLogout`),Je=(0,Q.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{i(`home`),me(!1)},"aria-label":g(`nav.goHome`),title:g(`nav.goHome`),...r===`home`?{"aria-current":`page`}:{},children:[(0,Q.jsx)(kt,{className:`ui-v2 brand-logo-v2 h-[24px] w-[27px]`,label:g(`app.logoAria`)}),(0,Q.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Q.jsxs)(`span`,{className:`ver`,title:Me,children:[`v`,Me]})]}),Ye=(0,Q.jsxs)(`button`,{type:`button`,className:`brand brand-home brand--strip`,onClick:()=>i(`home`),"aria-label":g(`nav.goHome`),title:g(`nav.goHome`),...r===`home`?{"aria-current":`page`}:{},children:[(0,Q.jsx)(kt,{className:`ui-v2 brand-logo-v2 h-[22px] w-[25px]`,label:g(`app.logoAria`)}),(0,Q.jsx)(`span`,{className:`name`,children:`opencodex`})]}),Xe=y&&r!==`startup`&&(!_.connected||w)&&(0,Q.jsx)(uk,{pageName:g(`quotaSummary.aria`),title:g(`errorBoundary.title`),message:g(`errorBoundary.message`),detailsLabel:g(`errorBoundary.details`),reloadLabel:g(`errorBoundary.reload`),children:(0,Q.jsx)(OX,{apiBase:Y})},Y);return(0,Q.jsxs)(`div`,{ref:xe,className:`app${he?` app--desktop`:``}${ve?` app--macos`:``}${ge?` app--nav-collapsed`:``}`,children:[(0,Q.jsx)(BX,{apiBase:Y,enabled:y&&!_.connected&&!p()&&!S,onSettled:ee}),(0,Q.jsx)(UX,{apiBase:Y,enabled:y&&!_.connected&&!p()&&!S&&w&&H}),G&&(0,Q.jsx)(zn,{tone:G.tone,onDismiss:()=>te(null),dismissLabel:g(`common.close`),children:G.text}),(0,Q.jsxs)(`header`,{className:`mobile-topbar`,inert:pe,...he?ZZ():{},children:[(0,Q.jsx)(`button`,{ref:Se,type:`button`,className:`menu-toggle`,onClick:()=>me(e=>!e),"aria-expanded":pe,"aria-controls":`app-sidebar`,"aria-label":g(pe?`nav.closeMenu`:`nav.openMenu`),title:g(pe?`nav.closeMenu`:`nav.openMenu`),children:(0,Q.jsx)(ie,{})}),Je,(0,Q.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(_.connected||Ge)&&w&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{We()},disabled:z,"aria-label":z?g(`connection.sessionLoggingOut`):qe,title:qe,children:(0,Q.jsx)(Ie,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:Ue,disabled:Le,"aria-label":g(_.connected?`connection.disconnect`:`dash.stop`),title:g(_.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(oe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{He()},disabled:Ve,"aria-label":g(`dash.codexRestart`),title:g(`dash.codexRestart`),children:(0,Q.jsx)(Ke,{})})]})]}),pe&&(0,Q.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>me(!1),"aria-hidden":`true`}),(0,Q.jsx)($Z,{collapsed:ge,onToggle:_e,brand:Ye}),(0,Q.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${pe?` open`:``}`,ref:De,tabIndex:-1,children:[(0,Q.jsxs)(`div`,{className:`drawer-head`,children:[Je,(0,Q.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>me(!1),"aria-label":g(`nav.closeMenu`),title:g(`nav.closeMenu`),children:(0,Q.jsx)(Ie,{})})]}),(0,Q.jsx)(`nav`,{children:(0,Q.jsx)(oZ,{activeGroupId:ce?.id??null,pageLabel:Te,pageAvailable:Ee,onNavigate:we,onReveal:Ce,desktopShell:he,t:g})}),(0,Q.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Q.jsx)(GZ,{label:g(`dash.actions`),statusLabel:g(Ne?`dash.online`:`dash.offline`),online:Ne,detail:Fe,stopLabel:g(_.connected?`connection.disconnect`:`dash.stop`),stoppingLabel:g(`dash.stopping`),restartLabel:g(`dash.codexRestart`),restartingLabel:g(`dash.codexRestarting`),leverHint:g(`shellV2.leverHint`,{restart:g(`dash.codexRestart`),stop:g(_.connected?`connection.disconnect`:`dash.stop`)}),leverText:{hover:g(`shellV2.leverHover`),cancel:g(`shellV2.leverCancel`),restart:g(`shellV2.leverRelease`,{action:g(`shellV2.leverReload`)}),stop:g(`shellV2.leverRelease`,{action:_.connected?g(`connection.disconnect`):g(`shellV2.leverStop`)})},stopping:Le,restarting:Ve,onStop:Ue,onRestart:()=>{He()},session:(_.connected||Ge)&&w?{label:qe,busyLabel:g(`connection.sessionLoggingOut`),busy:z,onClick:()=>{We()}}:void 0}),(0,Q.jsxs)(`div`,{className:`sidebar-pref-row`,children:[(0,Q.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Q.jsx)(at,{"aria-hidden":!0}),(0,Q.jsx)(Vn,{value:f,options:t.map(e=>({value:e.code,label:u(e.code)})),onChange:e=>h(e),label:g(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>KX(`classic`),"aria-label":g(`shellV2.uiClassic`),title:g(`shellV2.uiClassicHint`),children:(0,Q.jsx)(Ft,{})}),je]}),(0,Q.jsx)(NX,{apiBase:Y,onOpenUpdate:()=>{me(!1),!Cf()&&i(`dashboard`,`update`)},onOpenTerminalCommand:()=>{me(!1),Tf()},version:(0,Q.jsxs)(`span`,{className:`sidebar-version`,title:Me,children:[`v`,Me]})}),ye&&(0,Q.jsx)(`div`,{className:`sidebar-meta-row`,children:(0,Q.jsx)(FZ,{percent:be.percent,canZoomIn:be.canZoomIn,canZoomOut:be.canZoomOut,onStep:be.step})})]})]}),(0,Q.jsxs)(`main`,{className:`main`,inert:pe,children:[he?(0,Q.jsx)(eQ,{children:Xe}):Xe,(0,Q.jsxs)(`div`,{className:`main-inner${r===`models`&&o===`combos`?` main-inner--combos`:``}`,children:[y&&le.length>1&&(0,Q.jsx)(sZ,{items:le.map(e=>({page:e,label:g(nQ[e])})),currentPage:r,onNavigate:i,ariaLabel:g(`nav.sectionNavigation`),onFocusOrphaned:cQ}),y&&_.link&&(0,Q.jsx)($,{tone:`warn`,children:_.link.home?g(`connection.linkManaged`,{home:_.link.home,linkId:_.link.linkId}):g(`connection.linkManagedUnnamed`,{linkId:_.link.linkId})}),(0,Q.jsx)(uk,{pageName:g(nQ[ue]),title:g(`errorBoundary.title`),message:g(`errorBoundary.message`),detailsLabel:g(`errorBoundary.details`),reloadLabel:g(`errorBoundary.reload`),children:y?(0,Q.jsxs)(Q.Fragment,{children:[S&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:g(S===`client-state-changed`?`connection.clientStateChanged`:`connection.machineUnavailable`)}),(_.connected&&!w||fe)&&(0,Q.jsx)(eH,{target:_.shared,focusOnMount:fe,onConnected:async e=>{fe&&await MV(Y,void 0,e),e.throwIfAborted(),M(!1),T(q(`shared`)),k(e=>e+1)}},`${_.shared.serverOrigin}:${_.shared.bootstrapPath}`),r===`home`&&(0,Q.jsx)(km,{apiBase:Y,navigate:i,onReloadCodex:()=>{He()},reloadingCodex:Ve}),r===`setup`&&(0,Q.jsx)(Lm,{apiBase:Y,navigate:i}),r===`advanced`&&(0,Q.jsx)(Vm,{navigate:i}),r===`dashboard`&&(0,Q.jsx)(Gp,{apiBase:Y,targetKey:ae.key,readOnly:_.link!==void 0,connected:_.connected,authenticationPending:_.connected&&!w,refreshEpoch:E}),r===`startup`&&(0,Q.jsx)(iJ,{apiBase:Y,machineApiBase:re,connected:_.connected}),r===`providers`&&(0,Q.jsx)(vE,{apiBase:Y,targetKey:ae.key,targetLabel:ae.label}),r===`models`&&(0,Q.jsx)(eN,{apiBase:Y,restartEpoch:ze,connected:_.connected,catalogSyncedAt:_.catalogSyncedAt,reportRestart:J},Y),r===`subagents`&&(0,Q.jsx)(ZN,{apiBase:Y},Y),r===`advisor`&&(0,Q.jsx)(uN,{apiBase:Y},Y),r===`logs`&&(0,Q.jsx)(iL,{apiBase:Y}),r===`usage`&&(0,Q.jsx)(iz,{apiBase:Y,connected:_.connected||p(),apiKeyId:_.apiKeyId,topology:S||p()&&!_.connected?`unknown`:_.usageTopology}),r===`storage`&&(0,Q.jsx)(Nz,{apiBase:Y}),r===`remote`&&!fe&&(0,Q.jsx)(QY,{apiBase:Y,diagnosticsApiBase:_.link?re:Y,sessionReady:w,pairingRecoveryAvailable:de,onRequestPairing:()=>M(!0),workspaceAvailable:se,onOpenWorkspace:()=>i(`remote-workspace`)},`${Y}:${E}`),r===`remote-workspace`&&(0,Q.jsx)(oQ,{available:se,apiBase:Y,hubOrigin:_.shared.serverOrigin,onOpenRemoteLink:()=>i(`remote`)}),r===`codex-set`&&(0,Q.jsx)(MH,{apiBase:Y,machineApiBase:re,connected:_.connected,targetKey:ae.key}),ue===`integrations`&&(0,Q.jsx)(Oq,{apiBase:Y,machineApiBase:re,connected:_.connected})]}):(0,Q.jsx)(`div`,{className:`alert`,children:g(`connection.discovering`)})},ue)]})]})]})}export{pa as $,jo as A,oi as At,eo as B,Xo as C,mi as Ct,Lo as D,li as Dt,Ho as E,ui as Et,xo as F,Aa as G,Wa as H,ao as I,Ea as J,ja as K,mo as L,ko as M,To as N,Io as O,si as Ot,Co as P,da as Q,ro as R,oQ as RemoteWorkspaceRoute,Qo as S,hi as St,Uo as T,di as Tt,Ha as U,no as V,Ma as W,Ca as X,wa as Y,Ta as Z,os as _,bi as _t,Fs as a,qi as at,es as b,_i as bt,ys as c,Xi as ct,hs as d,lQ as default,ji as dt,va as et,ms as f,Ai as ft,ss as g,Ci as gt,ls as h,wi as ht,Is as i,Ki as it,Ao as j,ri as jt,Po as k,ci as kt,vs as l,Wi as lt,us as m,Oi as mt,_c as n,$i as nt,Ps as o,Ji as ot,fs as p,Ei as pt,Oa as q,cc as r,Qi as rt,Ms as s,Yi as st,tQ as t,ua as tt,_s as u,Vi as ut,as as v,yi as vt,Go as w,fi as wt,$o as x,gi as xt,ts as y,vi as yt,io as z};