@bitkyc08/opencodex 2.96.0 → 2.98.0-preview.20261107
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.
- package/bin/ocx.mjs +215 -20
- package/gui/dist/assets/App-6TFtZsUF.css +1 -0
- package/gui/dist/assets/App-B8_sOxoz.js +59 -0
- package/gui/dist/assets/Tray-DpWEp6ee.js +1 -0
- package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
- package/gui/dist/assets/brand-mark-VPhzz-WE.js +1 -0
- package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/gui/dist/assets/index-5REODpG3.css +2 -0
- package/gui/dist/assets/index-BWKBeK77.js +94 -0
- package/gui/dist/assets/segment-thumb-features-BQYzrze9.js +1 -0
- package/gui/dist/classic/assets/App-Bz65x1J6.js +58 -0
- package/gui/dist/{assets/Tray-BOPQyDbH.js → classic/assets/Tray-kk7mdO6I.js} +1 -1
- package/gui/dist/classic/assets/index-Dp2j8bSc.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CvamtHjB.js +1 -0
- package/gui/dist/classic/index.html +47 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/favicon.svg +14 -0
- package/gui/dist/index.html +15 -2
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +17 -8
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/google.ts +7 -7
- package/src/adapters/kiro/adapter.ts +18 -3
- package/src/adapters/kiro/conversation.ts +8 -8
- package/src/adapters/kiro/payload.ts +45 -12
- package/src/adapters/kiro/stream.ts +230 -14
- package/src/adapters/kiro/structured-output-json.ts +191 -0
- package/src/adapters/kiro/structured-output-schema.ts +542 -0
- package/src/adapters/kiro/structured-output.ts +367 -0
- package/src/adapters/kiro-constants.ts +24 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/kiro-tools.ts +14 -9
- package/src/adapters/kiro-wire.ts +9 -5
- package/src/adapters/ollama-native.ts +11 -1
- package/src/adapters/openai-chat/messages.ts +58 -5
- package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
- package/src/adapters/openai-chat/passthrough.ts +5 -3
- package/src/adapters/openai-chat/tool-schema.ts +83 -13
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/opengateway-input.ts +18 -6
- package/src/adapters/openai-responses/passthrough.ts +5 -4
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/qoder/live-models.ts +115 -1
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/failure-verdict.ts +21 -0
- package/src/claude/inbound-content-options.ts +15 -2
- package/src/claude/inbound-model-options.ts +2 -1
- package/src/claude/inbound-records.ts +2 -0
- package/src/claude/inbound.ts +17 -11
- package/src/claude/outbound.ts +98 -22
- package/src/cli/capabilities-access-remote.ts +13 -0
- package/src/cli/capabilities-base.ts +26 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capabilities-provider-models.ts +3 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +12 -4
- package/src/cli/config-command.ts +11 -2
- package/src/cli/connect.ts +17 -2
- package/src/cli/dispatch.ts +14 -177
- package/src/cli/doctor.ts +95 -7
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +17 -8
- package/src/cli/link-apply-restart.ts +9 -2
- package/src/cli/link.ts +1 -1
- package/src/cli/models.ts +124 -38
- package/src/cli/registry.ts +12 -4
- package/src/cli/restart-failure.ts +17 -0
- package/src/cli/root.ts +8 -0
- package/src/cli/stop-approval.ts +2 -2
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +161 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/cli/system-restart-client.ts +5 -0
- package/src/cli/uninstall-client-state.ts +12 -1
- package/src/cli/update-restart-child.ts +13 -3
- package/src/cli/update-restart-home.ts +6 -3
- package/src/cli/update-restart.ts +36 -19
- package/src/client/connect.ts +35 -15
- package/src/client/hub-client.ts +5 -0
- package/src/client/link-home.ts +3 -2
- package/src/client/link-management-relay.ts +39 -2
- package/src/client/link-readiness.ts +3 -1
- package/src/client/machine-api.ts +2 -1
- package/src/client/machine-listener.ts +10 -0
- package/src/client/orphan-token-recovery.ts +322 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/auth-context.ts +49 -103
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +18 -12
- package/src/codex/forward-transport-headers.ts +35 -6
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/lineage.ts +13 -7
- package/src/codex/native-profile-api.ts +27 -1
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/shim-diagnostics.ts +7 -0
- package/src/codex/shim-legacy-record.ts +290 -0
- package/src/codex/shim-windows-refresh.ts +9 -2
- package/src/codex/shim-wrapper-write.ts +7 -0
- package/src/codex/shim.ts +80 -21
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/diagnostics.ts +9 -9
- package/src/config/load-degrade.ts +27 -27
- package/src/config/process-state.ts +5 -0
- package/src/config/provider-validation.ts +9 -2
- package/src/config/removed-opencode-free-backup.ts +6 -3
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/config/tracked-runtime-inspection.ts +3 -3
- package/src/generated/compatibility-version.json +595 -255
- package/src/images/loop.ts +4 -3
- package/src/lib/client-error-body.ts +215 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership-removal.ts +422 -0
- package/src/lib/config-ownership.ts +650 -81
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/crash-guard.ts +4 -2
- package/src/lib/desktop-cli-handoff.d.mts +4 -5
- package/src/lib/desktop-cli-handoff.mjs +18 -17
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/errors.ts +1 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/local-management-capability.ts +3 -1
- package/src/lib/messages-error-body.ts +162 -0
- package/src/lib/messages-sse-error-presentation.ts +93 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/passive-read.ts +9 -4
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/socks5-fetch.ts +21 -9
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +95 -12
- package/src/lib/windows-owner-acl.ts +22 -9
- package/src/lib/winsw.ts +5 -5
- package/src/lib/workflow-budget.ts +3 -1
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +42 -73
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +21 -11
- package/src/protocols/codecs/messages-ir.ts +15 -9
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +30 -7
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/encoders/messages.ts +72 -28
- package/src/protocols/trace.ts +18 -0
- package/src/providers/antigravity-models.ts +45 -12
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/free-directory.ts +2 -2
- package/src/providers/quota/anthropic-usage-windows.ts +13 -3
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/reasoning-metadata.ts +2 -1
- package/src/providers/registry/entries-extended.ts +9 -0
- package/src/providers/request-pacing.ts +3 -2
- package/src/reasoning-effort.ts +7 -2
- package/src/remote/hub-usage.ts +3 -0
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +57 -0
- package/src/server/anthropic-rate-limit-headers.ts +75 -3
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +174 -84
- package/src/server/context-history.ts +5 -1
- package/src/server/gui-static.ts +4 -1
- package/src/server/hub-usage.ts +7 -2
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/link-management.ts +8 -0
- package/src/server/index/ollama-routes.ts +91 -0
- package/src/server/index/serve-options.ts +44 -24
- package/src/server/index/startup-warnings.ts +5 -12
- package/src/server/index/websocket-handler.ts +5 -2
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +9 -3
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/logs-usage-routes.ts +89 -4
- package/src/server/management/provider-routes.ts +2 -22
- package/src/server/management/qoder-provider-probe.ts +105 -0
- package/src/server/management/route-registry.ts +4 -1
- package/src/server/management/usage-aggregate-cache.ts +15 -5
- package/src/server/management/usage-source-facets.ts +38 -0
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +12 -4
- package/src/server/messages-native.ts +123 -47
- package/src/server/messages-response-headers.ts +25 -11
- package/src/server/messages-shared.ts +99 -65
- package/src/server/messages-sse-error-filter.ts +199 -0
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +91 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +17 -6
- package/src/server/responses/adapter-delivery.ts +17 -10
- package/src/server/responses/adapter-dispatch.ts +32 -31
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +24 -19
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/codex-ws-wire.ts +19 -3
- package/src/server/responses/compact.ts +57 -24
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +17 -6
- package/src/server/responses/core-combo-failure.ts +7 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +43 -27
- package/src/server/responses/core-errors.ts +24 -21
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +9 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/empty-completion-guard.ts +4 -1
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +20 -18
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +69 -48
- package/src/server/responses/request-transport.ts +36 -31
- package/src/server/responses/response-effects.ts +3 -2
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/terminal-guard.ts +30 -0
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/restart-replacement.ts +3 -1
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/sse-payload-rewrite.ts +23 -11
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/server/ws-bridge.ts +4 -0
- package/src/service/definition.ts +36 -4
- package/src/service/launchd.ts +89 -32
- package/src/service/logging.ts +34 -7
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/service/plist-xml.ts +59 -0
- package/src/service/state.ts +8 -0
- package/src/service/systemd-env.ts +2 -0
- package/src/service/systemd.ts +31 -7
- package/src/service/windows-taskxml.ts +16 -7
- package/src/service-manager-probe.ts +4 -10
- package/src/types/config.ts +2 -0
- package/src/types/provider.ts +2 -0
- package/src/types/request.ts +13 -1
- package/src/update/config-preflight.ts +48 -0
- package/src/update/index.ts +148 -26
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/client.ts +43 -0
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +64 -27
- package/src/usage/source-facets.ts +51 -0
- package/src/usage/source-filter.ts +65 -0
- package/src/usage/summary.ts +50 -8
- package/src/web-search/anthropic-executor.ts +105 -24
- package/src/web-search/executor.ts +5 -3
- package/src/web-search/loop.ts +33 -6
- package/src/web-search/progress-stream.ts +64 -5
- package/gui/dist/assets/App-bwugJRKn.js +0 -58
- package/gui/dist/assets/index-ebuVUtB7.js +0 -94
- package/gui/dist/assets/quota-summary-6HsrHQAy.js +0 -1
- /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
- /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/segment-thumb-features-BQYzrze9.js","assets/index-BWKBeK77.js","assets/index-5REODpG3.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,L as l,M as u,N as d,O as f,P as p,R as m,S as h,T as g,U as _,V as v,W as y,_ as b,a as x,b as S,c as C,d as w,f as T,g as E,h as D,i as O,j as k,k as A,l as j,m as M,n as N,o as P,p as F,r as I,s as L,t as R,u as z,v as B,w as V,x as H,y as U,z as W}from"./index-BWKBeK77.js";import{$ as ee,A as te,At as ne,B as G,Bt as K,C as re,Ct as q,D as ie,Dt as ae,E as oe,Et as se,F as ce,Ft as le,G as ue,Gt as J,H as de,Ht as fe,I as pe,It as me,J as he,Jt as ge,K as _e,Kt as ve,L as ye,Lt as be,M as xe,Mt as Se,N as Ce,Nt as we,O as Te,Ot as Ee,P as De,Pt as Oe,Q as ke,R as Ae,Rt as je,S as Me,St as Ne,T as Pe,Tt as Fe,U as Ie,Ut as Le,V as Re,Vt as ze,W as Be,Wt as Ve,X as He,Y as Ue,Yt as We,Z as Ge,_ as Ke,_t as qe,at as Je,b as Ye,bt as Xe,ct as Ze,dt as Qe,et as $e,ft as et,g as tt,gt as nt,h as rt,ht as it,it as at,j as ot,jt as st,k as ct,kt as lt,lt as ut,mt as dt,n as ft,nt as Y,ot as pt,pt as mt,q as ht,qt as gt,r as _t,rt as vt,st as yt,t as bt,tt as xt,ut as St,v as Ct,vt as wt,w as Tt,wt as Et,x as Dt,xt as Ot,y as kt,yt as At,z as jt,zt as Mt}from"./brand-mark-VPhzz-WE.js";var X=o(_(),1);function Nt(){return typeof document<`u`&&document.visibilityState===`hidden`||typeof window<`u`&&window.__OPENCODEX_HOST_VISIBLE__===!1}function Pt(e){let t=Nt(),n=()=>{let n=Nt();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 Ft=new Map,It=new Set,Lt=3e4,Rt=`ocx-resource-deadline`,zt={data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1};function Bt(e){let t=Ft.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},Ft.set(e,t)),t}function Vt(e){for(let t of e.listeners)t()}var Ht=new Map;function Ut(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0&&e.pauseWhenHiddenByListener.get(t)===!1)return!0;return!1}function Wt(e){if(e.stores.size===0)return!1;if(!Xt())return!0;for(let t of e.stores)if(Ut(t))return!0;return!1}function Gt(e){for(let t of e.stores){let e=Zt(t);e&&rn(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}function Kt(e,t){let n=Wt(t);n&&t.timer===null?t.timer=setInterval(()=>Gt(t),e):(!n&&t.timer!==null&&(clearInterval(t.timer),t.timer=null),t.stores.size===0&&Ht.delete(e))}function qt(){for(let[e,t]of[...Ht])Kt(e,t)}function Jt(e){let t=e.pollIntervalMs;if(t===void 0)return;let n=Ht.get(t);e.pollIntervalMs=void 0,n&&(n.stores.delete(e),Kt(t,n))}function Yt(e,t){let n=Ht.get(t);n||(n={timer:null,stores:new Set},Ht.set(t,n)),n.stores.add(e),e.pollIntervalMs=t,Kt(t,n)}function Xt(){return Nt()}function Zt(e){if(!Xt())return Qt(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 Qt(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 $t(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)Jt(e),nn(e);else if(t===e.pollIntervalMs){let n=Ht.get(t);n&&Kt(t,n),tn(e)}else Jt(e),Yt(e,t),tn(e)}var en=null;function tn(e){typeof document>`u`||en||(en=Pt(()=>{if(qt(),!Xt())for(let e of Ht.values())for(let t of e.stores){let e=Qt(t);e&&rn(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}))}function nn(e){en&&(Ht.size>0||(en(),en=null))}async function rn(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??Lt,s=!1,c=setTimeout(()=>{s=!0,i.abort(Rt)},o),l=e.snapshot.data===void 0||n?.forceLoading===!0;e.snapshot={...e.snapshot,loading:l?!0:e.snapshot.loading,refreshing:!0},Vt(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,It.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),Vt(e)}}function an(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},Vt(e)),!0)}function on(e,t){Jt(t),nn(t),setTimeout(()=>{t.subscriberCount===0&&Ft.get(e)===t&&(t.inflight?.abort(),t.inflight=null,t.inflightOwner=null,Ft.delete(e))},0)}function sn(e,t,n){let{fetcher:r,pollMs:i,pauseWhenHidden:a=!0,deadlineMs:o,staleAfterMs:s}=n,c=Bt(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||It.has(e)||n)&&rn(c,r,{replaceInflight:!0,owner:t,deadlineMs:o})}return $t(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=an(c,t);if(c.subscriberCount===0)on(e,c);else{if(n){let e=Qt(c);e&&rn(c,e.fetcher,{replaceInflight:!0,owner:e.owner,deadlineMs:e.deadlineMs})}$t(c)}}}function cn(e,t,n,r){let i=Bt(e);i.subscriberCount===0&&i.snapshot.data===void 0&&(pn(e,t),!It.has(e)&&typeof r==`number`&&typeof n==`number`&&Date.now()-n<r&&(i.seedNeedsRevalidate=!1,i.lastSettledAt=n))}function ln(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&&cn(e,n.initialData,n.initialDataCachedAt,s);let c=(0,X.useRef)(t);(0,X.useLayoutEffect)(()=>{c.current=t});let l=(0,X.useCallback)(e=>c.current(e),[]),u=(0,X.useRef)(null),d=(0,X.useCallback)(t=>r?(u.current=t,sn(e,t,{fetcher:l,pollMs:i,pauseWhenHidden:a,deadlineMs:o,staleAfterMs:s})):()=>{},[e,l,i,r,a,o,s]),f=(0,X.useCallback)(()=>r?Bt(e).snapshot:zt,[e,r]),p=(0,X.useSyncExternalStore)(d,f,f),m=(0,X.useCallback)(t=>{if(!r)return;let n=Bt(e);rn(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 un(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 dn(e,t,n,r){let i=ln(e,n,r),a=(0,X.useRef)(null),o=(0,X.useRef)(null);return(0,X.useLayoutEffect)(()=>{let n=a.current,r=o.current;a.current=t,o.current=e,un(n,t)&&(r===null||r===e)&&i.refresh({forceLoading:!0})}),i}function fn(e){It.add(e);let t=Ft.get(e);if(!t)return;let n=Qt(t);n&&rn(t,n.fetcher,{replaceInflight:!0,owner:n.owner,deadlineMs:n.deadlineMs})}function pn(e,t){let n=Bt(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(),Vt(n)}function mn(e){return e.replace(/^#\/?/,``)}function hn(e){let t=e.indexOf(`?`);return t<0?{path:e,query:``}:{path:e.slice(0,t),query:e.slice(t+1)}}function gn(e,t=window){let n=mn(e);if(mn(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function _n(e,t=window){let n=mn(e);mn(t.location.hash)!==n&&(t.location.hash=n)}var vn=s(),yn=4,bn=8,xn=8,Sn=280,Cn=120,wn=160,Tn=12;function En(){return typeof window<`u`?window.innerHeight:800}function Dn(){return typeof window<`u`?window.innerWidth:1024}function On(e,{align:t,placement:n=`below`,menuHeight:r=Sn,maxMenuHeight:i=Sn,menuWidth:a}={}){let o=Math.min(Math.max(r,Cn),i),s=En(),c=Dn();if(n===`right`){let t=s-e.top-xn,n=e.top-xn,r=o+bn>t&&n>t,a=Math.max(xn,Math.min(e.right+Tn,c-wn-xn));return r?{position:`fixed`,left:a,bottom:s-e.top+bn,minWidth:wn,maxHeight:Math.max(Cn,Math.min(i,e.top-xn-yn))}:{position:`fixed`,top:e.top,left:a,minWidth:wn,maxHeight:Math.max(Cn,Math.min(i,s-e.top-xn))}}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-xn,f=e.top-xn;if(o+yn>d&&f>d){let t={position:`fixed`,bottom:s-e.top+bn,minWidth:u,maxHeight:Math.max(0,Math.min(i,f-yn))};return l===`right`?t.right=Math.max(xn,c-e.right):t.left=Math.max(xn,Math.min(e.left,c-xn-u)),t}let p={position:`fixed`,top:e.bottom+yn,minWidth:u,maxHeight:Math.max(0,Math.min(i,d-yn))};return l===`right`?p.right=Math.max(xn,c-e.right):p.left=Math.max(xn,Math.min(e.left,c-xn-u)),p}var Z=I();function kn({on:e,mixed:t=!1,onClick:n,disabled:r,label:i,showLabel:a=!1,title:o}){let s=a&&!!i;return(0,Z.jsxs)(`button`,{type:`button`,className:`switch${e?` on`:``}${t?` mixed`:``}${s?` switch-labeled`:``}`,onClick:n,disabled:r,"aria-pressed":t?`mixed`:e,"aria-label":s?void 0:i??(e?`enabled`:`disabled`),title:o,children:[(0,Z.jsx)(`span`,{className:`knob`}),s?(0,Z.jsx)(`span`,{className:`switch-labeled-text text-label muted`,children:i}):null]})}function Q({tone:e,children:t}){return(0,Z.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,Z.jsx)(ut,{}):(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{children:t})]})}function An({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,vn.createPortal)((0,Z.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,Z.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,Z.jsx)(ut,{}):(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,Z.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function jn(e){return e.textValue===void 0?typeof e.label==`string`||typeof e.label==`number`?String(e.label):e.value:e.textValue}function $({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,X.useId)(),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(),[O,k]=(0,X.useState)(!1),A=m??!O,j=(0,X.useRef)(null),M=(0,X.useRef)(null),N=(0,X.useRef)(null),P=(0,X.useRef)({text:``,at:0}),F=(0,X.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,X.useCallback)((e=!1)=>{C(!1),T(null),e&&M.current?.focus()},[]),V=(0,X.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&&jn(r).toLocaleLowerCase().startsWith(a))return V(n),!0}return!1},U=(0,X.useCallback)(e=>{if(!A)return;let t=M.current;t&&D(On(t.getBoundingClientRect(),{align:d,placement:f,menuHeight:e}))},[d,f,A]);(0,X.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,X.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,X.useLayoutEffect)(()=>{if(!S||!A||!N.current||!M.current)return;let e=N.current.offsetHeight;if(!e)return;let t=On(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,X.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()}},te=S&&t[R]?F(R):void 0,ne=S&&!r?(0,Z.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,Z.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:Y(`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,Z.jsxs)(`div`,{ref:j,className:Y(`custom-select`,_&&`w-full min-w-0`,h),style:{position:`relative`,display:_?`block`:`inline-block`,...u},children:[(0,Z.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:Y(`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":te,"aria-label":a,children:[(0,Z.jsx)(`span`,{className:_?`min-w-0 truncate`:void 0,children:I?.label??e}),(0,Z.jsx)(St,{style:{flexShrink:0,width:12,height:12,color:`var(--muted)`,transform:S?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),(b||y!==void 0)&&(0,Z.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?ne&&(0,vn.createPortal)(ne,document.body):ne]})}function Mn({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,X.useRef)(null),d=(0,X.useRef)(null),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)({}),g=(0,X.useId)();(0,X.useLayoutEffect)(()=>{if(!e)return;let t=()=>{u.current&&h(On(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,X.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,Z.jsx)(`div`,{ref:d,id:g,role:`dialog`,"aria-label":r,className:Y(`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,Z.jsxs)(`div`,{className:`custom-select`,style:{position:`relative`,display:`inline-block`},children:[(0,Z.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,Z.jsx)(St,{style:{flexShrink:0,width:12,height:12,color:`var(--muted)`}})]}),f?_:_&&(0,vn.createPortal)(_,document.body)]})}$.Popup=Mn;function Nn({icon:e,title:t,children:n,className:r,style:i}){return(0,Z.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,Z.jsx)(`div`,{className:`title`,children:t}),n&&(0,Z.jsx)(`div`,{className:`text-control`,children:n})]})}function Pn({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,X.useState)(!1),o=(0,X.useId)(),s=(0,X.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,X.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,Z.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,Z.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var Fn=45e3,In=2147483647;async function Ln(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 Rn(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function zn(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=Rn(await e.json(),t)}catch{}throw Error(n)}return Ln(e)}async function Bn(e){if(!e.ok)return null;try{return await Ln(e)}catch{return null}}var Vn=[`gpt-6-luna`,`gpt-5.6-luna`];function Hn(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length===0?Vn:t.filter(e=>!e.includes(`/`))}function Un(e){return Hn(e).join(`, `)}function Wn(e){return Hn(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function Gn(e,t){return Hn(t).some(t=>e.startsWith(t))}function Kn(e,t){let n=Hn(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 qn(e,t,n=[`gpt-6.1-terra`,`gpt-5.6-terra`]){let r=Hn(e),i=n.some(e=>e!==``&&r.some(t=>e.startsWith(t))),a=Wn(e);return i?a:`${a} (+ ${t})`}var Jn=`dashboard/update`;function Yn(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function Xn(){return window.location.hash.replace(/^#\/?/,``)===Jn}function Zn(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function Qn(e,t){let n=await zn(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var $n=[`low`,`medium`,`high`,`xhigh`];function er(e){return e?.includes(`-preview.`)?`preview`:`latest`}function tr(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 nr(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 rr(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 ir(e){return{vision:{reasoning:e}}}function ar(e){return{vision:{enabled:e}}}function or(e){return{webSearch:{enabled:e}}}function sr(e){return e?.applied===!1&&e.reason!==`not_requested`}function cr(e,t){return t?.reason===`not_requested`&&sr(e)?e:t}function lr(e){return{vision:{maxDescriptionsPerTurn:e}}}function ur(e){return{vision:{timeoutMs:e}}}var dr=Fn,fr=In,pr=1;function mr(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function hr(e){let t=mr(e);if(!(t===void 0||t<pr||t>fr))return t}var gr=[`low`,`medium`,`high`,`xhigh`,`max`];function _r(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...gr];let r=gr.filter(e=>n.includes(e));return r.length>0?r:[...gr]}function vr(e,t){let n=yr(e,t);return e.includes(n)?e:[n,...e]}function yr(e,t){if(e.length===0||e.includes(t))return t;let n=gr.indexOf(t),r=e[0],i=gr.indexOf(r);for(let t of e){let e=gr.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function br(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 xr(e,t,n,r){if(e===void 0){let e=br(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 Sr(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):br(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function Cr(e,t,n){let r=Hn(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 wr(e,t){let n=e.find(e=>e.id===t)?.provider;return n===`anthropic`||n===`anthropic2`?`anthropic`:`openai`}function Tr(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 Er(e,t,n){let r=t.find(e=>e.value===n);return{backend:r?.backend??wr(e,n),model:r?.model??n}}function Dr(e,t,n){return t.find(e=>e.value===n)?.backend||(n.includes(`/`)?`routed`:wr(e,n))}var Or=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{Or=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{Or=!1},{capture:!0,passive:!0}));function kr(e){if(e){if(Or)e.focus({preventScroll:!0});else try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function Ar(e,t){let n=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let r=n.current;r&&(e?r.open||r.showModal():(r.open&&r.close(),kr(t.current)))},[e,t]),(0,X.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),kr(t.current)},[t]),n}var jr=`https://opencodex.me/guides/subagent-v1-default/`;function Mr(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.mode;return n!==`v1`&&n!=="default"&&n!==`v2`||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:jr}}function Nr(e){return e==="default"?`base`:e}function Pr({reason:e,mode:t,docsUrl:n,busy:r=!1,onContinue:i,onChooseV1:a,onDismiss:o}){let s=c(),l=(0,X.useId)(),u=(0,X.useId)(),d=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,X.useCallback)(e=>{e.preventDefault(),!r&&o()},[r,o]),p=Nr(t),m=e===`advisory`;return(0,Z.jsxs)(`dialog`,{ref:d,"aria-labelledby":l,"aria-describedby":u,className:`modal-overlay`,"data-subagent-surface-reason":e,onCancel:f,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,disabled:r,onClick:()=>{r||o()}}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:480},children:[(0,Z.jsx)(`h3`,{id:l,children:s(m?`subagentSurface.advisoryTitle`:`subagentSurface.selectionTitle`,{mode:p})}),(0,Z.jsxs)(`div`,{id:u,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Z.jsx)(at,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Z.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:s(m?`subagentSurface.advisoryBody`:`subagentSurface.selectionBody`,{mode:p})})]}),(0,Z.jsx)(`p`,{className:`text-label`,style:{marginTop:12},children:(0,Z.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:s(`subagentSurface.learnMore`)})}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:i,children:s(`subagentSurface.continue`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:a,children:s(`subagentSurface.switchToV1`)})]})]})]})}function Fr(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsxs)(`div`,{className:`modal-card`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,Z.jsxs)(`div`,{className:`update-row`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,Z.jsx)($,{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,Z.jsx)(Nn,{className:`update-empty`,icon:(0,Z.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{children:c})]}),l&&!s&&(0,Z.jsxs)(`div`,{className:`update-box`,children:[(0,Z.jsxs)(`div`,{className:`spread`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,Z.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,Z.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,Z.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),l.command&&(0,Z.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,Z.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,Z.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Z.jsx)(at,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,Z.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Z.jsx)(at,{}),` `,t(`dash.updateUnavailable`),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,Z.jsx)(Mt,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,Z.jsxs)(`div`,{className:`update-recheck`,children:[(0,Z.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:tr(l.reason,t)})}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,Z.jsx)(Mt,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,Z.jsxs)(`div`,{className:`spread update-restart`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,Z.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,Z.jsx)(`span`,{className:`knob`})})]})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,Z.jsx)(`div`,{style:{marginTop:12},children:(0,Z.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,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:Un(C?.sourceModels)})}),(0,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]}),(E||T)&&(0,Z.jsx)(Pr,{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 Ir({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,Z.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,Z.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,Z.jsx)(Nn,{title:e(`dash.noModels`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Z.jsx)(ze,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Z.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,Z.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,Z.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,Z.jsxs)(`div`,{className:`dash-model-group`,children:[(0,Z.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,Z.jsx)(St,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`font-semibold`,children:Ge(t,e)}),(0,Z.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,Z.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,Z.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}function Lr(e,t){let n=Math.max(0,Math.floor(e)),r=m(t,`uptime.day`),i=m(t,`uptime.hour`),a=m(t,`uptime.minute`),o=m(t,`uptime.second`);if(n<300)return`${n}${o}`;let s=Math.floor(n/60);if(s<60)return`${s}${a}`;let c=Math.floor(s/60);if(c<24){let e=s%60;return e>0?`${c}${i} ${e}${a}`:`${c}${i}`}let l=Math.floor(c/24),u=c%24;return u>0?`${l}${r} ${u}${i}`:`${l}${r}`}function Rr(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 zr(e){return!!e&&typeof e==`object`&&`error`in e&&e.error===`read_failed`}var Br=class extends Error{constructor(){super(`usage ledger read failed`),this.name=`UsageReadFailedError`}};async function Vr(e,t){let n;try{n=await e.json()}catch{throw Error(t??`${e.status} ${e.statusText}`.trim())}if(zr(n))throw new Br;if(!e.ok)throw Error(t??`${e.status} ${e.statusText}`.trim());return n}function Hr(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}function Ur({data:e}){let t=c();return Rr(e).usageIncomplete?(0,Z.jsx)(Q,{tone:`warn`,children:t(`usage.incomplete`)}):null}var Wr=(0,X.createContext)({});function Gr(e){let t=(0,X.useRef)(null);return t.current===null&&(t.current=e()),t.current}var Kr=typeof window<`u`?X.useLayoutEffect:X.useEffect,qr=(0,X.createContext)(null);function Jr(e,t){e.indexOf(t)===-1&&e.push(t)}function Yr(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var Xr=(e,t,n)=>n>t?t:n<e?e:n,Zr={},Qr=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),$r=e=>/^0[^.\s]+$/u.test(e);function ei(e){let t;return()=>(t===void 0&&(t=e()),t)}var ti=e=>e,ni=class{constructor(){this.subscriptions=[]}add(e){return Jr(this.subscriptions,e),()=>this.remove(e)}remove(e){Yr(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}},ri=e=>e*1e3,ii=e=>e/1e3,ai=(e,t)=>t?1e3/t*e:0,oi=e=>Array.isArray(e)&&typeof e[0]==`number`,si={delta:0,timestamp:0,isProcessing:!1},ci;function li(){ci=void 0}var ui={now:()=>(ci===void 0&&ui.set(si.isProcessing||Zr.useManualTiming?si.timestamp:performance.now()),ci),set:e=>{ci=e,queueMicrotask(li)}},di=e=>Math.round(e*1e5)/1e5,fi=e=>t=>typeof t==`string`&&t.startsWith(e),pi=fi(`--`),mi=fi(`var(--`),hi=e=>mi(e)?gi.test(e.split(`/*`)[0].trim()):!1,gi=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function _i(e){return typeof e==`string`&&e.split(`/*`)[0].includes(`var(--`)}var vi={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},yi={...vi,transform:e=>Xr(0,1,e)},bi={...vi,default:1},xi=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Si(e){return e==null}var Ci=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,wi=(e,t)=>n=>!!(typeof n==`string`&&Ci.test(n)&&n.startsWith(e)||t&&!Si(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ti=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(xi);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Ei=e=>Xr(0,255,e),Di={...vi,transform:e=>Math.round(Ei(e))},Oi={test:wi(`rgb`,`red`),parse:Ti(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Di.transform(e)+`, `+Di.transform(t)+`, `+Di.transform(n)+`, `+di(yi.transform(r))+`)`},ki=(e,t,n)=>{let r=e.substring(1+t*n,1+(t+1)*n);return n>1?r:r+r};function Ai(e){let t=e.length>5?2:1,n=ki(e,3,t);return{red:parseInt(ki(e,0,t),16),green:parseInt(ki(e,1,t),16),blue:parseInt(ki(e,2,t),16),alpha:n?parseInt(n,16)/255:1}}var ji={test:wi(`#`),parse:Ai,transform:Oi.transform},Mi=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Ni=Mi(`deg`),Pi=Mi(`%`),Fi=Mi(`px`),Ii=Mi(`vh`),Li=Mi(`vw`),Ri={...Pi,parse:e=>Pi.parse(e)/100,transform:e=>Pi.transform(e*100)},zi={test:wi(`hsl`,`hue`),parse:Ti(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Pi.transform(di(t))+`, `+Pi.transform(di(n))+`, `+di(yi.transform(r))+`)`},Bi={test:e=>Oi.test(e)||ji.test(e)||zi.test(e),parse:e=>Oi.test(e)?Oi.parse(e):zi.test(e)?zi.parse(e):ji.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Oi.transform(e):zi.transform(e),getAnimatableNone:e=>{let t=Bi.parse(e);return t.alpha=0,Bi.transform(t)}},Vi=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,Hi=new RegExp(xi.source),Ui=new RegExp(Vi.source,`i`);function Wi(e){return isNaN(e)&&typeof e==`string`&&(Hi.test(e)||Ui.test(e))}var Gi=`number`,Ki=`color`,qi=`var`,Ji=`var(`,Yi="${}",Xi=/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 Zi(e){let t=e.toString();return Hi.test(t)||Ui.test(t)}function Qi(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(Xi,e=>(Bi.test(e)?(r.color.push(a),i.push(Ki),n.push(Bi.parse(e))):e.startsWith(Ji)?(r.var.push(a),i.push(qi),n.push(e)):(r.number.push(a),i.push(Gi),n.push(parseFloat(e))),++a,Yi)).split(Yi),indexes:r,types:i}}function $i(e){return Qi(e).values}function ea({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===Gi?di(r[a]):e===Ki?Bi.transform(r[a]):r[a]}return i}}function ta(e){return ea(Qi(e))}var na=e=>typeof e==`number`?0:Bi.test(e)?Bi.getAnimatableNone(e):e,ra=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:na(e);function ia(e){let t=Qi(e);return ea(t)(t.values.map((e,n)=>ra(e,t.split[n])))}var aa={test:Wi,parse:$i,createTransformer:ta,getAnimatableNone:ia},oa=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`];function sa(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 ca=40;function la(e,t,n={delta:0,timestamp:0,isProcessing:!1}){let r=!1,i=!0,a=()=>r=!0,o=oa.reduce((e,t)=>(e[t]=sa(a),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=Zr.useManualTiming,o=a?n.timestamp:performance.now();r=!1,a||(n.delta=i?1e3/60:Math.max(Math.min(o-n.timestamp,ca),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:oa.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<oa.length;t++)o[oa[t]].cancel(e)},state:n,steps:o}}var{schedule:ua,cancel:da,steps:fa}=la(typeof requestAnimationFrame<`u`?requestAnimationFrame:ti,!0,si),pa=(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)})`},ma=e=>e!==null;function ha(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(ma),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}function ga(e,t){return{kind:e,animation:t,timestamp:ui.now(),frameTimestamp:si.timestamp,frameIsProcessing:si.isProcessing}}function _a(e,t,n){let r=globalThis.__MOTION_INSPECT__;if(r)try{r({...ga(`animation-start`,e),options:n?{...t,...n}:t})}catch{}}function va(e,t){let n=globalThis.__MOTION_INSPECT__;if(n)try{n({...ga(`layout-animation-start`,e),node:t})}catch{}}var ya=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)}},ba=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function xa(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(xi)||[];if(!r)return e;let i=n.replace(r,``),a=+!!ba.has(t);return r!==n&&(a*=100),t+`(`+a+i+`)`}var Sa=/\b([a-z-]*)\(.*?\)/gu,Ca={...aa,getAnimatableNone:e=>{let t=e.match(Sa);return t?t.map(xa).join(` `):e}},wa={...aa,getAnimatableNone:e=>{let t=aa.parse(e);return aa.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},Ta={...vi,transform:Math.round},Ea={rotate:Ni,pathRotation:Ni,rotateX:Ni,rotateY:Ni,rotateZ:Ni,scale:bi,scaleX:bi,scaleY:bi,scaleZ:bi,skew:Ni,skewX:Ni,skewY:Ni,distance:Fi,translateX:Fi,translateY:Fi,translateZ:Fi,x:Fi,y:Fi,z:Fi,perspective:Fi,transformPerspective:Fi,opacity:yi,originX:Ri,originY:Ri,originZ:Fi},Da={borderWidth:Fi,borderTopWidth:Fi,borderRightWidth:Fi,borderBottomWidth:Fi,borderLeftWidth:Fi,borderRadius:Fi,borderTopLeftRadius:Fi,borderTopRightRadius:Fi,borderBottomRightRadius:Fi,borderBottomLeftRadius:Fi,width:Fi,maxWidth:Fi,height:Fi,maxHeight:Fi,top:Fi,right:Fi,bottom:Fi,left:Fi,inset:Fi,insetBlock:Fi,insetBlockStart:Fi,insetBlockEnd:Fi,insetInline:Fi,insetInlineStart:Fi,insetInlineEnd:Fi,padding:Fi,paddingTop:Fi,paddingRight:Fi,paddingBottom:Fi,paddingLeft:Fi,paddingBlock:Fi,paddingBlockStart:Fi,paddingBlockEnd:Fi,paddingInline:Fi,paddingInlineStart:Fi,paddingInlineEnd:Fi,margin:Fi,marginTop:Fi,marginRight:Fi,marginBottom:Fi,marginLeft:Fi,marginBlock:Fi,marginBlockStart:Fi,marginBlockEnd:Fi,marginInline:Fi,marginInlineStart:Fi,marginInlineEnd:Fi,fontSize:Fi,backgroundPositionX:Fi,backgroundPositionY:Fi,...Ea,zIndex:Ta,fillOpacity:yi,strokeOpacity:yi,numOctaves:Ta},Oa={...Da,color:Bi,backgroundColor:Bi,outlineColor:Bi,fill:Bi,stroke:Bi,borderColor:Bi,borderTopColor:Bi,borderRightColor:Bi,borderBottomColor:Bi,borderLeftColor:Bi,filter:Ca,WebkitFilter:Ca,mask:wa,WebkitMask:wa},ka=e=>Oa[e],Aa=new Set([Ca,wa]);function ja(e,t){let n=ka(e);return Aa.has(n)||(n=aa),n.getAnimatableNone?n.getAnimatableNone(t):void 0}function Ma(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var Na=e=>e*180/Math.PI,Pa=e=>Ia(Na(Math.atan2(e[1],e[0]))),Fa={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:Pa,rotateZ:Pa,skewX:e=>Na(Math.atan(e[1])),skewY:e=>Na(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ia=e=>(e%=360,e<0&&(e+=360),e),La=Pa,Ra=e=>Math.hypot(e[0],e[1]),za=e=>Math.hypot(e[4],e[5]),Ba={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ra,scaleY:za,scaleZ:e=>Math.hypot(e[8],e[9],e[10]),scale:e=>(Ra(e)+za(e))/2,rotateX:e=>Ia(Na(Math.atan2(e[6],e[5]))),rotateY:e=>Ia(Na(Math.atan2(-e[2],e[0]))),rotateZ:La,rotate:La,skewX:e=>Na(Math.atan(e[4])),skewY:e=>Na(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Va(e){return+!!e.includes(`scale`)}function Ha(e,t){if(!e||e===`none`)return Va(t);let n=e.match(/^matrix(3d)?\(([-\d.e\s,]+)\)$/u);if(!n)return Va(t);let r=(n[1]?Ba:Fa)[t],i=n[2].split(`,`).map(e=>parseFloat(e));return typeof r==`function`?r(i):i[r]}var Ua=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return Ha(n,t)},Wa=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`scaleZ`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],Ga=new Set([...Wa,`pathRotation`]),Ka=e=>e===vi||e===Fi,qa=new Set([`x`,`y`,`z`]),Ja=Wa.filter(e=>!qa.has(e));function Ya(e){let t=[];return Ja.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 Xa=new Set([`bottom`,`right`]);function Za(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 Qa=({transform:e})=>Ha(e,`x`),$a=({transform:e})=>Ha(e,`y`),eo={width:({width:e,paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r},i)=>Za(e,i,`x`,t,n,r),height:({height:e,paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r},i)=>Za(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:Qa,y:$a,translateX:Qa,translateY:$a},to=new Set,no=!1,ro=!1,io=!1;function ao(){if(ro){let e=[],t=new Set,n=new Set;to.forEach(r=>{r.needsMeasurement&&(e.push(r),t.add(r.element),Xa.has(r.name)&&n.add(r.element))});let r=new Map;n.forEach(e=>{let t=Ya(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)})}ro=!1,no=!1,to.forEach(e=>e.complete(io)),to.clear()}function oo(){to.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ro=!0)})}function so(){io=!0,oo(),ao(),io=!1}function co(e,t,n){if(typeof e==`string`){if(Qr(e)||$r(e))return parseFloat(e);if(!aa.test(e)&&aa.test(n))return ja(t,n)}return e??void 0}var lo=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?(to.add(this),no||(no=!0,ua.read(oo),ua.resolveKeyframes(ao))):(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=co(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])}Ma(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),to.delete(this)}cancel(){this.state===`scheduled`&&(to.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},uo=e=>e.startsWith(`--`);function fo(e,t,n){uo(t)?e.style.setProperty(t,n):e.style[t]=n}var po={};function mo(e,t){let n=ei(e);return()=>po[t]??n()}var ho=mo(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),go=mo(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),_o=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,vo={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:_o([0,.65,.55,1]),circOut:_o([.55,0,1,.45]),backIn:_o([.31,.01,.66,-.59]),backOut:_o([.33,1.53,.69,.99])};function yo(e,t){if(e)return typeof e==`function`?go()?pa(e,t):`ease-out`:oi(e)?_o(e):Array.isArray(e)?e.map(e=>yo(e,t)||vo.easeOut):vo[e]}function bo(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=yo(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 xo(e){return typeof e==`function`&&`applyToOptions`in e}function So({type:e,...t}){return xo(e)&&go()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Co=class extends ya{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=So(e);this.animation=bo(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=ha(r,this.options,o,this.speed);this.updateMotionValue?.(e),fo(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()},_a(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 ii(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+ii(e)}get time(){return ii(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=ri(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&&ho()?(this.animation.timeline=e,t?.(this.animation),ti):n(this)}},wo=new Set([`opacity`,`clipPath`,`filter`,`transform`]),To=(e,t)=>t&&typeof e==`number`?t.transform(e):e,Eo={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},Do=Wa.length,Oo={},ko=(e,t,n=To(t,Ea[e]))=>(Oo[e]||(Oo[e]=(Eo[e]||e)+`(`))+n+`)`,Ao=(e,t)=>(typeof t==`number`?t:parseFloat(t))===+!!e.startsWith(`scale`);function jo(e,t,n){let r=``;for(let i=0;i<Do;i++){let a=Wa[i],o=e[a];if(o===void 0)continue;let s=n&&(t[a]=To(o,Da[a]));Ao(a,o)||(r+=ko(a,o,s||void 0)+` `)}let i=e.pathRotation;return i&&(r+=ko(`rotate`,i)),r=r.trim(),n?n(t,r):r||`none`}var Mo=new WeakMap,No=30,Po=e=>!isNaN(parseFloat(e)),Fo={current:void 0},Io=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=ui.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=ui.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Po(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 ni)).add(t)}onChangeSubscribe(e){let{events:t}=this;return!t.change&&!this.changeSubscriber?this.changeSubscriber=e:(t.change||(t.change=new ni,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(){ua.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=ui.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(){Fo.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=ui.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>No)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,No);return ai(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 Lo(e,t){return new Io(e,t)}function Ro(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function zo(e,t,n,r){let i=t=>typeof t==`function`?t(n===void 0?e.custom:n,...Ro(r)):t;return t=i(t),typeof t==`string`&&(t=e.variants&&e.variants[t]),i(t)}var Bo=e=>!!(e&&e.getVelocity),Vo=`data-framer-appear-id`;function Ho(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(Ga.has(e))o=!0;else if(pi(e))i[e]=n;else{let t=To(n,Da[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=jo(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 Uo={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Wo={offset:`strokeDashoffset`,array:`strokeDasharray`};function Go(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?Uo:Wo;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var Ko=[`transform`,`opacity`,`clipPath`,`filter`,`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function qo(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(Ho(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 Ko)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&&Go(d,i,a,o,!1)}var{schedule:Jo,cancel:Yo}=la(queueMicrotask,!1),Xo={};function Zo(e){return Bo(e)?e.get():e}var Qo=()=>({translate:0,scale:1,origin:0,originPoint:0}),$o=()=>({x:Qo(),y:Qo()}),es=()=>({min:0,max:0}),ts=()=>({x:es(),y:es()}),ns={current:void 0},rs=new WeakMap;function is(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function as(e){return typeof e==`string`||Array.isArray(e)}var os=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],ss=[`initial`].concat(os);function cs(e){if(is(e.animate))return!0;for(let t=0;t<ss.length;t++)if(as(e[ss[t]]))return!0;return!1}function ls(e){return!!(cs(e)||e.variants)}function us(e,t,n){for(let r in t){let i=t[r],a=n[r];if(Bo(i))e.addValue(r,i);else if(Bo(a))e.addValue(r,Lo(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,Lo(t===void 0?i:t,{owner:e}))}}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var ds={current:null},fs={current:!1},ps=typeof window<`u`;function ms(){if(fs.current=!0,ps){if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>ds.current=e.matches;e.addEventListener(`change`,t),t()}else ds.current=!1}}var hs=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],gs={};function _s(e){gs=e}function vs(){return gs}var ys=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=lo,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=ui.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,ua.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=cs(t),this.isVariantNode=ls(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&&Bo(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,rs.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:(fs.current||ms(),this.shouldReduceMotion=ds.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection?.unmount(),da(this.notifyUpdate),da(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&&wo.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Co({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:ri(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=Ga.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&ua.preRender(this.notifyUpdate),n&&(this.projection&&(this.projection.isTransformDirty=!0),Mo.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 gs){let t=gs[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):ts()}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)&&Mo.get(this.current)?.demote(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<hs.length;t++){let n=hs[t];this.propEventSubscriptions[n]?.(),delete this.propEventSubscriptions[n];let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=us(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=Lo(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`&&(Qr(n)||$r(n))?n=parseFloat(n):typeof n!=`number`&&!aa.test(n)&&aa.test(t)&&(n=ja(e,t)),this.setBaseTarget(e,Bo(n)?n.get():n)),Bo(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}on(e,t){return(this.events[e]||(this.events[e]=new ni)).add(t)}notify(e,...t){this.events[e]?.notify(...t)}scheduleRenderMicrotask(){Jo.render(this.render)}};function bs(e,{layout:t,layoutId:n}){return Ga.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!Xo[e]||e===`opacity`)}function xs(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(Bo(r[t])||i&&Bo(i[t])||bs(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}var Ss=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Cs(e,t,n){let r=xs(e,t,n);for(let n in e)if(n!==`children`&&(Bo(e[n])||Bo(t[n]))){let t=Wa.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var ws=(0,X.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`}),Ts=(0,X.createContext)({strict:!1}),Es={animation:[`variants`,...os],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`]},Ds=!1;function Os(){if(Ds)return;let e={};for(let t in Es)e[t]={isEnabled:e=>Es[t].some(t=>!!e[t])};_s(e),Ds=!0}function ks(){return Os(),vs()}function As(e){let t=ks();for(let n in e)t[n]={...t[n],...e[n]};_s(t)}function js({children:e,features:t,strict:n=!1}){let[,r]=(0,X.useState)(!Ms(t)),i=(0,X.useRef)(void 0);if(!Ms(t)){let{renderer:e,...n}=t;i.current=e,As(n)}return(0,X.useEffect)(()=>{Ms(t)&&t().then(({renderer:e,...t})=>{As(t),i.current=e,r(!0)})},[]),(0,Z.jsx)(Ts.Provider,{value:{renderer:i.current,strict:n},children:e})}function Ms(e){return typeof e==`function`}var Ns=(0,X.createContext)({});function Ps(e,t){if(cs(e)){let{initial:t,animate:n}=e;return{initial:t===!1||as(t)?t:void 0,animate:as(n)?n:void 0}}return e.inherit===!1?{}:t}function Fs(e){let{initial:t,animate:n}=Ps(e,(0,X.useContext)(Ns));return(0,X.useMemo)(()=>({initial:t,animate:n}),[Is(t),Is(n)])}function Is(e){return Array.isArray(e)?e.join(` `):e}var Ls=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Rs(e,t,n){for(let r in t)!Bo(t[r])&&!bs(r,n)&&(e[r]=t[r])}function zs({transformTemplate:e},t){return(0,X.useMemo)(()=>{let n=Ls();return Ho(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Bs(e,t){let n=e.style||{},r={};return Rs(r,n,e),Object.assign(r,zs(e,t)),r}function Vs(e,t){let n={},r=Bs(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 Hs=()=>({...Ls(),attrs:{}});function Us(e,t,n,r){let i=(0,X.useMemo)(()=>{let n=Hs();return qo(n,t,Ss(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};return Rs(t,e.style,e),{...i,style:{...t,...i.style}}}return i}var Ws=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 Gs(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||Ws.has(e)}function Ks(e,t){return e.startsWith(`on`)?!Gs(e):t?.(e)??!Gs(e)}function qs(e,t,n,r){let i={};for(let a in e)(a!==`values`||typeof e.values!=`object`)&&(Bo(e[a])||(Ks(a,r)||n===!0&&Gs(a)||!t&&!Gs(a)||e.draggable&&a.startsWith(`onDrag`))&&(i[a]=e[a]));return i}var Js=[`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 Ys(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(Js.indexOf(e)>-1||/[A-Z]/u.test(e))}function Xs(e,t,n,{latestValues:r},i,a=!1,o,s){let c=(o??Ys(e)?Us:Vs)(t,r,i,e),l=qs(t,typeof e==`string`,a,s),u=e===X.Fragment?{}:{...l,...c,ref:n},{children:d}=t,f=(0,X.useMemo)(()=>Bo(d)?d.get():d,[d]);return(0,X.createElement)(e,{...u,children:f})}function Zs({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:Qs(n,r,i,e),renderState:t()}}function Qs(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=Zo(a[e]);let{initial:o,animate:s}=e,c=cs(e),l=ls(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`&&!is(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=zo(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 $s=e=>(t,n)=>{let r=(0,X.useContext)(Ns),i=(0,X.useContext)(qr),a=()=>Zs(e,t,r,i);return n?a():Gr(a)},ec=$s({scrapeMotionValuesFromProps:xs,createRenderState:Ls}),tc=$s({scrapeMotionValuesFromProps:Cs,createRenderState:Hs}),nc=Symbol.for(`motionComponentSymbol`);function rc(e,t,n){let r=(0,X.useRef)(n);(0,X.useInsertionEffect)(()=>{r.current=n});let i=(0,X.useRef)(null);return(0,X.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 ic=(0,X.createContext)({});function ac(e,t,n,r,i,a){let{visualElement:o}=(0,X.useContext)(Ns),s=(0,X.useContext)(Ts),c=(0,X.useContext)(qr),l=(0,X.useContext)(ws),u=l.reducedMotion,d=l.skipAnimations,f=(0,X.useRef)(null),p=(0,X.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,X.useContext)(ic);m&&!m.projection&&i&&(m.type===`html`||m.type===`svg`)&&i.create(m,n,h),(0,X.useInsertionEffect)(()=>{m&&m.props!==n&&m.update(n,c)});let g=n[Vo],_=(0,X.useRef)(!!g&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return Kr(()=>{p.current&&m&&(m.animationState?.animateChanges(),m.enteringChildren=void 0)},[]),Kr(()=>{p.current=!0,m&&(window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),_.current&&m.animationState&&m.animationState.animateChanges())}),(0,X.useEffect)(()=>{m&&(!_.current&&m.animationState&&m.animationState.animateChanges(),_.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),!1),m.enteringChildren=void 0)}),m}function oc(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&As(r);let a=n?n===`svg`:Ys(e),o=a?tc:ec;function s(n,s){let c,l=sc(n);Gr(()=>!!ns.current?.sharedNodes.get(l)?.lead&&n.initial)&&(n={...n,initial:!1});let u={...(0,X.useContext)(ws),...n,layoutId:l},{isStatic:d,isValidProp:f}=u,p=Fs(n),m=o(n,d);if(!d&&typeof window<`u`){cc(u,r);let t=lc(u);p.visualElement=ac(e,m,u,i,t.ProjectionNode,a),(t.isEnabled||p.visualElement?.projection?.options.layoutId)&&(c=t.MeasureLayout)}return(0,Z.jsxs)(Ns.Provider,{value:p,children:[c&&p.visualElement?(0,Z.jsx)(c,{visualElement:p.visualElement,...u}):null,Xs(e,n,rc(m,p.visualElement,s),m,d,t,a,f)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,X.forwardRef)(s);return c[nc]=e,c}function sc({layoutId:e}){let t=(0,X.useContext)(Wr).id;return t&&e!==void 0?t+`-`+e:e}function cc(e,t){(0,X.useContext)(Ts).strict}function lc(e){let{drag:t,layout:n}=ks();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:r.MeasureLayout,isEnabled:t?.isEnabled(e)||n?.isEnabled(e),ProjectionNode:r.ProjectionNode}}function uc(e,t){if(typeof Proxy>`u`)return oc;let n=new Map,r=(n,r)=>oc(n,r,e,t);return new Proxy((e,t)=>r(e,t),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,oc(a,void 0,e,t)),n.get(a))})}var dc=uc();function fc(){!fs.current&&ms();let[e]=(0,X.useState)(ds.current);return e}var pc=dc,mc=()=>R(()=>import(`./segment-thumb-features-BQYzrze9.js`).then(e=>e.default),__vite__mapDeps([0,1,2])),hc={type:`spring`,stiffness:420,damping:36},gc={duration:0};function _c({children:e}){return(0,Z.jsx)(js,{features:mc,children:e})}function vc({layoutId:e}){let t=fc();return(0,Z.jsx)(pc.span,{layoutId:e,"aria-hidden":!0,transition:t?gc:hc,className:`absolute inset-0 rounded-[inherit] bg-raised shadow-sm ring-1 ring-line dark:bg-surface-2`})}function yc({items:e,value:t,onChange:n,"aria-label":r,size:i=`md`,className:a}){let o=(0,X.useId)(),s=(0,X.useRef)([]),c=Math.max(0,e.findIndex(e=>e.value===t));return(0,Z.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:Y(`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,Z.jsx)(_c,{children:e.map((e,t)=>{let r=t===c;return(0,Z.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:Y(`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,Z.jsx)(vc,{layoutId:o}),(0,Z.jsx)(`span`,{className:`relative inline-flex items-center gap-1.5`,children:e.label})]},e.value)})})})}var bc={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`},xc=(0,X.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,...bc,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,X.createElement)(t,{...n,...m,...a,opacity:i,key:n.key})});return(0,X.createElement)(`svg`,h,g)});xc.displayName=`HugeiconsIcon`;var Sc=[[`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`}]],Cc=[[`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`}]],wc=[[`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`}]],Tc=[[`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`}]],Ec=[[`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`}]],Dc=[[`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`}]],Oc=[[`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`}]],kc=[[`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`}]],Ac=[[`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`}]],jc=[[`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`}]],Mc=[[`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`}]],Nc=[[`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`}]],Pc=[[`path`,{d:`M5 14L8.5 17.5L19 6.5`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,key:`0`}]];function Fc({id:e,title:t,lede:n,children:r,className:i}){let a=(0,X.useId)();return(0,Z.jsxs)(`section`,{id:e,"aria-labelledby":a,className:Y(`pv2-section min-w-0 scroll-mt-6 rounded-card bg-surface p-1`,i),children:[(0,Z.jsxs)(`header`,{className:`flex flex-col gap-0.5 px-4 pt-3 pb-3`,children:[(0,Z.jsx)(`h3`,{id:a,className:`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em] text-fg`,children:t}),n&&(0,Z.jsx)(`p`,{className:`m-0 max-w-[70ch] text-[13px] leading-[18px] text-fg-muted`,children:n})]}),(0,Z.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 Ic({label:e,expanded:t,controls:n,onClick:r,buttonRef:i,popup:a}){return(0,Z.jsx)(`button`,{ref:i,type:`button`,onClick:r,"aria-label":e,title:e,"aria-expanded":t,"aria-controls":n,"aria-haspopup":a,className:Y(`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,Z.jsx)(xc,{icon:Dc,size:15,strokeWidth:1.8,"aria-hidden":`true`})})}function Lc({label:e,labelFor:t,labelId:n,hint:r,details:i,help:a,badge:o,control:s,children:l,stacked:u,inline:d,className:f,busy:p}){let m=c(),h=(0,X.useId)(),[g,_]=(0,X.useState)(!1),v=typeof e==`string`?e:void 0,y=`m-0 text-[14px] leading-5 font-medium text-fg`;return(0,Z.jsxs)(`div`,{className:Y(`pv2-row flex min-w-0 flex-col gap-3 px-4 py-3.5`,f),"aria-busy":p||void 0,children:[(0,Z.jsxs)(`div`,{className:Y(`flex min-w-0 flex-col gap-3`,!u&&`sm:flex-row sm:items-center sm:justify-between sm:gap-6`,d&&`flex-row items-center justify-between gap-4`),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-h-[22px] flex-wrap items-center gap-x-1.5 gap-y-1`,children:[t?(0,Z.jsx)(`label`,{htmlFor:t,id:n,className:y,children:e}):(0,Z.jsx)(`span`,{id:n,className:y,children:e}),i&&(0,Z.jsx)(Ic,{label:v?m(`proxyV2.detailsFor`,{name:v}):m(`proxyV2.details`),expanded:g,controls:h,onClick:()=>_(e=>!e)}),a,o]}),r&&(0,Z.jsx)(`p`,{className:`m-0 max-w-[62ch] text-[13px] leading-[18px] text-fg-muted`,children:r}),i&&(0,Z.jsx)(`div`,{id:h,hidden:!g,className:`pv2-details mt-1.5 max-w-[68ch] text-[13px] leading-[19px] text-fg-muted`,children:i})]}),s&&(0,Z.jsx)(`div`,{className:Y(`pv2-row-control flex min-w-0 flex-wrap items-center gap-2`,!u&&`sm:shrink-0 sm:justify-end`,d&&`shrink-0`),children:s})]}),l]})}function Rc({locale:e,health:t,providers:n,usage30d:r,usageLoading:i,healthLoading:a,startupHealth:o,projectConfigWarnings:s}){let l=c(),u=t?.status===`ok`,d=!!r&&r.summary.requests>0;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`dash-overview-head flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 xl:grid-cols-5`,children:[(0,Z.jsx)(zc,{label:l(`dash.status`),busy:a,children:(0,Z.jsxs)(`span`,{className:Y(`flex items-center gap-2`,u?`text-success`:`text-danger`),children:[(0,Z.jsx)(`span`,{className:Y(`size-2 shrink-0 rounded-full`,u?`bg-success`:`bg-danger`),"aria-hidden":`true`}),l(u?`dash.online`:`dash.offline`)]})}),(0,Z.jsx)(zc,{label:l(`dash.version`),busy:a,title:t?.version,children:(0,Z.jsx)(`span`,{className:`dash-stat-version block truncate`,children:t?.version??`—`})}),(0,Z.jsx)(zc,{label:l(`dash.uptime`),busy:a,children:t?Lr(t.uptime,e):`—`}),(0,Z.jsx)(zc,{label:l(`dash.providers`),busy:a,children:n.length}),(0,Z.jsx)(zc,{label:l(`dash.tokens30d`),busy:i,sub:d?l(`dash.coverage`).replace(`{pct}`,`${Math.round(r.summary.coverageRatio*100)}%`):void 0,children:d?Ue(r.summary.totalTokens,e):`—`})]}),(0,Z.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>_n(`startup`),className:Y(`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,Z.jsx)(`span`,{className:Y(`size-2 shrink-0 rounded-full`,o===`error`?`bg-danger`:o===`at-risk`?`bg-warning`:`bg-success`),"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:l(o===`error`?`startup.error`:o===`at-risk`?`startup.summary.atRisk`:o===`protected`?`startup.summary.protected`:`startup.summary.native`)}),(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`,className:`shrink-0 text-fg-subtle transition-transform duration-150 group-hover:translate-x-0.5`})]}):(0,Z.jsx)(`div`,{className:`h-[var(--ocx-control-h)] rounded-control bg-surface`,"aria-hidden":`true`})})]}),(0,Z.jsx)(Ur,{data:r}),s.length>0&&(0,Z.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,Z.jsx)(at,{}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-semibold`,children:l(`dash.projectConfigTitle`)}),(0,Z.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:l(`dash.projectConfigHint`)}),(0,Z.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,Z.jsxs)(`li`,{style:{marginBottom:8},children:[(0,Z.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,Z.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}function zc({label:e,children:t,sub:n,busy:r,title:i}){return(0,Z.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,Z.jsx)(`span`,{className:`text-xs font-medium text-fg-subtle`,children:e}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-[17px] leading-6 font-semibold tracking-[-0.01em] tabular-nums text-fg`,children:t}),n&&(0,Z.jsx)(`span`,{className:`dash-stat-coverage truncate text-xs text-fg-subtle`,children:n})]})}function Bc({maMode:e,maBusy:t,switchMaMode:n}){let r=c();return(0,Z.jsx)(`fieldset`,{disabled:t,className:`dash-ma-switch m-0 min-w-0 border-0 p-0 disabled:opacity-60`,children:(0,Z.jsx)(yc,{"aria-label":r(`dash.multiAgent`),value:e,onChange:t=>{t!==e&&n(t)},items:[`v1`,`default`,`v2`].map(e=>({value:e,label:r(`models.v2Mode_${e}`)}))})})}function Vc({maHelpTriggerRef:e,maHelpOpen:t,setMaHelpOpen:n}){let r=c();return(0,Z.jsx)(Ic,{buttonRef:e,label:r(`dash.multiAgent`),expanded:t,controls:`multi-agent-help-dialog`,popup:`dialog`,onClick:()=>n(!0)})}var Hc=`gpt-daybreak-blue-latest`,Uc=`gpt-6-astra`,Wc=`gpt-6-sol`,Gc=`gpt-6-luna`,Kc=`gpt-6.1-sol`,qc=`gpt-6.1-terra`,Jc=`gpt-6-astra-minor`,Yc=Object.freeze({contextWindow:272e3,maxContextWindow:872e3,maxInputTokens:872e3});Object.freeze({...Yc,contextWindow:5e5}),Object.freeze({...Yc,contextWindow:5e5});var Xc=new Set([Hc,Jc]),Zc=Object.freeze({[Hc]:`gpt-5.6-sol`,[Jc]:Uc});Object.freeze(Object.keys(Zc)),Object.freeze({[Hc]:{displayName:`Daybreak Blue`,description:`Frontier general-purpose model with safeguards for defensive cybersecurity work.`},[Jc]:{displayName:`GPT-6-Astra-Minor`,description:`Unreleased GPT-6 Astra variant; shown only when your account's Codex roster lists it.`}});var Qc=[...Object.freeze([`gpt-5.5`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`,Hc,Uc,Wc,Gc,Kc,qc,Jc])],$c=new Set(Qc);[...Xc];var el=18e5,tl=[`account_unavailable`,`access_denied`,`rate_limited`,`upstream_error`,`redirect_blocked`,`destination_blocked`,`dns_failed`,`timeout`,`transport_error`,`response_unusable`];function nl(e){return tl.find(t=>t===e)}var rl=6e4,il=864e5;function al(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 ol=1e3,sl=12e4,cl=4e3;function ll(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 ul(e){return e?e.adapter===`jev-decision`?e.disabled===!0?`disabled`:ll(e.baseUrl??``)?!e.defaultModel?.trim()&&!e.models?.[0]?.trim()?`model`:null:`endpoint`:`notDecision`:`missing`}function dl(e){return e.name===`jev`?e.adapter===`jev-decision`&&e.disabled!==!0&&e.hasApiKey===!0:ul(e)===null}var fl={typesafe:`cws.jev.backend.typesafe`,systemone:`cws.jev.backend.systemone`,model:`cws.jev.backend.model`,unknown:`cws.jev.backend.unknown`};function pl(e){return e.decisionModel==null?e.decisionProvider!=null&&e.decisionProvider.trim()!==`jev`?`systemone`:`typesafe`:`model`}function ml(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 hl(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=>!ml(e,n,r)).sort((e,t)=>e.localeCompare(t))}var gl=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],_l=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`,`jev`],vl={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`},yl={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`},bl={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`},xl=new Set(_l),Sl={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 Cl(e,t,n=`strict`){let r=e.filter(e=>e.provider.trim()&&e.model.trim());if(r.length===0)return[...gl];let i=new Set(gl),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[...gl];let o=new Set(a);return gl.filter(e=>o.has(e))}var wl=el,Tl=0;function El(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-${++Tl}`}}function Dl(e){return e===`disabled`?`disabled`:`auto`}function Ol(e){return e===`adaptive`?`adaptive`:`strict`}var kl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Al=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,jl=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Ml(e){return kl.test(e.trim())}function Nl(e){return`combo/${e.trim()}`}function Pl(e,t){return(typeof t==`string`?t.trim():``)||Nl(e)}function Fl(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!jl.test(n));return{...e,alias:n?t:null,model:Pl(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function Il(e){let t=typeof e==`string`?e.trim():``;return t&&t!==`jev`?t:null}function Ll(e){return typeof e==`number`&&Number.isInteger(e)?e:null}function Rl(e){return typeof e==`string`&&e.trim()?e.trim():null}function zl(e){return typeof e==`string`&&xl.has(e)?e:`failover`}function Bl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Vl(e){return typeof e==`string`&&gl.includes(e)?e:null}function Hl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Ul(e){if(!Array.isArray(e)||e.length===0)return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`||!gl.includes(r))return;let e=r;if(n.has(e))return;n.add(e),t.push(e)}return t}function Wl(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=Hl(t.weight),o=Ul(t.reasoningEfforts);a.push(El({provider:n,model:r,...i===void 0?{}:{weight:i},...o===void 0?{}:{reasoningEfforts:o},...typeof t.modelProfile==`string`?{modelProfile:t.modelProfile}:{}}))}let o=Il(t.decisionProvider),s=Rl(t.decisionModel),c=Ll(t.decisionTimeoutMs),l=t.sessionPin===null?null:al(t.sessionPin);n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():Pl(r,Rl(t.alias)),alias:Rl(t.alias),nativeAlias:t.nativeAlias===!0,displayName:Rl(t.displayName),strategy:zl(t.strategy),stickyLimit:Bl(t.stickyLimit),defaultEffort:Vl(t.defaultEffort),imageInput:Dl(t.imageInput),reasoningEffortMode:Ol(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 Gl(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 Kl(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 ql(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Jl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Yl(e,t){let n=ql(e.routingQuota);if(!n||n.state!==`available`&&n.state!==`exhausted`)return null;let r=Jl(n.updatedAt),i=Jl(n.validUntil);return r===null||r<0||r>t||t-r>=wl||i===null||i<=t||i>r+wl?null:{state:n.state,validUntil:i}}function Xl(e,t){return Yl(e,t)?.state??`unknown`}function Zl(e,t=Date.now()){if(!Array.isArray(e))return;let n;for(let r of e){let e=ql(r);if(!e||typeof e.provider!=`string`||!e.provider.trim())continue;let i=Yl(e,t);i&&(n===void 0||i.validUntil<n)&&(n=i.validUntil)}return n}function Ql(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=ql(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Xl(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function $l(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 eu(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&&$l(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function tu(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 nu(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)&&tu(e,r)&&(e.modelProfile??``)===(r.modelProfile??``)})}function ru(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:Il(e.decisionProvider),decisionModel:e.decisionModel?.trim()||null,decisionTimeoutMs:e.decisionTimeoutMs??null,...e.sessionPin===void 0?{}:{sessionPin:e.sessionPin}}:{}}}}function iu(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Ml(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(!Al.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&jl.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&&!$c.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=>!gl.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&&!al(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`&&pl(e)===`model`){let n=e.decisionModel?.trim()??``;if(!n||n.length>512||e.decisionProvider!=null||ml(n,t.combos??[],e)||t.decisionModels&&!t.decisionModels.includes(n))return`invalidDecisionModel`}return e.strategy===`jev`&&pl(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 au(e=``){return{id:e,model:e?Nl(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`strict`,targets:[El()]}}var ou=[`gpt-6-astra`,`gpt-5.6-sol`,`gpt-5.6-luna`];function su(e,t,n){let r=ou.flatMap(n=>{let r=e.find(e=>e.id===n&&(t===void 0||t.has(e.provider)));return r?[El({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:Il(n),targets:r.length>0?r:[El()]}}function cu(e,t){let n=Il(e);return n===null?null:ul(Object.hasOwn(t,n)?t[n]:void 0)}function lu(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=ul(e);return{id:e.name,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t?{issue:t}:{}}}),r=Il(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 uu(e,t){if(e.strategy!==`jev`)return null;let n=Il(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 du=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],fu=[`manual`,`auto`],pu=300,mu=[`manual`,`manual+auto`,`auto`],hu={manual:`compactionRouting.triggersManual`,"manual+auto":`compactionRouting.triggersBoth`,auto:`compactionRouting.triggersAuto`},gu=[`all`,`selected`],_u={all:`compactionRouting.sourcesAll`,selected:`compactionRouting.sourcesSelected`};function vu(e){if(!e)return`manual`;let t=e.includes(`auto`);return e.includes(`manual`)?t?`manual+auto`:`manual`:t?`auto`:`manual`}function yu(e){if(e===`auto`)return[`auto`];if(e===`manual+auto`)return[`manual`,`auto`]}function bu(e){let t=new Map;for(let n of Wl(e))t.set(n.model,[...new Set(n.targets.flatMap(e=>e.provider?[e.provider]:[]))]);return t}function xu(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`||!du.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`&&fu.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 Su(e){if(!e)return``;try{return new URL(e).hostname||e}catch{return e}}function Cu(e,t){let n=t.get(e);return n?`${e} (${n})`:e}function wu(e){return(0,Z.jsx)(Tu,{...e},e.apiBase)}function Tu({apiBase:t,models:n,providers:r=[]}){let i=c(),[a,o]=(0,X.useState)(void 0),[s,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(`manual`),[m,h]=(0,X.useState)(`all`),[g,_]=(0,X.useState)([]),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(()=>new Map),O=(0,X.useRef)(!1),k=(0,X.useRef)(null),A=(0,X.useCallback)(e=>{o(e),l(e?.model??``),d(e?.reasoningEffort??``),p(vu(e?.triggers)),h(e?.sourceModels?`selected`:`all`),_(e?.sourceModels??[])},[]),j=e=>{_(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),T(null)},M=(0,X.useCallback)(async()=>{if(k.current)return;let n=e(15e3);k.current=n,C(!1);try{let e=xu(await Qn(await fetch(`${t}/api/settings`,{signal:n.signal})));O.current&&k.current===n&&A(e);let r=await fetch(`${t}/api/combos`,{signal:n.signal}).then(Qn).then(bu).catch(()=>new Map);O.current&&k.current===n&&D(r)}catch{O.current&&k.current===n&&C(!0)}finally{n.clear(),k.current===n&&(k.current=null)}},[t,A]);(0,X.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||a===void 0)return;let n=e(15e3);k.current=n,x(!0),T(null);try{let e=xu(await Qn(await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({compactionRouting:s?{model:s,...u?{reasoningEffort:u}:{},...yu(f)?{triggers:yu(f)}:{},...m===`selected`&&g.length>0?{sourceModels:g}:{}}:null}),signal:n.signal})));O.current&&k.current===n&&(A(e),T(`saved`))}catch{O.current&&k.current===n&&T(`failed`)}finally{n.clear(),O.current&&k.current===n&&x(!1),k.current===n&&(k.current=null)}},P=[{value:``,label:i(`compactionRouting.currentModel`)},...[...new Set([...n.map(e=>e.namespaced),...s?[s]:[]])].map(e=>({value:e,label:He(e,i)}))],F=[...new Set([...r.map(e=>e.name),...n.flatMap(e=>e.provider?[e.provider]:[])])].map(e=>`${e}/*`),I=new Set([...F,...n.map(e=>e.namespaced)]),L=(a?.sourceModels??[]).filter(e=>!I.has(e)),R=b||a===void 0||S,z=a?.sourceModels?`selected`:`all`,B=new Set(a?.sourceModels),V=s!==(a?.model??``)||u!==(a?.reasoningEffort??``)||f!==vu(a?.triggers)||m!==z||m===`selected`&&(g.length!==(a?.sourceModels?.length??0)||g.some(e=>!B.has(e))),H=m===`selected`&&g.length===0,U=new Set(g),W=[...new Set(n.map(e=>e.namespaced))].filter(e=>e.toLowerCase().includes(v.trim().toLowerCase())),ee=e=>(0,Z.jsxs)(`label`,{children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:U.has(e),disabled:R,onChange:()=>{j(e)}}),(0,Z.jsx)(`span`,{children:e})]},e),te=E.get(s),ne=te!==void 0||s.startsWith(Nl(``)),G=s.slice(0,Math.max(s.indexOf(`/`),0)),K=new Map(r.map(e=>[e.name,Su(e.baseUrl)]).filter(([,e])=>e)),re=ne?``:Cu(G||s,K),q=te?.map(e=>Cu(e,K)).join(`, `)||i(`compactionRouting.comboProvidersUnknown`),ie=f!==`manual`,ae=g.join(`, `),oe=!s||H?null:ne?m===`selected`?i(`compactionRouting.comboWarningScoped`,{combo:s,providers:q,sources:ae}):i(`compactionRouting.comboWarning`,{combo:s,providers:q}):m===`selected`?i(`compactionRouting.providerWarningScoped`,{provider:re,sources:ae}):i(`compactionRouting.providerWarning`,{provider:re});return(0,Z.jsxs)(`section`,{className:`panel`,"aria-labelledby":`compaction-routing-title`,"aria-busy":b||a===void 0&&!S,children:[(0,Z.jsxs)(`div`,{className:`spread`,style:{alignItems:`flex-start`,flexWrap:`wrap`},children:[(0,Z.jsxs)(`div`,{style:{flex:`1 1 20rem`,minWidth:0},children:[(0,Z.jsx)(`div`,{className:`font-semibold`,id:`compaction-routing-title`,children:i(`compactionRouting.title`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.description`)}),(0,Z.jsxs)(`details`,{className:`pv2-more`,children:[(0,Z.jsx)(`summary`,{children:i(`proxyV2.details`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.dataNotice`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.effortHint`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.sourcesHint`)})]})]}),(0,Z.jsxs)(`div`,{className:`dash-delegation-controls compaction-routing-controls`,style:{flex:`0 1 auto`},children:[(0,Z.jsxs)(`div`,{className:`compaction-field`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-model`,children:i(`compactionRouting.model`)}),(0,Z.jsx)($,{id:`compaction-routing-model`,value:s,options:P,disabled:R,label:i(`compactionRouting.model`),onChange:e=>{l(e),e||(d(``),p(`manual`),h(`all`),_([])),T(null)}})]}),(0,Z.jsxs)(`div`,{className:`compaction-field`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-triggers`,children:i(`compactionRouting.triggers`)}),(0,Z.jsx)($,{id:`compaction-routing-triggers`,value:f,disabled:R||!s,align:`right`,label:i(`compactionRouting.triggers`),options:mu.map(e=>({value:e,label:i(hu[e])})),onChange:e=>{p(e),T(null)}})]}),(0,Z.jsxs)(`div`,{className:`compaction-field`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-sources`,children:i(`compactionRouting.sources`)}),(0,Z.jsx)($,{id:`compaction-routing-sources`,value:m,disabled:R||!s,align:`right`,label:i(`compactionRouting.sources`),options:gu.map(e=>({value:e,label:i(_u[e])})),onChange:e=>{h(e),T(null)}})]}),(0,Z.jsxs)(`div`,{className:`compaction-field`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-effort`,children:i(`compactionRouting.effort`)}),(0,Z.jsx)($,{id:`compaction-routing-effort`,value:u,disabled:R||!s,align:`right`,label:i(`compactionRouting.effort`),options:[{value:``,label:i(`compactionRouting.currentEffort`)},...du.map(e=>({value:e,label:i(`models.reasoningEffort.${e}`)}))],onChange:e=>{d(e),T(null)}})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:R||!V||H,onClick:()=>{N()},children:i(b?`common.saving`:`common.save`)})]})]}),s&&m===`selected`&&(0,Z.jsxs)(`div`,{className:`compaction-sources-block`,children:[(0,Z.jsx)(`div`,{className:`field-label compaction-sources-title`,children:i(`compactionRouting.sourcesGridTitle`)}),(0,Z.jsxs)(`div`,{className:`source-scope-groups`,children:[F.length>0&&(0,Z.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesProviders`)}),F.map(ee)]}),n.length>0&&(0,Z.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesModels`)}),(0,Z.jsx)(`input`,{type:`search`,className:`input`,value:v,disabled:R,"aria-label":i(`pws.modelSearchPlaceholder`),placeholder:i(`pws.modelSearchPlaceholder`),onChange:e=>y(e.target.value)}),W.slice(0,pu).map(ee),W.length>pu&&(0,Z.jsx)(`p`,{className:`muted text-label`,children:i(`pws.modelsTruncated`,{shown:pu,total:W.length})})]}),L.length>0&&(0,Z.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesSaved`)}),L.map(ee)]}),H&&(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.sourcesNone`)})]})]}),oe&&(0,Z.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Z.jsx)(at,{width:14}),` `,oe]}),s&&ie&&(0,Z.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Z.jsx)(at,{width:14}),` `,i(`compactionRouting.autoNotice`)]}),S&&(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[i(`compactionRouting.loadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{M()},children:i(`common.retry`)})]}),w===`failed`&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:i(`compactionRouting.saveFailed`)}),w===`saved`&&(0,Z.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:i(`compactionRouting.saved`)})]})}function Eu(e){if(!(`reasoningRetention`in e))throw Error(`Missing reasoningRetention settings`);return e.reasoningRetention??null}function Du({apiBase:e}){let t=c();return(0,Z.jsxs)(`details`,{className:`panel`,children:[(0,Z.jsx)(`summary`,{className:`font-semibold`,children:t(`reasoningRetention.advanced`)}),(0,Z.jsx)(Ou,{apiBase:e},e)]})}function Ou({apiBase:t}){let n=c(),[r,i]=(0,X.useState)(),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(`20`),[u,d]=(0,X.useState)(`100000`),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(!1),y=(0,X.useRef)(null),b=(0,X.useCallback)(e=>{i(e),o(e?.enabled===!0),l(String(e?.maxContextPercent??20)),d(String(e?.maxTokens??1e5))},[]),x=(0,X.useCallback)(async()=>{if(y.current)return;let n=e(15e3);y.current=n,h(!1);try{let e=Eu(await Qn(await fetch(`${t}/api/settings`,{signal:n.signal})));v.current&&y.current===n&&b(e)}catch{v.current&&y.current===n&&h(!0)}finally{n.clear(),y.current===n&&(y.current=null)}},[t,b]);(0,X.useEffect)(()=>{v.current=!0;let e=window.setTimeout(()=>{x()},0);return()=>{window.clearTimeout(e),v.current=!1,y.current?.controller.abort(),y.current?.clear(),y.current=null}},[x]);let S=s.trim()!==``&&Number.isFinite(Number(s))&&Number(s)>0&&Number(s)<=100,C=u.trim()!==``&&Number.isSafeInteger(Number(u))&&Number(u)>0,w=!a||S&&C,T=a!==(r?.enabled===!0)||a&&(Number(s)!==(r?.maxContextPercent??20)||Number(u)!==(r?.maxTokens??1e5)),E=async(n=!1)=>{if(y.current||r===void 0||!n&&!w)return;let i=e(15e3);y.current=i,p(!0),_(null);try{let e=Eu(await Qn(await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:i.signal,body:JSON.stringify({reasoningRetention:n?null:a?{enabled:!0,maxContextPercent:Number(s),maxTokens:Number(u)}:{enabled:!1}})})));v.current&&y.current===i&&(b(e),_(`saved`))}catch{v.current&&y.current===i&&_(`failed`)}finally{i.clear(),v.current&&y.current===i&&p(!1),y.current===i&&(y.current=null)}},D=f||r===void 0||m;return(0,Z.jsxs)(`section`,{"aria-labelledby":`reasoning-retention-title`,"aria-busy":f||r===void 0&&!m,children:[(0,Z.jsx)(`div`,{className:`font-semibold`,id:`reasoning-retention-title`,children:n(`reasoningRetention.title`)}),(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:n(`reasoningRetention.description`)}),(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:n(`reasoningRetention.storageHint`)}),(0,Z.jsx)(kn,{on:a,disabled:D,label:n(`reasoningRetention.enable`),showLabel:!0,onClick:()=>{o(e=>!e),_(null)}}),(0,Z.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`,alignItems:`flex-end`},children:[a&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-percent`,children:[n(`reasoningRetention.percent`),(0,Z.jsx)(`input`,{id:`reasoning-retention-percent`,className:`input`,type:`number`,min:`0`,max:`100`,step:`any`,value:s,disabled:D,"aria-invalid":!S||void 0,"aria-describedby":S?void 0:`reasoning-retention-error`,onInput:e=>{l(e.currentTarget.value),_(null)}})]}),(0,Z.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-tokens`,children:[n(`reasoningRetention.tokens`),(0,Z.jsx)(`input`,{id:`reasoning-retention-tokens`,className:`input`,type:`number`,min:`1`,step:`1`,value:u,disabled:D,"aria-invalid":!C||void 0,"aria-describedby":C?void 0:`reasoning-retention-error`,onInput:e=>{d(e.currentTarget.value),_(null)}})]})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:D||!w||!T,onClick:()=>{E()},children:n(`common.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:D||r===null&&!T,onClick:()=>{E(!0)},children:n(`reasoningRetention.reset`)})]}),!w&&(0,Z.jsx)(`div`,{id:`reasoning-retention-error`,className:`notice notice-err`,role:`alert`,children:n(`reasoningRetention.invalid`)}),m&&(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[n(`reasoningRetention.loadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{x()},children:n(`common.retry`)})]}),g===`failed`&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:n(`reasoningRetention.saveFailed`)}),g===`saved`&&(0,Z.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:n(`reasoningRetention.saved`)})]})}var ku=0;function Au(e){let t=e.split(/\n{2,}/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}function ju(e,t,n,r){let i=l[e],a=`opencodex-action-dialog-${++ku}`,o=document.activeElement,s=typeof o?.focus==`function`?o:null,c=!1,u=document.createElement(`dialog`);u.id=a,u.className=`modal-overlay`,u.setAttribute(`aria-labelledby`,`${a}-body`);let d=document.createElement(`button`);d.type=`button`,d.className=`modal-backdrop-dismiss`,d.tabIndex=-1,d.setAttribute(`aria-label`,i[`common.close`]);let f=document.createElement(`form`);f.className=`modal-card`;let p=e=>{if(!c){c=!0,window.removeEventListener(`hashchange`,m),window.removeEventListener(`popstate`,m),document.removeEventListener(`keydown`,h),r?.removeEventListener(`abort`,m);try{u.open&&typeof u.close==`function`&&u.close(),u.remove(),s?.isConnected&&s.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:`${a}-body`,finish:p}}function Mu(e,t,n,r=`div`){let i=document.createElement(r);i.id=t;for(let e of Au(n)){let t=document.createElement(`p`);t.className=`modal-desc`,t.textContent=e,i.append(t)}return e.append(i),i}function Nu(e){let t=e.locale??p(),n=l[t],r=e.tone===`danger`;return new Promise(i=>{if(e.signal?.aborted){i(!1);return}let{form:a,bodyId:o,finish:s}=ju(t,!1,i,e.signal);Mu(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 Pu(e){let t=e.locale??p(),n=l[t];return new Promise(r=>{if(e.signal?.aborted){r(null);return}let{form:i,bodyId:a,finish:o}=ju(t,null,r,e.signal),s=document.createElement(`input`),c=`${a}-input`,l=Mu(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 Fu(){return Nt()}function Iu(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function Lu(e){typeof window<`u`&&typeof window.clearInterval==`function`?window.clearInterval(e):clearInterval(e)}function Ru(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=Iu(o,t))},c=()=>{i!==null&&(Lu(i),i=null)},l=()=>{r&&(Fu()?c():(o(),s()))};r&&Fu()||s();let u=r?Pt(l):null;return n?.immediate&&o(),()=>{a=!0,c(),u?.()}}var zu=new Map;function Bu(e,t){let n=`${e}:${t}`,r=zu.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),zu.set(n,r)),r}var Vu=new Map;function Hu(e){let t=Vu.get(e);return t||(t=new Intl.NumberFormat(e),Vu.set(e,t)),t}function Uu(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`${Bu(t,r===0?0:1).format(i)} ${n[r]}`}function Wu(e,t){return!Number.isFinite(e)||e<0?`—`:Lr(e/1e3,t)}function Gu(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function Ku(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 qu(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:(Gu(n)-Gu(t))/r*36e5}function Ju({label:e,value:t,sub:n,tone:r}){return(0,Z.jsxs)(`div`,{className:`stat`,children:[(0,Z.jsx)(`div`,{className:`label`,children:e}),(0,Z.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,Z.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function Yu({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,Z.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,Z.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,Z.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,Z.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,Z.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:Uu(e,r),t!==null&&(0,Z.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,Uu(t,r)]})]})]}),(0,Z.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,Z.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,Z.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var Xu=60,Zu=1500,Qu=12e4;function $u({apiBase:t}){let{locale:n,t:r}=a(),[i,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(`idle`),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!1;return(async()=>{try{let n=await fetch(`${t}/api/startup-health`);if(!n.ok||e)return;let r=await n.json();e||m(r.protection===`none`)}catch{}})(),()=>{e=!0}},[t]),(0,X.useEffect)(()=>{let n=!1,r=!1,i=null,a=async()=>{if(r)return;r=!0;let a=e(1e4);i=a;try{let e=await fetch(`${t}/api/system/memory`,{signal:a.signal});if(!e.ok)throw Error(`memory unavailable`);let r=await e.json();if(n)return;o(r),c(!1),g(typeof r.activeTurnCount==`number`),r.isDraining&&l===`idle`&&u(`draining`),(l===`draining`||l===`reconnecting`)&&_!=null&&typeof r.pid==`number`&&r.pid!==_&&!r.isDraining&&(u(`idle`),v(null),f(null))}catch{if(n)return;l===`draining`||l===`reconnecting`?u(`reconnecting`):c(!0)}finally{a.clear(),i===a&&(i=null),r=!1}};a();let s=Ru(()=>void a(),5e3);return()=>{n=!0,i?.controller.abort(),i?.clear(),s()}},[t,l,_]),(0,X.useEffect)(()=>{if(l!==`reconnecting`)return;let n=!1,i=!1,a=null,o=Date.now(),s=()=>{if(i||n)return;i=!0;let s=e(5e3);a=s,fetch(`${t}/api/system/health`,{cache:`no-store`,signal:s.signal}).then(async e=>{if(n)return;if(!e.ok){Date.now()-o>=Qu&&(u(`error`),f(r(`dash.mem.restartFailed`)));return}let t=_==null;if(_!=null)try{let n=await e.json();t=typeof n.pid==`number`&&n.pid!==_}catch{t=!0}n||(t?(u(`idle`),v(null),f(null)):Date.now()-o>=Qu&&(u(`error`),f(r(`dash.mem.restartFailed`))))}).catch(()=>{n||Date.now()-o>=Qu&&(u(`error`),f(r(`dash.mem.restartFailed`)))}).finally(()=>{s.clear(),a===s&&(a=null),i=!1})};s();let c=setInterval(s,Zu);return()=>{n=!0,a?.controller.abort(),a?.clear(),clearInterval(c)}},[t,l,_,r]);let y=async()=>{let e=i?.activeTurnCount??0,n=[r(`dash.mem.restartConfirm`,{count:e,seconds:Xu})];if(p&&n.push(r(`dash.mem.restartNoSupervisor`)),await Nu({message:n.join(`
|
|
3
|
+
|
|
4
|
+
`),tone:`danger`})){f(null),v(typeof i?.pid==`number`?i.pid:null),u(`draining`);try{if(!(await fetch(`${t}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{u(`error`),v(null),f(r(`dash.mem.restartFailed`))}}};if(s&&!i&&l===`idle`)return(0,Z.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Z.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Z.jsx)(vt,{width:16,height:16,"aria-hidden":`true`}),r(`dash.mem.title`)]}),(0,Z.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:r(`dash.mem.unavailable`)})]});let b=i?.watchdog?qu(i.watchdog.samples):null,x=i?i.observedBytes??i.watchdog?.observedBytes??Gu(i):null,S=i?Ku(i):null,C=(()=>{let e=i?.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=i?.responseState,T=i?.activeTurnCount,E=l===`draining`||l===`reconnecting`;return(0,Z.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Z.jsxs)(`div`,{className:`mem-head`,children:[(0,Z.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,Z.jsx)(vt,{width:16,height:16,"aria-hidden":`true`}),r(`dash.mem.title`)]}),h&&(0,Z.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,Z.jsxs)(`span`,{className:`mem-inflight`,children:[(0,Z.jsx)(`span`,{className:`mem-inflight-label`,children:r(`dash.mem.inFlight`)}),(0,Z.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof T==`number`?Hu(n).format(T):`—`})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:E,onClick:()=>{y()},children:r(`dash.mem.restart`)})]})]}),(0,Z.jsx)(Yu,{observedBytes:x,thresholdBytes:i?.watchdog?.warnThresholdBytes??null,metric:S,locale:n,t:r}),(0,Z.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,Z.jsx)(Ju,{label:r(`dash.mem.rss`),value:i?Uu(i.rss,n):`—`}),(0,Z.jsx)(Ju,{label:r(`dash.mem.jsHeap`),value:i?Uu(i.heapUsed,n):`—`,sub:i?r(`dash.mem.jsHeapArena`,{total:Uu(i.heapTotal,n)}):void 0}),(0,Z.jsx)(Ju,{label:r(`dash.mem.jscHeap`),value:i?.jscHeap?Uu(i.jscHeap.heapSize,n):`—`}),(0,Z.jsx)(Ju,{label:r(`dash.mem.growth`),value:b===null?`—`:`${b>=0?`+`:`−`}${Uu(Math.abs(b),n)}${r(`dash.mem.perHour`)}`,tone:C})]}),(0,Z.jsxs)(`details`,{style:{marginTop:10},children:[(0,Z.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:r(`dash.mem.details`)}),(0,Z.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:r(`dash.mem.hint`)}),(0,Z.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:r(`dash.mem.runtime`)}),(0,Z.jsxs)(`div`,{className:`stat-row`,children:[(0,Z.jsx)(Ju,{label:r(`dash.mem.observed`),value:x===null?`—`:`${Uu(x,n)} (${S})`}),(0,Z.jsx)(Ju,{label:r(`dash.mem.external`),value:i?.external===void 0?`—`:Uu(i.external,n)}),(0,Z.jsx)(Ju,{label:r(`dash.mem.arrayBuffers`),value:i?.arrayBuffers===void 0?`—`:Uu(i.arrayBuffers,n)})]}),(0,Z.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:r(`dash.mem.store`)}),(0,Z.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:r(`dash.mem.storeHint`)}),(0,Z.jsxs)(`div`,{className:`stat-row`,children:[(0,Z.jsx)(Ju,{label:r(`dash.mem.storeEntries`),value:w?Hu(n).format(w.count):`—`}),(0,Z.jsx)(Ju,{label:r(`dash.mem.storeTotal`),value:w?Uu(w.totalBytes,n):`—`}),(0,Z.jsx)(Ju,{label:r(`dash.mem.storeLargest`),value:w?Uu(w.largestBytes,n):`—`}),(0,Z.jsx)(Ju,{label:r(`dash.mem.storeOldest`),value:w?w.count===0?`—`:Wu(w.oldestAgeMs,n):`—`})]}),i?.watchdog&&(0,Z.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,Z.jsx)(Ju,{label:r(`dash.mem.threshold`),value:Uu(i.watchdog.warnThresholdBytes,n)}),(0,Z.jsx)(Ju,{label:r(`dash.mem.lastWarn`),value:i.watchdog.lastWarnAt?new Date(i.watchdog.lastWarnAt).toLocaleString(n):r(`dash.mem.never`)})]})]}),h&&(0,Z.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[l===`draining`&&(0,Z.jsx)(`span`,{className:`muted text-control`,children:r(`dash.mem.draining`,{count:typeof T==`number`?T:0})}),l===`reconnecting`&&(0,Z.jsx)(`span`,{className:`muted text-control`,children:r(`dash.mem.reconnecting`)}),l===`error`&&d&&(0,Z.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:d}),p&&l===`idle`&&(0,Z.jsx)(`span`,{className:`muted text-control`,children:r(`dash.mem.restartNoSupervisor`)})]})]})}var ed=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function td(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`||!ed.includes(a)))throw Error(`invalid effort`);n[e]={model:i,...a?{reasoningEffort:a}:{}}}return n}function nd(e,t){return e?{model:e,...t?{reasoningEffort:t}:{}}:void 0}function rd(e){return(0,Z.jsx)(id,{...e},e.apiBase)}function id({apiBase:t,models:n}){let r=c(),[i,a]=(0,X.useState)(void 0),[o,s]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(``),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),C=(0,X.useRef)(!1),w=(0,X.useRef)(null),T=(0,X.useRef)(null),E=Ar(o,T),D=(0,X.useCallback)(e=>{a(e),u(e.extract?.model??``),f(e.extract?.reasoningEffort??``),m(e.consolidation?.model??``),g(e.consolidation?.reasoningEffort??``)},[]),O=(0,X.useCallback)(async()=>{if(w.current)return;let n=e(15e3);w.current=n,b(!1);try{let e=td(await Qn(await fetch(`${t}/api/settings`,{signal:n.signal})));C.current&&w.current===n&&D(e)}catch{C.current&&w.current===n&&b(!0)}finally{n.clear(),w.current===n&&(w.current=null)}},[t,D]);(0,X.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||i===void 0)return;let n=e(15e3);w.current=n,v(!0),S(null);let r=nd(l,d),a=nd(p,h);try{let e=td(await Qn(await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({memoryModels:r||a?{...r?{extract:r}:{},...a?{consolidation:a}:{}}:null}),signal:n.signal})));C.current&&w.current===n&&(D(e),S(`saved`))}catch{C.current&&w.current===n&&S(`failed`)}finally{n.clear(),C.current&&w.current===n&&v(!1),w.current===n&&(w.current=null)}},A=[{value:``,label:r(`memoryModels.off`)},...[...new Set([...n.map(e=>e.namespaced),...[l,p].filter(Boolean)])].map(e=>({value:e,label:He(e,r)}))],j=[{value:``,label:r(`memoryModels.defaultEffort`)},...ed.map(e=>({value:e,label:r(`models.reasoningEffort.${e}`)}))],M=_||i===void 0||y,N=l!==(i?.extract?.model??``)||d!==(i?.extract?.reasoningEffort??``)||p!==(i?.consolidation?.model??``)||h!==(i?.consolidation?.reasoningEffort??``),P=!!l!=!!p,F=r(`memoryModels.info`),I=(e,t,n,i,a)=>(0,Z.jsxs)(`div`,{className:`spread memory-models-row`,style:{flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Z.jsxs)(`div`,{style:{flex:`1 1 18rem`,minWidth:0},children:[(0,Z.jsx)(`div`,{className:`font-semibold`,children:r(`memoryModels.${e}`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:r(`memoryModels.${e}Hint`)})]}),(0,Z.jsxs)(`div`,{className:`memory-models-controls`,children:[(0,Z.jsx)($,{id:`memory-models-${e}`,value:t,options:A,disabled:M,label:r(`memoryModels.model`),onChange:e=>{i(e),e||a(``),S(null)}}),(0,Z.jsx)($,{id:`memory-models-${e}-effort`,value:n,options:j,disabled:M||!t,align:`right`,label:r(`memoryModels.effort`),onChange:e=>{a(e),S(null)}})]})]});return(0,Z.jsxs)(`section`,{className:`panel`,"aria-labelledby":`memory-models-title`,"aria-busy":_||i===void 0&&!y,children:[(0,Z.jsxs)(`div`,{className:`font-semibold`,id:`memory-models-title`,style:{display:`flex`,alignItems:`center`,gap:6},children:[r(`memoryModels.title`),(0,Z.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:()=>s(e=>!e),"aria-label":r(`memoryModels.infoLabel`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`memory-models-help-dialog`,children:(0,Z.jsx)(q,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:r(`memoryModels.description`)}),I(`extract`,l,d,u,f),I(`consolidation`,p,h,m,g),(0,Z.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`,flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Z.jsx)(`div`,{className:`muted setting-hint`,style:{flex:`1 1 18rem`,minWidth:0},children:r(`memoryModels.dataNotice`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:M||!N,onClick:()=>{k()},children:r(_?`common.saving`:`common.save`)})]}),P&&(0,Z.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Z.jsx)(at,{width:14}),` `,r(`memoryModels.accountNotice`)]}),y&&(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[r(`memoryModels.loadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{O()},children:r(`common.retry`)})]}),x===`failed`&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:r(`memoryModels.saveFailed`)}),x===`saved`&&(0,Z.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:r(`memoryModels.saved`)}),(0,Z.jsxs)(`dialog`,{ref:E,id:`memory-models-help-dialog`,className:`modal-overlay`,style:{display:o?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`memory-models-help-title`,onCancel:e=>{e.preventDefault(),s(!1)},children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>s(!1)}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:`memory-models-help-title`,children:r(`memoryModels.title`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>s(!1),"aria-label":r(`common.close`),children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:F}),(0,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>s(!1),children:r(`common.ok`)})})]})]})]})}function ad(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 od({apiBase:e}){return(0,Z.jsx)(sd,{apiBase:e},e)}function sd({apiBase:t}){let n=c(),[r,i]=(0,X.useState)(),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(!1),_=(0,X.useRef)(null),v=(0,X.useCallback)(e=>{i(e),o(e.modelSwitch),l(e.accountSwitch)},[]),y=(0,X.useCallback)(async()=>{if(_.current)return;let n=e(15e3);_.current=n,p(!1);try{let e=ad(await Qn(await fetch(`${t}/api/native-reasoning-retention`,{signal:n.signal})));g.current&&_.current===n&&v(e)}catch{g.current&&_.current===n&&p(!0)}finally{n.clear(),_.current===n&&(_.current=null)}},[t,v]);(0,X.useEffect)(()=>{g.current=!0;let e=window.setTimeout(()=>{y()},0);return()=>{window.clearTimeout(e),g.current=!1,_.current?.controller.abort(),_.current?.clear(),_.current=null}},[y]);let b=async(n=!1)=>{if(_.current||r===void 0)return;let i=e(15e3);_.current=i,d(!0),h(null);try{let e=ad(await Qn(await fetch(`${t}/api/native-reasoning-retention`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:i.signal,body:JSON.stringify(n?null:{modelSwitch:a,accountSwitch:s})})));g.current&&_.current===i&&(v(e),h(`saved`))}catch{g.current&&_.current===i&&h(`failed`)}finally{i.clear(),g.current&&_.current===i&&d(!1),_.current===i&&(_.current=null)}},x=u||r===void 0||f,S=a!==r?.modelSwitch||s!==r?.accountSwitch;return(0,Z.jsxs)(`section`,{className:`panel`,"aria-labelledby":`native-reasoning-retention-title`,"aria-busy":u||r===void 0&&!f,children:[(0,Z.jsx)(`div`,{className:`font-semibold`,id:`native-reasoning-retention-title`,children:n(`nativeReasoningRetention.title`)}),(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:n(`nativeReasoningRetention.description`)}),(0,Z.jsxs)(`div`,{className:`stack`,style:{gap:`var(--space-3)`},children:[(0,Z.jsxs)(`div`,{className:`spread`,children:[(0,Z.jsx)(`span`,{children:n(`nativeReasoningRetention.modelSwitch`)}),(0,Z.jsx)(kn,{on:a,disabled:x,label:n(`nativeReasoningRetention.modelSwitch`),onClick:()=>{o(e=>!e),h(null)}})]}),(0,Z.jsxs)(`div`,{className:`spread`,children:[(0,Z.jsx)(`span`,{children:n(`nativeReasoningRetention.accountSwitch`)}),(0,Z.jsx)(kn,{on:s,disabled:x,label:n(`nativeReasoningRetention.accountSwitch`),onClick:()=>{l(e=>!e),h(null)}})]}),(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:n(`nativeReasoningRetention.accountHint`)}),(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:x||!S,onClick:()=>{b()},children:n(`common.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:x||!S&&!r?.modelSwitch&&!r?.accountSwitch,onClick:()=>{b(!0)},children:n(`nativeReasoningRetention.reset`)})]})]}),f&&(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[n(`nativeReasoningRetention.loadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{y()},children:n(`common.retry`)})]}),m===`failed`&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:n(`nativeReasoningRetention.saveFailed`)}),m===`saved`&&(0,Z.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:n(`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 ld({apiBase:t,section:n,readOnly:r=!1,embedded:i=!1}){let a=c(),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),h=(0,X.useRef)(!1),g=(0,X.useRef)(0),_=(0,X.useCallback)(async()=>{if(h.current)return;let n=++g.current,r=e(15e3);try{let e=await fetch(t+`/api/fallback`,{signal:r.signal}),i=e.ok?cd(await e.json()):null;if(!i)throw Error(`shape`);!h.current&&n===g.current&&(s(i),u(!1))}catch{!h.current&&n===g.current&&u(!0)}finally{r.clear()}},[t]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{_()},0),t=Ru(()=>{_()},3e4);return()=>{window.clearTimeout(e),t()}},[_]);let v=(0,X.useCallback)(async n=>{if(h.current||r)return;h.current=!0,g.current+=1,m(!0),f(!1);let i=e(15e3);try{let e=await fetch(t+`/api/fallback`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({writes:n}),signal:i.signal}),r=e.ok?cd(await e.json()):null;if(!r)throw Error(`save`);g.current+=1,s(r)}catch{f(!0)}finally{i.clear(),h.current=!1,m(!1)}},[t,r]),y=e=>a(e===!1?`fallback.state.off`:e===!0?`fallback.state.on`:`fallback.state.inherit`),b=p||r;if(!o)return n===`devices`?null:(0,Z.jsxs)(`section`,{className:`panel fallback-panel`,"aria-busy":!l||void 0,children:[!i&&(0,Z.jsx)(`h3`,{children:a(n===`routing`?`fallback.title`:`fallback.devices.title`)}),(0,Z.jsx)(`p`,{className:`card-sub`,role:`status`,children:a(l?`fallback.loadFailed`:`common.loading`)}),l&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{_()},children:a(`common.retry`)})]});if(n===`devices`)return(0,Z.jsxs)(`section`,{className:`panel fallback-panel`,children:[(0,Z.jsx)(`h3`,{children:a(`fallback.devices.title`)}),(0,Z.jsx)(`p`,{className:`card-sub`,children:a(r?`fallback.devices.childNote`:`fallback.devices.desc`)}),o.devices.length===0?(0,Z.jsx)(`p`,{className:`card-sub`,children:a(`fallback.devices.empty`)}):(0,Z.jsxs)(`table`,{className:`fallback-devices`,"aria-label":a(`fallback.devices.title`),children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`fallback-device-head`,children:[(0,Z.jsx)(`th`,{scope:`col`,children:a(`fallback.devices.device`)}),(0,Z.jsx)(`th`,{scope:`col`,children:a(`fallback.devices.local`)}),(0,Z.jsx)(`th`,{scope:`col`,children:a(`fallback.devices.chains`)})]})}),(0,Z.jsx)(`tbody`,{children:o.devices.map(e=>{let t=e.model!==!1&&e.provider!==!1,n=e.alias??e.id;return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsxs)(`td`,{children:[(0,Z.jsx)(`strong`,{children:n}),e.alias&&(0,Z.jsx)(`code`,{className:`fallback-device-id`,children:e.id})]}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(ud,{label:a(`fallback.devices.localFor`,{name:n}),on:e.localFallback,disabled:b,onToggle:()=>{v([{scope:`device`,key:e.id,setting:`localFallback`,value:!e.localFallback||null}])}})}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(ud,{label:a(`fallback.devices.chainsFor`,{name:n}),on:t,disabled:b,onToggle:()=>{let n=!t&&null;v([{scope:`device`,key:e.id,setting:`model`,value:n},{scope:`device`,key:e.id,setting:`provider`,value:n}])}})})]},e.id)})})]}),d&&(0,Z.jsx)(Q,{tone:`err`,children:a(`fallback.saveFailed`)})]});let x=[...Object.entries(o.providers).map(([e,t])=>({scope:`provider`,key:e,value:t})),...Object.entries(o.routes).map(([e,t])=>({scope:`route`,key:e,value:t}))],S=o.last;return(0,Z.jsxs)(`section`,{className:`panel fallback-panel`,"aria-label":i?a(`fallback.title`):void 0,children:[!i&&(0,Z.jsx)(`h3`,{children:a(`fallback.title`)}),(0,Z.jsx)(`p`,{className:`card-sub`,children:a(r?`fallback.devices.childNote`:`fallback.desc`)}),[`model`,`provider`].map(e=>(0,Z.jsxs)(`div`,{className:`fallback-switch-row`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`strong`,{children:a(e===`model`?`fallback.model`:`fallback.provider`)}),(0,Z.jsx)(`div`,{className:`card-sub`,children:a(e===`model`?`fallback.modelHint`:`fallback.providerHint`)})]}),(0,Z.jsx)(ud,{label:a(e===`model`?`fallback.model`:`fallback.provider`),on:o.global[e],disabled:b,onToggle:()=>{v([{scope:`global`,setting:e,value:!o.global[e]&&null}])}})]},e)),(0,Z.jsx)(`p`,{className:`card-sub faint`,children:a(`fallback.rotationNote`)}),x.length>0&&(0,Z.jsxs)(`div`,{className:`fallback-overrides`,children:[(0,Z.jsx)(`strong`,{children:a(`fallback.overrides`)}),(0,Z.jsx)(`ul`,{children:x.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{children:a(e.scope===`provider`?`fallback.scope.provider`:`fallback.scope.route`,{name:e.key})}),(0,Z.jsxs)(`span`,{className:`card-sub`,children:[a(`fallback.model`),`: `,y(e.value.model),` · `,a(`fallback.provider`),`: `,y(e.value.provider)]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:b,onClick:()=>{v([`model`,`provider`].filter(t=>e.value[t]!==void 0).map(t=>({scope:e.scope,key:e.key,setting:t,value:null})))},children:a(`fallback.clear`)})]},e.scope+`:`+e.key))})]}),(0,Z.jsxs)(`div`,{className:`fallback-last`,"aria-live":`polite`,children:[(0,Z.jsx)(`strong`,{children:a(`fallback.last`)}),S?(0,Z.jsxs)(`p`,{className:`card-sub`,children:[(0,Z.jsx)(`time`,{dateTime:S.at,children:new Date(S.at).toLocaleString()}),` · `,(0,Z.jsx)(`code`,{children:S.route}),`: `,(0,Z.jsx)(`code`,{children:S.from}),` → `,(0,Z.jsx)(`code`,{children:S.to}),` (`,(0,Z.jsx)(`code`,{children:S.trigger}),`) · `,a(S.outcome===`refused`?`fallback.last.refused`:`fallback.last.taken`)]}):(0,Z.jsx)(`p`,{className:`card-sub`,children:a(`fallback.last.none`)})]}),d&&(0,Z.jsx)(Q,{tone:`err`,children:a(`fallback.saveFailed`)})]})}function ud({label:e,on:t,disabled:n,onToggle:r}){return(0,Z.jsx)(`button`,{type:`button`,className:`toggle `+(t?`on`:``),"aria-pressed":t,"aria-label":e,title:e,onClick:r,disabled:n,children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})}function dd({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,X.useRef)(null),g=(0,X.useRef)(null),[_,v]=(0,X.useState)(),y=(0,X.useCallback)(()=>{n.current&&v(On(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,X.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,X.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,X.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,X.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,Z.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,Z.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,Z.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Z.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,Z.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,Z.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,Z.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,Z.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Z.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,Z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Z.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:pr,max:fr,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,Z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,Z.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:pr,max:fr})})]})]}):null}function fd(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 pd({options:e,sourceModels:t,disabled:n=!1,saving:r=!1,onChange:i,className:a}){let o=c(),s=(0,X.useId)();return!e||e.length===0?null:(0,Z.jsxs)(`div`,{className:[`shadow-source-toggles`,a].filter(Boolean).join(` `),role:`group`,"aria-label":o(`shadowCall.sources`),"aria-describedby":s,children:[(0,Z.jsx)(`div`,{className:`shadow-source-toggle-list`,children:e.map(e=>{let a=Gn(e.id,t),s=Kn(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,Z.jsxs)(`span`,{className:`shadow-source-toggle${a?` on`:``}`,children:[(0,Z.jsx)(kn,{on:a,onClick:()=>{`sourceModels`in s&&i(s.sourceModels)},disabled:n||r||c!==void 0||l,label:`${e.id} (${fd(o,e.role)})`,title:u}),(0,Z.jsx)(`code`,{className:`shadow-source-id`,children:Wn([e.id])}),(0,Z.jsx)(`span`,{className:`muted text-caption shadow-source-role`,children:fd(o,e.role)}),d?(0,Z.jsx)(`span`,{className:`muted text-caption shadow-source-reason`,children:d}):null]},e.id)})}),(0,Z.jsx)(`span`,{id:s,className:`muted text-caption shadow-source-hint`,children:o(`shadowCall.sourceHint`)})]})}var md=`w-[15rem] max-w-full`,hd=`w-[9.5rem] max-w-full`;function gd({d:e}){let{t,maMode:n,maError:r}=e;return(0,Z.jsxs)(Fc,{id:`proxy-subagents`,title:t(`proxyV2.secSubagents`),lede:t(`proxyV2.secSubagentsLede`),children:[(0,Z.jsx)(Lc,{label:t(`dash.multiAgent`),hint:t(`proxyV2.maModeHint`),help:(0,Z.jsx)(Vc,{...e}),control:(0,Z.jsx)(Bc,{maMode:n,maBusy:e.maBusy,switchMaMode:e.switchMaMode}),children:r&&(0,Z.jsx)(`div`,{role:`alert`,className:`text-[13px] break-words text-danger`,children:r})}),(0,Z.jsx)(_d,{apiBase:e.apiBase,d:e}),(0,Z.jsx)(vd,{apiBase:e.apiBase,d:e})]})}function _d({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`)},...$n.map(e=>({value:e,label:e}))],h=async t=>{if(!u){p(!0);try{let n=await Qn(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Lc,{className:`dash-effort-panel`,label:n(`dash.effortCapLabel`),hint:n(`proxyV2.effortCapHint`),help:(0,Z.jsx)(Ic,{buttonRef:a,label:n(`dash.effortCapLabel`),expanded:o,controls:`effort-cap-help-dialog`,popup:`dialog`,onClick:()=>s(e=>!e)}),control:(0,Z.jsx)($,{value:c,options:m,fullWidth:!0,className:hd,onChange:e=>{h({effortCap:e||null})},disabled:u,label:n(`dash.effortCapLabel`),align:`right`})}),(0,Z.jsx)(Lc,{label:n(`dash.subagentEffortCapLabel`),hint:n(`proxyV2.subagentEffortCapHint`),control:(0,Z.jsx)($,{value:l,options:m,fullWidth:!0,className:hd,onChange:e=>{h({subagentEffortCap:e||null})},disabled:u,label:n(`dash.subagentEffortCapLabel`),align:`right`})})]})}function vd({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,Z.jsx)(Lc,{className:`dash-delegation-row`,label:t(`dash.injectionLabel`),hint:t(`proxyV2.injectionHint`),control:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)($,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:He(`${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:md}),n&&i.length>0&&(0,Z.jsx)($,{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:hd}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>_n(`#subagents`),children:t(`dash.injectionManage`)})]})})}function yd({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,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}):null,u=(0,Z.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[13px] leading-[19px] text-fg-muted`,children:t(`dash.codexRemoteHistoryHint`)});return(0,Z.jsxs)(Fc,{id:`proxy-codex`,title:t(`proxyV2.secCodex`),lede:t(`proxyV2.secCodexLede`),children:[(0,Z.jsx)(Lc,{label:t(`dash.codexAutoStart`),hint:t(`proxyV2.autoStartShort`),details:t(`dash.codexAutoStartHint`),inline:!0,control:(0,Z.jsx)(bd,{on:n?.codexAutoStart??!0,label:t(`dash.codexAutoStart`),disabled:c,onClick:a})}),(0,Z.jsx)(Lc,{label:t(`dash.codexDesktopAuthless`),hint:t(`proxyV2.authlessShort`),details:t(`dash.codexDesktopAuthlessHint`),inline:!0,control:(0,Z.jsx)(bd,{on:n?.codexDesktopAuthless??!1,label:t(`dash.codexDesktopAuthless`),disabled:c,onClick:o}),children:(n?.codexDesktopAuthless||n?.catalogRefreshPending)&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[n?.codexDesktopAuthless&&u,l]})}),(0,Z.jsx)(Lc,{label:t(`dash.codexClientCompaction`),hint:t(`proxyV2.clientCompactionShort`),details:t(`dash.codexClientCompactionHint`),inline:!0,control:(0,Z.jsx)(bd,{on:n?.codexClientCompaction??!1,label:t(`dash.codexClientCompaction`),disabled:c,onClick:s}),children:(!n?.codexDesktopAuthless&&n?.codexClientCompaction||n?.catalogRefreshPending)&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[!n?.codexDesktopAuthless&&n?.codexClientCompaction&&u,l]})}),(0,Z.jsx)(xd,{d:e})]})}function bd({on:e,label:t,disabled:n,onClick:r}){return(0,Z.jsx)(`button`,{type:`button`,className:`switch ${e?`on`:``}`,onClick:r,disabled:n,"aria-label":t,"aria-pressed":e,children:(0,Z.jsx)(`span`,{className:`knob`})})}function xd({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,X.useState)(!1),_=(0,X.useRef)(null);(0,X.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Lc,{className:`maintenance-panel dash-sync-summary`,label:t(`dash.syncModels`),hint:t(`dash.syncModelsHint`),control:(0,Z.jsxs)(`div`,{className:`maintenance-actions flex items-center gap-2`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-sm`,onClick:v,disabled:r||i,children:[(0,Z.jsx)(Mt,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,Z.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,Z.jsxs)(`div`,{className:`notice ${d.status===`failed`?`notice-err`:`notice-ok`} dash-update-job`,role:`status`,children:[d.status===`failed`?(0,Z.jsx)(at,{}):(0,Z.jsx)(Mt,{}),(0,Z.jsxs)(`span`,{children:[nr(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,Z.jsxs)(`div`,{className:`action-toast notice ${m?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[m?(0,Z.jsx)(at,{}):(0,Z.jsx)(ut,{}),(0,Z.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:l.added}),l.warning?` ${l.warning}`:``,l.nativeSubagentDefaultsWarning?` ${l.nativeSubagentDefaultsWarning}`:``,l.staleAppServerHint?(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(N,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,Z.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Z.jsx)(We,{width:13,height:13,"aria-hidden":`true`})})]}),!h&&u&&(0,Z.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{children:t(`dash.syncFailed`,{error:u})}),(0,Z.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Z.jsx)(We,{width:13,height:13,"aria-hidden":`true`})})]})]})}function Sd({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=_r(o,v),T=yr(w,C),E=String(n?.vision?.maxDescriptionsPerTurn??8),D=String(n?.vision?.timeoutMs??dr),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)(null),[M,N]=(0,X.useState)(!1),[P,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(!1),R=(0,X.useRef)(null),z=O??E,B=A??D,V=(e=z)=>{let t=mr(e);t===void 0?(k(e),N(!0)):(N(!1),k(null),t!==(n?.vision?.maxDescriptionsPerTurn??8)&&s(lr(t)))},H=(e=B)=>{let t=hr(e);t===void 0?(j(e),F(!0)):(F(!1),j(null),t!==(n?.vision?.timeoutMs??dr)&&s(ur(t)))};return(0,Z.jsxs)(Fc,{id:`proxy-sidecars`,title:t(`proxyV2.secSidecars`),lede:t(`proxyV2.secSidecarsLede`),children:[(0,Z.jsxs)(`div`,{className:`pv2-row dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!n||void 0,children:[(0,Z.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Z.jsx)(`div`,{className:`pv2-row-label`,children:t(`dash.webSearchSidecar`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)}),sr(c)&&(0,Z.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{children:t(`dash.webSearchCodexSync`)})]})]}),(0,Z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Z.jsx)(`div`,{className:`dash-sidecar-select-row`,children:(0,Z.jsx)($,{value:S,options:[{value:``,label:t(`dash.webSearchOff`)},...i],onChange:e=>{if(e===``){s(or(!1));return}let t={webSearch:Er(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,Z.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Z.jsx)($,{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,Z.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Z.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,title:t(`dash.webSearchStreamHint`),children:[(0,Z.jsx)(`span`,{className:`muted setting-hint dash-sidecar-toggle-label`,children:t(`dash.webSearchStream`)}),(0,Z.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,Z.jsx)(`span`,{className:`knob`})})]})]})]}),(0,Z.jsxs)(`div`,{className:`pv2-row dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!n||void 0,children:[(0,Z.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Z.jsx)(`div`,{className:`pv2-row-label`,children:t(`dash.visionSidecar`)}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,Z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Z.jsxs)(`div`,{className:`dash-sidecar-select-row`,children:[(0,Z.jsx)($,{value:v,options:[{value:``,label:t(`dash.visionOff`)},...a],onChange:e=>{if(e===``){s(ar(!1));return}let t=yr(_r(o,e),T),n={vision:{model:e,backend:Dr(o,a,e),reasoning:t}};_||(n.vision={...n.vision,enabled:!0}),s(n)},disabled:!n||r,label:t(`dash.sidecarModel`)}),(0,Z.jsx)($,{value:T,options:vr(w,T).map(e=>({value:e,label:e})),onChange:e=>{s(ir(e))},disabled:!_||!n||r,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),n&&y===`anthropic`&&(0,Z.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Z.jsx)($,{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,Z.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Z.jsx)(`div`,{className:`dash-sidecar-trailing-row`,children:(0,Z.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,Z.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`,style:{transform:I?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,vn.createPortal)((0,Z.jsx)(dd,{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,Z.jsxs)(Lc,{className:`dash-shadow-row`,busy:!l,label:t(`dash.shadowCallIntercept`),hint:t(`proxyV2.shadowShort`),help:(0,Z.jsx)(Ic,{buttonRef:f,label:t(`dash.shadowCallIntercept`),expanded:p,controls:`shadow-call-help-dialog`,popup:`dialog`,onClick:()=>m(e=>!e)}),badge:(0,Z.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:`⚠ ${qn(l?.sourceModels,g)}`}),control:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)($,{value:l?.model??``,options:Cr(o,l?.model,l?.sourceModels).map(e=>e.value===``?e:{...e,label:He(e.value,t)}),onChange:e=>{h({model:e})},disabled:!l||u||!l?.enabled,label:t(`dash.shadowCallModel`),align:`right`,fullWidth:!0,className:md}),(0,Z.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,Z.jsx)(`span`,{className:`knob`})})]}),children:[(0,Z.jsx)(pd,{className:`dash-shadow-sources`,options:l?.sourceModelOptions,sourceModels:l?.sourceModels,disabled:!l?.enabled,saving:u,onChange:e=>void h({sourceModels:e})}),d&&(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{children:d})]})]})]})}function Cd({readOnly:e=!1,...t}){let{t:n}=t;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(gd,{d:t}),(0,Z.jsx)(yd,{d:t}),(0,Z.jsx)(Sd,{d:t}),(0,Z.jsxs)(Fc,{id:`proxy-compaction`,title:n(`proxyV2.secCompaction`),lede:n(`proxyV2.secCompactionLede`),children:[(0,Z.jsx)(wu,{apiBase:t.apiBase,models:t.models,providers:t.providers}),(0,Z.jsx)(od,{apiBase:t.apiBase}),(0,Z.jsx)(Du,{apiBase:t.apiBase})]}),(0,Z.jsxs)(Fc,{id:`proxy-memory`,title:n(`proxyV2.secMemory`),lede:n(`proxyV2.secMemoryLede`),children:[(0,Z.jsx)(rd,{apiBase:t.apiBase,models:t.models}),(0,Z.jsx)($u,{apiBase:t.apiBase})]}),(0,Z.jsx)(Fc,{id:`proxy-fallback`,title:n(`proxyV2.secFallback`),lede:n(`proxyV2.secFallbackLede`),children:(0,Z.jsx)(ld,{apiBase:t.apiBase,section:`routing`,readOnly:e,embedded:!0})})]})}var wd=[[`proxy-subagents`,`proxyV2.secSubagents`],[`proxy-codex`,`proxyV2.secCodex`],[`proxy-sidecars`,`proxyV2.secSidecars`],[`proxy-compaction`,`proxyV2.secCompaction`],[`proxy-memory`,`proxyV2.secMemory`],[`proxy-fallback`,`proxyV2.secFallback`]];function Td({items:e,label:t,className:n}){let r=fc(),[i,a]=(0,X.useState)(e[0]?.id??``),o=e.map(e=>e.id).join(`|`);(0,X.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,Z.jsxs)(`nav`,{"aria-label":t,className:Y(`pv2-index min-w-0`,n),children:[(0,Z.jsx)(`p`,{className:`m-0 mb-1.5 hidden px-2.5 text-xs font-medium text-fg-subtle lg:block`,children:t}),(0,Z.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,Z.jsx)(`li`,{className:`shrink-0`,children:(0,Z.jsx)(`button`,{type:`button`,"aria-current":t?`location`:void 0,onClick:()=>s(e.id),className:Y(`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 Ed({readOnly:e=!1,...t}){let n=wd.map(([e,n])=>({id:e,label:t.t(n)}));return(0,Z.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,Z.jsx)(Rc,{...t}),(0,Z.jsxs)(`div`,{className:`pv2-overview-grid grid min-w-0 gap-5 lg:grid-cols-[11rem_minmax(0,1fr)] lg:gap-8`,children:[(0,Z.jsx)(Td,{items:n,label:t.t(`proxyV2.indexLabel`),className:`lg:sticky lg:top-4 lg:self-start`}),(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col gap-5`,children:(0,Z.jsx)(Cd,{...t,readOnly:e})})]})]})}function Dd({t:e,providers:t}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,Z.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,Z.jsx)(Nn,{title:(0,Z.jsx)(N,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,Z.jsx)(`div`,{className:`tbl-wrap`,children:(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:e(`dash.col.name`)}),(0,Z.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,Z.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,Z.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,Z.jsx)(`tbody`,{children:t.map(t=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`font-semibold`,children:Ge(t.name,e)}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,Z.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,Z.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var Od=`__ocxCachedAt`;function kd(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Ad(n)?n.data:n}catch{return null}}function Ad(e){return typeof e==`object`&&!!e&&typeof e[Od]==`number`&&`data`in e}function jd(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Ad(n)?{data:n.data,cachedAt:n[Od]}:{data:n,cachedAt:null}}catch{return null}}function Md(e,t){try{sessionStorage.setItem(e,JSON.stringify({[Od]:Date.now(),data:t}))}catch{}}function Nd(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function Pd(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 Fd(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,X.useMemo)(()=>a?jd(a):null,[a]),c=dn(e,t,(0,X.useCallback)(async e=>{let t=await n(e);return a&&Md(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:Pd(c,i,r.enabled!==!1)}}function Id(){return typeof navigator>`u`?``:navigator.userAgent}function Ld(e=Id()){return e.match(/OpenCodexDesktop\/(\S+)/)?.[1]??null}function Rd(e=Id()){return Ld(e)!==null}var zd=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function Bd(e=typeof location>`u`?``:location.search){let t=new URLSearchParams(e).get(`desktop_session`);return t&&zd.test(t)?t:null}function Vd(e,t,n){let r=e+`/api/update/badge`;if(!Rd(t))return r;let i=Bd(n);return r+`?surface=desktop`+(i?`&session=`+encodeURIComponent(i):``)}function Hd(e=Id()){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 Ud(e=Id()){if(!Rd(e))return null;let t=Hd(e);return t===`windows`?`http://tauri.localhost/update.html`:t===`macos`||t===`linux`?`tauri://localhost/update.html`:null}function Wd(e=Id()){let t=Ud(e);return t?(window.location.assign(t),!0):!1}function Gd(e=Id()){if(!Rd(e))return null;let t=Hd(e);return t===`windows`?`http://tauri.localhost/cli.html`:t===`macos`||t===`linux`?`tauri://localhost/cli.html`:null}function Kd(e=Id()){let t=Gd(e);return t?(window.location.assign(t),!0):!1}function qd(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 Jd(e){return e.desktop!==void 0&&(e.desktop.owned||e.desktop.supervisor!==void 0)}function Yd(e,t){return t?`startup.unhealthy`:e.viable?`startup.viable`:e.running&&!e.loginEnabled&&(e.owned||e.supervisor!==void 0)?`startup.desktopLoginUnverified`:`startup.unhealthy`}function Xd(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 Zd(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Qd(e,t){return{request:++e.current,mutation:t.current}}var $d=2e3;function ef(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function tf(e){return e?e.stale&&e.status!==`error`:!1}function nf(e,t){return!t||t.diagnosticStale||e!==null&&e!==`error`?e:t.status}var rf=3e4;function af(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function of(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function sf(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=ef(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(of(e,t))throw e;return{status:`error`,stale:!1}}}async function cf(e,t){try{return(await Bn(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function lf(e,t){return Qn(await fetch(`${e}/api/models`,{signal:t}))}async function uf(e,t){return Vr(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function df(e,t,n){let{request:r,mutation:i}=Qd(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 Qn(a),c;try{if(o.ok){let e=await o.json();Zd({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else Zd({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{Zd({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 ff(e,t,n){let{request:r,mutation:i}=Qd(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Qn(await fetch(`${e}/api/settings`,{signal:t})),o,s;return Zd({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 pf(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`};let r=await n.json(),i=Mr(r.multiAgentSurfaceAdvisory);return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?{maMode:r.multiAgentMode,advisory:i}:{maMode:`default`,advisory:i}}catch(e){if(of(e,t))throw e;return{maMode:`default`}}}async function mf(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 Qn(d),t=await Qn(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(of(e,t))throw e;return n(`invalid`)}}finally{r.abort()}}async function hf(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={...af(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 gf(e){if(_f(e)&&Array.isArray(e.clientIntegrations))return e.clientIntegrations.filter(e=>_f(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 _f(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vf(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function yf(e){if(!_f(e))throw Error(`invalid selected models response`);let t=e.selected;if(!_f(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,vf(t)]))}async function bf(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 yf(await r.json())}function xf(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Sf(e,t,n,r,i){return xf(e,t,n,r)&&!i}async function Cf(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 wf(e,t){return e===t}function Tf(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 Ef(e){return e.some(e=>e.pricingStatus!==void 0)}function Df(e,t){return t?e.filter(e=>e.pricingStatus===`free`):[...e]}function Of(e,t){return e&&Ef(t)}function kf(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t>=127&&t<=159||t===8232||t===8233})}function Af(e){let t=e.trim();return t?t.length>128?`models.displayNameTooLong`:t.includes(`/`)?`models.displayNameNoSlash`:kf(t)?`models.displayNameNoControl`:null:`models.displayNameRequired`}var jf=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Mf(e){return e===`shadow_call_target_invalid`?`models.shadowCallTargetInvalid`:e===`shadow_call_source_invalid`?`models.shadowCallSourceInvalid`:`models.shadowCallSaveFailed`}var Nf=Array.from({length:18},(e,t)=>1e5+t*5e4),Pf=new Set(Nf),Ff=[272e3,372e3,922e3],If=new Set(Ff),Lf=`custom`,Rf=[4,8,16,32,64,128,256,500,1e3],zf=new Set(Rf);function Bf(e,t){return t?Math.max(0,e-1):e}function Vf(e,t){return t?e+1:e}var Hf=`ocx-models-collapsed:v2`;function Uf(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 Wf(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Gf(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);Sf(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?He(a.namespaced,r):a.namespaced})}return i}function Kf(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 qf(e=localStorage){try{let t=e.getItem(Hf);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 Jf(e,t=localStorage){try{t.setItem(Hf,JSON.stringify([...e]))}catch{}}function Yf(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 Xf=`ocx.dash.controls.v1:`,Zf=`ocx.dash.overview.v1:`,Qf=`ocx.dash.usage30d.v1:`,$f=`ocx.dash.startup.v1:`,ep=`ocx.dash.maMode.v1:`;function tp(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 np(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 rp(e){return`${Xf}${e}`}function ip(e,t=0){let{locale:n,t:r}=a(),[i,o]=(0,X.useState)(Yn),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(new Set),d=(0,X.useMemo)(()=>kd(rp(e)),[e]),f=(0,X.useMemo)(()=>kd(`${Zf}${e}`),[e]),p=(0,X.useMemo)(()=>kd(`${Qf}${e}`),[e]),m=(0,X.useMemo)(()=>{let t=kd(`${$f}${e}`);return t===`error`?null:t},[e]),h=(0,X.useMemo)(()=>kd(`${ep}${e}`),[e]),[g,_]=(0,X.useState)(()=>f?.health??null),[v,y]=(0,X.useState)(()=>m),[b,x]=(0,X.useState)(()=>f?.providers??[]),[S,C]=(0,X.useState)([]),[w,T]=(0,X.useReducer)(tp,{settings:d?.settings??null,beforeSave:null}),{settings:E}=w,D=w.beforeSave!==null,[O,k]=(0,X.useState)(()=>d?.sidecar??null),[A,j]=(0,X.useState)(()=>d?.shadowCall??null),[M,N]=(0,X.useState)(()=>p),[P,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(),[R,z]=(0,X.useState)(!1),[B,V]=(0,X.useState)(null),[H,U]=(0,X.useState)(!1),[W,ee]=(0,X.useState)(!1),[te,ne]=(0,X.useState)(()=>h??`default`),[G,K]=(0,X.useState)(!1),[re,q]=(0,X.useState)(null),[ie,ae]=(0,X.useState)(null),[oe,se]=(0,X.useState)(null),[ce,le]=(0,X.useState)(null),ue=ie?.apiBase===e?ie.advisory:null,J=oe===e,de=ce?.apiBase===e?ce.mode:null,[fe,pe]=(0,X.useState)(!1),[me,he]=(0,X.useState)(!1),[ge,_e]=(0,X.useState)(!1),[ve,ye]=(0,X.useState)(``),[be,xe]=(0,X.useState)(``),[Se,Ce]=(0,X.useState)([]),[we,Te]=(0,X.useState)([]),[Ee,De]=(0,X.useState)(!1),[Oe,ke]=(0,X.useState)(!0),[Ae,je]=(0,X.useState)(!1),[Me,Ne]=(0,X.useState)(``),[Pe,Fe]=(0,X.useState)(``),[Ie,Le]=(0,X.useState)(!1),[Re,ze]=(0,X.useState)(null),[Be,Ve]=(0,X.useState)(null),[He,Ue]=(0,X.useState)([]),[We,Ge]=(0,X.useState)(!1),[Ke,qe]=(0,X.useState)(`latest`),[Je,Ye]=(0,X.useState)(!0),[Xe,Ze]=(0,X.useState)(!1),Qe=(0,X.useRef)(0),$e=(0,X.useRef)(null),et=(0,X.useRef)(0),tt=(0,X.useRef)(0),nt=(0,X.useRef)(0),rt=(0,X.useRef)(!1),it=(0,X.useRef)(0),at=(0,X.useRef)(0),ot=(0,X.useRef)(!1),[st,ct]=(0,X.useState)(null),[lt,ut]=(0,X.useState)(null),[dt,ft]=(0,X.useState)(null),[Y,pt]=(0,X.useState)(!1),[mt,ht]=(0,X.useState)(!1),gt=(0,X.useRef)(null),_t=(0,X.useRef)(null),vt=(0,X.useRef)(null),yt=(0,X.useRef)(null),bt=Ar(me,gt),xt=Ar(We,_t),St=Ar(fe,vt),Ct=Ar(ge,yt);(0,X.useEffect)(()=>{let e=()=>o(Yn());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,X.useEffect)(()=>()=>{et.current+=1,$e.current!==null&&(window.clearTimeout($e.current),$e.current=null)},[]);let wt=(0,X.useRef)(m),Tt=(0,X.useRef)(0),Et=(0,X.useRef)({settingsRequestEpochRef:tt,settingsMutationEpochRef:nt,settingsMutationInFlightRef:rt,shadowCallRequestEpochRef:it,shadowCallMutationEpochRef:at,shadowCallMutationInFlightRef:ot}).current,Dt=dn(`dashboard-startup-health:${e}`,[e,t],t=>sf(e,t),{pollMs:3e4}),Ot=tf(Dt.data),kt=Dt.refresh;(0,X.useEffect)(()=>{if(!Ot)return;let e=window.setTimeout(()=>{kt()},$d);return()=>window.clearTimeout(e)},[Ot,kt]);let At=dn(`dashboard-overview:${e}`,[e,t],t=>mf(e,t),{pollMs:5e3}),jt=Pd(At,e=>e.health===null,!0),Mt=g!==null||At.data!==void 0,Nt=dn(`dashboard-ma-mode:${e}`,[e,t],t=>pf(e,t),{pollMs:5e3}),Pt=dn(`dashboard-sidecars:${e}`,[e,t],async t=>{let n=Tt.current;return{...await df(e,t,Et),startupHealthGeneration:n}},{pollMs:5e3}),Ft=dn(`dashboard-settings:${e}`,[e,t],async t=>{let n=Tt.current;return{...await ff(e,t,Et),startupHealthGeneration:n}},{pollMs:5e3}),It=dn(`dashboard-multi-agent:${e}`,[e,t],t=>hf(e,t),{pollMs:5e3,enabled:Mt}),Lt=dn(Hr(e),[e,t],t=>uf(e,t),{enabled:Mt,pollMs:6e4,deadlineMs:6e4}),Rt=dn(`dashboard-diagnostics:${e}`,[e,t],t=>cf(e,t),{pollMs:rf,enabled:Mt}),zt=dn(`dashboard-models:${e}`,[e,mt,t],t=>lf(e,t),{enabled:Mt&&!mt});(0,X.useEffect)(()=>{if(Dt.data!==void 0){let t=Dt.data;Tt.current+=1,y(t.status),wt.current=t.status,t.status!==`error`&&!t.stale&&Nd(`${$f}${e}`,t.status)}},[Dt.data,e]),(0,X.useEffect)(()=>{let t=At.data;t&&(t.health&&(_(t.health),x(t.providers),Nd(`${Zf}${e}`,{health:t.health,providers:t.providers})),ht(t.error))},[At.data,e]),(0,X.useEffect)(()=>{Nt.data!==void 0&&(ne(Nt.data.maMode),ae({advisory:Nt.data.advisory??null,apiBase:e}),Nd(`${ep}${e}`,Nt.data.maMode))},[Nt.data,e]);let Bt=Nt.data!==void 0||h!==null;(0,X.useEffect)(()=>{let e=It.data;e&&(e.injection&&(ke(e.injection.multiAgentGuidanceEnabled),je(e.injection.syncCodexSubagentDefaults),ye(e.injection.injectionModel),xe(e.injection.injectionEffort),Ce(e.injection.injectionEfforts),Te(e.injection.injectionAvailable)),e.effortCaps&&(Ne(e.effortCaps.effortCap),Fe(e.effortCaps.subagentEffortCap)))},[It.data]),(0,X.useEffect)(()=>{let t=Pt.data;if(!t)return;k(t.sidecar),t.shadowCall!==void 0&&j(t.shadowCall);let n=kd(rp(e))??{};Nd(rp(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[Pt.data,e]),(0,X.useEffect)(()=>{let t=Ft.data;if(t&&(t.settings!==void 0&&T({type:`polled`,settings:t.settings}),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===Tt.current)){let n=nf(wt.current,t.startupHealthSeed);y(n),wt.current=n,n&&Nd(`${$f}${e}`,n)}},[Ft.data,e]),(0,X.useEffect)(()=>{if(!E)return;let t=kd(rp(e))??{};Nd(rp(e),{...t,settings:E})},[E,e]),(0,X.useEffect)(()=>{Lt.data!==void 0&&(N(Lt.data),Nd(`${Qf}${e}`,Lt.data))},[Lt.data,e]),(0,X.useEffect)(()=>{Rt.data&&Ue(Rt.data)},[Rt.data]),(0,X.useEffect)(()=>{zt.data&&C(zt.data),U(zt.loading)},[zt.data,zt.loading]),(0,X.useEffect)(()=>()=>{tt.current+=1,it.current+=1},[]);let Vt=dn(dt?.id&&dt.restart?`update-job:${e}:${dt.id}`:`update-job:idle:${e}`,[e,dt?.id,dt?.restart,dt?.latestVersion],async t=>{if(!dt?.id||!dt.restart)return{reconnecting:!1};let n=dt.latestVersion;try{let r=await Qn(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(dt.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Qn(await fetch(`${e}/healthz`,{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:!!(dt?.id&&dt.restart),pauseWhenHidden:!1});(0,X.useEffect)(()=>{let e=Vt.data;e&&(`job`in e&&e.job&&ft(e.job),pt(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[Vt.data]);let Ht=(0,X.useMemo)(()=>np(S),[S]),Ut=(0,X.useMemo)(()=>{let e=s.trim().toLowerCase();if(!e)return Ht;let t=[];for(let[n,r]of Ht){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Ht,s]),Wt=(0,X.useMemo)(()=>{let e=O?.webSearch?.backend;return xr(O?.webSearchModels,S,O?.webSearch?.model,e===`routed`?void 0:e)},[S,O?.webSearchModels,O?.webSearch]),Gt=(0,X.useMemo)(()=>Sr(O?.visionModels,S,O?.vision?.model,O?.vision?.backend),[O?.visionModels,S,O?.vision]),Kt=async t=>{if(!O||P)return;t=Tr(O,t);let n=O,r={webSearch:rr(O.webSearch,t.webSearch),vision:rr(O.vision,t.vision),...O.visionModels?{visionModels:O.visionModels}:{},...O.webSearchModels?{webSearchModels:O.webSearchModels}:{}};F(!0),k(r);try{let n=await Qn(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);L(e=>cr(e,n.codexWebSearch)),k({webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=kd(rp(e))??{};Nd(rp(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}}})}catch{k(n)}finally{F(!1)}};async function qt(t){if(!A||R)return;let n=A,i={...A,...t};z(!0),V(null),ot.current=!0,j(i);try{let i=await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!i.ok){j(n);let e=await i.json().catch(()=>null);V(r(Mf(e?.code)));return}at.current+=1}catch{j(n),V(r(`models.networkError`))}finally{ot.current=!1,z(!1)}}let Jt=async(t,n=!1)=>{K(!0),q(null);try{let i={multiAgentMode:t};n&&(i.multiAgentSurfaceAdvisoryAcknowledged=!0);let a=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(a.ok)ne(t),n&&se(e),Nd(`${ep}${e}`,t);else{let e=r(`dash.maSwitchFailed`,{status:String(a.status)});try{let t=await a.json();e=typeof t.error==`string`&&t.error||typeof t.message==`string`&&t.message||e}catch{}q(e)}}catch(e){q(e instanceof Error?e.message:r(`dash.maNetworkError`))}finally{K(!1)}},Yt=async t=>{G||te===t||(t===`v1`?await Jt(`v1`):le({mode:t,apiBase:e}))},Xt=async()=>{se(e);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentSurfaceAdvisoryAcknowledged:!0})});t.ok||q(r(`dash.maSwitchFailed`,{status:String(t.status)}))}catch(e){q(e instanceof Error?e.message:r(`dash.maNetworkError`))}},Zt=async()=>{let e=de;le(null),e?await Jt(e,!0):await Xt()},Qt=async()=>{le(null),te===`v1`?await Xt():await Jt(`v1`,!0)},$t=()=>{de?le(null):se(e)},en=!de&&!J&&ue?.required===!0,tn=async t=>{if(!Ee){De(!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 Qn(await fetch(`${e}/api/injection-model`)),r=af(n);ke(r.multiAgentGuidanceEnabled),je(r.syncCodexSubagentDefaults),ye(r.injectionModel),xe(r.injectionEffort),Array.isArray(n.efforts)&&Ce(n.efforts),Array.isArray(n.available)&&Te(n.available)}catch{}finally{De(!1)}}},nn=async t=>{if(!E||D||W)return;let n=!(E[t]??t===`codexAutoStart`);rt.current=!0,T({type:`save-started`,key:t,value:n});try{let r=await Qn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({[t]:n})}),`save failed`);nt.current+=1,T({type:`save-succeeded`,key:t,settings:r}),(t===`codexDesktopAuthless`||t===`codexClientCompaction`)&&await cn()}catch{T({type:`save-failed`}),ht(!0)}finally{rt.current=!1,T({type:`save-finished`})}},rn=()=>nn(`codexAutoStart`),an=()=>nn(`codexDesktopAuthless`),on=()=>nn(`codexClientCompaction`),sn=(0,X.useCallback)(()=>{ze(null),Ve(null)},[]),cn=async()=>{if(!W){ee(!0),ze(null),Ve(null);try{let t=await Qn(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);ze(t),t.ok&&t.status===`applied`&&(T({type:`applied`}),L(void 0)),t.projectConfigGrouped&&Ue(t.projectConfigGrouped)}catch(e){Ve(e instanceof Error?e.message:String(e))}finally{ee(!1)}}},ln=async(t,n=!1)=>{n&&(Qe.current=0),$e.current!==null&&(window.clearTimeout($e.current),$e.current=null);let r=++et.current;Ze(!0),ut(null),ct(null);try{let n=await Qn(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==et.current)return;if(ct(n),n.reason===`latest_unavailable`&&Qe.current<2){let e=++Qe.current;$e.current=window.setTimeout(()=>{r===et.current&&($e.current=null,ln(t))},800*e);return}n.reason!==`latest_unavailable`&&(Qe.current=0),Ze(!1)}catch(e){if(r!==et.current)return;ut(e instanceof Error?e.message:String(e)),Ze(!1)}},un=()=>{et.current+=1,$e.current!==null&&(window.clearTimeout($e.current),$e.current=null),Ze(!1),Ge(!1)},fn=()=>{if(Wd())return;let e=er(g?.version);qe(e),Ye(!0),Ge(!0),ln(e,!0)},pn=e=>{qe(e),ln(e,!0)},mn=(0,X.useRef)(fn);return(0,X.useEffect)(()=>{mn.current=fn}),(0,X.useEffect)(()=>{let e=()=>{Xn()&&(gn(`dashboard`),mn.current())},t=Xn()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:n,t:r,selectedSection:i,setSelectedSection:o,modelQuery:s,setModelQuery:c,expandedProviders:l,setExpandedProviders:u,health:g,startupHealth:v,providers:b,models:S,settings:E,sidecar:O,shadowCall:A,usage30d:M,usageLoading:Lt.loading&&!M,healthLoading:At.loading&&!g,sidecarSaving:P,shadowCallSaving:R,shadowCallError:B,modelsLoading:H,settingsSaving:D,syncing:W,maMode:te,maModeResolved:Bt,maBusy:G,setMaHelpOpen:pe,maHelpOpen:fe,maError:re,maAdvisory:ue,maAdvisoryOpen:en,pendingMaMode:de,keepMaMode:Zt,chooseMaV1:Qt,dismissMaSurfaceDialog:$t,effortCapHelpOpen:me,setEffortCapHelpOpen:he,shadowCallHelpOpen:ge,setShadowCallHelpOpen:_e,injectionModel:ve,injectionEffort:be,injectionEfforts:Se,injectionAvailable:we,injectionSaving:Ee,multiAgentGuidanceEnabled:Oe,syncCodexSubagentDefaults:Ae,saveInjection:tn,effortCap:Me,subagentEffortCap:Pe,effortCapSaving:Ie,setEffortCap:Ne,setSubagentEffortCap:Fe,setEffortCapSaving:Le,syncResult:Re,syncError:Be,projectConfigWarnings:He,updateOpen:We,updateChannel:Ke,setUpdateRestart:Ye,updateRestart:Je,updateLoading:Xe,updateCheck:st,updateError:lt,updateJob:dt,reconnecting:Y,error:mt||jt.showError,connectionFailure:At.data?.failure??(jt.showError?`unavailable`:void 0),refreshDashboard:At.refresh,effortCapHelpTriggerRef:gt,updateTriggerRef:_t,maHelpTriggerRef:vt,shadowCallHelpTriggerRef:yt,effortCapHelpDialogRef:bt,updateDialogRef:xt,maHelpDialogRef:St,shadowCallHelpDialogRef:Ct,filteredGroups:Ut,sidecarModels:Wt,visionModels:Gt,sidecarCodexApply:I,saveSidecar:Kt,saveShadowCall:qt,switchMaMode:Yt,toggleCodexAutoStart:rn,toggleCodexDesktopAuthless:an,toggleCodexClientCompaction:on,runSync:cn,clearSyncFeedback:sn,fetchUpdateCheck:ln,closeUpdateDialog:un,openUpdateDialog:fn,changeUpdateChannel:pn,runUpdate:async()=>{if(st?.canUpdate){ut(null);try{let t=await Qn(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Ke,restart:Je})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);ft(t.job),pt(!1),un()}catch(e){ut(e instanceof Error?e.message:String(e))}}}}}function ap(e){_n(Zn(e))}function op({apiBase:e,readOnly:t=!1,connected:n=!1,authenticationPending:r=!1,refreshEpoch:i=0}){let a=ip(e,i),{t:o,error:s,selectedSection:c,providers:l,models:u,modelsLoading:d,modelQuery:f,setModelQuery:p,filteredGroups:m,expandedProviders:h,setExpandedProviders:g}=a;if(r)return null;let _=a.connectionFailure===`auth`||a.connectionFailure===`denied`;if(s&&(_||!a.health))return(0,Z.jsxs)(Nn,{style:{marginTop:40},icon:(0,Z.jsx)(at,{}),title:(0,Z.jsx)(`span`,{style:{color:`var(--red)`},children:o(a.connectionFailure===`denied`?`dash.permissionDenied`:a.connectionFailure===`auth`?`dash.authRequired`:`dash.dataUnavailable`)}),children:[!n&&a.connectionFailure===`unavailable`&&(0,Z.jsx)(N,{k:`dash.runStart`,cmd:`ocx start`}),(0,Z.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>a.refreshDashboard(),children:o(`common.retry`)})]});let v=(0,Z.jsx)(Ed,{...a,readOnly:t}),y=(0,Z.jsx)(Dd,{t:o,providers:l}),b=(0,Z.jsx)(Ir,{t:o,models:u,modelsLoading:d,modelQuery:f,setModelQuery:p,filteredGroups:m,expandedProviders:h,setExpandedProviders:g}),x=(0,Z.jsx)(Fr,{...a}),S=[{id:`overview`,label:o(`dash.workspace.overview`),body:v},{id:`providers`,label:o(`dash.activeProviders`),body:y},{id:`models`,label:o(`dash.availableModels`),body:b}],C=S.find(e=>e.id===c)??S[0],w=ap,T=e=>{let t=S.findIndex(e=>e.id===c),n=-1;if(e.key===`ArrowRight`?n=(t+1)%S.length:e.key===`ArrowLeft`?n=(t-1+S.length)%S.length:e.key===`Home`?n=0:e.key===`End`&&(n=S.length-1),n<0)return;e.preventDefault();let r=S[n];w(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,Z.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[s&&(0,Z.jsxs)(Q,{tone:`warn`,children:[o(`dash.staleData`),` `,(0,Z.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>a.refreshDashboard(),children:o(`common.retry`)})]}),(0,Z.jsxs)(`header`,{className:`mb-5 flex flex-col gap-1.5`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:o(`shellV2.pageProxyDetails`)}),(0,Z.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[14px] leading-[1.55] text-fg-muted`,children:o(c===`overview`?`proxyV2.pageLede`:`dash.subtitle`)})]}),(0,Z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":o(`dash.workspace.sections`),children:S.map(e=>(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":c===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:c===e.id?0:-1,className:`page-tab${c===e.id?` page-tab--active`:``}`,onClick:()=>w(e.id),onKeyDown:T,children:e.label},e.id))}),(0,Z.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${C.id}`,"aria-labelledby":`dashboard-tab-${C.id}`,tabIndex:0,children:C.body}),x]})}var sp={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`},cp={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`},lp=(0,X.forwardRef)(function({variant:e=`outline`,size:t=`md`,className:n,type:r=`button`,...i},a){return(0,Z.jsx)(`button`,{ref:a,type:r,className:Y(`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`,sp[e],cp[t],n),...i})}),up=Object.freeze([`completed`,`failed`,`incomplete`,`aborted`]);Object.freeze(up.filter(e=>e!==`aborted`)),Object.freeze([`terminal`,`client_cancel`,`non_stream`,`body_stall`,`body_overflow`]);function dp(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 fp(e,t){return e.filter(e=>e.timestamp>=t&&dp(e)===`failed`)}var pp=864e5;async function mp(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function hp({apiBase:e,navigate:t,onReloadCodex:n,reloadingCodex:r}){let i=c(),a=p(),o=new Intl.NumberFormat(a),s=new Intl.NumberFormat(a,{notation:`compact`,maximumFractionDigits:1}),l=dn(`home-health:${e}`,[e],t=>mp(`${e}/healthz`,t),{pollMs:3e4}),u=dn(`home-usage:${e}`,[e],t=>mp(`${e}/api/usage?range=7d`,t),{pollMs:6e4}),d=dn(`home-config:${e}`,[e],t=>mp(`${e}/api/config`,t)),f=dn(`home-startup:${e}`,[e],t=>mp(`${e}/api/startup-health`,t)),m=dn(`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 fp(r.logs,Date.now()-pp)},{pollMs:3e4}),h=m.error==null&&m.data!==void 0,g=h?m.data??[]:[],_=l.data!=null,v=Object.keys(d.data?.providers??{}).length,y=u.data?.summary?.requests??0,b=u.data?.summary?.totalTokens??0,x=l.data?.uptime??0,S=[{key:`provider`,done:v>0,title:i(`shellV2.stepProvider`),hint:i(`shellV2.stepProviderHint`),go:()=>t(`providers`)},{key:`request`,done:y>0,title:i(`shellV2.stepFirstRequest`),hint:i(`shellV2.stepFirstRequestHint`),go:()=>t(`integrations`)},{key:`autostart`,done:!!(f.data&&(f.data.protection!==`none`||f.data.serviceInstalled||f.data.shimInstalled)),title:i(`shellV2.stepAutostart`),hint:i(`shellV2.stepAutostartHint`),go:()=>t(`startup`)}],C=S.filter(e=>e.done).length,w=C===S.length,T=_?h?g.length>0?i(`shellV2.homeErrorsToday`,{count:o.format(g.length)}):i(`shellV2.homeOk`):i(`shellV2.homeErrorsUnavailable`):i(`shellV2.homeDown`);return(0,Z.jsxs)(`div`,{className:`ui-v2 flex flex-col gap-6 font-sans text-fg`,children:[(0,Z.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,Z.jsx)(`span`,{className:`relative inline-flex size-3 shrink-0`,"aria-hidden":!0,children:(0,Z.jsx)(`span`,{className:Y(`relative size-3 rounded-full`,_?!h||g.length?`bg-warning`:`bg-success`:`bg-danger`)})}),(0,Z.jsx)(`h1`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-balance`,children:T})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(lp,{variant:`outline`,onClick:n,disabled:r,children:[(0,Z.jsx)(`span`,{className:Y(`inline-flex`,r&&`animate-spin`),children:(0,Z.jsx)(Mt,{})}),i(r?`dash.codexRestarting`:`dash.codexRestart`)]}),(0,Z.jsx)(lp,{variant:`primary`,onClick:()=>t(`logs`),children:i(`shellV2.openLogs`)})]})]}),(0,Z.jsxs)(`section`,{className:`grid grid-cols-2 gap-3 md:grid-cols-4`,children:[(0,Z.jsx)(gp,{label:i(`shellV2.tileVersion`),value:l.data?.version?`v${l.data.version}`:`—`}),(0,Z.jsx)(gp,{label:i(`shellV2.tileUptime`),value:_?i(`shellV2.uptimeValue`,{h:String(Math.floor(x/3600)),m:String(Math.floor(x%3600/60))}):`—`}),(0,Z.jsx)(gp,{label:i(`shellV2.tileRequests`),value:o.format(y)}),(0,Z.jsx)(gp,{label:i(`shellV2.tileTokens`),value:s.format(b)})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-col gap-4 rounded-card bg-surface p-5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-[15px] font-semibold`,children:i(`shellV2.checklistTitle`)}),(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:i(`shellV2.checklistProgress`,{done:String(C),total:String(S.length)})})]}),(0,Z.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-surface-2`,"aria-hidden":!0,children:(0,Z.jsx)(`div`,{className:`h-full origin-left rounded-full bg-accent transition-transform duration-[600ms] ease-soft`,style:{transform:`scaleX(${C/S.length})`}})}),w?(0,Z.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:i(`shellV2.checklistAllDone`)}):(0,Z.jsx)(`ol`,{className:`m-0 flex list-none flex-col gap-1 p-0`,children:S.map((e,t)=>{let n=!e.done&&S.findIndex(e=>!e.done)===t;return(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`button`,{type:`button`,onClick:e.go,className:Y(`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,Z.jsx)(`span`,{className:Y(`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,Z.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,Z.jsx)(`span`,{className:Y(`text-[14px] font-medium`,e.done&&`text-fg-subtle line-through`),children:e.title}),!e.done&&(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted`,children:e.hint})]}),!e.done&&(0,Z.jsxs)(`span`,{className:`text-[13px] font-medium text-highlight opacity-0 transition-opacity group-hover:opacity-100`,children:[i(`shellV2.stepOpen`),` →`]})]})},e.key)})})]}),(0,Z.jsxs)(`section`,{className:`flex flex-col gap-3 rounded-card bg-surface p-5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-[15px] font-semibold`,children:i(`shellV2.recentErrors`)}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`logs`),className:`cursor-pointer text-[13px] font-medium text-highlight hover:underline`,children:i(`shellV2.viewAll`)})]}),h?g.length===0?(0,Z.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:i(`shellV2.noErrors`)}):(0,Z.jsx)(`ul`,{className:`m-0 flex list-none flex-col gap-1 p-0`,children:g.slice(0,4).map(e=>(0,Z.jsxs)(`li`,{className:`flex items-baseline gap-2.5 rounded-control px-1 py-1.5 text-[13px]`,children:[(0,Z.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,Z.jsx)(`span`,{className:`rounded-full bg-warning-soft px-1.5 text-[11px] font-semibold text-warning tabular-nums`,children:e.status}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1 truncate`,children:[e.provider,` · `,e.model]})]},`${e.timestamp}:${e.model}`))}):(0,Z.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:i(`shellV2.homeErrorsUnavailable`)}),(0,Z.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,Z.jsxs)(`span`,{children:[i(`shellV2.tileProviders`),` `,(0,Z.jsx)(`b`,{className:`font-semibold text-fg tabular-nums`,children:o.format(v)})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`dashboard`,`update`),className:`cursor-pointer font-medium text-highlight hover:underline`,children:i(`shellV2.checkUpdate`)})]})]})]})]})}function gp({label:e,value:t}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1 rounded-card bg-surface px-4 py-3.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium text-fg-subtle`,children:e}),(0,Z.jsx)(`span`,{className:`truncate text-stat font-semibold tracking-[-0.02em] tabular-nums`,children:t})]})}var _p={done:`bg-success-soft text-success`,todo:`bg-highlight-soft text-highlight`,optional:`bg-surface-2 text-fg-muted`};function vp({title:e,term:t,body:n,badge:r,icon:i,onOpen:a,openLabel:o}){return(0,Z.jsxs)(`button`,{type:`button`,onClick:a,"aria-label":`${e} — ${o}`,className:Y(`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,Z.jsxs)(`span`,{className:`flex items-start justify-between gap-3`,children:[i&&(0,Z.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,Z.jsx)(`span`,{className:Y(`ml-auto rounded-full px-2 py-0.5 text-[11px] font-semibold`,_p[r.tone]),children:r.label})]}),(0,Z.jsxs)(`span`,{className:`flex flex-col gap-1`,children:[(0,Z.jsx)(`span`,{className:`text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:e}),t&&(0,Z.jsx)(`span`,{className:`font-mono text-[11px] text-fg-subtle`,children:t})]}),(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:n}),(0,Z.jsxs)(`span`,{className:`mt-auto inline-flex items-center gap-1 pt-1 text-[13px] font-medium text-highlight`,children:[o,(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`transition-transform duration-300 ease-soft group-hover:translate-x-0.5`,children:`→`})]})]})}var yp=Y(`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`),bp=`flex min-w-0 flex-col overflow-hidden rounded-[12px] bg-raised ring-1 ring-inset ring-line`,xp=`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`;async function Sp(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Cp({apiBase:e,navigate:t}){let n=c(),r=dn(`home-config:${e}`,[e],t=>Sp(`${e}/api/config`,t)),i=dn(`setup-usage:${e}`,[e],t=>Sp(`${e}/api/usage?range=all`,t)),a=dn(`home-startup:${e}`,[e],t=>Sp(`${e}/api/startup-health`,t)),o={label:n(`shellV2.badgeOptional`),tone:`optional`},s=r.data?Object.keys(r.data.providers??{}).length>0:void 0,l=i.data?(i.data.summary?.requests??0)>0:void 0,u=a.data?a.data.protection!==`none`||!!(a.data.serviceInstalled||a.data.shimInstalled):void 0,d=[{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:l,open:()=>t(`integrations`)},{key:`request`,title:n(`shellV2.stepFirstRequest`),hint:n(`shellV2.stepFirstRequestHint`),done:l,open:()=>t(`providers`)},{key:`autostart`,title:n(`shellV2.stepAutostart`),hint:n(`shellV2.stepAutostartHint`),done:u,open:()=>t(`startup`)}],f=d.filter(e=>e.done===!0).length,p=f===d.length,m=d.findIndex(e=>e.done===!1),h=n(`shellV2.stepOpen`);return(0,Z.jsxs)(`div`,{className:`ui-v2 flex flex-col gap-8 font-sans text-fg`,children:[(0,Z.jsxs)(`header`,{className:`flex max-w-[640px] flex-col gap-2`,children:[(0,Z.jsx)(`h1`,{className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:n(`shellV2.setupTitle`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[15px] text-fg-muted`,children:n(`shellV2.setupIntro`)})]}),(0,Z.jsxs)(`section`,{"aria-labelledby":`setup-essentials`,className:`flex max-w-[760px] flex-col gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,Z.jsx)(`h2`,{id:`setup-essentials`,className:xp,children:n(`connectV2.setupEssentials`)}),(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:n(`shellV2.checklistProgress`,{done:String(f),total:String(d.length)})})]}),(0,Z.jsx)(`div`,{className:`h-1 overflow-hidden rounded-full bg-surface-2`,role:`progressbar`,"aria-labelledby":`setup-essentials`,"aria-valuemin":0,"aria-valuemax":d.length,"aria-valuenow":f,children:(0,Z.jsx)(`div`,{className:`h-full origin-left rounded-full bg-accent transition-transform duration-[600ms] ease-soft`,style:{transform:`scaleX(${f/d.length})`}})}),p&&(0,Z.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:n(`shellV2.checklistAllDone`)}),(0,Z.jsx)(`ol`,{className:Y(bp,`m-0 mt-1 list-none divide-y divide-line p-0`),children:d.map((e,t)=>(0,Z.jsx)(wp,{step:e,index:t,current:t===m,openLabel:h,doneLabel:n(`shellV2.badgeDone`),todoLabel:n(`shellV2.badgeTodo`)},e.key))})]}),(0,Z.jsxs)(`section`,{"aria-labelledby":`setup-optional`,className:`flex flex-col gap-3`,children:[(0,Z.jsx)(`h2`,{id:`setup-optional`,className:xp,children:n(`connectV2.setupOptional`)}),(0,Z.jsxs)(`div`,{className:`grid max-w-[760px] gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)(vp,{icon:(0,Z.jsx)(Et,{}),title:n(`shellV2.setupApiKeys`),body:n(`shellV2.setupApiKeysHint`),badge:o,onOpen:()=>t(`integrations`,`keys`),openLabel:h}),(0,Z.jsx)(vp,{icon:(0,Z.jsx)(ne,{}),title:n(`shellV2.setupRemote`),body:n(`shellV2.setupRemoteHint`),badge:o,onOpen:()=>t(`remote`),openLabel:h})]})]})]})}function wp({step:e,index:t,current:n,openLabel:r,doneLabel:i,todoLabel:a}){let o=e.done===!0;return(0,Z.jsxs)(`li`,{className:Y(`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3.5`,n&&`bg-surface`),children:[(0,Z.jsx)(`span`,{className:Y(`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,Z.jsx)(ut,{strokeWidth:2.5}):t+1}),(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-1 basis-[16rem] flex-col gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:Y(`text-[14px] leading-5 font-medium`,o&&`text-fg-muted`),children:e.title}),e.done!==void 0&&(0,Z.jsx)(`span`,{className:Y(`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,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:e.hint})]}),(0,Z.jsx)(lp,{size:`sm`,variant:n?`primary`:`outline`,onClick:e.open,"aria-label":`${e.title} — ${r}`,className:`max-sm:ml-11`,children:r})]})}var Tp=[{id:`subagents`,title:`shellV2.advSubagents`,when:`shellV2.advSubagentsWhen`,term:{name:`Subagents`},Icon:yt,page:`subagents`,finds:[`dash.injectionLabel`,`dash.multiAgent`],words:[`delegation`,`agents`]},{id:`advisor`,title:`shellV2.advAdvisor`,when:`shellV2.advAdvisorWhen`,term:{name:`Advisor`},Icon:Ve,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:vt,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`],words:[`web search`,`vision`,`shadow`,`fallback`,`reasoning`,`update`,`sync`]},{id:`routing`,title:`shellV2.advRouting`,when:`shellV2.advRoutingWhen`,term:{key:`proxyV2.advTermRouting`},Icon:Le,page:`models`,subPath:`routing`},{id:`prompt`,title:`shellV2.advPrompt`,when:`shellV2.advPromptWhen`,term:{key:`proxyV2.advTermPrompt`},Icon:ve,page:`codex-set`,subPath:`prompt`},{id:`claude`,title:`shellV2.advClaude`,when:`shellV2.advClaudeWhen`,term:{name:`Claude Code`},Icon:Qe,page:`claude`,subPath:`code`},{id:`providers`,title:`shellV2.advProviders`,when:`shellV2.advProvidersWhen`,term:{key:`proxyV2.advTermProviders`},Icon:fe,page:`providers`},{id:`storage`,title:`shellV2.advStorage`,when:`shellV2.advStorageWhen`,term:{key:`proxyV2.advTermStorage`},Icon:Ot,page:`storage`},{id:`diagnostics`,title:`shellV2.advDiagnostics`,when:`shellV2.advDiagnosticsWhen`,term:{key:`logs.tabDebug`},Icon:se,page:`logs`,subPath:`debug`},{id:`desktop`,title:`shellV2.advDesktopCompat`,when:`shellV2.advDesktopCompatWhen`,term:{key:`proxyV2.advTermDesktop`},Icon:et,page:`codex-set`,subPath:`desktop`}];function Ep(e){return`name`in e.term?e.term.name:v[e.term.key]}function Dp({navigate:e}){let t=c(),[n,r]=(0,X.useState)(``),i=e=>`name`in e.term?e.term.name:t(e.term.key),a=(0,X.useDeferredValue)(n.trim().toLowerCase()),o=Tp.filter(e=>!a||[t(e.title),t(e.when),i(e),Ep(e),...(e.finds??[]).map(e=>t(e)),...e.words??[]].some(e=>e.toLowerCase().includes(a)));return(0,Z.jsxs)(`div`,{className:`ui-v2 flex flex-col gap-6 font-sans text-fg`,children:[(0,Z.jsxs)(`header`,{className:`flex flex-wrap items-end justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex max-w-[640px] flex-col gap-2`,children:[(0,Z.jsx)(`h1`,{className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:t(`shellV2.pageAllSettings`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[15px] text-fg-muted`,children:t(`shellV2.advancedIntro`)})]}),(0,Z.jsxs)(`label`,{className:`relative flex w-full items-center sm:w-72`,children:[(0,Z.jsx)(`span`,{className:`pointer-events-none absolute left-3 text-fg-subtle [&_svg]:size-4`,children:(0,Z.jsx)(ze,{"aria-hidden":!0})}),(0,Z.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,Z.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,Z.jsx)(`p`,{className:`m-0 rounded-card bg-surface p-6 text-center text-[14px] text-fg-muted`,children:t(`shellV2.advancedEmpty`)}):(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 xl:grid-cols-3`,children:o.map(n=>(0,Z.jsx)(vp,{icon:(0,Z.jsx)(n.Icon,{"aria-hidden":!0}),title:t(n.title),term:i(n),body:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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 Op(e){let t=Object.create(null);for(let n of e)t[n.provider]={requests:n.requests,totalTokens:n.totalTokens};return t}function kp(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 Ap(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 jp={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function Mp(e,t,n){let r=typeof t==`object`&&t?t:jp,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 Np(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 Pp(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 Fp(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function Ip(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 Lp(e,t=`en`){return Ip(e,t)}function Rp(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function zp(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:e===`Total subscription credits`?4.5:5}var Bp=`Total subscription credits`;function Vp(e){return e.trim().toLowerCase()===Bp.toLowerCase()?Bp:e}function Hp(e,t){if(e===void 0||!t)return!1;let n=Vp(e);for(let e of t)if(Vp(e)===n)return!0;return!1}function Up(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 Wp(e,t,n){let r=Tt(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=Vp(e.label),r=Up(t,n);i.push({rank:zp(t),row:{id:JSON.stringify([e.modelId??null,e.label,e.resetAt??null]),customLabel:t,label:r,limitLabel:r,percent:e.percent,resetAt:e.resetAt}})}if(r.creditsUsd&&typeof r.creditsUsd.percent==`number`&&!r.customWindows?.some(e=>e.modelId===void 0&&Vp(e.label)===Bp)){let e=Up(Bp,n);i.push({rank:zp(Bp),row:{customLabel:Bp,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 Gp(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&&Vp(e.label)===Bp)&&typeof e.creditsUsd?.percent==`number`&&t.push(e.creditsUsd.percent),t.length?Math.max(...t):-1}function Kp(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 qp(e){return e>=99.5}function Jp(e,t){return t>0&&e>=t}function Yp(e,t){return Jp(e,t)||qp(e)?`bar-warn`:`bar-green`}function Xp(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Zp(e){return{"--bar-scale":String(Xp(e)/100)}}function Qp(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 $p({quota:e,plan:t,threshold:n,t:r,className:i,layout:o=`compact`,pending:s=!1,incompleteWindowKeys:c,incompleteCustomWindowLabels:l,observedAt:u,afterWeekly:d}){let{locale:f}=a(),p=Wp(e,t,r),m=u===void 0?null:Qp(u,r),h=m===null?null:(0,Z.jsx)(`p`,{className:`quota-observed muted`,title:r(`quota.observedHint`),children:r(`quota.observedAgo`).replace(`{age}`,m)});return p.length===0?s?o===`stacked`?(0,Z.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,Z.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,Z.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,Z.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,Z.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,Z.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,Z.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,Z.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,Z.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):o===`compact`&&d?(0,Z.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:d}):null:o===`stacked`?(0,Z.jsxs)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:[h,p.map(e=>(0,Z.jsx)(tm,{row:e,threshold:n,t:r,locale:f,incomplete:e.windowKey?c?.has(e.windowKey)===!0:Hp(e.customLabel,l)},e.id))]}):(0,Z.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:[h,p.map(e=>(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsx)(em,{credits:e.customLabel===Bp,label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:f}),e.windowKey===`weekly`&&d]},e.id)),!p.some(e=>e.windowKey===`weekly`)&&d]})}function em({credits:e,label:t,percent:n,resetAt:r,threshold:i,t:a,locale:o}){let s=qp(n),c=Jp(n,i),l=Yp(n,i),u=rm(r,a,o),d=u.day||u.time?`${a(`codexAuth.resets`)} ${u.day} ${u.time}`.replace(/\s+/g,` `).trim():void 0,f=u.day!==``||u.time!==``;return(0,Z.jsxs)(`div`,{className:`quota-row${e?` quota-row--credits`:``}${c?` quota-row--warn`:``}${s?` quota-row--exhausted`:``}`,children:[(0,Z.jsx)(`span`,{className:`quota-label`,title:d,children:t}),(0,Z.jsx)(`span`,{className:`quota-reset-label`,children:f?a(`codexAuth.resets`):``}),(0,Z.jsx)(`span`,{className:`quota-reset-day`,children:u.day}),(0,Z.jsx)(`span`,{className:`quota-reset-time`,children:u.time}),(0,Z.jsx)(`div`,{className:`bar`,title:d,children:(0,Z.jsx)(`div`,{className:`bar-fill ${l}`,style:Zp(n)})}),(0,Z.jsxs)(`span`,{className:`quota-val${c?` quota-val--warn`:``}`,title:s?a(`quota.limitReached`):d,"aria-label":d,children:[c&&(0,Z.jsx)(at,{width:12,height:12,"aria-hidden":`true`}),Math.round(n),`%`,s?` · ${a(`quota.limitReached`)}`:``]})]})}function tm({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=qp(e.percent),o=Jp(e.percent,t),s=Yp(e.percent,t),c=im(e.resetAt,n,r);return(0,Z.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,Z.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Z.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,Z.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,Z.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`)})]}),(0,Z.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,Z.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Z.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,Z.jsx)(`div`,{className:`bar-fill ${s}`,style:Zp(e.percent)})}),(0,Z.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,Z.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,Z.jsx)(at,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function nm(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 rm(e,t,n){let r=nm(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=Kp(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 im(e,t,n=`en`,r=Date.now()){let i=nm(e);if(!i)return``;let{date:a,ms:o}=i,s=Kp(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 am({credits:e,updatedAt:t}){let{t:n,locale:r}=a(),i=e=>new Intl.NumberFormat(r,{maximumFractionDigits:2}).format(e),o=e=>n(`quota.workbuddy.amount`,{amount:i(e)}),s=e.total>0?Math.min(100,e.used/e.total*100):0;return(0,Z.jsxs)(`div`,{"data-workbuddy-credits":!0,children:[(0,Z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Z.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,Z.jsx)(`strong`,{children:o(e.remaining)})]}),(0,Z.jsx)($p,{quota:{updatedAt:t,customWindows:[{label:n(`quota.totalSubscriptionCredits`),percent:s}]},threshold:80,t:n,layout:`stacked`}),(0,Z.jsxs)(`div`,{className:`pws-capacity-details`,children:[(0,Z.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Z.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,Z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Z.jsx)(`span`,{children:n(`quota.workbuddy.${e.kind}`)}),(0,Z.jsxs)(`strong`,{children:[o(e.remaining),` / `,i(e.total)]})]},e.kind)),e.frozen>0&&(0,Z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Z.jsx)(`span`,{children:n(`quota.workbuddy.frozen`)}),(0,Z.jsx)(`strong`,{children:o(e.frozen)})]}),e.expiring&&(0,Z.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 om(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 sm(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function cm({report:e,pending:t}){let n=c(),{locale:r}=a(),i=te(e),o=ct(e),s=ce(e),l=o?.creditsUsd,u=i?.presentation===`aggregate`,d=new Set,f=new Set;if(u&&i){i.fiveHour?.incomplete&&d.add(`fiveHour`),i.weekly?.incomplete&&d.add(`weekly`),i.monthly?.incomplete&&d.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&f.add(e.label)}let p=u&&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}))]:[],m=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),h=e=>{let t=sm(e);return t===null?null:new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(t)},g=om(r),_=e=>new Intl.NumberFormat(g,{style:`currency`,currency:`USD`}).format(e),v=l?.expiresAt===void 0?null:(e=>{let t=sm(e);return t===null?null:new Intl.DateTimeFormat(g,{dateStyle:`medium`}).format(t)})(l.expiresAt);return(0,Z.jsxs)(Z.Fragment,{children:[o?.workbuddyCredits&&(0,Z.jsx)(am,{credits:o.workbuddyCredits,updatedAt:o.updatedAt}),u&&(0,Z.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(o||t)&&(0,Z.jsx)($p,{quota:o,threshold:80,t:n,layout:`stacked`,pending:t,...s===void 0?{}:{observedAt:s},incompleteWindowKeys:u?d:void 0,incompleteCustomWindowLabels:u?f:void 0}),(l||i)&&(0,Z.jsxs)(`div`,{className:`pws-capacity-details`,children:[l&&(0,Z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Z.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,Z.jsx)(`strong`,{children:_(l.remaining)})]}),v!==null&&(0,Z.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Z.jsx)(`span`,{children:n(`quota.creditsPeriodEnds`,{date:v})})}),p.flatMap(({key:e,label:t,window:r})=>{let i=r.nextRecoveryAt===void 0?null:h(r.nextRecoveryAt);return i!==null&&r.nextRecoveryPercent!==void 0?[(0,Z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Z.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,i]}),(0,Z.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:m(r.nextRecoveryPercent)})})]},e)]:[]}),u&&i&&i.currentAccount?.quota&&(0,Z.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,Z.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,Z.jsx)($p,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i&&i.incomplete&&i.excludedAccounts>0&&(0,Z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts})}),i&&i.unknownPlanAccounts>0&&(0,Z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.uncalibratedPlan`,{count:i.unknownPlanAccounts})}),i&&i.partialWindowAccounts>0&&(0,Z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function lm({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:o,onEditConfig:s,onRefreshAllQuotas:l}){let u=c(),{locale:d}=a(),f=Np(u),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),_=async()=>{if(l&&!p){m(!0),g(null);try{let e=await l();g({ok:e,text:u(e?`pws.quotaRefreshDone`:`codexAuth.quotaRefreshFailed`)})}catch{g({ok:!1,text:u(`codexAuth.quotaRefreshFailed`)})}finally{m(!1)}}},v=(0,X.useMemo)(()=>[...e.ready,...e.needsSetup,...e.disabled],[e]),y=(0,X.useMemo)(()=>new Set(v.map(e=>e.name)),[v]),b=(0,X.useMemo)(()=>Pp(e,{}),[e]),x=b.length,S=(0,X.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),C=e.ready.length-S,w=e.needsSetup.length+S,T=(0,X.useMemo)(()=>{let e=[];for(let n of v){let r=t[n.name],i=r?ct(r):null,a=r?te(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?Gp(i):-1})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[v,t]),E=(0,X.useMemo)(()=>{let e={};for(let[t,r]of Object.entries(n))y.has(t)&&(e[t]=r);return Ap(e).slice(0,4)},[n,y]),D=e=>{let t=Fp(e);return t===`reauth`?u(`pws.attention.reauth`):t===`missing`?u(`pws.attention.missingCredentials`):e};return(0,Z.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,Z.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,Z.jsx)(`div`,{className:`pws-dashboard-header-text`,children:(0,Z.jsx)(`h2`,{className:`pws-dashboard-title`,children:u(`pws.dashboard.title`)})}),(0,Z.jsxs)(`div`,{className:`pws-dashboard-header-actions`,children:[h&&(0,Z.jsx)(`span`,{role:`status`,className:h.ok?`pws-status-ok`:`pws-status-warn`,children:h.text}),l&&(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:p,onClick:()=>{_()},children:[(0,Z.jsx)(Mt,{width:14,height:14,"aria-hidden":`true`}),` `,u(p?`codexAuth.refreshingQuota`:`pws.refreshAllQuotas`)]}),s&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:u(`prov.editJson`)})]})]}),(0,Z.jsxs)(`dl`,{className:`pws-dashboard-summary`,children:[(0,Z.jsx)(um,{count:C,label:u(`pws.status.ready`),tone:`ok`}),(0,Z.jsx)(um,{count:w,label:u(S>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,Z.jsx)(um,{count:e.disabled.length,label:u(`prov.disabledBadge`),tone:`muted`})]}),x>0&&(0,Z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":u(`pws.attentionTitle`),children:[(0,Z.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:u(`pws.attentionTitle`)}),(0,Z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-banners`,children:b.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>o(e.name),children:[(0,Z.jsx)(`span`,{className:`pws-dashboard-banner-icon`,"aria-hidden":`true`,children:(0,Z.jsx)(at,{width:16,height:16})}),(0,Z.jsx)(oe,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ge(e.name,u)}),(0,Z.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:D(e.reason)})]}),(0,Z.jsx)(St,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,Z.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,Z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":u(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,Z.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:u(`pws.dashboard.rateLimits`)}),T.length>0?(0,Z.jsx)(`div`,{className:`pws-dashboard-rows`,children:T.map(({item:e,report:t})=>(0,Z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>o(e.name),children:[(0,Z.jsx)(oe,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,Z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ge(e.name,u)}),(0,Z.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:u(`pws.dashboard.checkedAgo`,{time:Mp(t.updatedAt,f)})})]}),(0,Z.jsx)(St,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,Z.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Z.jsx)(cm,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,Z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Z.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Z.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Z.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Z.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,Z.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Z.jsx)($p,{quota:null,threshold:80,t:u,layout:`stacked`,pending:!0})})]},t))}):(0,Z.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:u(`pws.dashboard.noRateLimits`)})]}),(0,Z.jsx)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":u(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:(0,Z.jsxs)(`details`,{className:`pws-dashboard-recent-details`,children:[(0,Z.jsx)(`summary`,{className:`pws-dashboard-section-title`,children:u(`pws.dashboard.recentlyUsed`)}),E.length>0?(0,Z.jsx)(`div`,{className:`pws-dashboard-rows`,children:E.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>o(e.name),children:[(0,Z.jsx)(oe,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ge(e.name,u)}),(0,Z.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:u(`pws.dashboard.requests`,{count:Ip(e.requests,d)})}),(0,Z.jsx)(St,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,Z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Z.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Z.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Z.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Z.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,Z.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:u(`pws.dashboard.noUsage`)})]})})]})]})}function um({count:e,label:t,tone:n}){return(0,Z.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}${e>0?` has-count`:``}`,children:[(0,Z.jsxs)(`dt`,{className:`pws-dashboard-card-label`,children:[(0,Z.jsx)(`span`,{className:`pws-dashboard-card-dot`,"aria-hidden":`true`}),t]}),(0,Z.jsx)(`dd`,{className:`pws-dashboard-card-count`,children:e})]})}function dm({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=c(),o=(0,X.useRef)(null);return(0,X.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,Z.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,Z.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,Z.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,Z.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,Z.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,Z.jsx)(`textarea`,{ref:o,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":a(`pws.jsonEditorDesc`)}),i&&(0,Z.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}function fm(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid model response`);return e}function pm(e){if(typeof e!=`string`||!e.trim())throw Error(`Invalid model identity`);return e}function mm(e){if(!Array.isArray(e))throw Error(`Invalid model inventory`);let t=new Map,n=[];for(let r of e){let e=fm(r),i=pm(e.provider),a=pm(e.id),o=pm(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&&pm(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 hm(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 gm(e){let t=fm(e),n=Object.assign(Object.create(null),yf(t));for(let[e,t]of Object.entries(n))pm(e),t.forEach(pm);let r=Object.fromEntries(Object.entries(fm(t.available)).map(([e,t])=>{if(pm(e),!Array.isArray(t))throw Error(`Invalid available models`);return[e,t.map(pm)]})),i=Object.hasOwn(t,`liveModelCounts`)?fm(t.liveModelCounts):{},a=Object.fromEntries(Object.entries(i).map(([e,t])=>{if(pm(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 _m(e){let t=fm(e);return{id:pm(t.id),provider:pm(t.provider),modelId:pm(t.modelId)}}function vm(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=_m(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 ym(e,t,n){let r=_m(e);if(r.provider!==t||r.modelId!==n)throw Error(`Unexpected created model`);return r}function bm(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 xm(e){if(e===void 0)return;let t=fm(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 Sm(e){if(!Array.isArray(e))throw Error(`Invalid providers discovery response`);let t=Object.create(null);for(let n of e){let e=fm(n),r=pm(e.name),i=xm(e.discovery);i&&(t[r]=i)}return t}var Cm=[{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 wm(e){return Ce(kd(e))}function Tm({providers:t,apiBase:n,defaultProvider:r,selectedName:i,onSelect:a,onRemoveProvider:o,onAddProvider:s,onEditConfig:l,jsonEditor:u,jsonSaving:d=!1,modelsRefreshToken:f=0,fetchDiscovery:p=!1,onModelsSettled:m,activeAccountNeedsReauth:h,quotaRefreshEpoch:g=0,quotaForceRefresh:_=!1,onQuotaRefreshSettled:v,onRefreshAllQuotas:y,detail:b}){let x=c(),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)({ready:!0,needsSetup:!0,disabled:!0}),[E,D]=(0,X.useState)({free:!0,paid:!0}),[O,k]=(0,X.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[A,j]=(0,X.useState)(`az`),[M,N]=(0,X.useState)(!1),[P,F]=(0,X.useState)(null),[I,L]=(0,X.useState)(null),[R,z]=(0,X.useState)(!1),[B,V]=(0,X.useState)(!1),H=`ocx.providers.quotas.v1:${n}`,U=`ocx.providers.usage.v2:${n}`,[W,ee]=(0,X.useState)(()=>Rr(kd(U))),[te,ne]=(0,X.useState)(()=>kd(U)?.totals??{}),[K,re]=(0,X.useState)(()=>kd(U)?.models??{}),[q,ae]=(0,X.useState)(()=>wm(H)??{}),[oe,se]=(0,X.useState)(()=>!kd(U)),[ce,le]=(0,X.useState)(()=>{let e=wm(H);return!e||Object.keys(e).length===0}),[ue,J]=(0,X.useState)(0),de=JSON.stringify([n,f,ue]),fe=I?.revision===de&&!R&&!B,pe=(0,X.useMemo)(()=>hm(I?.rows??[]),[I]),me=(0,X.useRef)(m);(0,X.useEffect)(()=>{me.current=m},[m]);let he=(0,X.useRef)(null),ve=dn(Hr(n),[n],async e=>await Vr(await fetch(n+`/api/usage?range=30d`,{signal:e})),{deadlineMs:6e4}),be=(0,X.useMemo)(()=>{let e=G(Re(t));return Ae(e,h??{})},[t,h]),xe=(0,X.useCallback)(()=>{z(!0),V(!1),J(e=>e+1)},[]);(0,X.useEffect)(()=>{let t=!1,r=e(6e4),i=window.setTimeout(()=>{z(!0),(async()=>{let e=!1;try{let[i,a]=await Promise.all([fetch(`${n}/api/selected-models`,{signal:r.signal}).then(zn).then(gm),fetch(`${n}/api/models`,{signal:r.signal}).then(zn).then(mm)]),o=p?await fetch(`${n}/api/providers`,{signal:r.signal}).then(zn).then(Sm):void 0;if(t)return;L({revision:de,selection:i,rows:a,...o?{discovery:o}:{}}),V(!1),e=!0}catch{if(t)return;V(!0)}finally{r.controller.abort(),r.clear(),t||(z(!1),me.current?.(e))}})()},0);return()=>{t=!0,window.clearTimeout(i),r.controller.abort(),r.clear()}},[n,p,de]),(0,X.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=ve.data;if(e)return;if(!t){ve.loading&&se(!kd(U));return}let n=Op(t.providers??[]);ne(n);let r=kp(t.models??[],n);re(r);let i=Rr(t);ee(i),Nd(U,{totals:n,models:r,...i}),se(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[n,U,ve.data,ve.loading]),(0,X.useEffect)(()=>{let t=!1,r=window.setTimeout(()=>{let r=wm(H);(!r||Object.keys(r).length===0)&&le(!0);let a=e(2e4);i=()=>{a.controller.abort(),a.clear()},fetch(`${n}/api/provider-quotas${_?`?refresh=1`:``}`,{signal:a.signal}).then(e=>Bn(e)).then(e=>{if(t)return;if(!e){_&&v?.(!1,g);return}let n=De(e.reports);ae(n),Nd(H,n),_&&v?.(!0,g)}).catch(()=>{t||(ae(e=>{let t=Ce(e)??{};return Nd(H,t),t}),_&&v?.(!1,g))}).finally(()=>{a.clear(),t||le(!1)})},0),i;return()=>{t=!0,window.clearTimeout(r),i?.()}},[n,g,_,H,v]),(0,X.useEffect)(()=>{if(!M)return;let e=e=>{he.current&&!he.current.contains(e.target)&&N(!1)},t=e=>{e.key===`Escape`&&N(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[M]);let Se=(0,X.useMemo)(()=>[...be.ready,...be.needsSetup,...be.disabled],[be]),we=(0,X.useMemo)(()=>Se.filter(Ie).length,[Se]),Te=Se.length-we,Ee=(0,X.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of Se)e[ye(t)]+=1;return e},[Se]),Oe=(0,X.useMemo)(()=>{let e=S.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=Ie(t);return!(n&&!E.free||!n&&!E.paid||!O[ye(t)])});return _e(n,A)};return{ready:w.ready?t(be.ready):[],needsSetup:w.needsSetup?t(be.needsSetup):[],disabled:w.disabled?t(be.disabled):[]}},[be,S,w,E,O,A]),ke=!w.ready||!w.needsSetup||!w.disabled||!E.free||!E.paid||!O.cloud||!O.local||!O.selfHosted||!O.login||A!==`az`,je=()=>{T({ready:!0,needsSetup:!0,disabled:!0}),D({free:!0,paid:!0}),k({cloud:!0,local:!0,selfHosted:!0,login:!0}),j(`az`)},Me=(0,X.useMemo)(()=>i?Se.find(e=>e.name===i)??null:null,[i,Se]),Ne=(0,X.useMemo)(()=>{let e=new Map;for(let t of Se){let n=Ge(t.name,x);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,x]);if(Se.length===0)return(0,Z.jsx)(Em,{onAddProvider:s});let Pe=[{key:`ready`,label:x(`pws.status.ready`),count:be.ready.length},{key:`needsSetup`,label:x(`pws.status.needsSetup`),count:be.needsSetup.length},{key:`disabled`,label:x(`prov.disabledBadge`),count:be.disabled.length}],Fe=[{id:`ready`,label:x(`pws.status.ready`),count:Oe.ready.length,ariaLabel:x(`pws.groupReady`,{count:Oe.ready.length}),items:Oe.ready},{id:`needs-setup`,label:x(`pws.status.needsSetup`),count:Oe.needsSetup.length,ariaLabel:x(`pws.groupNeedsSetup`,{count:Oe.needsSetup.length}),items:Oe.needsSetup},{id:`disabled`,label:x(`prov.disabledBadge`),count:Oe.disabled.length,ariaLabel:x(`pws.groupDisabled`,{count:Oe.disabled.length}),items:Oe.disabled}],Le=Fe.flatMap(e=>e.items.map(e=>e.name)),Be=P&&Le.includes(P)?P:i&&Le.includes(i)?i:Le[0]??null;return(0,Z.jsx)(`div`,{className:`pws-shell-container`,children:(0,Z.jsxs)(`div`,{className:`pws-root`,children:[(0,Z.jsxs)(`aside`,{className:`pws-rail`,"aria-label":x(`pws.providerList`),children:[(0,Z.jsxs)(`div`,{className:`pws-search-row`,children:[(0,Z.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Z.jsx)(ze,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Z.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:x(`pws.searchPlaceholder`),value:S,onChange:e=>C(e.target.value),"aria-label":x(`pws.searchPlaceholder`)})]}),(0,Z.jsxs)(`div`,{className:`pws-filter-wrap`,ref:he,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ke||M?` pws-filter-btn--active`:``}`,onClick:()=>N(e=>!e),"aria-label":x(`pws.filterAria`),"aria-expanded":M,"aria-controls":`pws-provider-filters`,children:[(0,Z.jsx)(nt,{width:18,height:18,"aria-hidden":`true`}),ke&&(0,Z.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),M&&(0,Z.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":x(`pws.providerFiltersAria`),children:[(0,Z.jsx)(`div`,{className:`pws-filter-title`,children:x(`pws.filters`)}),(0,Z.jsx)(`div`,{className:`pws-filter-head`,children:x(`pws.filterStatus`)}),Pe.map(({key:e,label:t,count:n})=>(0,Z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:w[e],onChange:()=>T(t=>({...t,[e]:!t[e]}))}),(0,Z.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Z.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Z.jsx)(`div`,{className:`pws-filter-head`,children:x(`pws.pricing`)}),(0,Z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:E.free,onChange:()=>D(e=>({...e,free:!e.free}))}),(0,Z.jsx)(`span`,{className:`pws-filter-label`,children:x(`modal.badge.free`)}),(0,Z.jsx)(`span`,{className:`pws-filter-count`,children:we})]}),(0,Z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:E.paid,onChange:()=>D(e=>({...e,paid:!e.paid}))}),(0,Z.jsx)(`span`,{className:`pws-filter-label`,children:x(`pws.paid`)}),(0,Z.jsx)(`span`,{className:`pws-filter-count`,children:Te})]}),(0,Z.jsx)(`div`,{className:`pws-filter-head`,children:x(`pws.filterType`)}),[{key:`cloud`,label:x(`pws.type.cloud`),count:Ee.cloud},{key:`local`,label:x(`pws.type.local`),count:Ee.local},{key:`selfHosted`,label:x(`pws.type.selfHosted`),count:Ee.selfHosted},{key:`login`,label:x(`pws.type.login`),count:Ee.login}].map(({key:e,label:t,count:n})=>(0,Z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:O[e],onChange:()=>k(t=>({...t,[e]:!t[e]}))}),(0,Z.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Z.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Z.jsx)(`div`,{className:`pws-filter-head`,children:x(`pws.sort`)}),(0,Z.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":x(`pws.sortProvidersAria`),children:Cm.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`pws-sort-btn${A===e.id?` pws-sort-btn--active`:``}`,onClick:()=>j(e.id),"aria-pressed":A===e.id,children:x(e.labelKey)},e.id))}),(0,Z.jsx)(`div`,{className:`pws-filter-footer`,children:(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:je,disabled:!ke,children:x(`pws.resetAll`)})})]})]})]}),(0,Z.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":x(`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(Oe).every(e=>e.length===0)&&(0,Z.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:x(S?`pws.noSearchResults`:ke?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Fe.map(({id:e,label:t,count:n,ariaLabel:s,items:c})=>c.length===0?null:(0,Z.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,Z.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,Z.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,Z.jsx)(`span`,{className:`pws-rail-group-count`,children:n})]}),c.map(e=>(0,Z.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,Z.jsx)(ie,{item:e,selected:i===e.name,tabbable:Be===e.name,modelCount:I?Object.hasOwn(pe,e.name)?pe[e.name]:0:void 0,isDefault:r===e.name,showConfigId:Ne.has(Ge(e.name,x)),onClick:()=>a(e.name),onFocus:()=>F(e.name)}),o&&(0,Z.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),o(e.name)},title:x(`pws.removeConfirmTitle`),children:(0,Z.jsx)(ge,{width:14,height:14})})]},e.name))]},e))]})]}),(0,Z.jsxs)(`main`,{className:`pws-main`,"aria-label":x(`pws.workspaceMainAria`),children:[!u?.open&&(0,Z.jsx)(Ur,{data:W}),u?.open?(0,Z.jsx)(dm,{editor:u,providerName:x(`nav.providers`),saving:d,onSave:()=>{u.onSave()}}):Me?b?.(fe&&Me.discovery===void 0&&I?.discovery?.[Me.name]?{...Me,discovery:I.discovery[Me.name]}:Me,{usageTotals:te[Me.name],modelUsage:K[Me.name],quotaReport:q[Me.name],availableModels:I?.selection.available[Me.name]??[],hasLiveModels:(I?.selection.liveModelCounts[Me.name]??0)>0,selectedModels:I?.selection.selected[Me.name]??[],modelRows:I?.rows.filter(e=>e.provider===Me.name)??null,modelRevision:de,modelRowsReady:fe,modelsLoading:R||!fe&&!B,modelsLoadFailed:B,onRetryModels:xe})??(0,Z.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,Z.jsx)(`h3`,{children:Ge(Me.name,x)}),(0,Z.jsx)(`p`,{className:`muted`,children:x(`pws.detailComingSoon`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>a(null),children:x(`modal.back`)})]}):(0,Z.jsx)(lm,{sections:be,quotaReports:q,usageTotals:te,usageLoading:oe,quotasLoading:ce,onSelectProvider:e=>a(e),onEditConfig:l,...y?{onRefreshAllQuotas:y}:{}})]})]})})}function Em({onAddProvider:e}){let t=c();return(0,Z.jsx)(`div`,{className:`pws-empty-root`,children:(0,Z.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,Z.jsx)(`div`,{"aria-hidden":`true`,children:(0,Z.jsx)(Ze,{style:{width:64,height:64}})}),(0,Z.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,Z.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:(0,Z.jsx)(wt,{width:18,height:18})}),(0,Z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,Z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:(0,Z.jsx)(ae,{width:18,height:18})}),(0,Z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,Z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:(0,Z.jsx)(Et,{width:18,height:18})}),(0,Z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,Z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function Dm(e){if(de(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||pe(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0,r=t===`key`||n||t===``,i=e.keyOptional===!0||he(e);return!r||i&&!n?null:`api-keys`}function Om(e,t,n,r=!1){let i=r?void 0:t.alias?.trim();if(i)return i;let a=r?void 0:t.email?.trim();if(a)return a;let o=e.findIndex(e=>e.id===t.id);return n(`pws.accountOrdinal`,{count:String(o>=0?o+1:1)})}function km(e){return e===`anthropic`||e===`anthropic2`}function Am(e,t){return e===`anthropic`?!0:e!==`anthropic2`||!t?!1:Object.hasOwn(t,`anthropicOAuthInstance`)&&t.anthropicOAuthInstance===`anthropic2`&&t.adapter===`anthropic`&&t.authMode===`oauth`}function jm({quota:e,quotaMode:t,quotaUnavailable:n,quotaPending:r,quotaFailure:i}){let a=c(),o=ct({quota:e});if(t===`unsupported`)return(0,Z.jsx)(`p`,{className:`muted`,"data-quota-state":`unsupported`,children:a(`pws.quotaUnsupported`)});let s=t===`probe`&&n?nl(i):void 0,l=t===`probe`&&r===!0;return(0,Z.jsxs)(`div`,{"data-quota-state":n?`unavailable`:l?`pending`:o?`ready`:t===`passive`?`unobserved`:`unknown`,children:[n&&(0,Z.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:a(s?`pws.quotaFailure.${s}`:`pws.accountQuotaUnavailable`)}),o||l?(0,Z.jsx)(cm,{report:{quota:o,updatedAt:o?.updatedAt,...t===`passive`?{observed:!0}:{}},pending:l&&!o}):!n&&(0,Z.jsx)(`p`,{className:`muted`,children:a(t===`passive`?`pws.quotaUnobserved`:`pws.quotaUnavailable`)}),n&&o&&(0,Z.jsxs)(`p`,{className:`muted`,children:[a(`pws.stats.quotaUpdated`),`: `,Mp(o.updatedAt,Np(a))]})]})}function Mm({report:e,reading:t,onRefreshQuota:n}){let r=c(),i=ot(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:ct(i),...i?.observed===!0?{quotaMode:`passive`}:{}},s=ct({quota:o.quota}),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),p=async()=>{if(n&&!l){u(!0),f(null);try{f(await n())}catch{f(!1)}finally{u(!1)}}};return(0,Z.jsxs)(`section`,{className:`pws-usage-block`,"aria-label":r(`pws.currentAccountUsage`),children:[(0,Z.jsxs)(`div`,{className:`pws-usage-block-head`,children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:r(`pws.currentAccountUsage`)}),t?.planLabel&&(0,Z.jsx)(`span`,{className:`badge badge-green`,children:t.planLabel}),n&&o.quotaMode!==`unsupported`&&(0,Z.jsxs)(`div`,{className:`pws-quota-refresh`,children:[d!==null&&(0,Z.jsx)(`span`,{role:`status`,className:d?`pws-status-ok`:`pws-status-warn`,children:r(d?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:l,onClick:()=>{p()},children:[(0,Z.jsx)(Mt,{width:14,height:14,"aria-hidden":`true`}),` `,r(l?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Z.jsx)(jm,{...o}),s&&!o.quotaUnavailable&&o.quotaMode!==`unsupported`&&(0,Z.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[!a&&i?.source?.trim()&&(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:r(`pws.stats.source`)}),(0,Z.jsx)(`dd`,{children:xe(i.source)})]}),(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:r(`pws.stats.quotaUpdated`)}),(0,Z.jsx)(`dd`,{children:Mp(s.updatedAt,Np(r))})]})]})]})}function Nm(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 Pm(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function Fm(e){return ue(e.id,Pm(e))}function Im(e){return pe(Pm(e))}function Lm(e){let t={accounts:[],free:[],local:[],paid:[]};for(let n of e){let e=Fm(n);t[e===`accounts`?`accounts`:Im(n)?`local`:e].push(n)}return t}function Rm(e){return!!e?.trim()}var zm=new Set([`local`,`localhost`,`ollama`,`vllm`,`lmstudio`,`lm studio`,`self-hosted`,`selfhosted`]);function Bm(e,t){let n=t.trim().toLowerCase();return!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||e.adapter.toLowerCase()===n?!0:zm.has(n)&&Im(e)}function Vm(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 Hm(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 Um(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 Wm={main:0,standard:1};function Gm(e){let t=e.filter(e=>e.sponsor);return t.length===0?e:(t.sort((e,t)=>Wm[e.sponsor]-Wm[t.sponsor]||e.label.localeCompare(t.label,void 0,{sensitivity:`base`})||e.id.localeCompare(t.id)),[...t,...e.filter(e=>!e.sponsor)])}var Km={name:`OrcaRouter`,title:`pws.sponsor.orcaTitle`,description:`pws.sponsor.orcaDescription`},qm={orcarouter:Km,"orcarouter-oauth":Km,tokenlab:{name:`TokenLab`,title:`pws.sponsor.tokenlabTitle`,description:`pws.sponsor.tokenlabDescription`}};function Jm(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 Ym({item:e,preset:t}){let n=c();if(!t?.sponsor||!Nm(e,[t]))return null;let r=Object.hasOwn(qm,t.id)?qm[t.id]:void 0;if(!r)return null;let i=Jm(t.sponsorUrl),a=Jm(t.dashboardUrl);return(0,Z.jsxs)(`section`,{className:`pws-sponsor`,"aria-label":`${r.name} · ${n(`modal.badge.sponsor`)}`,children:[(0,Z.jsxs)(`div`,{className:`pws-sponsor-copy`,children:[(0,Z.jsxs)(`div`,{className:`pws-sponsor-byline`,children:[(0,Z.jsx)(`span`,{children:r.name}),(0,Z.jsx)(`span`,{className:`pws-sponsor-badge`,children:n(`modal.badge.sponsor`)})]}),(0,Z.jsx)(`h3`,{children:n(r.title)}),(0,Z.jsx)(`p`,{children:n(r.description)})]}),(i||a)&&(0,Z.jsxs)(`div`,{className:`pws-sponsor-actions`,children:[i&&(0,Z.jsxs)(`a`,{className:`btn btn-primary`,href:i,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.visit`,{provider:r.name}),(0,Z.jsx)(dt,{width:14,height:14,"aria-hidden":`true`})]}),a&&a!==i&&(0,Z.jsxs)(`a`,{className:`pws-sponsor-console`,href:a,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.console`),(0,Z.jsx)(dt,{width:13,height:13,"aria-hidden":`true`})]})]})]})}function Xm(e){return e.filter(e=>e.outcome===`failed`).map(e=>e.model)}function Zm({apiBase:e,provider:t,models:n,gate:r,blocked:i}){let o=c(),{locale:s}=a(),[l,u]=(0,X.useState)([]),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)({kind:`idle`}),y=(0,X.useRef)(null),b=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{y.current&&(y.current.abort(),y.current=null,r.release()),b.current?.abort(),b.current=null},[r]);async function x(n,r){try{let i=await zn(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}),o(`pws.completion.failed`));if(!i)return{model:n,outcome:`skipped`,detail:o(`pws.completion.failed`)};if(!i.applicable){let e=`${o(`pws.completion.notApplicable`)}: ${o(`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 a=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:a}:{model:n,outcome:`failed`,latencyMs:i.totalLatencyMs,detail:a}}catch(e){return{model:n,outcome:`skipped`,detail:e instanceof Error?e.message:o(`pws.completion.failed`)}}}async function S(){if(n.length===0||y.current||b.current||!r.claim())return;let e=new AbortController;y.current=e,f(!0),m(!1),u([]),g(null),v({kind:`idle`});try{if(!await Nu({message:o(`pws.completion.allConfirm`,{count:String(n.length),provider:t}),confirmLabel:o(`pws.completion.runAll`),signal:e.signal,locale:s})||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){g(n.stop);break}u(e=>[...e,n])}}finally{y.current===e&&(y.current=null,r.release(),f(!1))}}function C(){y.current?.abort(),y.current=null,r.release(),m(!0),f(!1)}async function w(){let n=Xm(l);if(n.length===0||y.current||b.current)return;let r=new AbortController;b.current=r,v({kind:`busy`});let i=!1;try{if(i=await Nu({message:o(`pws.completion.disableConfirm`,{count:String(n.length),provider:t}),confirmLabel:o(`pws.completion.disableFailed`,{count:String(n.length)}),tone:`danger`,locale:s,signal:r.signal}),!i||r.signal.aborted||b.current!==r)return;await zn(await Cf(e,`models`,t,n.map(e=>({id:e})),!1,fetch,r.signal),o(`pws.completion.disableError`)),!r.signal.aborted&&b.current===r&&v({kind:`done`,count:n.length})}catch(e){!r.signal.aborted&&b.current===r&&v({kind:`error`,message:e instanceof Error?e.message:o(`pws.completion.disableError`)})}finally{b.current===r&&(b.current=null,i||v({kind:`idle`}))}}let T={ok:0,failed:0,skipped:0};for(let e of l)T[e.outcome]++;let E=T.failed,D=T.skipped+(d?0:n.length-l.length);return(0,Z.jsxs)(`div`,{className:`pws-completion-bulk`,children:[(0,Z.jsxs)(`div`,{className:`row pws-completion-bulk-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n.length===0||d||_.kind===`busy`||i,onClick:()=>void S(),children:d?o(`pws.completion.progress`,{done:String(l.length),total:String(n.length)}):o(`pws.completion.runAll`)}),d&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:C,children:o(`pws.completion.stop`)})]}),h&&(0,Z.jsx)(`p`,{role:`status`,className:`muted pws-completion-result`,children:h}),l.length>0&&(0,Z.jsxs)(`div`,{className:`pws-completion-result`,"data-completion-bulk-state":d?`running`:`done`,children:[!d&&(0,Z.jsxs)(`p`,{role:`status`,children:[p&&(0,Z.jsxs)(Z.Fragment,{children:[o(`pws.completion.stopped`,{done:String(l.length),total:String(n.length)}),` · `]}),o(`pws.completion.summary`,{passed:String(T.ok),failed:String(E),skipped:String(D)})]}),(0,Z.jsx)(`table`,{className:`pws-completion-table`,children:(0,Z.jsx)(`tbody`,{children:l.map(e=>(0,Z.jsxs)(`tr`,{"data-model-test-outcome":e.outcome,children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.model})}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`span`,{className:`badge ${e.outcome===`ok`?`badge-green`:e.outcome===`failed`?`badge-amber`:`badge-muted`}`,children:o(e.outcome===`ok`?`pws.completion.passed`:e.outcome===`failed`?`pws.completion.failedShort`:`pws.completion.notTested`)})}),(0,Z.jsx)(`td`,{className:`muted`,children:e.latencyMs===void 0?``:`${e.latencyMs} ms`}),(0,Z.jsx)(`td`,{className:`muted`,children:e.detail??``})]},e.model))})}),!d&&E>0&&_.kind!==`done`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:_.kind===`busy`,onClick:()=>void w(),children:o(`pws.completion.disableFailed`,{count:String(E)})}),_.kind===`done`&&(0,Z.jsx)(`p`,{role:`status`,className:`pws-status-ok`,children:o(`pws.completion.disabledDone`,{count:String(_.count)})}),_.kind===`error`&&(0,Z.jsx)(`p`,{role:`alert`,className:`pws-inline-error`,children:_.message})]})]})}function Qm(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 $m({apiBase:e,provider:t,models:n,probeKey:r,selectedModel:i,onSelectedModelChange:a,initialResult:o=null,initialError:s=null,onStatusChange:l,onFixCredentials:u,onFixSettings:d,onFixModels:f}){let p=c(),[m,h]=(0,X.useState)(``);i===void 0&&m!==``&&!n.includes(m)&&h(``);let g=i===void 0?m:i,_=n.includes(g)?g:``,[v,y]=(0,X.useState)(null),[b]=(0,X.useState)(()=>Qm(y));return(0,Z.jsxs)(`section`,{className:`pws-completion-test`,"aria-label":p(`pws.completion.title`),children:[(0,Z.jsx)(`h4`,{className:`pws-section-title`,children:p(`pws.completion.title`)}),(0,Z.jsx)($,{label:p(`pws.completion.model`),value:_,options:[{value:``,label:p(`pws.completion.choose`)},...n.map(e=>({value:e,label:e}))],onChange:e=>{e!==_&&(i===void 0&&h(e),a?.(e),l?.({status:`untested`,model:e}))}}),(0,Z.jsx)(eh,{apiBase:e,provider:t,model:_,initialResult:o,initialError:s,onStatusChange:l,onFixCredentials:u,onFixSettings:d,onFixModels:f,gate:b.single,blocked:v===`bulk`},JSON.stringify([e,r??``,t,_])),(0,Z.jsx)(Zm,{apiBase:e,provider:t,models:n,gate:b.bulk,blocked:v===`single`},JSON.stringify([e,r??``,t]))]})}function eh({apiBase:e,provider:t,model:n,initialResult:r=null,initialError:i=null,onStatusChange:o,onFixCredentials:s,onFixSettings:l,onFixModels:u,gate:d,blocked:f}){let p=c(),{locale:m}=a(),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(r),[y,b]=(0,X.useState)(i),x=(0,X.useRef)(null),S=(0,X.useRef)(!0);(0,X.useEffect)(()=>(S.current=!0,()=>{S.current=!1,x.current&&(x.current.abort(),x.current=null,d.release())}),[d]);async function C(){if(!n||x.current||!d.claim())return;let r=new AbortController;x.current=r,g(!0);let i=()=>S.current&&!r.signal.aborted&&x.current===r;try{let a=await Nu({message:p(`pws.completion.confirm`,{model:n,provider:t}),confirmLabel:p(`pws.completion.run`),signal:r.signal,locale:m});if(!i()||!a)return;v(null),b(null),o?.({status:`testing`,model:n});let s=await zn(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}),p(`pws.completion.failed`));if(!s)throw Error(p(`pws.completion.failed`));i()&&(v(s),o?.({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:p(`pws.completion.failed`);b(t),o?.({status:`failed`,model:n,result:null,error:t})}}finally{x.current===r&&(x.current=null,d.release(),S.current&&!r.signal.aborted&&g(!1))}}return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!n||h||f,onClick:()=>void C(),children:p(h?`pws.testing`:`pws.completion.run`)}),y&&(0,Z.jsx)(`p`,{role:`alert`,className:`pws-inline-error pws-completion-result`,children:y}),y&&(0,Z.jsx)(`div`,{role:`status`,className:`pws-completion-recovery pws-completion-result muted`,"data-failure-recovery":`request`,children:(0,Z.jsx)(`span`,{children:p(`pws.completion.recovery.request`,{model:n})})}),_&&(0,Z.jsx)(nh,{result:_,onFixCredentials:s,onFixSettings:l,onFixModels:u})]})}function th(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 nh({result:e,onFixCredentials:t,onFixSettings:n,onFixModels:r}){let i=c();if(!e.applicable)return(0,Z.jsxs)(`div`,{role:`status`,className:`pws-completion-result muted`,children:[(0,Z.jsxs)(`p`,{children:[i(`pws.completion.notApplicable`),`: `,i(`pws.completion.${e.reason}`)]}),e.detail&&(0,Z.jsx)(`p`,{children:i(`pws.completion.${e.detail}`)}),e.adapter&&(0,Z.jsx)(`p`,{children:(0,Z.jsx)(`code`,{children:e.adapter})})]});let a=th(e),o=t??n;return(0,Z.jsxs)(`div`,{role:`status`,className:`pws-completion-result`,"data-completion-test-state":e.ok?`ok`:`failed`,children:[(0,Z.jsx)(`p`,{className:e.ok?`pws-status-ok`:`pws-status-warn`,children:i(e.ok?`pws.completion.ok`:`pws.completion.failed`)}),(0,Z.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:i(`pws.completion.ttft`)}),(0,Z.jsx)(`dd`,{children:e.ttftMs===null?`—`:`${e.ttftMs} ms`})]}),(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:i(`pws.completion.total`)}),(0,Z.jsxs)(`dd`,{children:[e.totalLatencyMs,` ms`]})]})]}),(0,Z.jsx)(`p`,{children:e.upstreamModel===null?i(`pws.completion.unreported`,{model:e.wireModel}):i(`pws.completion.reported`,{upstream:e.upstreamModel,model:e.wireModel})}),(0,Z.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,Z.jsx)(`p`,{className:`muted`,children:i(`pws.completion.${e.comparisonNote}`)}),(0,Z.jsx)(`p`,{className:`muted`,children:i(`pws.completion.identity`)}),e.error&&(0,Z.jsxs)(`p`,{role:`alert`,className:`pws-inline-error`,children:[(0,Z.jsx)(`code`,{children:e.error.code}),e.error.status!==void 0&&(0,Z.jsxs)(Z.Fragment,{children:[` (`,e.error.status,`)`]}),`: `,e.error.message]}),a&&(0,Z.jsxs)(`div`,{className:`pws-completion-recovery muted`,"data-failure-recovery":a,children:[(0,Z.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,Z.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,Z.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,Z.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-connection`,onClick:n,children:i(`pws.completion.recovery.fixSettings`)}),a===`model`&&r&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-model`,onClick:r,children:i(`pws.firstResponse.openProviderModels`)}),a===`upstream`&&n&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,"data-recovery-action":`fix-settings`,onClick:n,children:i(`pws.completion.recovery.fixSettings`)})]})]})}function rh(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,n??null,r])}function ih(e,t=[]){return[...new Set([...e.models??[],...t,...e.defaultModel?[e.defaultModel]:[]])]}function ah(e,t,n,r=[],i=0){let a=rh(t,e,n,i),o=ih(e,r),[s,c]=(0,X.useState)(e.name),[l,u]=(0,X.useState)(a),[d,f]=(0,X.useState)(0),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(null),[_,v]=(0,X.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 oh({item:e,preset:t,usageTotals:n,quotaReport:r,currentQuotaReading:i,onRefreshQuota:o,oauthEmail:s,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:b,onOpenModelsTab:x,onOpenModels:S,onOpenConnect:C,onEditSettings:w,onViewUsage:T,onUpdateProvider:E,onCreateJevAuto:D,onReauthenticate:O,onCancelLogin:k,reauthBusy:A=!1}){let j=c(),{locale:M}=a(),N=jt(e),P=!!e.activeNeedsReauth||l?.needsReauth===!0,F=e.authMode===`oauth`&&l?.loggedIn===!1,I=e.disabled===!0?`disabled`:P||F||N===`needs-setup`?`needs-setup`:`ready`,L=j(I===`ready`?`pws.status.ready`:I===`needs-setup`?P?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),R=n?.requests,z=n?.totalTokens,B=ah(e,u,d,p),V=f??B,{connectionProbeKey:H,completionModels:U,selectedModel:W,completionProbe:ee,reverifyModel:te}=V,[ne,G]=(0,X.useState)(null),K=(0,X.useRef)(null),re=ne?.key===H&&ne.testing,q=ne?.key===H?ne.result:null,ie=[...new Set([...e.models??[],...e.defaultModel?[e.defaultModel]:[]])];(0,X.useEffect)(()=>()=>{K.current?.key===H&&(K.current.controller.abort(),K.current=null)},[H]);let ae=(0,X.useCallback)(async()=>{if(u===void 0)return;K.current?.controller.abort();let t=new AbortController;K.current={key:H,controller:t},G({key:H,testing:!0,result:null});try{let n=await zn(await fetch(`${u}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),j(`pws.connectionFailed`));if(!n)throw Error(j(`pws.connectionFailed`));t.signal.aborted||G({key:H,testing:!1,result:n})}catch(e){t.signal.aborted||G({key:H,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:j(`pws.connectionFailed`)}})}finally{K.current?.controller===t&&(K.current=null)}},[u,H,e.name,j]),oe=q?.applicable===!1?`not-applicable`:q?.ok===!0?`ok`:`failed`,se=q?.applicable===!1?j(`pws.connectionNotApplicable`):q?.ok===!0?q.message||j(`pws.connectionOk`):q?.error||j(`pws.connectionFailed`),ce=e.disabled===!0?`disabled`:P?`needs-attention`:F?`needs-login`:I===`needs-setup`?`needs-setup`:`saved`,le=j(ce===`disabled`?`pws.firstResponse.providerDisabled`:ce===`needs-attention`?`pws.firstResponse.providerNeedsAttention`:ce===`needs-login`?`pws.firstResponse.providerNeedsLogin`:ce===`needs-setup`?`pws.firstResponse.providerNeedsSetup`:`pws.firstResponse.providerSaved`),ue=(h??[]).filter(t=>t.provider===e.name),J=ue.filter(t=>Sf({[e.name]:m??[]},e.name,t.id,t.native===!0,t.disabled)),de=h!=null&&g,fe=de?ue.some(e=>e.initialSelectionPending===!0):e.initialModelSelection?.status===`pending`,pe=e.liveModels!==!1&&e.discovery?.status===`failed`?e.discovery:void 0,me=_?`loading`:v||pe&&(!de||fe||J.length===0)?`failed`:fe?`pending`:de?J.length>0?pe?`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`,he=me===`loading`?j(`pws.firstResponse.modelsLoading`):me===`failed`?pe?Tf(j,pe):j(`pws.firstResponse.modelsFailed`):me===`pending`?j(`pws.firstResponse.modelsPending`):me===`ready-discovery-failed`?j(`pws.firstResponse.modelsReadyDiscoveryFailed`,{count:J.length}):me===`ready`?j(`pws.firstResponse.modelsReady`,{count:J.length}):me===`all-off`?j(`pws.firstResponse.modelsAllOff`):me===`configured`?j(`pws.firstResponse.modelsConfigured`,{count:ie.length||p.length}):j(`pws.firstResponse.modelsEmpty`),ge=ee?.status??`untested`,_e=ge===`untested`&&te!==null,ve=ge===`testing`?j(`pws.testing`):ge===`ok`?j(`pws.firstResponse.probeOk`,{model:ee?.model??``}):ge===`failed`?j(`pws.firstResponse.probeFailed`,{model:ee?.model??``}):ge===`not-applicable`?j(`pws.completion.notApplicable`):_e?j(`pws.firstResponse.probeReverify`,{model:te}):j(`pws.firstResponse.probeUntested`),ye=km(e.name)&&Am(e.name,e)?void 0:s,be=x??S,xe=b??w;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ym,{item:e,preset:t}),(0,Z.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,Z.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,Z.jsxs)(`section`,{className:`pws-section`,"aria-label":j(`pws.connection`),children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:j(`pws.connection`)}),(0,Z.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:j(`dash.status`)}),(0,Z.jsxs)(`dd`,{className:I===`ready`?`pws-status-ok`:`pws-status-warn`,children:[I===`ready`?(0,Z.jsx)(ut,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Z.jsx)(at,{style:{width:13,height:13},"aria-hidden":`true`}),L]})]}),(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:j(`modal.baseUrl`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:j(`pws.cell.auth`)}),(0,Z.jsx)(`dd`,{children:ye?`${Te(e,j)} · ${ye}`:Te(e,j)})]}),(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:j(`modal.defaultModel`)}),(0,Z.jsx)(`dd`,{children:e.defaultModel??(0,Z.jsx)(`span`,{className:`muted`,children:`—`})})]})]}),(0,Z.jsxs)(`div`,{className:`pws-first-response`,"aria-label":j(`pws.firstResponse.title`),children:[(0,Z.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`provider`,"data-step-state":ce,children:[(0,Z.jsx)(`span`,{className:`pws-first-response-label`,children:j(`pws.firstResponse.stepProvider`)}),(0,Z.jsx)(`span`,{className:ce===`saved`?`pws-status-ok`:`pws-status-warn`,children:le})]}),(0,Z.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`models`,"data-step-state":me,children:[(0,Z.jsx)(`span`,{className:`pws-first-response-label`,children:j(`pws.firstResponse.stepModels`)}),(0,Z.jsx)(`span`,{className:me===`ready`?`pws-status-ok`:me===`failed`||me===`all-off`||me===`empty`||me===`ready-discovery-failed`?`pws-status-warn`:`muted`,children:he}),me===`failed`&&y&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:y,children:j(`common.retry`)}),be&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:be,children:j(`pws.firstResponse.openProviderModels`)})]}),(0,Z.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`clients`,"data-step-state":`info`,children:[(0,Z.jsx)(`span`,{className:`pws-first-response-label`,children:j(`pws.firstResponse.stepClients`)}),(0,Z.jsx)(`span`,{className:`muted`,children:j(`pws.firstResponse.clientStep`,{provider:e.name})}),C&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:C,children:j(`pws.firstResponse.openConnect`)})]}),(0,Z.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`probe`,"data-step-state":ge,..._e?{"data-reverify-pending":`true`}:{},children:[(0,Z.jsx)(`span`,{className:`pws-first-response-label`,children:j(`pws.firstResponse.stepProbe`)}),(0,Z.jsx)(`span`,{className:ge===`ok`?`pws-status-ok`:ge===`failed`||_e?`pws-status-warn`:`muted`,children:ve})]}),(0,Z.jsxs)(`div`,{className:`pws-first-response-row`,"data-first-response-step":`disconnect`,"data-step-state":`info`,children:[(0,Z.jsx)(`span`,{className:`pws-first-response-label`,children:j(`pws.firstResponse.stepDisconnect`)}),(0,Z.jsx)(`span`,{className:`muted`,children:j(`pws.firstResponse.disconnectNote`,{provider:e.name})}),C&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:C,children:j(`pws.firstResponse.openConnect`)})]})]}),u!==void 0&&(0,Z.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:re,onClick:()=>void ae(),children:j(re?`pws.testing`:`pws.testConnection`)}),q&&(0,Z.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`&&xe&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,"data-connection-recovery-action":`fix-connection`,onClick:xe,children:j(b?`pws.completion.recovery.fixAuth`:`pws.completion.recovery.fixSettings`)})]}),u!==void 0&&(0,Z.jsx)($m,{apiBase:u,provider:e.name,probeKey:H,models:U,selectedModel:W,onSelectedModelChange:V.selectModel,initialResult:ee?.result??null,initialError:ee?.error??null,onStatusChange:V.reportStatus,onFixCredentials:xe,onFixSettings:w,onFixModels:be},e.name),w&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:w,children:j(`pws.editSettings`)})]}),e.adapter===`jev-decision`&&D&&(0,Z.jsxs)(`section`,{className:`pws-section`,"aria-label":j(`cws.jev.create`),children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:j(`cws.jev.create`)}),(0,Z.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:j(`cws.jev.setupHint`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:D,children:j(`cws.jev.create`)})]}),(0,Z.jsxs)(`section`,{className:`pws-section`,"aria-label":j(`pws.authSummary`),children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:j(`pws.authSummary`)}),P?(0,Z.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,Z.jsx)(at,{style:{width:14,height:14},"aria-hidden":`true`}),(0,Z.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:j(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?j(`pws.attention.reauthForward`):j(`pws.attention.reauth`)]}),O&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:A,onClick:()=>O(),children:j(A?`prov.waitingBrowser`:`pws.reauthenticate`)}),A&&k&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:j(`common.cancel`)})]})]}):(0,Z.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,Z.jsx)(`span`,{className:`pws-auth-dot`}),(0,Z.jsx)(`span`,{children:e.authMode===`forward`?j(`pws.passthrough`):e.authMode===`oauth`?ye?j(`pws.loggedInAs`,{email:ye}):l?.loggedIn?j(`pws.loggedInTitle`):j(`pws.notLoggedIn`):e.hasApiKey?j(`pws.apiKeyConfigured`):Te(e,j)})]})]}),(0,Z.jsx)(sh,{item:e,onUpdateProvider:E})]}),(0,Z.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,Z.jsxs)(`section`,{className:`pws-section`,"aria-label":j(`pws.statsAria`),children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:j(`pws.statsTitle`)}),(0,Z.jsxs)(`dl`,{className:`pws-kv`,children:[typeof R==`number`&&(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:j(`pws.stats.totalRequests`)}),(0,Z.jsx)(`dd`,{className:`pws-kv-mono`,children:Ip(R,M)})]}),typeof z==`number`&&(0,Z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Z.jsx)(`dt`,{children:j(`pws.stats.totalTokens`)}),(0,Z.jsx)(`dd`,{className:`pws-kv-mono`,children:Lp(z,M)})]}),typeof R!=`number`&&typeof z!=`number`&&(0,Z.jsx)(`div`,{className:`muted`,children:j(`pws.usageUnavailable`)})]}),T&&(0,Z.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:T,children:[j(`pws.viewUsage`),` →`]})]}),(0,Z.jsx)(Mm,{report:r,reading:i,onRefreshQuota:o},`${e.name}:${d??``}`)]})]})]})}function sh({item:e,onUpdateProvider:t}){let n=c(),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),f=(0,X.useRef)(null);(0,X.useEffect)(()=>{r&&f.current?.focus()},[r]);let p=(0,X.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``))i(!1),d(``);else{l(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){d(a.error||n(`prov.saveFailed`));return}d(``),i(!1)}finally{l(!1)}}},[a,e.name,e.note,t,s,n]);return r?(0,Z.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Z.jsx)(`textarea`,{ref:f,className:`pws-notes-textarea`,value:a,onChange:e=>o(e.target.value),onBlur:()=>void p(),onKeyDown:t=>{t.key===`Escape`&&(o(e.note??``),d(``),i(!1))},placeholder:n(`pws.notePlaceholder`),rows:3,disabled:s}),u?(0,Z.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:u}):null]}):(0,Z.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Z.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),d(``),i(!0))},disabled:!t,children:e.note||(0,Z.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function ch(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function lh(e,t){let n=ch(e);for(let r of t)if(r!==e&&ch(r)===n)return!0;return!1}function uh({row:e,disambiguate:t,copied:n,isDefault:r,selected:i,action:a,disabled:o,onCopy:s,onRemove:l}){let u=c(),d=u(a===`delete`?`models.customDelete`:`models.hide`);return(0,Z.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:s,title:e.namespaced,"aria-label":u(n?`pws.modelCopied`:`pws.copyModelId`),children:(0,Z.jsx)(`span`,{className:`pws-model-id`,children:t?e.namespaced:e.id})}),r&&(0,Z.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}),i&&(0,Z.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}),a&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:e=>l(e.currentTarget),disabled:o,"aria-label":`${d}: ${e.namespaced}`,title:`${d}: ${e.namespaced}`,children:a===`delete`?(0,Z.jsx)(ge,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Z.jsx)(it,{style:{width:13,height:13},"aria-hidden":`true`})})]})}var dh=300;function fh(e){return(0,Z.jsx)(ph,{...e},JSON.stringify([e.apiBase,e.item.name]))}function ph({item:t,apiBase:n,availableModels:r,selectedModels:i,modelRows:a,modelRevision:o,modelRowsReady:s,modelsLoading:l=!1,modelsLoadFailed:u=!1,needsReauth:d=!1,onRetryModels:f,onOpenAccounts:p,onOpenModels:m}){let h=c(),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(0),w=JSON.stringify([n,t.name,o,S]),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)(null),F=(0,X.useRef)(null),I=(0,X.useRef)(!1),L=(0,X.useRef)(!0),R=(0,X.useRef)(o),z=(0,X.useRef)(null),B=(0,X.useRef)(null),V=(0,X.useRef)(null),H=T?.key===w&&D!==w,U=a!==null&&s&&!l&&!u&&H,W=U&&(!j||o!==j.revision),ee=k||!!j&&!W,te=(a??[]).filter(e=>e.provider===t.name),ne=te.some(e=>e.initialSelectionPending),G=!U||ee||ne,K=T?.rows.filter(e=>e.provider===t.name)??[],re=new Set(i),q=[...r,...t.models??[],...K.map(e=>e.modelId),...t.defaultModel?[t.defaultModel]:[]],ie=b.trim(),ae=!!ie&&(q.includes(ie)||lh(ie,q)),oe=te.filter(e=>!e.disabled),se=Ef(oe),ce=Of(v,oe),le=Df(oe,ce),ue=g.trim().toLowerCase(),J=le.filter(e=>[e.id,e.namespaced].some(e=>e.toLowerCase().includes(ue))),de=new Map;for(let e of oe)de.set(e.id,(de.get(e.id)??0)+1);(0,X.useEffect)(()=>{R.current=o},[o]),(0,X.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,X.useEffect)(()=>{let t=!1,r=e(2e4);return fetch(`${n}/api/custom-models`,{signal:r.signal}).then(zn).then(vm).then(e=>{t||(E({key:w,rows:e}),O(null))}).catch(()=>{t||O(w)}).finally(()=>r.clear()),()=>{t=!0,r.controller.abort(),r.clear()}},[n,w]),(0,X.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,a]);let fe=()=>{C(e=>e+1),f?.()},pe=async e=>{try{if(await navigator.clipboard.writeText((de.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{}},me=e=>e.custom===!0&&e.native!==!0&&K.some(t=>t.id===e.customId&&t.provider===e.provider&&t.modelId===e.id),he=e=>!U||e.initialSelectionPending?null:e.custom?me(e)?`delete`:null:e.native!==!0&&K.some(t=>t.modelId===e.id)?null:`hide`,ge=e=>{L.current?(M({...e,revision:R.current}),A(!1),fe()):f?.()},_e=async()=>{if(G||I.current||!ie||ae)return;I.current=!0,A(!0),M(null);let r=e(6e4),i={outcome:`unconfirmed`,refreshPending:!1};try{let e=await fetch(`${n}/api/custom-models`,{method:`POST`,signal:r.signal,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t.name,modelId:ie})});if(e.status===201){let n=await zn(e),r=ym(n,t.name,ie);if(T?.rows.some(e=>e.id===r.id))throw Error(`Reused custom identity`);i={outcome:`saved`,created:r,refreshPending:bm(n)},L.current&&x(``)}else e.status>=400&&e.status<500&&(i={outcome:`rejected`,refreshPending:!1})}catch{}finally{r.clear(),ge(i)}},ve=async(t,r)=>{let i=he(t);if(G||I.current||!i)return;if(I.current=!0,!await Nu({message:h(i===`delete`?`models.customDeleteConfirm`:`models.hideConfirm`,{name:t.namespaced}),confirmLabel:h(i===`delete`?`common.delete`:`common.ok`),tone:`danger`})){I.current=!1;return}A(!0),M(null),V.current={button:r,retained:document.activeElement===r};let a=e(6e4),o={outcome:`unconfirmed`,refreshPending:!1};try{let e=i===`delete`?await fetch(`${n}/api/custom-models/${encodeURIComponent(t.customId)}`,{method:`DELETE`,signal:a.signal}):await Cf(n,`models`,t.provider,[{id:t.id,native:t.native===!0}],!1,(e,t)=>fetch(e,{...t,signal:a.signal}));if(e.ok){let t=await zn(e);t&&typeof t==`object`&&!Array.isArray(t)&&`ok`in t&&t.ok===!0&&(o={outcome:i===`delete`?`deleted`:`hidden`,refreshPending:bm(t)})}else e.status>=400&&e.status<500&&(o={outcome:`rejected`,refreshPending:!1})}catch{}finally{a.clear(),ge(o)}},ye=j?.created&&W&&te.some(e=>e.customId===j.created?.id&&e.disabled),be=j&&(j.refreshPending||u||D===w),xe=j?j.outcome===`unconfirmed`?h(`pws.modelMutationUnconfirmed`):j.outcome===`rejected`?h(`models.customSaveFailed`):j.outcome===`saved`?h(be?`pws.modelSavedRefreshPending`:ye?`pws.modelSavedHidden`:`pws.modelSaved`):h(be?`pws.modelRemovedRefreshPending`:j.outcome===`deleted`?`pws.modelDefinitionDeleted`:`pws.modelHidden`):null;return(0,Z.jsxs)(`div`,{className:`pws-section`,children:[(0,Z.jsxs)(`div`,{className:`pws-section-head`,children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:h(`pws.tab.models`)}),a!==null&&(0,Z.jsx)(`span`,{className:`muted`,children:h(`pws.modelsAvailable`,{count:oe.length})})]}),(0,Z.jsx)(`div`,{className:`row`,children:(0,Z.jsx)(`button`,{ref:B,type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:h(`pws.manageModelVisibility`)})}),d&&(0,Z.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,Z.jsx)(`span`,{children:h(`pws.modelsNeedsReauth`)}),p&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:h(`pws.tab.accounts`)})]}),s&&r.length===0&&oe.length>0&&(t.models?.length??0)>0&&!d&&(0,Z.jsx)(`p`,{className:`muted text-label`,children:h(`pws.modelsConfiguredFallback`)}),ne&&(0,Z.jsx)(`p`,{role:`status`,className:`muted`,children:h(`pws.modelSelectionPending`)}),(0,Z.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${t.name}`,children:h(`models.customAdd`)}),(0,Z.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,Z.jsx)(`input`,{id:`pws-custom-model-${t.name}`,className:`input`,value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&_e()},placeholder:h(`models.customFieldModelIdPlaceholder`),"aria-label":h(`models.customAdd`),disabled:k}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{_e()},disabled:G||!ie||ae,children:h(k?`models.customSaving`:`models.customAddBtn`)})]}),ae&&(0,Z.jsx)(`p`,{className:`muted text-label`,role:`status`,children:h(`pws.modelKnown`)}),xe&&(0,Z.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:xe}),ye&&be&&(0,Z.jsx)(`p`,{className:`muted text-label`,role:`status`,children:h(`pws.modelSavedHidden`)}),j?.refreshPending&&(0,Z.jsx)(`p`,{className:`muted text-label`,role:`status`,children:h(`codexAuth.catalogRefreshPending`)}),u||D===w?(0,Z.jsxs)(`div`,{className:`pws-inline-error`,role:`alert`,children:[(0,Z.jsx)(`span`,{children:h(u?`pws.modelsLoadFailed`:`pws.modelOwnershipFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:fe,disabled:k,children:h(`common.retry`)})]}):(!U||ee)&&(0,Z.jsx)(`p`,{className:`muted`,role:`status`,children:h(!s||l?`pws.modelsLoading`:`pws.modelOwnershipLoading`)}),j&&(j.outcome===`unconfirmed`||j.refreshPending)&&!u&&D!==w&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:fe,disabled:k,children:h(`common.retry`)}),se&&(0,Z.jsx)(`div`,{className:`row`,children:(0,Z.jsx)(kn,{on:v,onClick:()=>y(!v),label:h(`models.freeOnly`),showLabel:!0})}),(0,Z.jsx)(`input`,{ref:z,type:`search`,className:`input pws-model-search`,placeholder:h(`pws.modelSearchPlaceholder`),value:g,onChange:e=>_(e.target.value),"aria-label":h(`pws.modelSearchPlaceholder`)}),a!==null&&oe.length===0?(0,Z.jsx)(`p`,{className:`muted`,children:h(`pws.noModels`)}):J.length===0&&a!==null?(0,Z.jsx)(`p`,{className:`muted`,role:`status`,children:h(ce&&le.length===0?`models.noFreeMatch`:`pws.noModelMatch`)}):(0,Z.jsx)(`ul`,{className:`pws-model-list`,children:J.slice(0,dh).map(e=>(0,Z.jsx)(uh,{row:e,disambiguate:(de.get(e.id)??0)>1,copied:N===e.namespaced,isDefault:e.id===t.defaultModel,selected:e.native!==!0&&re.has(e.id),action:he(e),disabled:G,onCopy:()=>{pe(e)},onRemove:t=>{ve(e,t)}},e.namespaced))}),J.length>dh&&(0,Z.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:h(`pws.modelsTruncated`,{shown:String(dh),total:String(J.length)})})]})}function mh({item:e,usageTotals:t,quotaReport:n,currentQuotaReading:r,quotaIdentity:i,modelUsage:o,onRefreshQuota:s}){let l=c(),{locale:u}=a(),d=t?.requests!==void 0,[f,p]=(0,X.useState)(null),m=(0,X.useMemo)(()=>o?.length?o.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[o]),h=(0,X.useMemo)(()=>{if(!m.length)return;let e=0,t=!1;for(let n of m)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[m]);return(0,Z.jsxs)(`div`,{className:`pws-section`,children:[(0,Z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:l(`pws.usageLast30d`)}),d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":l(`pws.usageLast30d`),children:[(0,Z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Z.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Rp(h,u)}),(0,Z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:l(`pws.estimatedCost`)})]}),(0,Z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Z.jsx)(`span`,{className:`pws-usage-metric-value`,children:Ip(t?.requests,u)}),(0,Z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:l(`pws.metricRequests`)})]}),(0,Z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Z.jsx)(`span`,{className:`pws-usage-metric-value`,children:Lp(t?.totalTokens,u)}),(0,Z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:l(`pws.metricTokens`)})]})]}),(0,Z.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:l(`pws.costDisclaimer`)})]}):(0,Z.jsx)(`p`,{className:`muted`,children:l(`pws.usageUnavailable`)})]}),m.length>0&&(0,Z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Z.jsx)(`h3`,{className:`pws-section-title`,children:l(`pws.modelBreakdown`)}),(0,Z.jsx)(`div`,{className:`tbl-wrap`,children:(0,Z.jsxs)(`table`,{className:`pws-model-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:l(`pws.col.model`)}),(0,Z.jsx)(`th`,{className:`num`,children:l(`pws.col.cost`)}),(0,Z.jsx)(`th`,{className:`num`,children:l(`pws.col.tokens`)}),(0,Z.jsx)(`th`,{className:`num`,children:l(`pws.col.requests`)}),(0,Z.jsx)(`th`,{children:l(`pws.col.share`)})]})}),(0,Z.jsx)(`tbody`,{children:m.map(e=>{let t=e.model,n=f===t;return(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,Z.jsxs)(`td`,{className:`mono`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>p(n?null:t),children:e.model}),e.hasUnresolvedRequestedModel&&(0,Z.jsx)(`div`,{className:`muted pws-model-attribution`,children:l(`pws.unresolvedRequestedModel`)})]}),(0,Z.jsx)(`td`,{className:`num mono`,children:Rp(e.estimatedCostUsd,u)}),(0,Z.jsx)(`td`,{className:`num mono`,children:Lp(e.totalTokens,u)}),(0,Z.jsx)(`td`,{className:`num`,children:e.requests}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`div`,{className:`pws-share-bar`,children:(0,Z.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,Z.jsx)(`tr`,{className:`pws-model-detail`,children:(0,Z.jsx)(`td`,{colSpan:5,children:(0,Z.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:l(`pws.tokenInput`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[` `,Lp(e.inputTokens,u)]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:l(`pws.tokenOutput`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[` `,Lp(e.outputTokens,u)]})]})]})})})]},t)})})]})})]}),(0,Z.jsx)(Mm,{report:n,reading:r,onRefreshQuota:s},`${e.name}:${i??``}`)]})}function hh(e){if(typeof e!=`string`)return;let t=e.trim();return t.length<=64&&/^[a-z0-9_.-]+$/.test(t)?t:void 0}var gh=[`pro`,`max_5x`,`max_20x`,`team`,`enterprise`,`ultra`];function _h(e){let t=hh(e===`Ultra`?`ultra`:e);if(!t)return;let n=t.replace(/^(?:default_)?claude_/,``);return gh.some(e=>e===n)?n:t}function vh(e){let t=_h(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 yh={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 bh(e,t,n){let r=Object.hasOwn(yh,n.reason)?e(yh[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)})}function xh(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function Sh(e){return xh(e)??`account-…`}function Ch(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 wh({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,Z.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,Z.jsx)(pt,{width:10,height:10,"aria-hidden":`true`})}),(0,Z.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Z.jsx)(Je,{width:10,height:10,"aria-hidden":`true`})})]})}function Th({accountLabel:e,globalThreshold:t,override:n,disabled:r=!1,inputId:i,hintText:a,onChange:o}){let s=c(),l=(0,X.useRef)(!1),u=(0,X.useRef)(!1),[d,f]=(0,X.useState)(!1),p=n!==null,[m,h]=(0,X.useState)({override:n,draft:String(n??t)});m.override!==n&&h({override:n,draft:String(n??t)});let{draft:g}=m,_=e=>h(t=>({...t,draft:e})),v=()=>h(e=>({...e,draft:String(e.override??t)})),y=r||d,b=a??s(`accountPool.autoSwitchHint`),x=(0,X.useId)(),S=async e=>{if(!(r||u.current)){u.current=!0,f(!0);try{await o(e)}finally{v(),u.current=!1,f(!1)}}},C=async()=>{if(!p||r||u.current)return;let e=g.trim(),t=e===``?NaN:Number(e);!Number.isInteger(t)||t<0||t>100?v():t!==n&&await S(t)},w=e=>{if(r||u.current)return;let t=Ch(g,e,0,100);_(t);let i=Number(t);i!==n&&S(i)};return(0,Z.jsxs)(`div`,{className:`codex-account-auto-switch`,title:b,"aria-busy":d,"aria-disabled":y,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(l.current?l.current=!1:C())},children:[(0,Z.jsx)(`label`,{className:`codex-account-auto-switch-label`,htmlFor:p?i:void 0,children:s(`accountPool.autoSwitchThreshold`)}),p&&(0,Z.jsxs)(`span`,{className:`codex-account-auto-switch-input-wrap`,children:[(0,Z.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:g,readOnly:y,"aria-disabled":y,"aria-label":s(`accountPool.autoSwitchThresholdAria`,{email:e}),"aria-describedby":x,onChange:e=>{y||_(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||y||(e.key===`Enter`?(e.preventDefault(),C()):e.key===`Escape`&&(e.preventDefault(),v()))}}),(0,Z.jsx)(`span`,{className:`codex-account-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Z.jsx)(wh,{disabled:r&&!d,incrementLabel:s(`codexAuth.autoSwitchThresholdInc`),decrementLabel:s(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>w(1),onDecrement:()=>w(-1)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`toggle codex-account-auto-switch-toggle ${p?`on`:``}`,disabled:r&&!d,"aria-disabled":y,"aria-pressed":p,"aria-label":s(`accountPool.autoSwitchOverrideAria`,{email:e}),"aria-describedby":x,onPointerDownCapture:()=>{l.current=!0},onPointerUp:()=>{l.current=!1},onPointerCancel:()=>{l.current=!1},onClick:()=>{l.current=!1,S(p?null:t)},children:(0,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsx)(`span`,{id:x,className:`sr-only`,children:b})]})}function Eh(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Dh(e){let t=Eh(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function Oh(e){return e===`reauth_required`}function kh(e){return!!e?.needsReauth||Oh(e?.health?.status)}function Ah(e){return e===`cooldown`}function jh(e){return e===`warning`||e===`reauth_required`}function Mh(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 Nh(e,t){let n=Mh(t);return n?e(n):null}function Ph(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):Sh(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 Fh(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return Ih(e)}function Ih(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 Lh(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}function Rh({title:e,meta:t,actions:n,children:r,className:i,bodyClassName:a,labelledBy:o,as:s=`section`}){let c=(0,X.useId)(),l=o??c;return(0,Z.jsxs)(s,{className:Y(`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,Z.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,Z.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,Z.jsx)(`span`,{className:`text-[12px] font-normal text-fg-subtle tabular-nums`,children:t})]}),n&&(0,Z.jsx)(`div`,{className:`ml-auto flex flex-wrap items-center justify-end gap-1.5`,children:n})]}),(0,Z.jsx)(`div`,{className:Y(`acc-panel__body flex min-w-0 flex-col rounded-[8px] bg-bg ring-1 ring-line`,a),children:r})]})}var zh={info:`text-fg-muted`,warn:`text-warning`,err:`text-danger`,ok:`text-success`};function Bh({tone:e=`info`,children:t,action:n,role:r,className:i}){let a=e===`ok`?ut:e===`info`?q:at;return(0,Z.jsxs)(`div`,{role:r,className:Y(`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,Z.jsx)(`span`,{className:Y(`mt-px shrink-0 [&_svg]:size-4`,zh[e]),"aria-hidden":`true`,children:(0,Z.jsx)(a,{})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 [overflow-wrap:anywhere]`,children:t}),n&&(0,Z.jsx)(`div`,{className:`-my-1 flex shrink-0 flex-wrap items-center gap-1.5`,children:n})]})}function Vh({tone:e}){return(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`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 Hh({open:e,controls:t,name:n,onToggle:r,className:i}){let a=c()(`accountsV2.about`,{name:n});return(0,Z.jsx)(`button`,{type:`button`,"aria-expanded":e,"aria-controls":t,"aria-label":a,title:a,onClick:r,className:Y(`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,Z.jsx)(q,{"aria-hidden":`true`})})}function Uh({id:e,open:t,children:n,className:r}){return(0,Z.jsx)(`div`,{id:e,hidden:!t,className:Y(`acc-help rounded-[8px] bg-surface-2/60 px-3 py-2.5 text-[13px] leading-[19px] text-fg-muted`,r),children:n})}function Wh(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t===127})}function Gh(e,t){let n=e.trim();return n.length>80||Wh(n)?t(`prov.aliasInvalid`):null}var Kh=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,deviceCode:``,instructions:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function qh(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 Jh({id:e,error:t,onIdChange:n,onStartOAuth:r,onStartDeviceOAuth:i,onClose:a}){let o=c();return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h3`,{style:{marginBottom:4},children:o(`codexAuth.addTitle`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:o(`codexAuth.addPickDesc`)}),(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:o(`codexAuth.addIdLabel`)}),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,Z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Z.jsx)(wt,{width:20}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`title`,children:o(`codexAuth.oauthLogin`)}),(0,Z.jsx)(`div`,{className:`sub`,children:o(`codexAuth.oauthDesc`)})]})]})}),(0,Z.jsx)(`button`,{type:`button`,className:`list-row`,onClick:i,style:{marginBottom:8},children:(0,Z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Z.jsx)(Fe,{width:20}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`title`,children:o(`codexAuth.deviceLogin`)}),(0,Z.jsx)(`div`,{className:`sub`,children:o(`codexAuth.deviceDesc`)})]})]})}),t&&(0,Z.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,style:{width:`100%`},children:o(`codexAuth.cancel`)})]})}var Yh=2500;function Xh(){let[e,t]=(0,X.useState)(null),n=(0,X.useRef)(null),r=(0,X.useRef)(0),i=(0,X.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,X.useEffect)(()=>i,[i]),{outcomeFor:(0,X.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,X.useCallback)((e,a)=>{let o=++r.current;Fh(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)},Yh))})},[i])}}function Zh(e){try{let t=new URL(e).protocol;return t===`https:`||t===`http:`}catch{return!1}}function Qh({url:e,openLabel:t}){let n=c(),{outcomeFor:r,copy:i}=Xh();if(!e)return null;let a=r(e),o=n(a===`copied`?`prov.linkCopied`:a===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`),s=Zh(e);return(0,Z.jsxs)(`div`,{className:`login-url-block`,children:[(0,Z.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,Z.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(e,e),children:[(0,Z.jsx)(Fe,{style:{width:13,height:13},"aria-hidden":`true`}),(0,Z.jsx)(`span`,{"aria-live":`polite`,children:o})]}),s&&(0,Z.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,Z.jsx)(dt,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t??n(`prov.didntOpen`)]})]})]})}function $h({hint:e,paste:t}){let n=c(),r=Xh(),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`),l=i||e.browserLaunch===`skipped`?n(`prov.openSignInPage`):void 0,u=i&&Zh(a)?()=>{r.copy(i,i),window.open(a,`_blank`,`noopener,noreferrer`)}:null;return(0,Z.jsxs)(`div`,{className:`login-hint`,children:[e.browserLaunch===`failed`&&a&&(0,Z.jsx)(`div`,{className:`notice-warn login-hint-launch-failed`,role:`status`,children:n(`prov.browserLaunchFailed`)}),i&&(0,Z.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,Z.jsx)(`span`,{className:`text-label`,children:n(`prov.deviceCode`)}),(0,Z.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:i}),(0,Z.jsx)(`button`,{type:`button`,className:u?`btn btn-ghost btn-sm`:`btn btn-primary btn-sm`,onClick:()=>r.copy(i,i),children:(0,Z.jsx)(`span`,{"aria-live":`polite`,children:s})}),u&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm login-hint-copy-open`,onClick:u,children:n(`prov.copyCodeAndOpen`)})]}),(0,Z.jsx)(Qh,{url:a,openLabel:l}),e.instructions&&(0,Z.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&!i&&(0,Z.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,Z.jsx)(`div`,{className:`muted text-label`,children:n(`prov.pasteRedirectHint`)}),(0,Z.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,Z.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,Z.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,Z.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function eg({reauthAccountId:e,authUrl:t,deviceCode:n,instructions:r,browserLaunch:i,manualCode:a,manualCodeBusy:o,manualCodeWaiting:s,statusNotice:l,statusTone:u,flowId:d,error:f,onSwitchToDevice:p,onManualCodeChange:m,onSubmitManualCode:h,onClose:g}){let _=c();return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h3`,{style:{marginBottom:4},children:_(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:_(`codexAuth.oauthWaiting`)}),(0,Z.jsx)($h,{hint:{url:t,deviceCode:n,instructions:r,browserLaunch:i},paste:{value:a,busy:o,disabled:o||s||!a.trim()||!d,submittingLabel:_(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:m,onSubmit:h}}),l&&(0,Z.jsx)(`div`,{className:u===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:l}),f&&(0,Z.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:f}),p&&!n&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,style:{width:`100%`,marginTop:8},children:_(`codexAuth.deviceLogin`)}),(0,Z.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,Z.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:g,style:{width:`100%`},children:_(`codexAuth.cancel`)})]})}var tg=`ocx.oauth.openBrowser`;function ng(){try{let e=window.localStorage.getItem(tg);return e===`0`?!1:e===`1`||void 0}catch{return}}function rg(){let e=ng();return e===void 0?{}:{openBrowser:e}}function ig(e){try{window.localStorage.setItem(tg,e?`1`:`0`)}catch{}}function ag(e){return e===`started`||e===`failed`||e===`skipped`?e:void 0}function og(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 sg=3e5,cg=96e4;function lg({apiBase:e,reauthAccountId:t,ui:n,dispatch:r,t:i}){let a=(0,X.useRef)(!0),o=(0,X.useRef)(0),s=(0,X.useRef)(!1),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(n.manualCodeState),p=(0,X.useRef)(null),m=(0,X.useRef)(null),h=(0,X.useRef)(()=>{}),g=(0,X.useRef)(()=>{}),_=n.manualCodeState===`submitting`,v=n.manualCodeState===`waiting`;(0,X.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,X.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let y=(0,X.useCallback)(()=>{c.current&&=(c.current(),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),b=(0,X.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),x=(0,X.useCallback)(async()=>{b();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-login-hint`,authUrl:``}),y(),p.current?.abort(),p.current=null,t&&await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})},[e,b,r,y]);(0,X.useEffect)(()=>(a.current=!0,()=>{b(),a.current=!1,m.current=null,p.current?.abort(),p.current=null;let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),y(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,b,r,y]);let S=(0,X.useCallback)((e,t)=>{h.current=e,g.current=t},[]),C=(0,X.useCallback)(()=>{n.step===`oauth-waiting`&&x(),g.current()},[n.step,x]),w=(0,X.useCallback)(async(n,m)=>{b(),d.current=null,r({type:`set-flow-id`,flowId:null});let _=new AbortController;p.current?.abort(),p.current=_,r({type:`reset-oauth-start`}),o.current=0;try{let p=t??n?.trim()??``,v=m?.device===!0,S=()=>fetch(`${e}/api/codex-auth/login`,{signal:_.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...rg(),...v?{device:!0}:{},...t?{id:t,reauth:!0}:p?{id:p}:{}})}),C=await S();if(!a.current)return;if(C.status===409){if(await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),!a.current||_.signal.aborted)return;if(C=await S(),C.status===409){r({type:`set-error`,error:i(`codexAuth.oauthAlreadyInProgress`)});return}}let w=await zn(C,i(`modal.networkError`));if(!a.current||!w)return;if(w.url){d.current=w.flowId??null,r({type:`set-flow-id`,flowId:w.flowId??null}),r({type:`set-login-hint`,authUrl:w.url,deviceCode:w.deviceCode,instructions:w.instructions,browserLaunch:ag(w.browserLaunch)}),r({type:`set-step`,step:`oauth-waiting`}),y();let n=w.flowId??``,m=t?`&reauth=1`:``,_=n?`${e}/api/codex-auth/login-status?flowId=${encodeURIComponent(n)}${p?`&accountId=${encodeURIComponent(p)}`:``}${m}`:`${e}/api/codex-auth/login-status`,S=new AbortController;u.current=S,c.current=Ru(async()=>{if(s.current||S.signal.aborted)return;s.current=!0;let e=AbortSignal.any([S.signal,AbortSignal.timeout(1e4)]);try{let n=await Bn(await fetch(_,{signal:e}));if(!a.current||S.signal.aborted)return;if(!n){o.current+=1,o.current>=3&&r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthStatusRetrying`),statusTone:`warn`});return}if(o.current=0,f.current===`waiting`?r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}):r({type:`set-status-notice`,statusNotice:``,statusTone:`ok`}),n.status===`done`){if(y(),b(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(og(n)),g.current()}else(n.status===`error`||n.status===`expired`)&&(y(),b(),d.current=null,r({type:`set-flow-id`,flowId:null}),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:n.error??i(`codexAuth.loginFailed`)})))}catch(e){if(!a.current||S.signal.aborted||e instanceof Error&&e.name===`AbortError`)return;o.current+=1,o.current>=3&&r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthStatusRetrying`),statusTone:`warn`})}finally{s.current=!1}},2e3),l.current=setTimeout(()=>{c.current&&(b(),x(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},v?cg:sg)}w.error&&!w.url&&r({type:`set-error`,error:w.error})}catch(e){a.current&&!(e instanceof Error&&e.name===`AbortError`)&&r({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[e,x,b,r,t,y,i]);return(0,X.useEffect)(()=>{t?m.current!==t&&(m.current=t,w()):m.current=null},[t,w]),{manualCodeBusy:_,manualCodeWaiting:v,bindCallbacks:S,closeModal:C,startOAuth:w,submitManualCode:(0,X.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(t&&s&&!_&&!v){r({type:`set-manual-code-state`,manualCodeState:`submitting`}),r({type:`set-status-notice`,statusNotice:``,statusTone:`ok`});try{let n=await fetch(`${e}/api/codex-auth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t,input:s})});if(!a.current)return;if(!n.ok){r({type:`set-error`,error:i(`prov.pasteFail`,{error:(await n.json().catch(()=>({}))).error??n.statusText})}),r({type:`set-manual-code-state`,manualCodeState:`idle`});return}r({type:`oauth-code-submitted`}),r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}),o.current=0}catch{a.current&&(r({type:`set-error`,error:i(`modal.networkError`)}),r({type:`set-manual-code-state`,manualCodeState:`idle`}))}}},[e,r,_,v,i,n.manualCode])}}function ug({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=c(),[a,o]=(0,X.useReducer)(qh,r,Kh),s=(0,X.useRef)(null),l=(0,X.useRef)(null),{manualCodeBusy:u,manualCodeWaiting:d,bindCallbacks:f,closeModal:p,startOAuth:m,submitManualCode:h}=lg({apiBase:e,reauthAccountId:r,ui:a,dispatch:o,t:i});(0,X.useEffect)(()=>{f(n,t)},[f,n,t]),(0,X.useEffect)(()=>{s.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(),()=>{s.current?.focus()}},[]);let g=(0,X.useCallback)(e=>{e.preventDefault(),p()},[p]),_=i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,Z.jsx)(`dialog`,{ref:l,"aria-label":_,className:`modal-overlay`,onCancel:g,children:(0,Z.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,Z.jsx)(Jh,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{m(a.id)},onStartDeviceOAuth:()=>{m(a.id,{device:!0})},onClose:p}),a.step===`oauth-waiting`&&(0,Z.jsx)(eg,{reauthAccountId:r,authUrl:a.authUrl,deviceCode:a.deviceCode,instructions:a.instructions,browserLaunch:a.browserLaunch,manualCode:a.manualCode,manualCodeBusy:u,manualCodeWaiting:d,statusNotice:a.statusNotice,statusTone:a.statusTone,flowId:a.flowId,error:a.error,onSwitchToDevice:()=>{m(a.id,{device:!0})},onManualCodeChange:e=>o({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{h()},onClose:p})]})})}var dg=[2,1,0,-1,-2],fg=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function pg(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function mg(e){let t=pg(e);return t>0?`+${t}`:String(t)}function hg(e){return fg.has(e)}function gg(e){return fg.get(e)??null}function _g(e,t){let n=pg(t);return e(`accountPool.priorityOption`,{name:e(gg(n)??`accountPool.priorityCustom`),value:mg(n)})}var vg=[`quota`,`round-robin`,`fill-first`,`reset-first`],yg=[`five-hour`,`weekly`,`max-utilization`],bg=`quota`,xg=`five-hour`,Sg=new Set(vg),Cg=new Set(yg);function wg(e){return typeof e==`string`&&Sg.has(e)?e:bg}function Tg(e){return typeof e==`string`&&Cg.has(e)?e:xg}function Eg(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Dg(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}var Og=`openai`;function kg(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:wg(r.strategy??n?.strategy),stickyLimit:Eg(r.stickyLimit??n?.stickyLimit),autoSwitchThreshold:typeof i==`number`?i:null,quotaWindow:(r.quotaWindow??n?.quotaWindow)===void 0||r.quotaWindow===null?null:Tg(r.quotaWindow??n?.quotaWindow),nativeMessages:km(t)?Object.hasOwn(r,`nativeMessages`)?r.nativeMessages===!0:n?.nativeMessages??!0:null,...r.warning===`config_bookkeeping_failed`?{warning:r.warning}:{}}}function Ag(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},...km(e)&&t.nativeMessages!==void 0?{nativeMessages:t.nativeMessages}:{}}}async function jg(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?kg(await i.json(),t):null}catch{return null}}var Mg=class extends Error{code=`config_save_state_unknown`;constructor(){super(`config_save_state_unknown`),this.name=`PoolSettingsSaveStateUnknownError`}};async function Ng(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(Ag(t,n))});if(!a.ok){if(km(t)&&a.status===409&&(await a.json().catch(()=>null))?.code===`config_save_state_unknown`)throw new Mg;return null}return kg(await a.json().catch(()=>({})),t,n)}catch(e){if(e instanceof Mg)throw e;return null}}async function Pg(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};let r=await Ng(e,Og,{strategy:t.strategy,stickyLimit:t.stickyLimit},n);return r?{ok:!0,strategy:r.strategy,stickyLimit:r.stickyLimit}:{ok:!1}}var Fg=1e4;function Ig(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Lg(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Rg(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function zg(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Bg(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Vg(e,t,n){if(e<=0){let t=Rg(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Lg(t)??Rg(0,n)}}async function Hg(e,t,n=(e,t)=>fetch(e,t),r=Fg){return!Number.isInteger(t)||t<0||t>100?!1:await Ng(e,Og,{threshold:t},(e,t)=>n(e,t),{signal:AbortSignal.timeout(r)})!==null}var Ug={short:90,long:98};function Wg(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}:{...Ug}}var Gg=3e4,Kg=new Map;function qg(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:null}function Jg(t,n=!0){let r=Kg.get(t),[i,a]=(0,X.useState)(()=>r?.accounts??[]),o=dn(Hr(t,`codex`),[t],async e=>Vr(await fetch(`${t}/api/usage?range=30d&surface=codex`,{signal:e}),`account usage load failed`),{enabled:n}),[s,c]=(0,X.useState)(()=>r?.activeId??null),[l,u]=(0,X.useState)(()=>r==null?`loading`:`ready`),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(0),[k,A]=(0,X.useState)(()=>r!=null),[j,M]=(0,X.useState)(0),N=(0,X.useRef)(null);N.current===null&&(N.current=new Set);let P=(0,X.useRef)(null),F=(0,X.useRef)(0),I=(0,X.useRef)(null),L=(0,X.useRef)(null);L.current===null&&(L.current=new Set);let R=(0,X.useRef)(null),z=(0,X.useRef)(null),B=(0,X.useRef)(!!r?.accounts.length),V=(0,X.useRef)(r!=null),H=(0,X.useRef)(null),U=(0,X.useRef)(null),W=(0,X.useRef)(null),ee=(0,X.useRef)(!1),te=(0,X.useCallback)(e=>(L.current.add(e),()=>{L.current.delete(e)}),[]),ne=(0,X.useCallback)(()=>Bg(R.current?.value),[]),G=(0,X.useCallback)(()=>R.current?.value,[]),K=(0,X.useCallback)(async(n=!1,r={})=>{let i=++F.current,o=r.validatePending===!0,s=Kg.get(t)?.accounts.length??0,l=e(o?3e4+12e4*Math.max(1,s):2e4),d=o?{}:null;d&&(N.current.add(d),M(N.current.size)),O(e=>e+1);try{let e=[...L.current],r=new Map;for(let t of e)r.set(t,t.beginActiveRead());!n&&!V.current&&u(`loading`);let s=null,d,p=(async()=>{try{let e=await fetch(`${t}/api/codex-auth/accounts${o?`/refresh`:n?`?refresh=1`:``}`,{method:o?`POST`:`GET`,signal:l.signal});if(!e.ok)throw Error(`account load failed`);let r=await e.json();return F.current===i&&(s=(r.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel,n=Pe(e.quota);return{...e,...t?{logLabel:t}:{},priority:pg(e.priority),autoSwitchThresholdOverride:qg(e.autoSwitchThresholdOverride),quotaAutoRefresh:e.quotaAutoRefresh??{...n,fiveHourEnabled:!1,weeklyEnabled:!1}}}),a(s),B.current=s.length>0,V.current=!0,u(`ready`),f(!1)),!0}catch{return!1}})(),m=(async()=>{try{let n=await fetch(`${t}/api/codex-auth/active`,{signal:l.signal});if(!n.ok)throw Error(`active account load failed`);let a=await n.json();if(F.current===i){let t=a.activeCodexAccountId??null,n=I.current;n&&n.staleReadsRemaining>0&&t!==n.id?--n.staleReadsRemaining:(I.current=null,d=t,c(t)),R.current={value:a},E(typeof a.pinnedAccountId==`string`?a.pinnedAccountId:null);for(let t of e)t.acceptActiveRead(a,r.get(t))}return!0}catch{if(F.current===i)for(let t of e)t.rejectActiveRead();return!1}})(),[h,g]=await Promise.all([p,m]);if(F.current!==i)return!1;if(h){u(`ready`),V.current=!0;let e=Kg.get(t);return Kg.set(t,{accounts:s??e?.accounts??[],activeId:d===void 0?e?.activeId??null:d}),g}return V.current||u(`error`),f(!0),!1}finally{l.clear(),d&&(N.current.delete(d),M(N.current.size)),O(e=>Math.max(0,e-1)),A(!0)}},[t]);(0,X.useEffect)(()=>{n&&P.current!==t&&(P.current=t,Promise.resolve().then(()=>{K()}))},[t,n,K]);let re=i.some(e=>e.hasCredential&&!e.quota);(0,X.useEffect)(()=>{if(!n||!re||j>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{N.current.size===0&&K(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[n,re,j,K]),(0,X.useEffect)(()=>{if(!(!n||j>0))return Ru(()=>{N.current.size===0&&K()},Gg)},[n,K,j]);let q=(0,X.useCallback)(()=>{let e={};return N.current.add(e),M(N.current.size),e},[]),ie=(0,X.useCallback)(e=>{N.current.delete(e)&&M(N.current.size)},[]),ae=(0,X.useCallback)(async(e,n)=>{if(z.current||U.current)return{ok:!1,reason:`busy`};z.current=e??`__main__`,m(e??`__main__`);let r=`request`;try{let i=await fetch(`${t}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:e,...n?{expectedPinnedAccountId:n.expectedPinnedAccountId}:{}})});if(!i.ok)throw(await i.json().catch(()=>({}))).code===`account_pin_changed`&&(r=`pin_changed`),Error(`account switch failed`);let a=(await i.json().catch(()=>({}))).activeCodexAccountId??e;return I.current={id:a??null,staleReadsRemaining:1},c(a??null),E(a??null),K(),{ok:!0,activeId:a??null}}catch{return e===null&&(I.current=null,await K()),{ok:!1,reason:r}}finally{z.current=null,m(null)}},[t,K]),oe=(0,X.useCallback)(async(e,n)=>{try{return(await fetch(`${t}/api/codex-auth/accounts/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e,alias:n.trim()})})).ok?(await K(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[t,K]),se=(0,X.useCallback)(async(e,n)=>{if(H.current)return{ok:!1,reason:`busy`};H.current={accountId:e},g(e);try{let r=await fetch(`${t}/api/codex-auth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e,paused:n})});if(!r.ok)return{ok:!1,reason:`request`};let i=await r.json().catch(()=>({})),o=i&&typeof i==`object`?i:{};if(a(t=>t.map(t=>t.id===e||e===`__main__`&&t.isMain?{...t,paused:n}:t)),Object.prototype.hasOwnProperty.call(o,`activeCodexAccountId`)){let e=o.activeCodexAccountId??null;I.current={id:e,staleReadsRemaining:1},c(e)}return n&&E(t=>t===e?null:t),K(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{H.current=null,g(null)}},[t,K]),ce=(0,X.useCallback)(async(e,n)=>{if(U.current||z.current)return{ok:!1,reason:`busy`};U.current={accountId:e},v(e);try{let r=await fetch(`${t}/api/codex-auth/accounts/priority`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e,priority:n})});if(!r.ok)return{ok:!1,reason:`request`};let i=await r.json().catch(()=>({})),o=pg((i&&typeof i==`object`?i:{}).priority??n);return a(t=>t.map(t=>t.id===e||e===`__main__`&&t.isMain?{...t,priority:o}:t)),E(null),I.current=null,K(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{U.current=null,v(null)}},[t,K]),le=(0,X.useCallback)(async(e,n)=>{if(W.current)return{ok:!1,reason:`busy`};W.current={accountId:e},b(e);try{let r=await fetch(`${t}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e,threshold:n})});if(!r.ok)return{ok:!1,reason:`request`};let i=await r.json().catch(()=>({})),o=i&&typeof i==`object`?i:{},s=Object.prototype.hasOwnProperty.call(o,`autoSwitchThresholdOverride`)?qg(o.autoSwitchThresholdOverride):n;return a(t=>t.map(t=>t.id===e||e===`__main__`&&t.isMain?{...t,autoSwitchThresholdOverride:s}:t)),K(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{W.current=null,b(null)}},[t,K]),ue=(0,X.useCallback)(async(e,n,r)=>{if(ee.current)return{ok:!1,reason:`busy`};ee.current=!0,S(e);try{return(await fetch(`${t}/api/codex-auth/accounts/credits`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).ok?(a(e=>e.map(r)),K(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}finally{ee.current=!1,S(null)}},[t,K]),J=(0,X.useCallback)((e,t)=>ue(e,{id:e,creditsAfterLimit:t},n=>n.id===e||e===`__main__`&&n.isMain?{...n,creditsAfterLimit:t}:n),[ue]),de=(0,X.useCallback)(e=>ue(`*`,{all:e},t=>({...t,creditsAfterLimit:e})),[ue]),fe=(0,X.useCallback)(async()=>{if(H.current)return{ok:!1,reason:`busy`};H.current=`bulk`,w(!0);try{let e=await fetch(`${t}/api/codex-auth/accounts/pause-exhausted`,{method:`PUT`});if(!e.ok)return{ok:!1,reason:`request`};let n=await e.json().catch(()=>({})),r=n&&typeof n==`object`?n:{},i=new Set(r.pausedAccountIds??[]);if(a(e=>e.map(e=>i.has(e.id)||i.has(`__main__`)&&e.isMain?{...e,paused:!0}:e)),Object.prototype.hasOwnProperty.call(r,`activeCodexAccountId`)){let e=r.activeCodexAccountId??null;I.current={id:e,staleReadsRemaining:1},c(e)}return E(e=>e!==null&&i.has(e)?null:e),K(),{ok:!0,pausedCount:r.pausedCount??i.size}}catch{return{ok:!1,reason:`request`}}finally{H.current=null,w(!1)}},[t,K]),pe=(0,X.useCallback)(async e=>{try{let n=await fetch(`${t}/api/codex-auth/accounts?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!n.ok)return{ok:!1,reason:`request`};let r=og(await n.json().catch(()=>({})));return await K(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[t,K]),me=(0,X.useCallback)(async()=>await K()?{ok:!0}:{ok:!1,reason:`reload`},[K]),he=s&&s!==`__main__`?i.find(e=>e.id===s):null,ge=i.find(e=>e.isMain),_e=he??ge,ve=!_e?.paused&&kh(_e);return{accounts:(0,X.useMemo)(()=>{let e=new Map((o.data?.accounts??[]).map(e=>[e.accountLogLabel,e]));return i.map(t=>{let n=t.isMain?`main`:t.logLabel,r=n?e.get(n):void 0;return r?{...t,usage30d:r}:t})},[i,o.data]),activeId:s,loadState:l,refreshing:D>0,refreshFailed:d,initialLoading:!k,switchingId:p,pauseUpdatingId:h,priorityUpdatingId:_,autoSwitchUpdatingId:y,creditsAfterLimitUpdatingId:x,pausingExhausted:C,activeNeedsReauth:ve,activePinnedId:T,load:K,switchAccount:ae,setAccountPaused:se,setAccountPriority:ce,setAccountAutoSwitchThreshold:le,setAccountCreditsAfterLimit:J,setAllCreditsAfterLimit:de,pauseExhaustedAccounts:fe,saveAlias:oe,removeAccount:pe,syncAfterAccountAdded:me,pauseRefresh:q,resumeRefresh:ie,subscribeLoadObserver:te,readLastThreshold:ne,readLastActive:G}}function Yg(t,n,r,i,a){let[o,s]=(0,X.useState)({apiBase:t,busy:!1}),c=(0,X.useRef)(null),l=(0,X.useRef)(0),u=(0,X.useEffectEvent)((e,t)=>{a?.onRead(e,t)}),d=a?.revision??0,f=(0,X.useRef)(null);o.apiBase!==t&&s({apiBase:t,busy:!1});let p=o.apiBase===t?o.visible:void 0,m=o.apiBase===t&&o.busy;return(0,X.useEffect)(()=>{let e=new AbortController;return c.current=e,()=>{e.abort(),f.current?.abort(),f.current=null}},[t]),(0,X.useEffect)(()=>{let n=new AbortController,r=e(15e3),i=l.current,a=fetch(`${t}/api/settings`,{signal:r.signal}).then(e=>{if(!e.ok)throw Error(`read`);return e.json()});return u(a,n.signal),a.then(e=>{n.signal.aborted||f.current||l.current!==i||e&&typeof e==`object`&&`showCodexCredits`in e&&typeof e.showCodexCredits==`boolean`&&s({apiBase:t,visible:e.showCodexCredits,busy:!1})}).catch(()=>{}).finally(()=>r.clear()),()=>{n.abort(),r.controller.abort(),r.clear()}},[t,d]),{visible:p,busy:m,toggle:async()=>{let a=c.current;if(p===void 0||m||f.current||!a||a.signal.aborted)return;let o=new AbortController;f.current=o;let u=e(15e3),d=()=>u.controller.abort();o.signal.addEventListener(`abort`,d,{once:!0});let h=()=>c.current===a&&!a.signal.aborted,g=!p;l.current+=1,s({apiBase:t,visible:g,busy:!0});try{let e;try{let n=await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:u.signal,body:JSON.stringify({showCodexCredits:g})});if(!n.ok)throw Error(`save`);let r=await n.json();if(typeof r?.showCodexCredits!=`boolean`)throw Error(`shape`);e=r.showCodexCredits}catch{h()&&(s({apiBase:t,visible:p,busy:!1}),r(i(`codexAuth.creditsToggleFailed`),`err`));return}if(!h())return;s({apiBase:t,visible:e,busy:!0}),r(i(e?`codexAuth.creditsShown`:`codexAuth.creditsHidden`),`ok`);try{let e=await n(!0);h()&&!e&&r(i(`codexAuth.quotaRefreshFailed`),`err`)}catch{h()&&r(i(`codexAuth.quotaRefreshFailed`),`err`)}}finally{u.clear(),o.signal.removeEventListener(`abort`,d),h()&&(f.current=null,s(e=>({...e,busy:!1})))}}}}var Xg=`https://auth.openai.com/codex/device`,Zg=2e3,Qg=1e4,$g=new Set([`identity_mismatch`,`credential_changed`,`native_main_unavailable`,`device_authorization_failed`,`publication_failed`,`reconciliation_failed`,`flow_in_progress`]);function e_(e){return typeof e==`string`&&$g.has(e)?e:`request_failed`}function t_(e){return typeof e==`string`&&e.startsWith(Xg)?e:``}function n_(e){return typeof e==`string`&&/^[A-Z0-9-]{1,16}$/i.test(e)?e:``}function r_(e,t){let[n,r]=(0,X.useState)({phase:`idle`}),i=(0,X.useRef)(null),a=(0,X.useRef)(null),o=(0,X.useRef)(null),s=(0,X.useRef)(null),c=(0,X.useRef)(!1),l=(0,X.useCallback)(()=>{s.current?.abort(),s.current=null},[]),u=(0,X.useCallback)(async()=>{let n=i.current;if(!n)l(),r({phase:`idle`});else{a.current=n;try{let a=await fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(n)}`,{method:`DELETE`}),o=await a.json().catch(()=>({}));if(c.current||i.current!==n)return;if(a.status===404&&o.code===`unknown_flow`){l(),i.current=null,r({phase:`failed`,code:`request_failed`});return}if(!a.ok||o.status!==`cancelled`&&o.status!==`succeeded`&&o.status!==`failed`)throw Error();l(),i.current=null,r(o.status===`failed`?{phase:`failed`,code:e_(o.code)}:{phase:o.status}),o.status===`succeeded`&&t()}catch{if(c.current||i.current!==n)return;r(e=>{if(c.current||i.current!==n)return e;let t=e.phase===`pending`||e.phase===`committing`?e:o.current;return t?.flowId===n?{...t,cancelFailed:!0}:e})}}},[e,t,l]),d=(0,X.useCallback)(async()=>{l(),i.current=null,a.current=null,o.current=null;let n=new AbortController;s.current=n;let u=()=>!n.signal.aborted&&!c.current&&s.current===n;r({phase:`starting`});let d;try{let t=await fetch(`${e}/api/codex-auth/main/reauth-device`,{method:`POST`,signal:n.signal}),i=await t.json().catch(()=>({}));if(!u())return;if(!t.ok){r({phase:`failed`,code:e_(i.code)});return}if(typeof i.flowId!=`string`||!i.flowId){r({phase:`failed`,code:`request_failed`});return}d=i.flowId}catch{u()&&r({phase:`failed`,code:`request_failed`});return}let f=d;i.current=f;let p=``,m=``;for(;u();){if(i.current!==f)return;try{let s=await fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(f)}`,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(Qg)])}),c=await s.json().catch(()=>({}));if(!u()||i.current!==f)return;if(!s.ok){if(s.status===404&&c.code===`unknown_flow`){l(),i.current=null,r({phase:`failed`,code:`request_failed`});return}let e=a.current===f;if(r(t=>!u()||i.current!==f||(t.phase===`pending`||t.phase===`committing`)&&t.flowId===f&&(e||t.cancelFailed)?t:{phase:`failed`,code:e_(c.code)}),!e)return}else if(p=t_(c.verificationUrl)||p,m=n_(c.deviceCode)||m,c.status===`pending`||c.status===`committing`){let e={phase:c.status,flowId:f,verificationUrl:p,deviceCode:m};o.current=e,r(t=>(t.phase===`pending`||t.phase===`committing`)&&t.flowId===f&&t.cancelFailed?{...e,cancelFailed:!0}:e)}else if(c.status===`succeeded`){i.current=null,r({phase:`succeeded`}),t();return}else if(c.status===`cancelled`){i.current=null,r({phase:`cancelled`});return}else if(c.status===`failed`){i.current=null,r({phase:`failed`,code:e_(c.code)});return}}catch{if(!u()||i.current!==f)return}await new Promise(e=>setTimeout(e,Zg))}},[e,t,l]);return(0,X.useEffect)(()=>(c.current=!1,()=>{c.current=!0,l();let t=i.current;i.current=null,t&&fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(t)}`,{method:`DELETE`}).catch(()=>{})}),[e,l]),{state:n,start:d,cancel:u}}var i_={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 a_(e){return(t,n)=>{let r=i_[e][t];for(let[e,t]of Object.entries(n??{}))r=r.split(`{${e}}`).join(String(t));return r}}var o_=`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(`.`),s_=class extends Error{code;constructor(e){super(e),this.code=e}};function c_(e){return e instanceof s_?e.code:`NETWORK_ERROR`}function l_(){throw new s_(`INVALID_RESPONSE`)}function u_(e){return!e||typeof e!=`object`||Array.isArray(e)?l_():e}function d_(e){return typeof e!=`string`||!e.trim()?l_():e}function f_(e){return e===null?null:d_(e)}function p_(e){return typeof e==`boolean`?e:l_()}function m_(e,t){return typeof e==`string`&&t.includes(e)?e:l_()}function h_(e){let t=u_(e);return{id:d_(t.id),label:d_(t.label),identityHint:d_(t.identityHint),state:m_(t.state,[`active`,`inactive`])}}function g_(e){let t=u_(e);if(!Array.isArray(t.profiles)||t.profiles.length>32)return l_();let n=t.profiles.map(h_),r=f_(t.activeProfileId);if(new Set(n.map(e=>e.id)).size!==n.length)return l_();let i=n.filter(e=>e.state===`active`);return(r===null?n.length!==0:i.length!==1||i[0].id!==r)?l_():{effectiveCodexHome:d_(t.effectiveCodexHome),activeProfileId:r,profiles:n}}function __(e){let t=u_(e);return{effectiveCodexHome:d_(t.effectiveCodexHome),activeProfileId:f_(t.activeProfileId),supported:p_(t.supported),authStatus:m_(t.authStatus,[`ok`,`missing`,`invalid`,`unreadable`]),keyStore:m_(t.keyStore,[`available`,`missing-key`,`unavailable`]),vaultStatus:m_(t.vaultStatus,[`ok`,`missing`,`invalid`]),recoveryPending:p_(t.recoveryPending)}}async function v_(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 s_(`INVALID_RESPONSE`)}if(n.throwIfAborted(),!a.ok){let e=o&&typeof o==`object`?o.code:void 0;throw new s_(typeof e==`string`&&o_.includes(e)?e:`INTERNAL_ERROR`)}return o}async function y_(e,t,n){let[r,i]=await Promise.allSettled([v_(e,``,t,void 0,n).then(g_),v_(e,`/doctor`,t,void 0,n).then(__)]);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 s_(`STATE_CHANGED`);return{doctor:i.value,list:r.value}}function b_(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 x_(e){let t=e.doctor;return!!e.list&&t.supported&&t.authStatus===`ok`&&t.keyStore===`available`&&t.vaultStatus!==`invalid`&&!t.recoveryPending}function S_(e,t){let n=e.doctor;return n.supported?t.kind===`recover`?n.recoveryPending:x_(e)&&!!e.list?.profiles.some(e=>e.id===t.target&&e.label===t.label&&e.state===`inactive`):!1}function C_(e,t){return e.doctor.effectiveCodexHome===t.doctor.effectiveCodexHome&&e.doctor.activeProfileId===t.doctor.activeProfileId&&e.doctor.recoveryPending===t.doctor.recoveryPending}async function w_(e,t,n,r){let i=u_(await v_(e,`/register`,n,{label:t.trim()},r)),a=d_(i.effectiveCodexHome);return h_(i.profile).state===`active`?a:l_()}async function T_(e,t,n,r,i){if(!n)throw new s_(`INVALID_REQUEST`);let a=u_(await v_(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 l_();if(t.kind===`switch`){let e=h_(a.activeProfile);if(e.id!==t.target||e.state!==`active`)return l_()}let o=t.kind===`recover`&&a.restartRequired===void 0&&a.recovered===!1?!1:p_(a.restartRequired);return{effectiveCodexHome:d_(a.effectiveCodexHome),restartRequired:o,...typeof a.recovered==`boolean`?{recovered:a.recovered}:{}}}var E_=2e4,D_=Symbol(`account-refresh-timeout`),O_=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=E_,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&&S_(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:c_(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 y_(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(D_)},this.accountRefreshTimeoutMs)});try{let t=await Promise.race([r,i]);this.current(e)&&(t===!1||t===D_)&&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 y_(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&&x_(e)&&await this.mutate(e,{label:t})}async confirm(){let{snapshot:e,action:t,confirmedStopped:n,refreshFailed:r}=this.state;e&&t&&n&&!r&&S_(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 y_(this.apiBase,r,this.fetchImpl);if(r.throwIfAborted(),!this.current(n)||this.state.blocked)return;if(this.accept(a),!C_(e,a)||(`action`in t?!S_(a,t.action):!x_(a)))throw new s_(`STATE_CHANGED`);if(i=!0,`label`in t){let i=await w_(this.apiBase,t.label,r,this.fetchImpl);if(!this.current(n))return;if(i!==e.doctor.effectiveCodexHome)throw new s_(`STATE_CHANGED`);this.resultHome=i,this.set({label:``,result:this.restartRequired?`restart`:`saved`})}else{let i=await T_(this.apiBase,t.action,!0,r,this.fetchImpl);if(!this.current(n))return;if(i.effectiveCodexHome!==e.doctor.effectiveCodexHome)throw new s_(`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:c_(e),previous:null})}finally{this.current(n)&&this.set({action:null,confirmedStopped:!1}),i&&await this.reconcile(n)}})}},k_={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`},A_=`ocx account main doctor`;function j_({t:e}){let[t,n=``]=e(`nativeMain.doctorHint`).split(`{cmd}`);return(0,Z.jsxs)(Z.Fragment,{children:[t,(0,Z.jsx)(`code`,{className:`chip`,children:A_}),n]})}function M_({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?b_(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,Z.jsxs)(`section`,{className:`panel`,"aria-labelledby":`${t}-heading`,style:{marginBottom:12},children:[(0,Z.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`},children:[(0,Z.jsx)(`strong`,{id:`${t}-heading`,children:e(`nativeMain.title`)}),(0,Z.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,Z.jsxs)(`div`,{id:`${t}-panel`,"aria-busy":r,children:[(0,Z.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.separate`)}),a&&(0,Z.jsxs)(`dl`,{children:[(0,Z.jsx)(`dt`,{children:e(`nativeMain.home`)}),(0,Z.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:(0,Z.jsx)(`code`,{children:a.doctor.effectiveCodexHome})}),a.list&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`dt`,{children:e(`nativeMain.current`)}),(0,Z.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:E?.label??e(`nativeMain.unregistered`)})]})]}),(0,Z.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.physicalHint`)}),i&&(0,Z.jsx)(`p`,{role:`status`,className:`notice notice-warn`,children:e(`nativeMain.busyOther`)}),r&&(0,Z.jsx)(`p`,{role:`status`,children:e(`nativeMain.working`)}),u&&(0,Z.jsxs)(`div`,{role:`alert`,className:`notice notice-err native-main-notice`,children:[(0,Z.jsx)(`p`,{children:e(k_[u])}),(0,Z.jsx)(`p`,{children:e(`nativeMain.retryHint`)}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`code`,{children:u}),` `,(0,Z.jsx)(j_,{t:e})]})]}),d&&!r&&!u&&!s&&(0,Z.jsxs)(`div`,{role:`status`,className:`notice native-main-notice`,children:[(0,Z.jsx)(`strong`,{children:e(`nativeMain.lastResult`)}),(0,Z.jsx)(`p`,{children:e(d===`saved`?`nativeMain.saved`:d===`restart`?`nativeMain.restart`:`nativeMain.done`)}),d!==`saved`&&a&&!f&&(0,Z.jsx)(`p`,{children:e(`nativeMain.reopenHint`)})]}),f&&(0,Z.jsx)(`p`,{role:`alert`,className:`notice notice-warn`,children:e(`nativeMain.refreshFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,disabled:S||!!s,children:e(`nativeMain.refresh`)}),a&&!a.doctor.supported&&(0,Z.jsx)(`p`,{role:`alert`,children:e(`nativeMain.unsupported`)}),w&&a?.doctor.supported&&!a.doctor.recoveryPending&&(0,Z.jsxs)(`p`,{role:`status`,children:[e(`nativeMain.unavailable`),` `,(0,Z.jsx)(`code`,{children:w})]}),a?.doctor.recoveryPending&&(0,Z.jsxs)(`div`,{className:`notice notice-warn`,children:[(0,Z.jsx)(`p`,{children:e(`nativeMain.recoveryHint`)}),(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.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,Z.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,Z.jsxs)(Z.Fragment,{children:[T.length===0&&(0,Z.jsx)(`p`,{children:e(`nativeMain.empty`)}),(0,Z.jsx)(`ul`,{style:{listStyle:`none`,padding:0},children:T.map(t=>(0,Z.jsxs)(`li`,{className:`row`,style:{padding:`8px 0`,flexWrap:`wrap`},children:[(0,Z.jsx)(`strong`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.label}),` `,(0,Z.jsx)(`code`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.identityHint}),t.state===`active`?(0,Z.jsx)(`span`,{className:`badge badge-green`,children:e(`nativeMain.active`)}):(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!S_(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!S_(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,Z.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.restoreHint`)})]}),(0,Z.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),v()},children:[(0,Z.jsx)(`label`,{htmlFor:`${t}-label`,children:e(`nativeMain.label`)}),(0,Z.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Z.jsx)(`input`,{id:`${t}-label`,className:`input min-w-0 flex-[1_1_14rem]`,value:o,onChange:e=>_(e.target.value),disabled:C||!!s||!x_(a),maxLength:80,autoComplete:`off`}),(0,Z.jsx)(`button`,{type:`submit`,className:`btn btn-sm`,disabled:C||!!s||!o.trim()||!x_(a),children:e(`nativeMain.save`)})]}),(0,Z.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.saveHint`)})]})]}),s&&a&&(0,Z.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,Z.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,Z.jsx)(`p`,{children:e(`nativeMain.confirmHint`)}),(0,Z.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:a.doctor.effectiveCodexHome}),(0,Z.jsxs)(`ol`,{children:[(0,Z.jsx)(`li`,{children:e(`nativeMain.stepClose`)}),(0,Z.jsx)(`li`,{children:e(`nativeMain.stepConfirm`)}),(0,Z.jsx)(`li`,{children:e(`nativeMain.stepResult`)})]}),(0,Z.jsx)(`p`,{children:(0,Z.jsxs)(`label`,{htmlFor:`${t}-stopped`,children:[(0,Z.jsx)(`input`,{id:`${t}-stopped`,type:`checkbox`,checked:c,disabled:C,onChange:e=>b(e.target.checked)}),` `,e(`nativeMain.stopped`)]})}),(0,Z.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-primary`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:C||!c||!S_(a,s),onClick:x,children:e(`nativeMain.confirm`)})]})]})]})]})}function N_(e){return(0,Z.jsx)(P_,{...e},e.apiBase)}function P_({apiBase:e,disabled:t=!1,onChanged:n}){let{locale:r}=a(),i=a_(r),o=(0,X.useId)(),[s]=(0,X.useState)(()=>new O_(e)),[c,l]=(0,X.useState)(s.state),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(!1);return(0,X.useLayoutEffect)(()=>s.attach(l),[s]),(0,X.useLayoutEffect)(()=>{s.updateOptions(t,n)},[s,t,n]),(0,X.useLayoutEffect)(()=>{c.action?(f.current=!0,d.current?.focus()):!c.busy&&f.current&&(f.current=!1,u.current?.focus())},[c.action,c.busy]),(0,Z.jsx)(M_,{t:i,id:o,...c,previousId:c.previous?.id??null,summaryRef:u,confirmationRef:d,onToggle:()=>{s.toggle()},onRefresh:()=>{s.refresh()},onLabel:e=>s.setLabel(e),onRegister:()=>{s.register()},onSelect:e=>s.select(e),onStopped:e=>s.setStopped(e),onConfirm:()=>{s.confirm()}})}var F_={"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 I_({threshold:e,draft:t,strategy:n=`quota`,hydrated:r=!0,saving:i,loadError:a,feedback:o,onDraftChange:s,onEditingChange:l,onCommit:u,onCancel:d,onToggle:f,onRetry:p}){let m=c(),h=(0,X.useRef)(!1),g=e>0,_=F_[n][g?`on`:`off`],v=i||!r,y=i?m(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,Z.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,Z.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,Z.jsx)(`strong`,{children:m(`codexAuth.autoSwitch`)}),(0,Z.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?m(`codexAuth.autoSwitchLoadFailed`):m(_,{threshold:e})}),(0,Z.jsx)(`div`,{className:`card-sub`,children:m(`codexAuth.failureRecoveryNote`)}),(0,Z.jsx)(`div`,{className:`card-sub`,children:m(`codexAuth.cacheWarning`)})]}),(0,Z.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(l(!1),h.current?h.current=!1:g&&!v&&u())},children:[a&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:m(`pws.retryAccounts`)}),g&&(0,Z.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:m(`codexAuth.autoSwitchThreshold`)}),(0,Z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Z.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":m(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||l(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),u()):e.key===`Escape`&&(e.preventDefault(),d()))}}),(0,Z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Z.jsx)(wh,{disabled:v,incrementLabel:m(`codexAuth.autoSwitchThresholdInc`),decrementLabel:m(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{l(!0),s(Ch(t,1,1,100))},onDecrement:()=>{l(!0),s(Ch(t,-1,1,100))}})]})]}),(0,Z.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,onPointerDownCapture:()=>{h.current=!0},onPointerUp:()=>{h.current=!1},onPointerCancel:()=>{h.current=!1},onClick:()=>{h.current=!1,f()},disabled:v,"aria-pressed":g,"aria-label":m(`codexAuth.autoSwitch`),"aria-describedby":x,title:m(`codexAuth.autoSwitch`),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,Z.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}function L_(){let[e,t]=(0,X.useState)(!1);return{open:e,id:(0,X.useId)(),toggle:()=>t(e=>!e)}}var R_={"reset-first":`accountPool.strategyResetFirst`,quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},z_={"reset-first":`accountPool.strategyHintResetFirst`,quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function B_({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:l,onStickyCommit:u}){let d=c(),f=L_(),p=vg.filter(e=>t||e!==`reset-first`).map(e=>({value:e,label:d(R_[e])})),m=n===void 0?null:e===`round-robin`?d(`accountPool.thresholdNotUsed`):n>0?d(e===`fill-first`?`accountPool.drainAtThreshold`:e===`reset-first`?`accountPool.resetBelowThreshold`:`accountPool.switchAtThreshold`,{threshold:String(n)}):d(`accountPool.proactiveSwitchingOff`);return(0,Z.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsxs)(`span`,{className:`acc-strategy-title flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`title`,id:`${a}-label`,children:d(`accountPool.strategy`)}),(0,Z.jsx)(Hh,{open:f.open,controls:f.id,name:d(`accountPool.strategy`),onToggle:f.toggle})]}),(0,Z.jsxs)(Uh,{id:f.id,open:f.open,className:`acc-strategy-help mt-1.5 flex flex-col gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`desc`,children:d(`accountPool.strategyDesc`)}),(0,Z.jsx)(`span`,{className:`desc`,children:d(z_[e])}),(0,Z.jsx)(`span`,{className:`desc`,children:d(`accountPool.unboundDefinition`)})]})]}),(0,Z.jsxs)(`div`,{className:`setting-controls`,children:[(0,Z.jsx)($,{id:a,value:e,options:p,disabled:i,label:d(`accountPool.strategy`),onChange:e=>s(e)}),m&&(0,Z.jsx)(`span`,{className:`badge badge-muted account-pool-threshold-badge`,"data-testid":`account-pool-threshold-summary`,children:m})]})]}),e===`round-robin`&&(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`label`,{className:`setting-label`,htmlFor:o,children:[(0,Z.jsx)(`span`,{className:`title`,children:d(`accountPool.stickyLimit`)}),(0,Z.jsx)(`span`,{className:`desc`,children:d(`accountPool.stickyLimitHelp`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Z.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":d(`accountPool.stickyLimitAria`),onChange:e=>l(e.target.value),onBlur:()=>u(),onKeyDown:e=>{e.nativeEvent.isComposing||i||e.key===`Enter`&&(e.preventDefault(),u())}}),(0,Z.jsx)(wh,{disabled:i,incrementLabel:d(`accountPool.stickyLimitInc`),decrementLabel:d(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=Ch(r,1,1,100);l(e),u(e)},onDecrement:()=>{let e=Ch(r,-1,1,100);l(e),u(e)}})]})})]})]})}function V_(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:wg(t.accountPoolStrategy),stickyLimit:Eg(t.accountPoolStickyLimit),threshold:n}}function H_({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r,threshold:i}){let a=c(),[o,s]=(0,X.useState)(bg),[l,u]=(0,X.useState)(1),[d,f]=(0,X.useState)(`1`),[p,m]=(0,X.useState)(void 0),[h,g]=(0,X.useState)(!1),_=(0,X.useRef)(!1),[v,y]=(0,X.useState)(!1),b=(0,X.useRef)(!1),x=(0,X.useRef)(!1),S=(0,X.useRef)(0),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(null),D=(0,X.useCallback)(e=>{let t=wg(e.accountPoolStrategy),n=Eg(e.accountPoolStickyLimit);typeof e.autoSwitchThreshold==`number`&&m(e.autoSwitchThreshold),s(t),r?.(t),u(n),f(String(n)),_.current=!0,g(!0),w(!1),E(null)},[r]),O=(0,X.useCallback)(e=>{let t=V_(e);t&&D({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit,autoSwitchThreshold:t.threshold})},[D]),k=(0,X.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(b.current){x.current=!0;return}D(n)}catch{b.current||w(!0)}},[e,D]),A=(0,X.useCallback)(()=>{x.current&&(x.current=!1,queueMicrotask(()=>{b.current?x.current=!0:k()}))},[k]);(0,X.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>S.current,acceptActiveRead:(e,t)=>{t===S.current&&(b.current?x.current=!0:O(e))},rejectActiveRead:()=>{_.current||w(!0)}});return!b.current&&n&&O(n()),e},[t,O,n]),(0,X.useEffect)(()=>{n&&!t&&(b.current||O(n()))},[n,O,t]),(0,X.useEffect)(()=>{t||k()},[k,t]);let j=(0,X.useCallback)(async t=>{if(b.current)return;let n=o,i=l;t.strategy!==void 0&&(s(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(u(t.stickyLimit),f(String(t.stickyLimit))),b.current=!0,y(!0),E(null),S.current+=1;let c=await Pg(e,t);S.current+=1,c.ok?(s(c.strategy),r?.(c.strategy),u(c.stickyLimit),f(String(c.stickyLimit)),_.current=!0,g(!0)):(E(a(`accountPool.strategyUpdateFailed`)),s(n),r?.(n),u(i),f(String(i))),b.current=!1,y(!1),A()},[e,r,A,l,o,a]),M=v||C||!h;return(0,Z.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":v||!h&&!C,children:[C&&(0,Z.jsx)(`div`,{className:`card-sub`,role:`alert`,children:a(`accountPool.strategyLoadFailed`)}),C&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{k()},children:a(`common.retry`)}),!C&&(0,Z.jsx)(B_,{codex:!0,strategy:o,threshold:i===void 0?p:i,stickyDraft:d,disabled:M,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{M||e===o||j({strategy:e})},onStickyDraftChange:f,onStickyCommit:e=>{if(M)return;let t=Dg(e??d);t===null?(f(String(l)),E(a(`accountPool.stickyLimitInvalid`))):t===l?f(String(t)):j({stickyLimit:t})}}),T&&(0,Z.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:T})]})}function U_({t:e,open:t,onToggle:n,children:r}){return(0,Z.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,Z.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,Z.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function W_(e,t){let[n,r]=(0,X.useState)(80),[i,a]=(0,X.useState)(`80`),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(80),h=(0,X.useRef)(!1),g=(0,X.useRef)(80),_=(0,X.useRef)(!1),v=(0,X.useRef)(!1),y=(0,X.useRef)(!1),b=(0,X.useRef)(0),x=(0,X.useRef)(null),S=(0,X.useRef)(null),C=(0,X.useCallback)(e=>{m.current=e,h.current=!0,s(!0),r(e),e>0&&(g.current=e),a(String(e>0?e:g.current))},[]),w=(0,X.useCallback)(e=>{_.current||v.current?x.current=e:(x.current=null,C(e))},[C]),T=(0,X.useCallback)(()=>{let e=x.current;return e!==null&&(x.current=null,C(e),!0)},[C]),E=(0,X.useCallback)(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null),p(null)},[]),D=(0,X.useCallback)((e,t)=>{S.current!==null&&window.clearTimeout(S.current),p({tone:t?`err`:`ok`,message:e}),S.current=window.setTimeout(()=>{p(null),S.current=null},5e3)},[]);(0,X.useEffect)(()=>()=>{S.current!==null&&window.clearTimeout(S.current)},[]);let O=(0,X.useCallback)(()=>(h.current||l(!1),b.current),[]),k=(0,X.useCallback)((e,t)=>{l(!1);let n=Bg(e),r=zg(_.current,v.current,t,b.current);r===`defer`?x.current=Ig(n):r===`apply`&&w(Ig(n))},[w]),A=(0,X.useCallback)(e=>{h.current||_.current||v.current||(l(!1),C(Ig(Bg(e))))},[C]),j=(0,X.useCallback)(()=>{h.current||l(!0)},[]),M=(0,X.useCallback)(async(n,r,i=!0)=>{if(v.current)return!1;v.current=!0,_.current=!1,E(),d(!0),b.current+=1;try{let a=await Hg(e,n);return b.current+=1,a?(x.current=null,C(n),i&&D(t.updated,!1)):(T()||C(r),D(t.updateFailed,!0)),a}finally{v.current=!1,d(!1)}},[e,C,E,t.updateFailed,t.updated,T,D]),N=(0,X.useCallback)(()=>{_.current=!1;let e=m.current;T()||a(String(e>0?e:g.current)),D(t.invalid,!0)},[t.invalid,T,D]),P=(0,X.useCallback)(()=>{_.current=!1,y.current=!0,E();let e=m.current;T()||a(String(e>0?e:g.current))},[E,T]),F=(0,X.useCallback)(async()=>{if(y.current)return y.current=!1,!0;if(!h.current||v.current)return!1;let e=m.current;_.current=!1;let t=Lg(i);return t===null?(N(),!1):t===e?(T()||a(String(t)),!0):M(t,e)},[i,T,N,M]),I=(0,X.useCallback)(async()=>{if(!h.current||v.current)return!1;let e=m.current;_.current=!1;let t=Vg(e,i,g.current),n=await M(t.threshold,e);return n?(g.current=t.lastEnabled,t.threshold===0&&a(String(t.lastEnabled)),n):!1},[i,M]);return{threshold:n,draft:i,hydrated:o,saving:u,loadError:c,feedback:f,beginServerRead:O,acceptServerRead:k,hydrateServerValue:A,rejectServerRead:j,setDraft:(0,X.useCallback)(e=>{h.current&&(_.current=!0,y.current=!1,E(),a(e))},[E]),setEditing:(0,X.useCallback)(e=>{_.current=e},[]),commit:F,cancel:P,toggle:I,retry:(0,X.useCallback)(()=>{l(!1),E()},[E])}}function G_({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=c(),a=pg(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,l=dg.map(e=>({value:String(e),label:_g(i,e)})),u=hg(a)?l:[{value:String(a),label:_g(i,a)},...l];return(0,Z.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,Z.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,Z.jsx)($,{id:n,value:String(a),options:u,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(pg(Number.parseInt(e,10)))}),(0,Z.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function K_({value:e}){let t=c(),n=pg(e);return n===0?null:(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:_g(t,n)})}function q_({summary:e,busy:t,onToggleAll:n}){let r=c(),i=(0,X.useId)(),a=e.total>0&&e.enabled===e.total,o=e.enabled>0&&!a;return(0,Z.jsxs)(`span`,{className:`codex-credit-spend`,"aria-busy":t||void 0,children:[(0,Z.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:r(`codexAuth.creditSpend`)}),(0,Z.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,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsx)(`span`,{id:i,className:`sr-only`,children:r(`codexAuth.creditsAfterLimitHint`)})]})}function J_({accountLabel:e,enabled:t,saving:n,disabled:r,hint:i,onChange:a}){let o=c(),s=(0,X.useId)(),l=t===!0,u=i??o(`codexAuth.creditsAfterLimitHint`);return(0,Z.jsxs)(`div`,{className:`codex-account-credits`,title:u,"aria-busy":n||void 0,children:[(0,Z.jsx)(`span`,{className:`codex-account-credits__label`,children:o(`codexAuth.creditsAfterLimit`)}),(0,Z.jsx)(`button`,{type:`button`,className:`toggle codex-account-credits__toggle ${l?`on`:``}`,disabled:r||n,"aria-pressed":l,"aria-label":o(`codexAuth.creditsAfterLimitAria`,{email:e}),"aria-describedby":s,onClick:()=>a(!l),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsx)(`span`,{id:s,className:`sr-only`,children:u})]})}function Y_({enabled:e}){let t=c();return e===!0?(0,Z.jsx)(`span`,{className:`badge badge-amber`,title:t(`codexAuth.creditsAfterLimitHint`),children:t(`codexAuth.creditsOn`)}):null}function X_({active:e=!1,paused:t=!1,dot:n,name:r,sub:i,chips:a,actions:o,more:s,children:c}){return(0,Z.jsxs)(`div`,{className:Y(`card acc-row`,e&&`card-active is-active`,t&&`is-paused`,s?`has-more`:void 0),children:[(0,Z.jsxs)(`div`,{className:`acc-row__head flex min-w-0 items-start gap-3`,children:[(0,Z.jsx)(`span`,{className:`flex h-5 items-center`,children:(0,Z.jsx)(Vh,{tone:n})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,Z.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,Z.jsx)(`span`,{className:`card-badges acc-chips flex flex-wrap items-center gap-1`,children:a})]}),i&&(0,Z.jsx)(`div`,{className:`acc-row__sub min-w-0 truncate text-[12.5px] leading-[18px] text-fg-muted`,children:i})]}),o&&(0,Z.jsx)(`div`,{className:`acc-row__actions flex shrink-0 flex-wrap items-center justify-end gap-1`,children:o})]}),c,s]})}function Z_(){return(0,Z.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`currentColor`,"aria-hidden":`true`,children:[(0,Z.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`}),(0,Z.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`}),(0,Z.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`})]})}function Q_({label:e,title:t,open:n,onToggle:r,heading:i,children:a}){return(0,Z.jsxs)(`details`,{className:`codex-account-more acc-more`,open:n,onToggle:r?e=>r(e.currentTarget.open):void 0,children:[(0,Z.jsx)(`summary`,{className:`acc-more__summary`,"aria-label":e,title:t,children:(0,Z.jsx)(Z_,{})}),(0,Z.jsxs)(`div`,{className:`codex-account-more-body acc-settings`,children:[i&&(0,Z.jsx)(`div`,{className:`acc-settings__heading`,children:i}),a]})]})}function $_({label:e,children:t,className:n}){return(0,Z.jsxs)(`div`,{className:Y(`acc-setting`,n),children:[e&&(0,Z.jsx)(`span`,{className:`acc-setting__label`,children:e}),(0,Z.jsx)(`div`,{className:`acc-setting__control`,children:t})]})}function ev({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,Z.jsxs)(`div`,{className:`quota-row quota-row--codex-credits`,title:f,children:[(0,Z.jsx)(`span`,{className:`quota-label`,children:t(`codexAuth.credits`)}),(0,Z.jsx)(`span`,{className:`quota-reset-label`,children:t(`codexAuth.creditsRemaining`)}),(0,Z.jsx)(`span`,{className:`quota-reset-day`}),(0,Z.jsx)(`span`,{className:`quota-reset-time`}),(0,Z.jsx)(`div`,{className:`bar`,"aria-hidden":`true`,children:(0,Z.jsx)(`div`,{className:`bar-fill bar-green`,style:{"--bar-scale":u?`1`:`0`}})}),(0,Z.jsx)(`span`,{className:`quota-val`,children:l})]})}function tv(e,t){return`${e??``}\0${JSON.stringify(t)}`}var nv={month:`short`,day:`numeric`,year:`numeric`},rv={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},iv=new Map;function av(e,t){let n=tv(e,t),r=iv.get(n);return r||(r=new Intl.DateTimeFormat(e,t),iv.set(n,r)),r}function ov(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:av(t,nv).format(n)}function sv(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:av(t,rv).format(n)}var cv=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function lv(e,t){return!Number.isFinite(e)||e<0?`—`:`~${cv.format(e)}`}function uv(e,t){return ov(e,t)}function dv(e,t){return sv(e,t)}function fv(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function pv({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=fv(n),s=o<=7;return(0,Z.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,Z.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Z.jsx)(gt,{width:13}),(0,Z.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,Z.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,Z.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,Z.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:uv(t,i)})}),(0,Z.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:dv(n,i),days:String(o)})})]})]})}function mv({t:e,onUnpin:t}){return(0,Z.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 hv({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,Z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Z.jsx)(gt,{width:12}),`0`]}):r===void 0?null:(0,Z.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,Z.jsx)(gt,{width:12}),r]})}function gv({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,Z.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function _v({pool:e,creditsVisible:t,loading:n=!1,activeId:r,accountModeState:i,switchActionLabel:o,threshold:s,onOpenReset:l,onSwitch:u,onTogglePause:d,pauseUpdatingId:f,pauseBusy:p,onPriorityChange:m,priorityUpdatingId:h,onAutoSwitchThresholdChange:g,autoSwitchDisabled:_,switchingId:v,pinnedId:y=null,onUnpin:b,onReauth:x,onEditAlias:S,onRemove:C,onToggleCreditsAfterLimit:w,creditsAfterLimitUpdatingId:T=null,onCopyDoctor:E,doctorCopyOutcomeFor:D}){let O=c(),{locale:k}=a(),A=e=>!e.paused&&r===e.id,j=Xh(),[M,N]=(0,X.useState)(new Set);return(0,Z.jsx)(Z.Fragment,{children:e.map(e=>{let r=t===!0&&e.credits!==void 0,a=e.health?.status,c=e.selectionExcludedReason===`plan_excluded`,P=!!e.needsReauth||Oh(a),F=Ah(a),I=e.health?.reason===`validation_pending`,L=Nh(O,e.health),R=Ph(O,`codex`,e.id,e.health),z=A(e),B=e.alias??e.email,V=E&&jh(a);return(0,Z.jsxs)(X_,{active:z,paused:e.paused,dot:P?`warn`:e.paused?`idle`:z?`active`:`ok`,name:B,sub:e.alias?e.email:void 0,chips:(0,Z.jsxs)(Z.Fragment,{children:[z&&!c&&!P&&!F&&!I&&(0,Z.jsx)(`span`,{className:`badge badge-primary`,children:O(i===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)}),e.plan&&(0,Z.jsx)(`span`,{className:`badge badge-plan`,children:e.plan}),c&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,title:O(`codexAuth.planExcludedHint`,{plan:e.selectionExcludedPlan??e.plan??``}),children:O(`codexAuth.planExcluded`)}),e.paused&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,title:e.pauseDetails?bh(O,k,e.pauseDetails):O(`codexAuth.pausedHint`),children:O(`codexAuth.paused`)}),(0,Z.jsx)(K_,{value:e.priority}),(0,Z.jsx)(Y_,{enabled:e.creditsAfterLimit}),e.id===y&&!e.paused&&(0,Z.jsx)(mv,{t:O,onUnpin:()=>b(e)}),(0,Z.jsx)(hv,{t:O,account:e,onClick:()=>l(e)}),L&&(0,Z.jsx)(`span`,{className:Dh(a),children:L}),P&&!L&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:O(`codexAuth.needsReauth`)})]}),actions:(0,Z.jsxs)(Z.Fragment,{children:[!e.paused&&!c&&(!z||y!==e.id)&&!P&&!F&&!I&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>u(e),children:o}),P&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>x(e.id),children:O(`codexAuth.reauthenticate`)}),(0,Z.jsxs)(`button`,{type:`button`,className:`acc-icon-btn codex-auth-action-btn`,onClick:()=>d(e),disabled:p,"aria-busy":f===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,Z.jsx)(le,{width:15}):(0,Z.jsx)(we,{width:15}),(0,Z.jsx)(`span`,{className:`sr-only`,children:(0,Z.jsx)(gv,{t:O,paused:e.paused,saving:f===e.id})})]})]}),more:(0,Z.jsxs)(Q_,{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:[(pg(e.priority)!==0||M.has(e.id))&&(0,Z.jsx)($_,{children:(0,Z.jsx)(G_,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:h!==null||v!==null,onChange:t=>m(e,t)})}),(0,Z.jsx)($_,{children:(0,Z.jsx)(Th,{accountLabel:B,globalThreshold:s,override:e.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${e.id}`,disabled:_,onChange:t=>g(e,t)},e.id)}),w&&(0,Z.jsx)($_,{children:(0,Z.jsx)(J_,{accountLabel:B,enabled:e.creditsAfterLimit,saving:T===e.id,disabled:T!==null,onChange:t=>w(e,t)})}),(0,Z.jsxs)($_,{label:(0,Z.jsxs)(`span`,{className:`mono`,children:[O(`prov.accountId`),`: `,Sh(e.id)]}),children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void S(e),children:O(`prov.editAlias`)}),(0,Z.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,Z.jsx)(We,{width:14}),` `,O(`common.remove`)]})]})]}),children:[(R||F||P)&&(0,Z.jsxs)(`div`,{className:`acc-row__notes`,children:[R&&(0,Z.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Z.jsx)(`span`,{children:R}),V&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-auth-action-btn`,onClick:()=>E(e.id),children:(0,Z.jsx)(`span`,{"aria-live":`polite`,children:Lh(O,D?.(e.id))})})]}),!R&&V&&(0,Z.jsx)(`div`,{className:`card-sub faint`,children:(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-auth-action-btn`,onClick:()=>E(e.id),children:(0,Z.jsx)(`span`,{"aria-live":`polite`,children:Lh(O,D?.(e.id))})})}),F&&(0,Z.jsx)(`div`,{className:`card-sub faint`,children:O(`pws.healthCooldownHint`)}),P&&(0,Z.jsx)(`div`,{className:`card-sub faint`,children:O(`codexAuth.tokenExpired`)})]}),!P&&!F&&(0,Z.jsx)(`div`,{className:`acc-row__meters`,children:(0,Z.jsx)($p,{quota:e.quota,plan:e.plan,threshold:e.autoSwitchThresholdOverride??s,t:O,pending:e.quota==null&&(n||!r),afterWeekly:r&&!n?(0,Z.jsx)(ev,{credits:e.credits,t:O,locale:k}):void 0})})]},e.id)})})}function vv({onReauth:e}){let t=c();return(0,Z.jsx)(Bh,{tone:`warn`,className:`acc-row-banner`,action:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)}),children:t(`codexAuth.tokenExpired`)})}function yv({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,threshold:a,unpin:o=!1,onCancel:s,onConfirm:l}){let u=c(),d=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,X.useCallback)(e=>{e.preventDefault(),s()},[s]),p=re(e.quota,e.plan),m=a!==void 0&&a>0&&p!==null&&p>=a;return(0,Z.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:f,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:s}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Z.jsx)(`h3`,{id:`codex-switch-title`,children:o?u(`codexAuth.unpinTitle`):n===`direct`?u(`codexAuth.preparePoolTitle`):e.id===`__main__`?u(`codexAuth.switchBack`):u(`codexAuth.switchTitle`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:o?u(`codexAuth.unpinDesc`):n===`direct`?u(`codexAuth.preparePoolDesc`):e.id===`__main__`?u(`codexAuth.switchBackDesc`):u(`codexAuth.switchDesc`)}),(0,Z.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,Z.jsx)(`strong`,{children:e.id===`__main__`?t||u(`codexAuth.codexApp`):e.email}),e.plan&&(0,Z.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),!o&&e.id!==`__main__`&&(0,Z.jsxs)(`div`,{className:`notice-warn`,children:[(0,Z.jsx)(at,{width:14}),` `,u(`codexAuth.cacheWarning`)]}),!o&&m&&(0,Z.jsxs)(`div`,{className:`notice-warn`,"data-testid":`codex-switch-threshold-warning`,children:[(0,Z.jsx)(at,{width:14}),` `,u(`codexAuth.switchExceedsThresholdWarning`,{threshold:a})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r||i,onClick:l,children:u(r?`pws.accountSwitching`:o?`codexAuth.unpinAction`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function bv({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:o,onShowConfirm:s,onCancelConfirm:c,onRedeem:l}){let{locale:u,t:d}=a(),f=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=f.current;e&&!e.open&&e.showModal()},[]);let p=(0,X.useCallback)(e=>{e.preventDefault(),o()},[o]);return(0,Z.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:p,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,onClick:o}),(0,Z.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Z.jsx)(`div`,{className:`confirm-icon`,children:(0,Z.jsx)(at,{width:22})}),(0,Z.jsx)(`h3`,{id:`codex-reset-title`,children:d(`codexAuth.confirmResetTitle`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,Z.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.confirmWhichCredit`,{date:uv(n[0].granted_at,u)})}),(0,Z.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.irreversible`)})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:c,children:d(`codexAuth.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:l,disabled:i,children:d(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,Z.jsx)(gt,{width:16}),` `,d(`codexAuth.resetCreditsTitle`)]}),(0,Z.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Z.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{style:{marginBottom:12},children:d(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,Z.jsx)(`p`,{className:`faint text-label`,children:d(`common.loading`)}),n&&n.length>0&&(0,Z.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,Z.jsx)(pv,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:u,t:d},`${e.granted_at}:${e.expires_at}`))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:s,disabled:i,children:d(`codexAuth.useOneCredit`)}),(0,Z.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:d(`codexAuth.fifoNote`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`faint`,children:d(`codexAuth.noResetCredits`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.earnCreditsHint`)})]})})]})})]})}function xv({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:o,onSwitch:s,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}=a(),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||Oh(t?.health?.status),N=Ah(t?.health?.status),P=t?.mainAccountHardLock,F=P?.enabled===!0&&P.state===`blocked`,I=Nh(e,t?.health),L=t?Ph(e,`codex`,A,t.health):null,R=y&&jh(t?.health?.status),z=t?.alias??(t?.email||e(`codexAuth.mainAccount`)),B=R?(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-auth-action-btn`,onClick:()=>y(A),children:(0,Z.jsx)(`span`,{"aria-live":`polite`,children:Lh(e,b?.(A))})}):null;return(0,Z.jsxs)(X_,{active:n&&!F,paused:t?.paused,dot:M||F?`warn`:t?.paused?`idle`:n?`active`:`ok`,name:t?.email||e(`codexAuth.appLogin`),chips:(0,Z.jsxs)(Z.Fragment,{children:[!t?.paused&&!F&&n&&(0,Z.jsx)(`span`,{className:`badge badge-primary`,children:e(r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)}),(0,Z.jsxs)(`span`,{className:`badge badge-plan acc-main-tag`,title:e(`codexAuth.appLogin`),children:[(0,Z.jsx)(ae,{width:11,"aria-hidden":`true`}),` `,e(`codexAuth.mainAccount`)]}),t?.plan&&(0,Z.jsx)(`span`,{className:`badge badge-plan`,children:t.plan}),t?.paused&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,Z.jsx)(K_,{value:j.priority}),(0,Z.jsx)(Y_,{enabled:t?.creditsAfterLimit}),g===`__main__`&&!t?.paused&&(0,Z.jsx)(mv,{t:e,onUnpin:()=>_(j)}),t&&(0,Z.jsx)(hv,{t:e,account:{...t,id:`__main__`},onClick:()=>v({...t,id:`__main__`})}),I&&(0,Z.jsx)(`span`,{className:Dh(t?.health?.status),children:I}),M&&!I&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&!F&&!n&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.current`)})]}),actions:(0,Z.jsxs)(Z.Fragment,{children:[!t?.paused&&!F&&(!n||g!==`__main__`)&&!M&&!N&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>s(j),children:o}),t&&(0,Z.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,Z.jsx)(le,{width:15}):(0,Z.jsx)(we,{width:15}),(0,Z.jsx)(`span`,{className:`sr-only`,children:(0,Z.jsx)(gv,{t:e,paused:!!t.paused,saving:l===`__main__`})})]})]}),more:t?(0,Z.jsxs)(Q_,{label:`${e(`codexAuth.moreActions`)} — ${e(`codexAuth.mainAccount`)}`,title:e(`codexAuth.moreActions`),children:[(0,Z.jsx)($_,{children:(0,Z.jsx)(G_,{value:j.priority,selectId:`codex-account-priority-${j.id}`,disabled:f!==null||h!==null,onChange:e=>d(j,e)})}),(0,Z.jsx)($_,{children:(0,Z.jsx)(Th,{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,Z.jsx)($_,{children:(0,Z.jsx)(J_,{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,Z.jsxs)(`div`,{className:`acc-row__notes`,children:[P?.enabled&&(0,Z.jsxs)(`div`,{className:`codex-main-hard-lock-status${F?` is-blocked`:``}`,children:[(0,Z.jsx)(`p`,{role:`status`,children:e(F?`codexAuth.mainHardLockBlocked`:P.state===`ready`?`codexAuth.mainHardLockMonitoring`:`codexAuth.mainHardLockUnknown`,Wg(P.thresholds))}),x?(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:x,children:e(`codexAuth.mainHardLockManage`)}):(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>_n(`codex-set`),children:e(`codexAuth.mainHardLockManage`)})]}),P?.externalUsage&&(0,Z.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Z.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainExternalUsageWarning`)})}),L&&(0,Z.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Z.jsx)(`span`,{children:L}),B]}),!L&&B&&(0,Z.jsx)(`div`,{className:`card-sub faint`,children:B}),N&&(0,Z.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),M&&(0,Z.jsxs)(`div`,{className:`card-sub faint acc-reauth`,children:[(0,Z.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainTokenExpired`)}),S&&(S.state.phase===`idle`||S.state.phase===`failed`||S.state.phase===`cancelled`)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsxs)(`span`,{className:`badge badge-amber`,children:[e(`codexAuth.mainReauthFailed`),`: `,S.state.code]})]}),S&&S.state.phase===`starting`&&(0,Z.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S&&(S.state.phase===`pending`||S.state.phase===`committing`)&&(0,Z.jsxs)(`span`,{className:`codex-main-reauth-pending`,children:[(0,Z.jsx)($h,{hint:{url:S.state.verificationUrl,deviceCode:S.state.deviceCode}}),(0,Z.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S.state.cancelFailed&&(0,Z.jsx)(`span`,{role:`status`,className:`badge badge-amber`,children:e(`codexAuth.mainReauthFailed`)}),(0,Z.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,Z.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.mainReauthSucceeded`)})]})]}),!M&&!N&&(0,Z.jsx)(`div`,{className:`acc-row__meters`,children:(0,Z.jsx)($p,{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,Z.jsx)(ev,{credits:t?.credits,t:e,locale:D}):void 0})})]})}function Sv({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,Z.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,Z.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,Z.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,Z.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,Z.jsxs)(`span`,{className:`codex-auth-credits-toggle`,children:[(0,Z.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:e(`codexAuth.creditsToggle`)}),(0,Z.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,Z.jsx)(`span`,{className:`toggle-knob`})})]}),f,t&&(0,Z.jsx)(Cv,{t:e,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,onRefresh:s,onPauseExhausted:c})]})]})}function Cv({t:e,refreshingQuota:t,pausingExhausted:n,pauseBusy:r,onRefresh:i,onPauseExhausted:a}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:a,disabled:t||n||!!r,children:[(0,Z.jsx)(we,{width:14}),` `,e(n?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:i,disabled:t||n||!!r,children:[(0,Z.jsx)(`span`,{className:Y(`inline-flex`,t&&`animate-spin`),children:(0,Z.jsx)(Mt,{width:14})}),` `,e(t?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})}function wv(e){return(0,Z.jsx)(`div`,{className:`codex-auth-actions-row`,children:(0,Z.jsx)(Cv,{...e})})}function Tv({t:e,loadState:t,refreshFailed:n,accountsCount:r,onRetry:i}){return t===`loading`&&r===0?(0,Z.jsxs)(`div`,{className:`codex-auth-load-skeleton acc-row-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,Z.jsxs)(`div`,{className:`card acc-row`,"aria-hidden":`true`,children:[(0,Z.jsxs)(`div`,{className:`acc-row__head flex items-center gap-3`,children:[(0,Z.jsx)(`span`,{className:`inline-block size-2 rounded-full bg-fg-subtle`}),(0,Z.jsx)(`span`,{className:`acc-skel h-3.5 w-48 rounded-full`}),(0,Z.jsx)(`span`,{className:`acc-skel h-4 w-16 rounded-full`})]}),(0,Z.jsx)(`div`,{className:`acc-row__meters`,children:(0,Z.jsx)($p,{quota:null,threshold:0,t:e,pending:!0})})]}),(0,Z.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,Z.jsx)(Bh,{tone:`err`,role:`alert`,className:`pwi-auth-state pwi-auth-state--error acc-row-banner`,action:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)}),children:e(`codexAuth.loadFailed`)}):n&&r>0?(0,Z.jsx)(Bh,{tone:`warn`,role:`status`,className:`pwi-auth-state pwi-auth-state--stale acc-row-banner`,action:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)}),children:e(`codexAuth.accountsRefreshFailed`)}):null}function Ev({t:e,onAdd:t}){return(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm acc-add-btn`,onClick:t,children:[(0,Z.jsx)(be,{width:14}),` `,e(`codexAuth.add`)]})}function Dv(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Ov(e,t,n,r){try{let i=await Bn(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:Dv(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 kv({windows:e,ready:t,busy:n,loadError:r,feedback:i,onToggle:a,onRetry:o}){let s=c(),l=e.filter(e=>e.available),u=e.some(e=>e.enabled),d=l.length?l.every(e=>e.enabled):u,f=u&&!d,p=l.length===0&&!u,m=n?s(`common.saving`):r?s(`codexAuth.quotaAutoRefreshLoadFailed`):t?i?.message??(p?s(`codexAuth.quotaAutoRefreshEmpty`):f?s(`codexAuth.quotaAutoRefreshMixed`):``):s(`common.loading`),h=!n&&(r||i?.failed);return(0,Z.jsxs)(`div`,{id:`codex-quota-activation`,className:`card card-row codex-quota-activation`,"aria-busy":n||!t&&!r||void 0,children:[(0,Z.jsxs)(`div`,{className:`codex-quota-activation__copy`,children:[(0,Z.jsx)(`strong`,{children:s(`codexAuth.quotaAutoRefresh`)}),(0,Z.jsx)(`div`,{id:`codex-quota-activation-desc`,className:`card-sub`,children:s(`codexAuth.quotaAutoRefreshAllHint`)}),m&&(0,Z.jsx)(`div`,{className:`card-sub${h?` is-error`:``}`,role:h?`alert`:`status`,children:m})]}),(0,Z.jsxs)(`div`,{className:`codex-quota-activation__controls`,children:[h&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:o,children:s(`common.retry`)}),(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${t&&d?`on`:``}`,"aria-label":s(`codexAuth.quotaAutoRefresh`),"aria-describedby":`codex-quota-activation-desc`,"aria-pressed":t?f?`mixed`:d:void 0,disabled:!t||n||p,onClick:()=>a(!d),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]})]})}function Av(e){return{enabled:e.filter(e=>e.creditsAfterLimit===!0).length,total:e.length}}function jv(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 Mv(e,t){return e.flatMap(e=>{let n=e.isMain?`__main__`:e.id,r=e.quotaAutoRefresh??Pe(e.quota);return[`fiveHour`,`weekly`].map(e=>({id:n,window:e,available:r[e===`fiveHour`?`fiveHourAvailable`:`weeklyAvailable`],enabled:t[n]?.[e]===!0}))})}var Nv=[`.pws-detail-panel`,`.pws-detail`,`.pws-main`,`.page-head`],Pv=`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function Fv(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 Iv(e){if(!(Fv(e)&&(e.focus(),document.activeElement===e))){for(let e of Nv)for(let t of document.querySelectorAll(e))for(let e of t.querySelectorAll(Pv))if(Fv(e)&&(e.focus(),document.activeElement===e))return}}function Lv(e){let t=c(),n=(0,X.useId)(),r=(0,X.useRef)(null),i=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=document.activeElement;return i.current?.focus(),()=>{Iv(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,Z.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,Z.jsxs)(`div`,{className:`modal-card`,ref:r,children:[(0,Z.jsx)(`div`,{className:`modal-head`,children:(0,Z.jsx)(`h2`,{id:n,style:{fontSize:`var(--text-subtitle)`,margin:0},children:t(`prov.modelsNoticeTitle`)})}),(0,Z.jsx)(`p`,{children:(0,Z.jsx)(`strong`,{style:{overflowWrap:`anywhere`},children:e.provider})}),(0,Z.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:s}),e.initialRegistration&&e.selection?.modelCount!==void 0&&(0,Z.jsx)(`p`,{className:`muted`,children:t(`prov.modelsNoticeCount`,{count:e.selection.modelCount})}),e.catalogRefreshPending&&(0,Z.jsx)(`p`,{className:`muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}),!e.loading&&(a||o)&&e.onRetry&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{e.onRetry?.(),i.current?.focus()},children:t(`common.retry`)}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:e.onClose,children:t(`common.close`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,ref:i,onClick:e.onOpenModels,children:t(`prov.modelsNoticeOpen`)})]})]})})}var Rv=`ocx doctor`;function zv({apiBase:t,accountModeState:n=null,banner:r=null,embedded:i=!1,onActiveNeedsReauthChange:a,controller:o,advancedExtras:s=null,hasMainHardLockSetting:l=!1}){let u=c(),d=W_(t,{updated:u(`codexAuth.autoSwitchUpdated`),updateFailed:u(`codexAuth.autoSwitchUpdateFailed`),invalid:u(`codexAuth.autoSwitchThresholdInvalid`)}),[f,p]=(0,X.useState)(null),{beginServerRead:m,acceptServerRead:h,rejectServerRead:g,hydrateServerValue:_}=d,v=Jg(t,!o),y=o??v,{accounts:b,activeId:x,loadState:S,refreshFailed:C,switchingId:w,pauseUpdatingId:T,priorityUpdatingId:E,autoSwitchUpdatingId:D,pausingExhausted:O,activePinnedId:k,load:A}=y,j=r_(t,()=>{A()}),M=j.state.phase===`starting`||j.state.phase===`pending`||j.state.phase===`committing`,[N,P]=(0,X.useState)(null),[F,I]=(0,X.useState)(null),[L,R]=(0,X.useState)(!1),[z,B]=(0,X.useState)(null),[V,H]=(0,X.useState)(!1),U=(0,X.useRef)(!1),W=(0,X.useCallback)(()=>{let e=document.getElementById(`codex-main-hard-lock-setting`);e?.focus(),e?.scrollIntoView({block:`nearest`})},[]);(0,X.useEffect)(()=>{V&&U.current&&(U.current=!1,W())},[V,W]);let ee=()=>{V?W():(U.current=!0,H(!0))},[te,ne]=(0,X.useState)(null),[G,K]=(0,X.useState)(null),[re,q]=(0,X.useState)(null),ie=(0,X.useRef)(null),[ae,oe]=(0,X.useState)(!1),[se,ce]=(0,X.useState)(null),[le,ue]=(0,X.useState)(null),J=(0,X.useRef)(0),de=(0,X.useRef)(null),fe=(0,X.useRef)(null),[pe,me]=(0,X.useState)(0),[he,ge]=(0,X.useState)(t),[_e,ve]=(0,X.useState)(null),ye=(0,X.useRef)(null),xe=le?.apiBase===t&&le.revision===pe?le:null,Se=xe?.settings??null,Ce=xe?.error??!1,we=se===t;he!==t&&(ge(t),me(e=>e+1),ue(null),ce(null),ve(null));let[Te,Ee]=(0,X.useState)(null),[De,Oe]=(0,X.useState)(!1),[ke,Ae]=(0,X.useState)(!1),[je,Me]=(0,X.useState)(null),[Ne,Pe]=(0,X.useState)(!1),Fe=Xh(),Ie=(0,X.useCallback)((e,t=`ok`)=>{ie.current&&clearTimeout(ie.current),K(e),q(t),ie.current=setTimeout(()=>{K(null),q(null),ie.current=null},5e3)},[]);(0,X.useEffect)(()=>()=>{ie.current&&clearTimeout(ie.current)},[]);let Le=Yg(t,A,Ie,u,{revision:pe,onRead:(e,n)=>{let r=J.current;e.then(e=>{n.aborted||J.current!==r||(ue({apiBase:t,revision:pe,settings:jv(e),error:!1}),ce(null))}).catch(()=>{n.aborted||J.current!==r||(ue({apiBase:t,revision:pe,settings:null,error:!0}),ce(null))})}}),Re=(0,X.useCallback)(e=>{Fe.copy(Rv,e)},[Fe]),{subscribeLoadObserver:ze,readLastThreshold:Be}=y;(0,X.useEffect)(()=>ze({beginActiveRead:m,acceptActiveRead:h,rejectActiveRead:g}),[ze,m,h,g]),(0,X.useEffect)(()=>{let e=Be();e!==void 0&&_(e)},[Be,_]),(0,X.useEffect)(()=>{if(!L&&!M)return;let e=y.pauseRefresh();return()=>y.resumeRefresh(e)},[y,L,M]);let Ve=x&&x!==`__main__`?b.find(e=>e.id===x):null,He=!Ve?.paused&&kh(Ve);(0,X.useEffect)(()=>{a?.(He)},[He,a]);let Ue=(0,X.useCallback)(e=>{ne(e),R(!0)},[]),We=(0,X.useCallback)(()=>{R(!1),ne(null)},[]),Ge=(0,X.useCallback)(e=>{y.syncAfterAccountAdded(),Ie(u(e.validationPending?`pws.healthLabel.validationPending`:e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.validationPending||e.catalogRefreshPending?`warn`:`ok`),We(),B(e.validationPending?null:{catalogRefreshPending:e.catalogRefreshPending})},[We,y,Ie,u]),Ke=async e=>{let t=await y.switchAccount(e);if(!t.ok){if(t.reason===`busy`)return;Ie(u(`codexAuth.switchFailed`),`err`);return}P(null);let r=t.activeId,i=r&&r!==`__main__`?b.find(e=>e.id===r)?.email??u(`pws.accountOrdinal`,{count:`1`}):u(`codexAuth.mainAccount`);Ie(u(n===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},qe=async()=>{if(!F)return;let e=await y.switchAccount(null,{expectedPinnedAccountId:F.id});if(e.ok)I(null),Ie(u(`codexAuth.unpinned`),`ok`);else{if(e.reason===`busy`)return;I(null),Ie(u(e.reason===`pin_changed`?`codexAuth.unpinChanged`:`codexAuth.unpinFailed`),`err`)}},Je=async e=>{let t=await Pu({message:u(`prov.aliasPrompt`),initialValue:e.alias??``,maxLength:80,validate:e=>Gh(e,u)});if(t===null)return;let n=await y.saveAlias(e.id,t);Ie(u(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},Ye=async e=>{let t=!e.paused,n=await y.setAccountPaused(e.id,t);(n.ok||n.reason!==`busy`)&&(P(t=>t?.id===e.id?null:t),Ie(u(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},Xe=async e=>{let t=await y.setAllCreditsAfterLimit(e);(t.ok||t.reason!==`busy`)&&Ie(u(t.ok?e?`codexAuth.creditsAllOnSucceeded`:`codexAuth.creditsAllOffSucceeded`:`codexAuth.creditsAllUpdateFailed`),t.ok?`ok`:`err`)},Ze=async(e,t)=>{if(t===e.priority)return;let n=await y.setAccountPriority(e.id,t);(n.ok||n.reason!==`busy`)&&Ie(u(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},Qe=async(e,t)=>{if(t===e.autoSwitchThresholdOverride)return!0;let n=await y.setAccountAutoSwitchThreshold(e.id,t);return!n.ok&&n.reason===`busy`?!1:(Ie(u(n.ok?`accountPool.autoSwitchUpdated`:`accountPool.autoSwitchUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`),n.ok)},$e=async(e,t)=>{let n=await y.setAccountCreditsAfterLimit(e.id,t);(n.ok||n.reason!==`busy`)&&Ie(u(n.ok?t?`codexAuth.creditsOnSucceeded`:`codexAuth.creditsOffSucceeded`:`codexAuth.creditsUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},et=async e=>{let t=b.find(t=>t.id===e)?.email??u(`pws.accountOrdinal`,{count:`1`});if(!await Nu({message:u(`codexAuth.removeConfirm`,{id:t}),confirmLabel:u(`common.remove`),tone:`danger`}))return;let n=await y.removeAccount(e);n.ok?n.catalogRefreshPending&&Ie(u(`codexAuth.catalogRefreshPending`),`warn`):Ie(u(`codexAuth.removeFailed`),`err`)},tt=async()=>{oe(!0);try{let e=await A(!0,{validatePending:!0});Ie(u(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{oe(!1)}},nt=async n=>{let r=de.current;if(fe.current||!r||r.signal.aborted||Se===null||S!==`ready`)return;let i=e(3e4);fe.current=i,J.current+=1;let a=()=>de.current===r&&!r.signal.aborted,o=Mv(b,Se);ce(t),ve(null);let s=!1;try{for(let e of o){if(n&&!e.available)continue;let r=n;if(e.enabled!==r){if(!a())return;if(i.signal.aborted){s=!0;break}try{if(!(await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:i.signal,body:JSON.stringify({codexQuotaAutoRefresh:{id:e.id,window:e.window,enabled:r}})})).ok)throw Error(`save`)}catch{s=!0}}}if(!a())return;i.clear();let r=e(15e3);fe.current=r;try{let e=await fetch(`${t}/api/settings`,{signal:r.signal});if(!e.ok)throw Error(`read`);let i=jv(await e.json());if(!a())return;s||=o.some(e=>(!n||e.available)&&i[e.id]?.[e.window]===!0!==n),ue({apiBase:t,revision:pe,settings:i,error:!1})}catch{if(!a())return;s=!0,ue({apiBase:t,revision:pe,settings:null,error:!0})}finally{r.clear()}if(!a())return;ye.current=s?{apiBase:t,enabled:n}:null,ve({apiBase:t,message:u(s?`codexAuth.quotaAutoRefreshPartial`:`codexAuth.quotaAutoRefreshUpdated`),failed:s})}finally{i.clear(),a()&&(fe.current=null,ce(null))}};(0,X.useEffect)(()=>{let e=new AbortController;return de.current=e,()=>{e.abort(),fe.current?.controller.abort(),fe.current?.clear(),fe.current=null}},[t,pe]);let rt=async()=>{let e=await y.pauseExhaustedAccounts();(e.ok||e.reason!==`busy`)&&Ie(e.ok?e.pausedCount>0?u(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):u(`codexAuth.pauseExhaustedNone`):u(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},it=async e=>{Ee(e),Oe(!1),Me(null),Pe(!0);try{let n=await Bn(await fetch(`${t}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(e.id)}`));if(n){let e=(n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime());Me(e)}}catch{}finally{Pe(!1)}},at=async e=>{Ae(!0);try{let n=await Ov(t,e,u,A);n.close&&(Ee(null),Oe(!1)),n.toast&&Ie(n.toast,n.ok?`ok`:`err`)}finally{Ae(!1)}},ot=b.find(e=>e.isMain),st=b.filter(e=>!e.isMain),ct=Av([...ot?.hasCredential?[ot]:[],...st]),lt=!ot?.paused&&(!x||x===`__main__`),ut=u(n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),dt=T!==null||O,ft=d.threshold,Y=!d.hydrated||D!==null,pt=!i;return(0,Z.jsxs)(`div`,{className:`acc-v2 flex flex-col ${i?`gap-3`:`gap-4`}`,children:[(0,Z.jsx)(Sv,{t:u,embedded:i,creditsVisible:Le.visible,creditsBusy:Le.busy,onToggleCredits:()=>{Le.toggle()},creditSpendControl:S===`loading`&&b.length===0?void 0:(0,Z.jsx)(q_,{summary:ct,busy:y.creditsAfterLimitUpdatingId!==null,onToggleAll:e=>{Xe(e)}}),refreshingQuota:ae,actionFeedback:G,actionFeedbackTone:re,pausingExhausted:O,pauseBusy:dt,onRefresh:()=>{tt()},onPauseExhausted:()=>{rt()}}),r,!i&&(0,Z.jsx)(wv,{t:u,refreshingQuota:ae,pausingExhausted:O,pauseBusy:dt,onRefresh:()=>{tt()},onPauseExhausted:()=>{rt()}}),(0,Z.jsx)(Tv,{t:u,loadState:S,refreshFailed:C,accountsCount:b.length,onRetry:()=>{A()}}),(S!==`loading`||b.length!==0)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Rh,{className:`acc-accounts acc-accounts--main`,children:(0,Z.jsx)(xv,{t:u,main:ot,creditsVisible:Le.visible,loading:S===`loading`,isMainActive:lt,accountModeState:n,threshold:ft,switchActionLabel:ut,onSwitch:P,onUnpin:I,onTogglePause:Ye,pauseUpdatingId:T,pauseBusy:dt,onPriorityChange:(e,t)=>{Ze(e,t)},priorityUpdatingId:E,onAutoSwitchThresholdChange:Qe,autoSwitchDisabled:Y,onToggleCreditsAfterLimit:(e,t)=>{$e(e,t)},creditsAfterLimitUpdatingId:y.creditsAfterLimitUpdatingId,switchingId:w,pinnedId:k,onOpenReset:it,onCopyDoctor:pt?Re:void 0,doctorCopyOutcomeFor:pt?Fe.outcomeFor:void 0,onManageMainHardLock:l?ee:void 0,mainReauth:j})}),(0,Z.jsx)(`div`,{className:`acc-native-main`,children:(0,Z.jsx)(N_,{apiBase:t,disabled:M,onChanged:()=>A(!1)})}),(0,Z.jsxs)(Rh,{className:`acc-accounts`,title:u(`codexAuth.accountPool`),meta:st.length>0?String(st.length):void 0,actions:(0,Z.jsx)(Ev,{t:u,onAdd:()=>R(!0)}),children:[He&&Ve&&(0,Z.jsx)(vv,{onReauth:()=>Ue(Ve.id)}),st.length===0&&(0,Z.jsxs)(`div`,{className:`acc-pool-empty`,children:[(0,Z.jsx)(`p`,{className:`acc-pool-empty__title`,children:u(`codexAuth.noPool`)}),(0,Z.jsx)(`p`,{className:`acc-pool-empty__hint`,children:u(`accountsV2.emptyPoolHint`)}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(!0),children:[(0,Z.jsx)(be,{width:14}),` `,u(`codexAuth.add`)]})]}),(0,Z.jsx)(_v,{pool:st,creditsVisible:Le.visible,loading:S===`loading`,activeId:x,accountModeState:n,switchActionLabel:ut,threshold:ft,onOpenReset:it,onSwitch:P,onUnpin:I,onTogglePause:Ye,pauseUpdatingId:T,pauseBusy:dt,onPriorityChange:(e,t)=>{Ze(e,t)},priorityUpdatingId:E,onAutoSwitchThresholdChange:Qe,autoSwitchDisabled:Y,onToggleCreditsAfterLimit:(e,t)=>{$e(e,t)},creditsAfterLimitUpdatingId:y.creditsAfterLimitUpdatingId,switchingId:w,pinnedId:k,onReauth:Ue,onEditAlias:Je,onRemove:et,onCopyDoctor:pt?Re:void 0,doctorCopyOutcomeFor:pt?Fe.outcomeFor:void 0})]})]}),(0,Z.jsx)(H_,{apiBase:t,subscribeLoadObserver:y.subscribeLoadObserver,readLastActive:y.readLastActive,onStrategyResolved:p,threshold:d.threshold}),(0,Z.jsxs)(U_,{t:u,open:V,onToggle:()=>H(e=>!e),children:[(0,Z.jsx)(kv,{windows:Mv(b,Se??{}),ready:Se!==null&&S===`ready`,busy:we,loadError:Ce||S===`error`,feedback:_e?.apiBase===t?_e:null,onToggle:e=>{nt(e)},onRetry:()=>{Ce||Se===null||S!==`ready`?(me(e=>e+1),A()):ye.current?.apiBase===t&&nt(ye.current.enabled)}}),f!==null&&(0,Z.jsx)(I_,{threshold:d.threshold,draft:d.draft,strategy:f,hydrated:d.hydrated,saving:d.saving,loadError:d.loadError,feedback:d.feedback,onDraftChange:d.setDraft,onEditingChange:d.setEditing,onCommit:d.commit,onCancel:d.cancel,onToggle:d.toggle,onRetry:()=>{d.retry(),A()}}),s]}),N&&(0,Z.jsx)(yv,{confirm:N,mainEmail:ot?.email,accountModeState:n,switchingId:w,orderBusy:E!==null,threshold:f&&f!==`round-robin`?ft:void 0,onCancel:()=>P(null),onConfirm:()=>{Ke(N.id===`__main__`?`__main__`:N.id)}}),F&&(0,Z.jsx)(yv,{unpin:!0,confirm:F,mainEmail:ot?.email,accountModeState:n,switchingId:w,orderBusy:E!==null,onCancel:()=>I(null),onConfirm:()=>{qe()}}),Te&&(0,Z.jsx)(bv,{resetPopup:Te,resetConfirm:De,creditDetails:je,creditDetailsLoading:Ne,redeeming:ke,onClose:()=>{Ee(null),Oe(!1),Me(null)},onShowConfirm:()=>Oe(!0),onCancelConfirm:()=>Oe(!1),onRedeem:()=>{at(Te.id)}}),L&&(0,Z.jsx)(ug,{apiBase:t,reauthAccountId:te??void 0,onClose:We,onAdded:Ge}),z&&(0,Z.jsx)(Lv,{provider:`openai`,loading:!1,failed:!1,providerKnown:!0,initialRegistration:!1,catalogRefreshPending:z.catalogRefreshPending,onClose:()=>B(null),onOpenModels:()=>{B(null),_n(`models`)}})]})}var Bv=`https://opencodex.me/guides/claude-code/#claude-oauth-account-pool-experimental`,Vv={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function Hv(e,t,n,r){let i=e(Vv[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 Uv({apiBase:e,provider:t=`anthropic`,accountCount:n,onThresholdChange:r}){let i=c(),[a,o]=(0,X.useState)(null),[s,l]=(0,X.useState)(`80`),[u,d]=(0,X.useState)(`1`),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(0),[w,T]=(0,X.useState)(!1),E=(0,X.useRef)(r),D=(0,X.useRef)(!0),O=(0,X.useRef)(e),k=(0,X.useRef)(t),A=(0,X.useRef)(null);(0,X.useLayoutEffect)(()=>(D.current=!0,()=>{D.current=!1,A.current?.abort(),A.current=null}),[]),(0,X.useLayoutEffect)(()=>{E.current=r,O.current=e,k.current=t},[e,t,r]),(0,X.useEffect)(()=>{let n=!1,r=new AbortController;return Promise.resolve().then(()=>jg(e,t,(e,t)=>fetch(e,t),{signal:r.signal})).then(e=>{if(!e)throw Error(`load`);return e}).then(e=>{if(n)return;let t=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=Eg(e.stickyLimit);o({enabled:e.enabled===!0,threshold:t,strategy:wg(e.strategy),stickyLimit:r,quotaWindow:Tg(e.quotaWindow),nativeMessages:e.nativeMessages===!0}),l(String(t)),E.current?.(t),d(String(r)),_(!1),x(!1),h(null),y(!1),T(!1)}).catch(()=>{n||r.signal.aborted||(_(!0),T(!1))}),()=>{n=!0,r.abort()}},[e,t,S]);let j=(0,X.useCallback)(async n=>{let r=e,s=t;A.current?.abort();let c=new AbortController;A.current=c;let u=()=>D.current&&O.current===r&&k.current===s&&A.current===c&&!c.signal.aborted,f=a;p(!0),h(null),y(!1);try{let e=await Ng(r,s,{enabled:n.enabled,threshold:n.threshold,strategy:n.strategy,stickyLimit:n.stickyLimit,quotaWindow:n.quotaWindow,nativeMessages:n.nativeMessages},(e,t)=>fetch(e,t),{signal:c.signal});if(!u())return;if(!e)throw Error(`save`);let t=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:n.threshold,i=wg(e?.strategy??n.strategy),a=Eg(e?.stickyLimit??n.stickyLimit),f=Tg(e?.quotaWindow??n.quotaWindow);o({enabled:e.enabled??n.enabled,threshold:t,strategy:i,stickyLimit:a,quotaWindow:f,nativeMessages:e.nativeMessages===!0}),l(String(t)),E.current?.(t),d(String(a)),y(e.warning===`config_bookkeeping_failed`)}catch(e){if(!u())return;if(e instanceof Mg){o(null),x(!0),_(!1),h(null);return}h(i(`anthropicPool.saveFailed`)),f&&(o(f),l(String(f.threshold)),d(String(f.stickyLimit)))}finally{let e=A.current===c;e&&(A.current=null),e&&D.current&&O.current===r&&k.current===s&&p(!1)}},[e,t,a,i]),M=a?.enabled===!0,N=a?.threshold??80,P=a?.strategy??`quota`,F=a?.stickyLimit??1,I=a?.quotaWindow??`five-hour`,L=a?.nativeMessages??!0,R=P===`round-robin`,z=w||a===null&&!g&&!b,B=z||f||g||b,V=B||!M&&n<2;return(0,Z.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":z||f,children:[(0,Z.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,Z.jsxs)(`div`,{style:{flex:1},children:[(0,Z.jsx)(`strong`,{children:i(`anthropicPool.title`)}),(0,Z.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:b?i(`anthropicPool.saveStateUnknown`):g?i(`anthropicPool.loadFailed`):z?i(`common.loading`):M?Hv(i,P,N,I):i(`anthropicPool.disabledDesc`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${M?`on`:``}`,disabled:V,"aria-pressed":b?void 0:M,"aria-label":i(`anthropicPool.title`),title:i(M?`anthropicPool.on`:`anthropicPool.off`),onClick:()=>{j({enabled:!M,threshold:N,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:L})},children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]}),(0,Z.jsx)(`p`,{className:`card-sub anthropic-pool-card__notice`,children:i(`anthropicPool.experimentalWarning`)}),n<2&&(0,Z.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:i(`anthropicPool.needTwoAccounts`)}),(0,Z.jsxs)(`details`,{className:`anthropic-pool-card__details`,children:[(0,Z.jsx)(`summary`,{children:i(`anthropicPool.detailsSummary`)}),(0,Z.jsx)(`p`,{children:i(`anthropicPool.detailsEnabling`)}),(0,Z.jsx)(`p`,{children:i(`anthropicPool.detailsFailover`)}),(0,Z.jsx)(`p`,{children:i(`anthropicPool.detailsActivity`)}),(0,Z.jsxs)(`label`,{className:`anthropic-pool-card__native-messages`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:a?L:!1,disabled:B||!a,"aria-label":i(`anthropicPool.nativeMessagesLabel`),"aria-describedby":`anthropic-pool-native-messages-help`,onChange:e=>{j({enabled:M,threshold:N,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:e.target.checked})}}),(0,Z.jsxs)(`span`,{className:`anthropic-pool-card__native-messages-copy`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:i(`anthropicPool.nativeMessagesLabel`)}),(0,Z.jsx)(`span`,{id:`anthropic-pool-native-messages-help`,className:`card-sub`,children:i(`anthropicPool.nativeMessagesHelp`)})]})]}),(0,Z.jsx)(`p`,{children:(0,Z.jsx)(`a`,{href:Bv,target:`_blank`,rel:`noreferrer`,children:i(`anthropicPool.detailsGuide`)})})]}),M&&a&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:i(`anthropicPool.threshold`)}),(0,Z.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:s,disabled:B,"aria-label":i(`anthropicPool.thresholdAria`),onChange:e=>l(e.target.value),onBlur:()=>{let e=Number(s);!Number.isInteger(e)||e<0||e>100?(l(String(N)),h(i(`anthropicPool.thresholdInvalid`))):e!==N&&j({enabled:!0,threshold:e,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:L})}}),(0,Z.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:i(`anthropicPool.thresholdHelp`)})]}),(0,Z.jsx)(B_,{strategy:P,stickyDraft:u,disabled:B,strategySelectId:`anthropic-pool-strategy`,stickyInputId:`anthropic-pool-sticky-limit`,onStrategyChange:e=>{e!==P&&j({enabled:!0,threshold:N,strategy:e,stickyLimit:F,quotaWindow:I,nativeMessages:L})},onStickyDraftChange:d,onStickyCommit:e=>{let t=Dg(e??u);t===null?(d(String(F)),h(i(`accountPool.stickyLimitInvalid`))):t===F?d(String(t)):j({enabled:!0,threshold:N,strategy:P,stickyLimit:t,quotaWindow:I,nativeMessages:L})}}),(0,Z.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:i(`accountPool.quotaWindow`)}),(0,Z.jsx)($,{id:`anthropic-pool-quota-window`,value:I,options:yg.map(e=>({value:e,label:i(Vv[e])})),disabled:B||R,label:i(`accountPool.quotaWindow`),onChange:e=>{let t=Tg(e);t!==I&&j({enabled:!0,threshold:N,strategy:P,stickyLimit:F,quotaWindow:t,nativeMessages:L})}}),(0,Z.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:i(`accountPool.quotaWindowDesc`)}),(0,Z.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:i(R?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),b&&(0,Z.jsxs)(`div`,{role:`alert`,className:`anthropic-pool-card__save-warning`,children:[(0,Z.jsx)(`p`,{children:i(`anthropicPool.saveStateUnknown`)}),g&&(0,Z.jsx)(`p`,{children:i(`anthropicPool.loadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w,onClick:()=>{_(!1),T(!0),C(e=>e+1)},children:i(`anthropicPool.reloadSettings`)})]}),v&&(0,Z.jsx)(`div`,{role:`status`,className:`anthropic-pool-card__save-warning`,children:i(`anthropicPool.saveWarning`)}),m&&(0,Z.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:m})]})}function Wv({serverDefault:e=!0}){let t=c(),[n,r]=(0,X.useState)(ng);return(0,Z.jsxs)(`label`,{className:`open-browser-pref`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:!(n??e),onChange:e=>{let t=!e.target.checked;r(t),ig(t)}}),(0,Z.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,Z.jsx)(`span`,{className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,Z.jsx)(`span`,{className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}function Gv(e){return e?.status===`ready`?e.coupons:[]}function Kv(){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 qv={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 Jv({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Z.jsx)(gt,{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,Z.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,Z.jsx)(gt,{width:12}),r===null?(0,Z.jsx)(at,{width:11}):r]})}function Yv({coupon:e,index:t,isNext:n,locale:r,t:i}){let a=e.validityEnd?fv(e.validityEnd):null;return(0,Z.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,children:[(0,Z.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Z.jsx)(gt,{width:13}),(0,Z.jsx)(`span`,{className:`credit-item-label`,children:n?i(`grokCoupon.couponNext`):i(`grokCoupon.couponLabel`,{n:String(t+1)})}),n&&(0,Z.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:i(`grokCoupon.couponNextBadge`)})]}),(0,Z.jsxs)(`div`,{className:`credit-item-dates`,children:[e.validityStart&&(0,Z.jsx)(`span`,{children:i(`grokCoupon.validFrom`,{date:uv(e.validityStart,r)})}),a!==null&&(0,Z.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`grokCoupon.expires`,{date:dv(e.validityEnd,r),days:String(a)})})]})]})}function Xv({accountId:e,accountLabel:t,entry:n,controller:r,onClose:i}){let{locale:o,t:s}=a(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),g=r.uncertain[e],[_,v]=(0,X.useState)(null),y=(0,X.useRef)(void 0);(0,X.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,X.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,X.useCallback)(e=>{e.preventDefault(),i()},[i]),x=Gv(n),S=x[0],C=()=>{if(g)return;let e=Kv();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:qv[n.code]??`grokCoupon.redeemFailed`}))},T=async()=>{g&&!m&&(h(!0),await r.refresh(e),h(!1))},E=g?Gv(n).some(e=>e.tokenId===g.tokenId):!1,D=String(x.length),O=e=>(0,Z.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:s(e.key,{count:D})});return(0,Z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`grok-coupon-title`,onCancel:b,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,Z.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:g?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Z.jsx)(`div`,{className:`confirm-icon`,children:(0,Z.jsx)(at,{width:22})}),(0,Z.jsx)(`h3`,{id:`grok-coupon-title`,children:s(`grokCoupon.title`)}),(0,Z.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:s(`grokCoupon.unknownOutcome`)}),!m&&(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(E?`grokCoupon.unresolved`:`grokCoupon.consumedElsewhere`)})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:s(`common.close`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{T()},disabled:m,children:s(m?`grokCoupon.checking`:`grokCoupon.checkResult`)})]})]}):u?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Z.jsx)(`div`,{className:`confirm-icon`,children:(0,Z.jsx)(at,{width:22})}),(0,Z.jsx)(`h3`,{id:`grok-coupon-title`,children:s(`grokCoupon.confirmTitle`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:s(`grokCoupon.confirmDesc`,{count:D})}),S?.validityEnd&&(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(`grokCoupon.confirmWhich`,{date:uv(S.validityEnd,o)})}),(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(`grokCoupon.irreversible`)}),_&&O(_)]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(!1),disabled:f,children:s(`common.cancel`)}),(0,Z.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,onClick:()=>{w()},disabled:f,children:s(f?`grokCoupon.redeeming`:`grokCoupon.redeem`)})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`h3`,{id:`grok-coupon-title`,children:[(0,Z.jsx)(gt,{width:16}),` `,s(`grokCoupon.title`)]}),(0,Z.jsx)(`div`,{className:`card-sub`,children:t}),(0,Z.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(`common.loading`)}):n.status===`error`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`faint`,role:`alert`,children:s(n.reason===`auth`?`grokCoupon.loadFailedAuth`:`grokCoupon.loadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{r.refresh(e)},children:s(`grokCoupon.retry`)})]}):x.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{style:{marginBottom:12},children:s(`grokCoupon.available`,{count:D})}),(0,Z.jsx)(`div`,{className:`credit-list`,children:x.map((e,t)=>(0,Z.jsx)(Yv,{coupon:e,index:t,isNext:t===0,locale:o,t:s},e.tokenId))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:C,disabled:f,children:s(`grokCoupon.useOne`)}),(0,Z.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:s(`grokCoupon.fifoNote`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`faint`,children:s(`grokCoupon.none`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:s(`grokCoupon.desc`)})]}),_&&O(_)]})]})})]})}var Zv=2e4,Qv=6e4,$v=3,ey={},ty=[`five_hour`,`seven_day`,`seven_day_overage_included`],ny=new Set([`unknown_outcome`,`journal_write_failed`,`in_flight`]);function ry(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iy(e){return e==null?null:typeof e==`string`?e:void 0}function ay(e){if(!ry(e))return null;let{id:t,label:n,resetsTotal:r,resetsLeft:i,paused:a,usableNow:o,useRequiresLimit:s}=e,c=iy(e.startsAt),l=iy(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(ry(e.percentUsed))for(let t of ty){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:ty.filter(t=>e.clears.includes(t))}}function oy(e){if(!ry(e)||typeof e.eligible!=`boolean`||!Array.isArray(e.grants))return null;let t=[];for(let n of e.grants){let e=ay(n);if(!e)return null;t.push(e)}let n=null,r=e.pendingOperation;return ry(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 sy(e){return e.eligible?e.grants.reduce((e,t)=>e+t.resetsLeft,0):0}function cy(e){if(e.eligible&&e.journalAvailable)return e.grants.find(t=>!t.paused&&t.usableNow&&t.resetsLeft>0&&(!t.useRequiresLimit||e.atLimit))}function ly(e){return ry(e)&&ry(e.error)&&typeof e.error.code==`string`&&e.error.code!==``?e.error.code:`failed`}function uy({apiBase:t,provider:n=`anthropic`,accountIds:r,enabled:i}){let a=`${t}\0${n}`,[o,s]=(0,X.useState)(()=>({namespace:a,entries:{}})),c=(0,X.useRef)(0),l=(0,X.useRef)(new Map),u=(0,X.useRef)({active:0,waiting:[]}),d=r.join(`\0`);(0,X.useLayoutEffect)(()=>{c.current+=1,l.current.clear();let e=u.current;u.current={active:0,waiting:[]};for(let t of e.waiting.splice(0))t();return()=>{c.current+=1}},[a]);let f=(0,X.useCallback)((e,t)=>{s(n=>({namespace:a,entries:{...n.namespace===a?n.entries:{},[e]:t}}))},[a]),p=(0,X.useCallback)(async(r,i)=>{if(c.current!==i)return;let a=(l.current.get(r)??0)+1;l.current.set(r,a);let o=u.current;o.active>=$v&&await new Promise(e=>o.waiting.push(e)),o.active+=1;let s=()=>c.current===i&&l.current.get(r)===a,d=e(Zv);try{if(!s())return;let e=await fetch(`${t}/api/anthropic/reset-grants?accountId=${encodeURIComponent(r)}${n===`anthropic`?``:`&provider=${encodeURIComponent(n)}`}`,{signal:d.signal}),i=e.ok?await e.json().catch(()=>null):null,a=ry(i)&&(i.provider===n||n===`anthropic`&&i.provider===void 0)?oy(i):null;if(!s())return;f(r,a?{status:`ready`,snapshot:a}:{status:`error`,reason:e.status===401?`auth`:`upstream`})}catch{if(!s())return;f(r,{status:`error`,reason:`upstream`})}finally{d.clear(),--o.active,o.waiting.shift()?.()}},[t,n,f]);(0,X.useEffect)(()=>{if(!i||d===``)return;let e=++c.current;return Promise.resolve().then(()=>{for(let t of d.split(`\0`))p(t,e)}),()=>{c.current+=1}},[i,d,p]);let m=(0,X.useCallback)(async e=>{f(e,{status:`loading`}),await p(e,c.current)},[p,f]),h=(0,X.useCallback)(async(r,i)=>{let a=c.current,o=e(Qv);try{let e=await fetch(`${t}/api/anthropic/reset-grants/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n===`anthropic`?{}:{provider:n},accountId:r,grantId:i.grantId,operationId:i.operationId}),signal:o.signal});if(!e.ok){let t=ly(await e.json().catch(()=>null));return ny.has(t)?{kind:`unknown`,code:t}:{kind:`refused`,code:t}}let s=await e.json().catch(()=>null);return!ry(s)||typeof s.code!=`string`||s.provider!==n&&(n!==`anthropic`||s.provider!==void 0)?{kind:`unknown`,code:`unknown_outcome`}:(a===c.current&&p(r,a),{kind:`settled`,code:s.code,replayed:s.replayed===!0,resetsLeft:typeof s.resetsLeft==`number`?s.resetsLeft:null})}catch{return{kind:`unknown`,code:`aborted`}}finally{o.clear()}},[t,n,p]);return{entries:o.namespace===a?o.entries:ey,refresh:m,spend:h}}function dy(){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 fy={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`},py={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 my({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Z.jsx)(gt,{width:12}),`0`]});let r=e.status===`ready`?sy(e.snapshot):null,i=e.status===`ready`&&cy(e.snapshot)!==void 0,a=r===null?n(`anthropicGrant.badgeErrorAria`):n(`anthropicGrant.badgeAria`,{count:String(r)});return(0,Z.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,Z.jsx)(gt,{width:12}),r===null?(0,Z.jsx)(at,{width:11}):r]})}var hy={five_hour:`anthropicGrant.windowFiveHour`,seven_day:`anthropicGrant.windowWeekly`,seven_day_overage_included:`anthropicGrant.windowOverage`};function gy({grant:e,snapshot:t,isNext:n,locale:r,t:i}){let a=e.endsAt?fv(e.endsAt):null,o=e.paused?i(`anthropicGrant.paused`):e.usableNow?e.useRequiresLimit&&!t.atLimit?i(`anthropicGrant.requiresLimit`):null:i(`anthropicGrant.notUsable`);return(0,Z.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,"data-anthropic-grant":e.id,children:[(0,Z.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Z.jsx)(gt,{width:13}),(0,Z.jsx)(`span`,{className:`credit-item-label`,children:e.label||e.id}),(0,Z.jsx)(`span`,{className:`badge badge-muted text-micro anthropic-grant-count`,children:i(`anthropicGrant.resetsLeft`,{left:String(e.resetsLeft),total:String(e.resetsTotal)})})]}),(0,Z.jsxs)(`div`,{className:`credit-item-dates`,children:[e.startsAt&&(0,Z.jsx)(`span`,{children:i(`anthropicGrant.validFrom`,{date:uv(e.startsAt,r)})}),e.endsAt&&a!==null&&(0,Z.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`anthropicGrant.expires`,{date:dv(e.endsAt,r),days:String(a)})})]}),e.clears.length>0&&(0,Z.jsx)(`div`,{className:`anthropic-grant-windows`,children:e.clears.map(t=>(0,Z.jsx)(`span`,{className:`anthropic-grant-window`,children:i(hy[t],{percent:String(e.percentUsed[t]??0)})},t))}),o&&(0,Z.jsx)(`div`,{className:`faint text-caption anthropic-grant-note`,children:o})]})}function _y(e){return e.kind===`settled`?e.replayed&&e.code===`reset`?{tone:`ok`,key:`anthropicGrant.replayed`}:{tone:e.code===`reset`?`ok`:`warn`,key:fy[e.code]??`anthropicGrant.failed`,count:e.resetsLeft===null?`?`:String(e.resetsLeft)}:{tone:`warn`,key:py[e.code]??`anthropicGrant.failed`}}var vy=new Set([`unknown_outcome_expired`,`operation_identity_mismatch`]);function yy({accountId:e,accountLabel:t,entry:n,controller:r,onClose:i}){let{locale:o,t:s}=a(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,X.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,X.useCallback)(e=>{e.preventDefault(),i()},[i]),x=n?.status===`ready`?n.snapshot:null,S=x?.pendingOperation,C=g??(S?{grantId:S.grantId,operationId:S.operationId}:null),w=x?cy(x):void 0,T=()=>{if(!w||C)return;let e=dy();e?(y(null),d({grantId:w.id,operationId:e})):y({tone:`warn`,key:`anthropicGrant.noOperationId`})},E=async t=>{if(f)return;let n=C!==null&&C.operationId===t.operationId;p(!0);let i=await r.spend(e,t);p(!1),d(null),i.kind===`unknown`||i.kind===`refused`&&n&&!vy.has(i.code)?(_(t),y(i.kind===`refused`?_y(i):null)):(_(null),y(_y(i)),i.kind===`refused`&&r.refresh(e))},D=async()=>{m||(h(!0),await r.refresh(e),h(!1))},O=e=>(0,Z.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:s(e.key,{count:e.count??``})}),k=u&&x?x.grants.find(e=>e.id===u.grantId):void 0,A=x?sy(x):0;return(0,Z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`anthropic-grant-title`,onCancel:b,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,Z.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:C?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Z.jsx)(`div`,{className:`confirm-icon`,children:(0,Z.jsx)(at,{width:22})}),(0,Z.jsx)(`h3`,{id:`anthropic-grant-title`,children:s(`anthropicGrant.title`)}),(0,Z.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:s(`anthropicGrant.unknownOutcome`)}),v&&O(v)]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:s(`common.close`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{D()},disabled:m||f,children:s(m?`anthropicGrant.checking`:`anthropicGrant.checkResult`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,"data-anthropic-grant-retry":!0,onClick:()=>{E(C)},disabled:f||m,children:s(f?`anthropicGrant.redeeming`:`anthropicGrant.retrySame`)})]})]}):u?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Z.jsx)(`div`,{className:`confirm-icon`,children:(0,Z.jsx)(at,{width:22})}),(0,Z.jsx)(`h3`,{id:`anthropic-grant-title`,children:s(`anthropicGrant.confirmTitle`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:s(`anthropicGrant.confirmDesc`)}),k&&(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(`anthropicGrant.confirmWhich`,{label:k.label||k.id})}),(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(`anthropicGrant.irreversible`)})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(null),disabled:f,children:s(`common.cancel`)}),(0,Z.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,"data-anthropic-grant-confirm":!0,onClick:()=>{E(u)},disabled:f,children:s(f?`anthropicGrant.redeeming`:`anthropicGrant.redeem`)})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`h3`,{id:`anthropic-grant-title`,children:[(0,Z.jsx)(gt,{width:16}),` `,s(`anthropicGrant.title`)]}),(0,Z.jsx)(`div`,{className:`card-sub`,children:t}),(0,Z.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Z.jsx)(`p`,{className:`faint text-label`,children:s(`common.loading`)}):n.status===`error`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`faint`,role:`alert`,children:s(n.reason===`auth`?`anthropicGrant.loadFailedAuth`:`anthropicGrant.loadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{r.refresh(e)},children:s(`anthropicGrant.retry`)})]}):n.snapshot.eligible?n.snapshot.grants.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{style:{marginBottom:12},children:s(`anthropicGrant.available`,{count:String(A)})}),(0,Z.jsx)(`div`,{className:`credit-list`,children:n.snapshot.grants.map(e=>(0,Z.jsx)(gy,{grant:e,snapshot:n.snapshot,isNext:e.id===w?.id,locale:o,t:s},e.id))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,"data-anthropic-grant-use":!0,style:{marginTop:12,width:`100%`},onClick:T,disabled:!w||f,children:s(`anthropicGrant.useOne`)}),(0,Z.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:s(`anthropicGrant.desc`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`faint`,children:s(`anthropicGrant.none`)}),(0,Z.jsx)(`p`,{className:`modal-desc`,children:s(`anthropicGrant.desc`)})]}):(0,Z.jsx)(`p`,{className:`faint`,children:s(`anthropicGrant.ineligible`)}),v&&O(v)]})]})})]})}var by=2e4,xy=3e4,Sy=3,Cy=`ocx.grok-coupon-holds.v1`,wy=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ty=new Set([`attempt_unresolved`,`attempt_in_progress`,`attempt_reconcile_failed`,`operation_state_changed`,`redeem_failed`,`attempt_mark_failed`,`operation_token_mismatch`]),Ey=new Set([`ledger_unavailable`,`capacity`]),Dy=new Set([`redeemed`,`auth_failed`,`fetch_resets_failed`,`no_coupons_available`,`coupon_unavailable`,`token_unresolved`]),Oy=new Map,ky=new Set,Ay;function jy(e){if(!e||typeof e!=`object`)return!1;let{tokenId:t,operationId:n}=e;return typeof t==`string`&&t.trim()!==``&&typeof n==`string`&&wy.test(n)}function My(){try{let e=window.sessionStorage.getItem(Cy);if(e!==Ay){Ay=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`)&&jy(n)&&(Oy.has(e)||(Oy=new Map(Oy).set(e,{tokenId:n.tokenId,operationId:n.operationId})))}}catch{}return Oy}function Ny(e){return ky.add(e),()=>{ky.delete(e)}}function Py(){try{let e=JSON.stringify(Object.fromEntries(Oy));window.sessionStorage.setItem(Cy,e),Ay=e}catch{}for(let e of ky)e()}function Fy(e,t){Oy=new Map(Oy).set(e,{...t}),Py()}function Iy(e,t){My().get(e)?.operationId===t&&(Oy=new Map(Oy),Oy.delete(e),Py())}function Ly(e,t){return Ty.has(e)||Ey.has(e)&&!!(t&&typeof t==`object`&&`operationId`in t)}function Ry(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 zy(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 By(e){if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&t.trim()!==``)return t}return null}function Vy(e){if(!e.validityEnd)return 1/0;let t=Date.parse(e.validityEnd);return Number.isNaN(t)?1/0:t}function Hy(e){return e.toSorted((e,t)=>Vy(e)-Vy(t))}function Uy({apiBase:t,accountIds:n,enabled:r}){let[i,a]=(0,X.useState)({}),o=(0,X.useSyncExternalStore)(Ny,My,My),s=(0,X.useMemo)(()=>{let e=`${t}\u0000`;return Object.fromEntries([...o].filter(([t])=>t.startsWith(e)).map(([t,n])=>[t.slice(e.length),n]))},[t,o]),c=(0,X.useRef)(0),l=(0,X.useRef)(new Map),u=(0,X.useRef)({active:0,waiting:[]}),d=n.join(`\0`),f=(0,X.useCallback)(async(n,r)=>{let i=(l.current.get(n)??0)+1;l.current.set(n,i);let o=u.current;o.active>=Sy&&await new Promise(e=>o.waiting.push(e)),o.active+=1;let s=()=>c.current===r&&l.current.get(n)===i,d=e(by);try{let e=await fetch(`${t}/api/grok/reset-coupons?accountId=${encodeURIComponent(n)}`,{signal:d.signal}),r=e.ok?Ry(await e.json().catch(()=>null)):null;if(!s())return;a(t=>({...t,[n]:r?{status:`ready`,coupons:Hy(r)}:{status:`error`,reason:e.status===401?`auth`:`upstream`}}))}catch{if(!s())return;a(e=>({...e,[n]:{status:`error`,reason:`upstream`}}))}finally{d.clear(),--o.active,o.waiting.shift()?.()}},[t]);return(0,X.useEffect)(()=>{if(!r||d===``)return;let e=++c.current;return Promise.resolve().then(()=>{for(let t of d.split(`\0`))f(t,e)}),()=>{c.current+=1}},[r,d,f]),{entries:i,uncertain:s,refresh:(0,X.useCallback)(async e=>{a(t=>({...t,[e]:{status:`loading`}})),await f(e,c.current)},[f]),redeem:(0,X.useCallback)(async(n,r)=>{let i=`${t}\u0000${n}`,a=(e,t=`attempt_unresolved`)=>({ok:!1,code:t,replayed:!1,operationId:e.operationId,uncertain:!0}),o=My().get(i);if(o)return a(o);Fy(i,r);let s=()=>Iy(i,r.operationId),l=e(xy);try{let e=await fetch(`${t}/api/grok/reset-coupons/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:n,tokenId:r.tokenId,operationId:r.operationId}),signal:l.signal});if(!e.ok){let t=await e.json().catch(()=>null),n=zy(t);return Ly(n,t)?a(r,n):(s(),{ok:!1,code:n,replayed:!1})}let i=await e.json().catch(()=>null),o=!!(i&&typeof i==`object`&&i.replayed===!0),u=By(i);return u===null||!Dy.has(u)?a(r,u??`attempt_unresolved`):(s(),await f(n,c.current),{ok:u===`redeemed`,code:u,replayed:o})}catch{return a(r,`aborted`)}finally{l.clear()}},[t,f])}}var Wy=new Set([`builder-id`,`google`,`github`,`iam-identity-center`]),Gy=new Set([`pending`,`select-profile`,`done`,`failed`,`expired`,`cancelled`]),Ky=/^(?:af|ap|ca|eu|il|me|mx|sa|us)-(?:central|east|north|northeast|northwest|south|southeast|southwest|west)-[1-9][0-9]?$/;function qy({startUrl:e,region:t}){return/^https:\/\/[a-z0-9][a-z0-9-]{0,62}\.awsapps\.com\/start\/?(?:#\/)?$/.test(e)&&Ky.test(t)}function Jy(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.flowId!=`string`||!t.flowId||!Wy.has(t.method)||!Gy.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`||!Ky.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 Yy(e){if(!e||[...e].some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127))return null;let t=/^https:\/\/([^/?#]+)/iu.exec(e)?.[1];if(!t||t.includes(`@`)||t.includes(`:`))return null;try{let t=new URL(e);if(t.protocol!==`https:`||t.username||t.password||t.port)return null;let n=t.hostname.toLowerCase(),r=/^device\.sso\.([a-z0-9-]+)\.amazonaws\.com$/.exec(n)?.[1];return!(r&&Ky.test(r))&&n!==`kiro.dev`&&!n.endsWith(`.kiro.dev`)?null:t.href}catch{return null}}function Xy(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 Zy=new Map;function Qy(e,t){let n=JSON.stringify([e,t]),r=Zy.get(n);if(r)return r;let i=(async()=>{await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t}),keepalive:!0})})().catch(()=>{}).finally(()=>{Zy.get(n)===i&&Zy.delete(n)});return Zy.set(n,i),i}async function $y(e,t,n){let r=JSON.stringify([e,t]),i=Zy.get(r);return i?(await i,$y(e,t,n)):n()}var eb=new Map,tb=new Map,nb=new Map,rb=(e,t)=>JSON.stringify([e,t]),ib=e=>new Promise(t=>setTimeout(t,e)),ab=65536;function ob(e){try{e.body?.cancel().catch(()=>{})}catch{}}function sb(e,t,n=45e3){let r=new AbortController,i,a=!1,o,s=new Promise(e=>{o=e}),c=e=>{a||(a=!0,clearTimeout(u),o(e))},l=()=>{if(!a){r.abort();try{i?.cancel().catch(()=>{})}catch{}c({kind:`retry`})}},u=setTimeout(l,Math.max(0,n));return(async()=>{try{let n=await fetch(`${e}/api/oauth/status?provider=kiro&flowId=${encodeURIComponent(t)}`,{signal:r.signal});if(a){ob(n);return}if(n.status===404){ob(n),c({kind:`missing`});return}if(!n.ok||!n.body){ob(n),c({kind:`retry`});return}i=n.body.getReader();let o=new TextDecoder,s=``,u=0;for(;;){let e=await i.read();if(a)return;if(e.done)break;if(u+=e.value.byteLength,u>ab){l();return}s+=o.decode(e.value,{stream:!0})}s+=o.decode();let d;try{d=JSON.parse(s)}catch{c({kind:`retry`});return}let f=Jy(d);c(f?{kind:`view`,view:f}:{kind:`retry`})}catch{c({kind:`retry`})}})(),{result:s,cancel:l}}async function cb(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 lb(e,t){let n=nb.get(e)??new Set;return n.add(t),nb.set(e,n),()=>{n.delete(t),n.size===0&&nb.delete(e)}}function ub(e,t,n){let r=rb(e,t);if(tb.has(r))return tb.get(r);tb.set(r,n);for(let t of nb.get(e)??[])t(n);return n}function db(e,t,n,r=`status`){return n.flowId!==t||r===`cancel`&&n.state!==`failed`?null:n.state===`done`?ub(e,t,`added`):n.state===`failed`?ub(e,t,`failed`):n.state===`expired`||n.state===`cancelled`?ub(e,t,`ended`):null}function fb(e,t,n,r){let i=rb(e,t),a=eb.get(i);if(a)return a;let o=tb.get(i);if(o)return Promise.resolve(o);let s=Math.min(Date.now()+96e4,(n??Date.now()+9e5)+6e4),c=(async()=>{let n=r;for(;Date.now()<s;){let r=s-Date.now(),a=n??sb(e,t,Math.min(45e3,r));n=void 0;let o=await cb(a,r);if(tb.has(i))return tb.get(i);if(o.kind===`missing`)return ub(e,t,`ended`);if(o.kind===`view`){let n=db(e,t,o.view);if(n)return n}let c=s-Date.now();if(c<=0)break;await ib(Math.min(2e3,c))}return n?.cancel(),ub(e,t,`ended`)})().finally(()=>{eb.delete(i)});return eb.set(i,c),c}var pb=(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})}),mb=Symbol(`closed`),hb=(e,t)=>new Promise(n=>{if(e.closed){n(mb);return}let r=!1,i=t=>{r||(r=!0,e.closedController.signal.removeEventListener(`abort`,a),n(t))},a=()=>i(mb);e.closedController.signal.addEventListener(`abort`,a,{once:!0}),t.then(t=>i(e.closed?mb:t),()=>i(mb))});function gb(e,t,n=pb){let[r,i]=(0,X.useState)({phase:`idle`}),a=(0,X.useRef)(null),o=(0,X.useRef)(!0),s=(0,X.useRef)(t);(0,X.useEffect)(()=>{s.current=t},[t]);let c=(0,X.useCallback)(async t=>{try{return await fetch(`${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]),l=(0,X.useCallback)(t=>{let n=t.view;n&&!t.terminal&&fb(e,n.flowId,n.expiresAt,t.inFlight)},[e]),u=(0,X.useCallback)(async()=>{let t=a.current;if(!t||t.closed||(t.closed=!0,t.closedController.abort(),a.current=null,t.waitController?.abort(),o.current&&i({phase:`cancelled`}),!t.view||t.terminal))return;let n=c(t.view);l(t);let r=await n,s=r?.ok?Jy(await r.json().catch(()=>null)):null;s&&db(e,t.view.flowId,s,`cancel`)},[e,c,l]);return(0,X.useEffect)(()=>(o.current=!0,()=>{o.current=!1,u()}),[u]),{state:r,start:(0,X.useCallback)(async(t,r)=>{if(a.current)return;let u={closed:!1,closedController:new AbortController};a.current=u,i({phase:`starting`});let d;try{d=await $y(e,`kiro`,()=>fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,method:t,...t===`iam-identity-center`?r:{}})}))}catch{!u.closed&&o.current&&i({phase:`failed`,error:`network`}),a.current===u&&(a.current=null);return}let f=d.ok?Jy(await d.json().catch(()=>null)):null;if(!f||f.method!==t)!u.closed&&o.current&&i({phase:`failed`,error:d.ok?`invalid`:`start`}),a.current===u&&(a.current=null);else if(u.view=f,u.closed){let t=c(f);l(u);let n=await t,r=n?.ok?Jy(await n.json().catch(()=>null)):null;r&&db(e,f.flowId,r,`cancel`)}else if(f.state!==`pending`&&f.state!==`select-profile`)f.state===`done`?s.current?.(`kiro`,`added`):f.state===`failed`&&s.current?.(`kiro`,`failed`),o.current&&i({phase:f.state,view:f}),u.terminal=f.state===`done`?`added`:f.state===`failed`?`failed`:`ended`,a.current=null;else{for(i({phase:f.state,view:f});!u.closed&&!u.terminal;){let t=new AbortController;if(u.waitController=t,await n(2e3,t.signal),u.waitController=void 0,u.closed||u.terminal)break;if(u.view?.expiresAt&&Date.now()>=u.view.expiresAt){u.terminal=`ended`,o.current&&i({phase:`expired`,view:u.view});break}let r=f.flowId,a=sb(e,r);u.inFlight=a;let c=await hb(u,a.result);if(c===mb||u.terminal)break;if(u.inFlight=void 0,c.kind===`missing`){u.terminal=`ended`,s.current?.(`kiro`,`ended`),i({phase:`ended`,view:u.view});break}let l=c.kind===`view`?c.view:null;if(l&&l.flowId===r){if(u.view=l,l.state===`pending`||l.state===`select-profile`)u.selecting||i({phase:l.state,view:l});else{u.terminal=l.state===`done`?`added`:l.state===`failed`?`failed`:`ended`,(l.state===`done`||l.state===`failed`)&&s.current?.(`kiro`,u.terminal),i({phase:l.state,view:l});break}}}a.current===u&&(a.current=null)}},[e,c,l,n]),selectProfile:(0,X.useCallback)(async t=>{let n=a.current;if(!n||n.closed||n.terminal||n.selecting||n.view?.state!==`select-profile`)return;let r=n.view;n.selecting=!0,i({phase:`selecting`,view:r});let c=null;try{let n=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,flowId:r.flowId,profileArn:t})});n.ok&&(c=Jy(await n.json()))}catch{}n.selecting=!1,!(n.closed||n.terminal||!o.current)&&(!c||c.flowId!==r.flowId||c.method!==`iam-identity-center`?i({phase:`select-profile`,view:r,error:`profile`}):(n.view=c,(c.state===`done`||c.state===`failed`)&&(n.terminal=c.state===`done`?`added`:`failed`,s.current?.(`kiro`,n.terminal),n.waitController?.abort()),i({phase:c.state,view:c})))},[e]),close:u,reset:(0,X.useCallback)(()=>{a.current||i({phase:`idle`})},[])}}function _b({disabled:e,onCli:t,onMethod:n}){let r=c();return(0,Z.jsxs)(`div`,{className:`kiro-login-choices`,role:`group`,"aria-label":r(`kiroLogin.chooseMethod`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:t,children:r(`kiroLogin.cli`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`iam-identity-center`),children:r(`kiroLogin.iam`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`builder-id`),children:r(`kiroLogin.builderId`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`google`),children:r(`kiroLogin.google`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`github`),children:r(`kiroLogin.github`)})]})}function vb({disabled:e,onStart:t,onBack:n}){let r=c(),i=(0,X.useId)(),[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)(`us-east-1`),[u,d]=(0,X.useState)(!1);return(0,Z.jsxs)(`form`,{className:`kiro-iam-form`,onSubmit:e=>{e.preventDefault();let n={startUrl:a.trim(),region:s.trim()};qy(n)?(d(!1),t(n)):d(!0)},children:[(0,Z.jsx)(`p`,{className:`muted`,children:r(`kiroLogin.iamDescription`)}),(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${i}-portal`,children:r(`kiroLogin.startUrl`)}),(0,Z.jsx)(`input`,{className:`input`,id:`${i}-portal`,type:`url`,required:!0,maxLength:2048,value:a,disabled:e,placeholder:`https://example.awsapps.com/start`,autoComplete:`url`,"aria-describedby":u?`${i}-error`:void 0,"aria-invalid":u||void 0,onChange:e=>{o(e.target.value),d(!1)}}),(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${i}-region`,children:r(`kiroLogin.region`)}),(0,Z.jsx)(`input`,{className:`input`,id:`${i}-region`,required:!0,maxLength:32,value:s,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)}}),u&&(0,Z.jsx)(`p`,{id:`${i}-error`,role:`alert`,className:`notice-warn`,children:r(`kiroLogin.invalidIam`)}),(0,Z.jsxs)(`div`,{className:`kiro-device-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:n,children:r(`kiroLogin.back`)}),(0,Z.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:e,children:r(`kiroLogin.continue`)})]})]})}function yb({profiles:e,disabled:t,onSelect:n}){let r=c(),i=(0,X.useId)(),[a,o]=(0,X.useState)(``);return(0,Z.jsxs)(`form`,{className:`kiro-iam-form`,onSubmit:t=>{t.preventDefault(),e.some(e=>e.arn===a)&&n(a)},children:[(0,Z.jsx)(`p`,{children:r(`kiroLogin.selectProfile`)}),(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:i,children:r(`kiroLogin.profile`)}),(0,Z.jsx)($,{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,Z.jsx)(`code`,{className:`kiro-device-destination`,children:a}),(0,Z.jsx)(`div`,{className:`kiro-device-actions`,children:(0,Z.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:t||!a,children:r(`kiroLogin.saveAccount`)})})]})}function bb({apiBase:e,triggerRef:t,addAccount:n,busy:r,onCli:i,onClose:a,onSettled:o,pollDelay:s}){let l=c(),u=(0,X.useId)(),d=Ar(!0,t),f=gb(e,o,s),[p,m]=(0,X.useState)(!1),h=Xh(),{state:g}=f,_=g.view,v=_?.verificationUriComplete??_?.verificationUri,y=Yy(v),b=()=>{f.close(),a()};return(0,Z.jsxs)(`dialog`,{ref:d,className:`kiro-device-dialog`,"aria-modal":`true`,"aria-labelledby":u,onCancel:e=>{e.preventDefault(),b()},children:[(0,Z.jsx)(`h2`,{id:u,children:l(`kiroLogin.title`)}),g.phase===`idle`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted`,children:l(n?`kiroLogin.addDescription`:`kiroLogin.loginDescription`)}),p?(0,Z.jsx)(vb,{disabled:r,onBack:()=>m(!1),onStart:e=>{f.start(`iam-identity-center`,e)}}):(0,Z.jsx)(_b,{disabled:r,onCli:()=>{a(),i(n)},onMethod:e=>{e===`iam-identity-center`?m(!0):f.start(e)}})]}),g.phase===`starting`&&(0,Z.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:l(`kiroLogin.starting`)}),_?.profiles&&(g.phase===`select-profile`||g.phase===`selecting`)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(yb,{profiles:_.profiles,disabled:g.phase===`selecting`,onSelect:e=>{f.selectProfile(e)}}),g.error===`profile`&&(0,Z.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,Z.jsxs)(Z.Fragment,{children:[_.userCode&&(0,Z.jsxs)(`div`,{className:`kiro-device-code`,children:[(0,Z.jsx)(`span`,{className:`kiro-device-code-value`,children:_.userCode}),(0,Z.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,Z.jsx)(`a`,{href:y,target:`_blank`,rel:`noopener noreferrer`,children:l(`kiroLogin.openVerification`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`kiro-device-destination`,children:v}),(0,Z.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.unexpectedHost`)})]})),_.warning===`duplicate_profile_arn`&&(0,Z.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.duplicate`)}),_.warning===`manual_review_required`&&(0,Z.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.manualReview`)})]}),(0,Z.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,Z.jsxs)(`div`,{className:`kiro-device-actions`,children:[(g.phase===`failed`||g.phase===`expired`||g.phase===`ended`)&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f.reset,children:l(`kiroLogin.tryAgain`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:b,children:l(`common.cancel`)})]})]})}var xb=262144,Sb=[],Cb=[];function wb(e){return!!e.needsReauth||Oh(e.health?.status)}function Tb({initialState:e,onUpdateProvider:t}){let n=c(),[r,i]=(0,X.useState)(e),[a,o]=(0,X.useState)(e),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``);e!==a&&(o(e),i(e));let f=r===`mixed`,p=async()=>{if(!t||s)return;let e=r===!1;l(!0),d(``);try{let r=await t(`xai`,{xaiResponsesOptIn:e});if(!r.ok){d(r.error??n(`prov.updateFail`));return}i(r.xaiResponsesOptInState??e)}catch{d(n(`prov.networkError`))}finally{l(!1)}};return(0,Z.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,Z.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,Z.jsx)(`span`,{className:`pwi-auth-optin-label`,children:n(`pws.xaiChatOptIn`)}),(0,Z.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[n(`pws.xaiChatOptInDesc`),f&&(0,Z.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,n(`pws.xaiChatOptInMixed`)]})]}),u&&(0,Z.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:u})]}),(0,Z.jsx)(kn,{on:r===!1,mixed:f,onClick:()=>{p()},disabled:!t||s,label:n(`pws.xaiChatOptIn`)})]})}var Eb=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Db=new Set([`imported`,`updated`,`failed`,`unsupported`]),Ob={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 kb(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ab(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function jb(e){if(!kb(e)||Object.keys(e).some(e=>!Eb.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!Ab(t)||!Ab(n)||!Ab(r)||!Ab(i)||!Ab(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(!kb(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||!Db.has(n)||!Ob[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 Mb({item:e,apiBase:t,oauth:n,accounts:r=Sb,keys:i=Cb,accountLoadState:o=`ready`,switchingAccountId:s=null,pausingAccountId:l=null,busy:u=!1,loginHint:d,authHandlers:f,onCodexActiveNeedsReauthChange:p,codexController:m,onUpdateProvider:h}){let g=c(),{locale:_}=a(),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),S=(0,X.useRef)(null),C=(0,X.useRef)(null),w=t=>{e.name===`kiro`?x({addAccount:t}):f?.onLogin(e.name,t)},[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(!1),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(`idle`),[N,P]=(0,X.useState)(null),F=(0,X.useRef)(null),[I,L]=(0,X.useState)(``),[R,z]=(0,X.useState)(!1),[B,V]=(0,X.useState)(``),[H,U]=(0,X.useState)(!0),W=JSON.stringify([t,e.name,r.find(e=>e.active)?.id,i.find(e=>e.active)?.id]),[ee,te]=(0,X.useState)({identity:W,refreshing:!1,result:null}),ne=ee.identity===W&&ee.refreshing,G=ee.identity===W?ee.result:null,K=(0,X.useRef)(0);(0,X.useEffect)(()=>(K.current+=1,()=>{K.current+=1}),[W]);let re=f?.onRefreshQuota,q=Dm({...e,hasApiKey:e.hasApiKey||i.length>0}),ie=q===`oauth-accounts`,oe=q===`api-keys`,se=ie&&e.name===`xai`&&r.length>0,ce=Uy({apiBase:t,accountIds:(0,X.useMemo)(()=>se?r.filter(e=>!wb(e)).map(e=>e.id):[],[se,r]),enabled:se}),[le,ue]=(0,X.useState)(null),J=km(e.name)&&Am(e.name,e),de=ie&&J&&r.length>0,fe=(0,X.useMemo)(()=>de?r.filter(e=>!wb(e)).map(e=>e.id):[],[de,r]),pe=uy({apiBase:t,provider:km(e.name)?e.name:`anthropic`,accountIds:fe,enabled:de}),me=`${t}\0${e.name}`,[he,_e]=(0,X.useState)(null),ve=he?.scope===me?he.account:null,ye=e=>{_e(e?{scope:me,account:e}:null)},be=async()=>{if(!re||ne)return;let t=++K.current;te({identity:W,refreshing:!0,result:null});try{let n=await re(e.name);K.current===t&&te({identity:W,refreshing:!1,result:{ok:n,text:g(n?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}})}catch{K.current===t&&te({identity:W,refreshing:!1,result:{ok:!1,text:g(`codexAuth.quotaRefreshFailed`)}})}};if(q===`codex-accounts`)return(0,Z.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":g(`pws.availableAccounts`),children:[(0,Z.jsx)(`h3`,{className:`pwi-section-title`,children:g(`pws.availableAccounts`)}),(0,Z.jsx)(`div`,{className:`pwi-auth-body`,children:(0,Z.jsx)(zv,{apiBase:t,embedded:!0,controller:m,onActiveNeedsReauthChange:p})})]});if(!q||!f)return null;let xe=d?.provider===e.name?d:null,Se=async()=>{let n=I.trim();if(n&&!R){z(!0),V(``);try{let r=await fetch(`${t}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,input:n})});if(!r.ok){let e=await r.json().catch(()=>({}));U(!1),V(g(`prov.pasteFail`,{error:e.error||r.statusText}));return}L(``),U(!0),V(g(`prov.pasteOk`))}catch{U(!1),V(g(`modal.networkError`))}finally{z(!1)}}},Ce=r.length>0||n?.loggedIn===!0,we=r.find(e=>e.active&&e.needsReauth),Te=!!we,Ee=ie?r:i,De=!!re&&!(Ee.length>0&&Ee.every(e=>e.quotaMode===`unsupported`)),Oe=async()=>{let t=T.trim();if(t){O(!0);try{await f.onAddApiKey(e.name,t)&&(E(``),y(!1))}finally{O(!1)}}},ke=async n=>{if(n&&!k){A(!0),M(`idle`),P(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>xb){M(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{M(`invalid`);return}let i=await fetch(`${t}/api/oauth/accounts/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`google-antigravity`,format:`cockpit-tools`,document:r})});if(!i.ok){M(`failed`);return}let a=jb(await i.json().catch(()=>null));if(!a){M(`failed`);return}P(a),M(`complete`);try{await f.onRetryAccounts?.(e.name)}catch{}}catch{M(`failed`)}finally{F.current&&(F.current.value=``),A(!1)}}};return(0,Z.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":g(ie?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,Z.jsxs)(`div`,{className:`pwi-auth-head`,children:[(0,Z.jsx)(`h3`,{className:`pwi-section-title`,children:g(ie?`pws.availableAccounts`:`pws.apiKeys`)}),(ie&&Ce||oe)&&De&&(0,Z.jsxs)(`div`,{className:`pwi-auth-head-actions`,children:[G&&(0,Z.jsx)(`span`,{role:`status`,className:G.ok?`pws-status-ok`:`pws-status-warn`,children:G.text}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ne||u||!!s,onClick:()=>{be()},children:[(0,Z.jsx)(Mt,{width:14,height:14,"aria-hidden":`true`}),` `,g(ne?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Z.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,Z.jsx)(Tb,{initialState:e.xaiResponsesOptInState??!0,onUpdateProvider:h}),ie&&(0,Z.jsxs)(Z.Fragment,{children:[J&&(0,Z.jsx)(Uv,{apiBase:t,provider:km(e.name)?e.name:`anthropic`,accountCount:r.length,onThresholdChange:t=>{f?.onAccountPoolThreshold?.(e.name,t)}},`${t}:${e.name}`),e.name===`google-antigravity`&&(0,Z.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:g(`pws.cockpitImportDescription`)}),(0,Z.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:g(`pws.cockpitImportFileLabel`)}),(0,Z.jsx)(`input`,{ref:F,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:k,onChange:e=>{ke(e.currentTarget.files?.[0])}})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k,onClick:()=>F.current?.click(),children:g(k?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,Z.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[j===`invalid`&&g(`pws.cockpitImportInvalid`),j===`failed`&&g(`pws.cockpitImportFailed`),j===`complete`&&N&&g(`pws.cockpitImportComplete`,{imported:N.importedCount,updated:N.updatedCount,failed:N.failedCount,unsupported:N.unsupportedCount})]})]}),(0,Z.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,Z.jsx)(`span`,{className:`pwi-auth-dot ${Te?`pwi-auth-dot--warn`:Ce?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`pwi-auth-status-text`,children:Ce?J||r.length>0?g(`pws.loggedInTitle`):n?.email??g(`pws.loggedInTitle`):n?.error||g(`pws.notLoggedInTitle`)}),(0,Z.jsxs)(`span`,{className:`pwi-auth-actions`,children:[we&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:u,onClick:()=>void f.onReauth(e.name,we.id),children:g(`pws.reauthenticate`)}),Ce?(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onLogout(e.name),children:g(`prov.logout`)}):(0,Z.jsxs)(`button`,{ref:e.name===`kiro`?S:void 0,type:`button`,className:`btn btn-primary btn-sm`,disabled:u||e.name===`kiro`&&!!b,onClick:()=>w(!1),children:[u?(0,Z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,Z.jsx)(ae,{style:{width:13,height:13},"aria-hidden":`true`}),g(u?`prov.waitingBrowser`:`prov.login`)]})]})]}),!u&&(0,Z.jsx)(Wv,{}),u&&xe&&(0,Z.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,Z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,Z.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,Z.jsx)(`div`,{className:`pwi-auth-wait-title`,children:g(`prov.waitingBrowser`)}),(0,Z.jsx)($h,{hint:{url:xe.url,deviceCode:xe.deviceCode,instructions:xe.instructions,browserLaunch:xe.browserLaunch},paste:{value:I,busy:R,message:B,ok:H,onChange:L,onSubmit:()=>{Se()}}}),f.onCancelLogin&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onCancelLogin?.(e.name),children:g(`common.cancel`)})]})]}),o===`loading`&&r.length===0&&(0,Z.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,Z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),g(`pws.accountsLoading`)]}),o===`error`&&(0,Z.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Z.jsx)(`span`,{children:g(`pws.accountsLoadFailed`)}),f.onRetryAccounts&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onRetryAccounts?.(e.name),children:g(`pws.retryAccounts`)})]}),r.length>0&&(0,Z.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=Om(r,t,g,J),i=J?vh(t.plan):e.name===`google-antigravity`?t.plan:void 0,a=s===t.id,o=l===t.id,c=t.health?.status,d=wb(t),p=Ah(c),m=Sh(t.id),h=Nh(g,t.health),v=J?null:Ph(g,e.name,t.id,t.health);return(0,Z.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Z.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!t.paused&&!d&&!p&&!s&&!l&&f.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${i?` — ${i}`:``}${t.active?` — ${g(`pws.accountCurrent`)}`:``}`,disabled:!!(t.paused||d||p||s||l),children:[(0,Z.jsx)(`span`,{className:`pwi-auth-dot ${d?`pwi-auth-dot--warn`:t.active&&!t.paused?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Z.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Z.jsxs)(`span`,{className:`pwi-auth-row-heading`,children:[(0,Z.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),i&&(0,Z.jsx)(`span`,{className:`badge badge-green`,children:i})]}),!J&&(0,Z.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${g(`prov.accountId`)}: ${m}`].filter(Boolean).join(` · `)}),v&&(0,Z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:v}),p&&(0,Z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:g(`pws.healthCooldownHint`)}),t.paused&&(0,Z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:g(`pws.accountPausedHint`)})]}),h&&(0,Z.jsx)(`span`,{className:Dh(c),children:h}),d&&!h&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:g(`pws.reauth`)}),Xy(t,e.name)&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:g(Xy(t,e.name))}),t.paused&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,title:t.pauseDetails?bh(g,_,t.pauseDetails):void 0,children:g(`codexAuth.paused`)}),t.active&&!t.paused&&(0,Z.jsx)(`span`,{className:`badge badge-primary`,children:g(`prov.accountActive`)}),a&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:g(`pws.accountSwitching`)})]}),typeof t.paused==`boolean`&&f.onPauseAccount&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":`${g(t.paused?`codexAuth.resume`:`codexAuth.pause`)} — ${n}`,title:t.paused?g(`pws.accountPausedHint`):void 0,"aria-busy":o,disabled:u||!!s||!!l,onClick:()=>void f.onPauseAccount(e.name,t,!t.paused),children:g(t.paused?`codexAuth.resume`:`codexAuth.pause`)}),d&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:u||!!s||!!l,onClick:()=>void f.onReauth(e.name,t.id),children:g(`pws.reauthenticate`)}),se&&!d&&(0,Z.jsx)(Jv,{entry:ce.entries[t.id],t:g,onClick:()=>ue(t)}),de&&!d&&(0,Z.jsx)(my,{entry:pe.entries[t.id],t:g,onClick:()=>ye(t)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onEditAlias(e.name,`oauth`,t.id,t.alias),children:g(`prov.editAlias`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${g(`common.remove`)} — ${n}`,title:`${g(`common.remove`)} — ${n}`,disabled:!!s||!!l,onClick:()=>void f.onRemoveAccount(e.name,t),children:(0,Z.jsx)(ge,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Z.jsxs)(`div`,{className:`pwi-auth-acct-quota`,children:[J&&t.autoSwitchThresholdOverride!==void 0&&t.autoSwitchThreshold!==void 0&&f.onAccountThreshold&&(0,Z.jsx)(Th,{accountLabel:n,inputId:`anthropic-threshold-${t.id}`,globalThreshold:t.autoSwitchThreshold,override:t.autoSwitchThresholdOverride,hintText:g(`pws.anthropicAccountThresholdHint`),disabled:u||!!s||!!l,onChange:n=>f.onAccountThreshold(e.name,t,n)}),(0,Z.jsx)(jm,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})]})]},t.id)})}),le&&(0,Z.jsx)(Xv,{accountId:le.id,accountLabel:Om(r,le,g),entry:ce.entries[le.id],controller:ce,onClose:()=>ue(null)}),ve&&(0,Z.jsx)(yy,{accountId:ve.id,accountLabel:Om(r,ve,g,J),entry:pe.entries[ve.id],controller:pe,onClose:()=>ye(null)},`${t}:${e.name}:${ve.id}`),o===`ready`&&Ce&&r.length===0&&(0,Z.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:g(`pws.noAccounts`)}),Ce&&(0,Z.jsxs)(`div`,{className:`pwi-auth-actions`,children:[(0,Z.jsx)(`button`,{ref:e.name===`kiro`?C:void 0,type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w(!0),disabled:u||!!s||e.name===`kiro`&&!!b,children:g(`pws.addAccount`)}),De&&(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ne||u||!!s,onClick:()=>{be()},children:[(0,Z.jsx)(Mt,{width:14,height:14,"aria-hidden":`true`}),` `,g(ne?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),e.name===`kiro`&&b&&(0,Z.jsx)(bb,{apiBase:t,triggerRef:b.addAccount?C:S,addAccount:b.addAccount,busy:u,onClose:()=>x(null),onCli:t=>{f.onLogin(e.name,t)},onSettled:f.onNativeLoginSettled}),oe&&(0,Z.jsxs)(Z.Fragment,{children:[i.length>0&&(0,Z.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,Z.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Z.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void f.onSwitchApiKey(e.name,t),disabled:t.active&&!t.disabled,"aria-label":t.disabled?`${g(`codexAuth.resume`)} — ${t.label??t.masked}`:void 0,children:[(0,Z.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Z.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Z.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,Z.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,g(`prov.accountId`),`: `,t.id]})]}),t.disabled&&(0,Z.jsxs)(`span`,{className:`badge badge-muted`,title:t.pauseDetails?bh(g,_,t.pauseDetails):void 0,children:[g(`codexAuth.paused`),` · `,g(`codexAuth.resume`)]}),t.active&&!t.disabled&&(0,Z.jsx)(`span`,{className:`badge badge-primary`,children:g(`prov.accountActive`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onEditAlias(e.name,`api-key`,t.id,t.label),children:g(`prov.editAlias`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${g(`common.remove`)} — ${t.label??t.masked}`,title:`${g(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void f.onRemoveApiKey(e.name,t),children:(0,Z.jsx)(ge,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Z.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:(0,Z.jsx)(jm,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})})]},t.id))}),v?(0,Z.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Z.jsx)(`input`,{className:`input`,type:`password`,value:T,onChange:e=>E(e.target.value),placeholder:g(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:D}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Oe(),disabled:D||!T.trim(),children:g(D?`pws.saving`:`pws.addKey`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{y(!1),E(``)},children:g(`common.cancel`)})]}):(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>y(!0),children:g(`pws.addKey`)})]})]})]})}function Nb(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 Pb(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 Fb(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}function Ib(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}}var Lb=`https://chatgpt.com/backend-api/codex`;function Rb(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 zb(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 Bb(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Rb(e.baseUrl)!==Lb?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function Vb(e){return e.id===`openai`}function Hb(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Ub(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return e.responsesPath?.trim()&&(t.responsesPath=e.responsesPath.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),Ib(e)&&e.preserveResponsesReasoningContent===!0&&(t.preserveResponsesReasoningContent=!0),t}function Wb(e,t){return Vb(e)?Gb(e):{name:t.name.trim(),provider:Ub(t)}}function Gb(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Kb=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function qb(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 Kb(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Kb(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Kb(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Gb(i))})).ok)throw new Kb(`codexAuth.enableOpenaiFailed`)}function Jb({checked:e,onChange:t}){let n=c();return(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Z.jsx)(`input`,{name:`preserveResponsesReasoningContent`,type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:n(`pws.responsesReasoningReplay`)}),(0,Z.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:n(`pws.responsesReasoningReplayHint`)})]})]})}var Yb=[`responses`,`chat`,`messages`],Xb=[`responses`,`chat`,`messages`,`other`],Zb=[`responses`,`chat`,`messages`,`other`,`ir`,`responses-internal`],Qb=[`native`,`translated`,`legacy-bridge`,`blocked`],$b=[`preserved`,`degraded`,`unknown`],ex=[`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`],tx=new Set(Yb),nx=new Set(Xb),rx=new Set(Zb),ix=new Set(Qb),ax=new Set($b),ox=new Set(ex);function sx(e){return typeof e==`string`&&tx.has(e)}function cx(e){return typeof e==`string`&&nx.has(e)}function lx(e){return typeof e==`string`&&rx.has(e)}function ux(e){return typeof e==`string`&&ix.has(e)}function dx(e){return typeof e==`string`&&ax.has(e)}function fx(e){return typeof e==`string`&&ox.has(e)}function px(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic-messages`:return`messages`;default:return}}function mx(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic`:return`messages`;default:return`other`}}var hx=[`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`],gx=new Set(hx);function _x(e){return typeof e==`string`&&gx.has(e)}var vx={"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`]},yx={pathHops:6,reasonCodes:8,featureEffects:24,candidates:16,attempts:16,identifierLength:200},bx=[`hard-pin`,`operator`,`registry`,`provider-default`];function xx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var Sx=new Set([`passthrough`,`translated`,`degraded`,`unsupported`]);function Cx(e,t,n){return Array.isArray(e)&&e.length<=t&&e.every(n)}function wx(e){return typeof e==`string`&&e.length>0&&e.length<=yx.identifierLength&&!/[\u0000-\u001f\u007f]/.test(e)}function Tx(e){return xx(e)&&_x(e.feature)&&typeof e.disposition==`string`&&Sx.has(e.disposition)}function Ex(e){return Cx(e,yx.pathHops,lx)&&e.length>0}function Dx(e){return Cx(e,yx.reasonCodes,fx)}function Ox(e){return Cx(e,yx.featureEffects,_x)}function kx(e){return xx(e)&&wx(e.provider)&&wx(e.model)&&wx(e.adapter)&&cx(e.upstream)&&ux(e.mode)&&(e.mode===`blocked`?Array.isArray(e.requestPath):Ex(e.requestPath))&&(e.mode===`blocked`?Array.isArray(e.responsePath):Ex(e.responsePath))&&dx(e.fidelity)&&Dx(e.reasonCodes)&&Cx(e.featureEffects,yx.featureEffects,Tx)&&Ox(e.unknownFeatures)&&typeof e.eligible==`boolean`}function Ax(e){return xx(e)&&e.schemaVersion===1&&(e.basis===`preview`||e.basis===`dispatch`)&&typeof e.contractVersion==`string`&&typeof e.policyRevision==`string`&&sx(e.inbound)&&wx(e.requestedModel)&&(e.routeKind===`direct`||e.routeKind===`combo`||e.routeKind===`policy`||e.routeKind===`unknown`)&&ux(e.mode)&&Dx(e.reasonCodes)&&Cx(e.candidates,yx.candidates,kx)&&Ox(e.guaranteedFeatures)&&Ox(e.partialFeatures)}function jx(e){return xx(e)&&typeof e.ordinal==`number`&&Number.isInteger(e.ordinal)&&e.ordinal>0&&cx(e.upstream)&&ux(e.mode)&&e.mode!==`blocked`&&Ex(e.requestPath)&&(e.responsePath===void 0||Ex(e.responsePath))}function Mx(e){return!(!xx(e)||e.v!==1||!sx(e.inbound)||!ux(e.mode)||e.upstream!==void 0&&!cx(e.upstream)||!(e.mode===`blocked`?Array.isArray(e.requestPath)&&e.requestPath.length===0&&Array.isArray(e.responsePath)&&e.responsePath.length===0:Ex(e.requestPath)&&Ex(e.responsePath))||!Dx(e.reasonCodes)||typeof e.contractVersion!=`string`||e.featureEffects!==void 0&&!Cx(e.featureEffects,yx.featureEffects,Tx)||e.attempts!==void 0&&!Cx(e.attempts,yx.attempts,jx)||e.planMismatch!==void 0&&e.planMismatch!==!0)}function Nx(e){if(Mx(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 Px=new Set(bx);function Fx(e){return typeof e==`string`&&Px.has(e)}function Ix(e){return xx(e)&&wx(e.model)&&wx(e.adapter)&&Fx(e.source)}function Lx(e){return xx(e)&&wx(e.name)&&wx(e.adapter)&&Fx(e.adapterSource)&&(e.authMode===null||wx(e.authMode))&&cx(e.upstream)&&Cx(e.modelOverrides,64,Ix)&&(e.modelOverridesTruncated===void 0||e.modelOverridesTruncated===!0)}var Rx=32,zx=new Map;function Bx(e,t,n){return JSON.stringify([e,t.model,t.inbound,[...new Set(t.features)].sort(),n])}function Vx(e,t){for(zx.delete(e),zx.set(e,t);zx.size>Rx;){let e=zx.keys().next().value;if(e===void 0)break;zx.delete(e)}}function Hx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ux(e){if(!Hx(e)||e.schemaVersion!==1||typeof e.policyRevision!=`string`||!Array.isArray(e.features)||!e.features.every(_x)||!Hx(e.surfaces))return null;let t={};for(let[n,r]of Object.entries(e.surfaces)){if(!sx(n)||!Hx(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 Wx(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=Ux(await n.json());if(!r)throw Error(`invalid protocol info`);return r}async function Gx(e,t,n){try{let r=await Wx(e,n);if(!r)return{kind:`unavailable`};let i=Bx(e,t,r.policyRevision),a=zx.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 Ax(s)?(Vx(Bx(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 Kx(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=Hx(i)&&Hx(i.error)&&typeof i.error.code==`string`?i.error.code:void 0;return e?{kind:`error`,code:e}:{kind:`error`}}let a=Ux(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 qx(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!Hx(i)||i.provider===void 0?{kind:`unavailable`}:!Lx(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 Jx={native:`logs.protocol.mode.native`,translated:`logs.protocol.mode.translated`,"legacy-bridge":`logs.protocol.mode.legacyBridge`,blocked:`logs.protocol.mode.blocked`},Yx={passthrough:`logs.protocol.disposition.passthrough`,translated:`logs.protocol.disposition.translated`,degraded:`logs.protocol.disposition.degraded`,unsupported:`logs.protocol.disposition.unsupported`},Xx={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`},Zx=` → `;function Qx(e,t){return t(Xx[e])}function $x(e,t){return e.map(e=>Qx(e,t)).join(Zx)}function eS(e,t){let n=Qx(e.inbound,t);if(e.mode===`blocked`)return n;let r=e.upstream??e.requestPath[e.requestPath.length-1];return r?`${n}${Zx}${Qx(r,t)}`:n}var tS={"hard-pin":`pws.protocol.source.hardPin`,operator:`pws.protocol.source.operator`,registry:`pws.protocol.source.registry`,"provider-default":`pws.protocol.source.providerDefault`};function nS({adapter:e}){let t=c();return(0,Z.jsxs)(`span`,{className:`ppp-wire`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)(`span`,{className:`muted`,children:Qx(mx(e),t)})]})}function rS({apiBase:e,providerName:t,savedAdapter:n,draftAdapter:r,refreshKey:i}){let a=c(),o=JSON.stringify([e??``,t,n,i??``]),[s,l]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(e===void 0)return;let n=new AbortController;return qx(e,t,n.signal).then(e=>{n.signal.aborted||l(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 u=s?.key===o?s:null;if(e===void 0||!u||u.kind===`hidden`)return null;let d=r&&r!==n?r:null;return(0,Z.jsxs)(`section`,{className:`ppp-card`,"aria-labelledby":`ppp-title`,"data-testid":`provider-protocol-panel`,children:[(0,Z.jsx)(`h3`,{id:`ppp-title`,children:a(`pws.protocol.title`)}),(0,Z.jsx)(`p`,{className:`pwi-settings-hint`,children:a(`pws.protocol.note`)}),u.kind===`error`?(0,Z.jsx)(`p`,{className:`muted small`,role:`status`,children:a(`pws.protocol.loadFailed`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`dl`,{className:`ppp-kv`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`pws.protocol.adapterLabel`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(nS,{adapter:u.summary.adapter})})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`pws.protocol.source`)}),(0,Z.jsx)(`dd`,{"data-adapter-source":u.summary.adapterSource,children:a(tS[u.summary.adapterSource])})]}),u.summary.authMode&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`pws.authMode`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`code`,{children:u.summary.authMode})})]})]}),d&&(0,Z.jsx)(`p`,{className:`ppp-pending`,role:`status`,children:a(`pws.protocol.pending`,{adapter:d})}),(0,Z.jsx)(`h4`,{children:a(`pws.protocol.overrides`)}),u.summary.modelOverrides.length===0?(0,Z.jsx)(`p`,{className:`muted small`,children:a(`pws.protocol.noOverrides`)}):(0,Z.jsxs)(`table`,{className:`ppp-overrides`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.model`)}),(0,Z.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.wire`)}),(0,Z.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.source`)})]})}),(0,Z.jsx)(`tbody`,{children:u.summary.modelOverrides.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.model})}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(nS,{adapter:e.adapter})}),(0,Z.jsx)(`td`,{"data-adapter-source":e.source,children:a(tS[e.source])})]},e.model))})]}),u.summary.modelOverridesTruncated&&(0,Z.jsx)(`p`,{className:`muted small`,children:a(`pws.protocol.overridesTruncated`,{count:u.summary.modelOverrides.length})})]})]})}function iS({value:e,onChange:t,status:n=[]}){let r=c(),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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:r(`pws.keySelection`)}),(0,Z.jsx)($,{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,Z.jsx)(`h4`,{children:r(`pws.keyLimits`)}),(0,Z.jsx)(`div`,{className:`pwi-key-limits`,style:{display:`flex`,flexWrap:`wrap`,gap:12},children:[`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`].map((t,n)=>(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flex:`1 1 160px`,minWidth:0},children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:r([`pws.pacingRpm`,`pws.pacingDelay`,`pws.pacingConcurrency`][n])}),(0,Z.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,Z.jsx)(`p`,{className:`pwi-settings-hint`,children:r(`pws.keySharedQuota`)}),n.length>0&&(0,Z.jsxs)(`table`,{style:{width:`100%`,tableLayout:`fixed`,overflowWrap:`anywhere`},children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:r(`pws.keyHandle`)}),(0,Z.jsx)(`th`,{children:r(`pws.keyStarts`)}),(0,Z.jsx)(`th`,{children:r(`pws.keyInFlight`)}),(0,Z.jsx)(`th`,{children:r(`pws.pacingQueued`)}),(0,Z.jsx)(`th`,{children:r(`pws.keyWait`)})]})}),(0,Z.jsx)(`tbody`,{children:n.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.id})}),(0,Z.jsx)(`td`,{children:e.starts}),(0,Z.jsx)(`td`,{children:e.inFlight}),(0,Z.jsx)(`td`,{children:e.queued}),(0,Z.jsx)(`td`,{children:e.cooldownUntil?r(`pws.keyCooldown`):`${e.nextSlotInMs} ms`})]},e.id))})]})]})}var aS=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],oS=[];function sS(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function cS(e){return e===void 0?``:String(e)}function lS(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function uS(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function dS(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 fS({item:t,availableModels:n=oS,apiBase:r,onUpdateProvider:i,onDirtyChange:a,onRegisterSave:o}){let s=c(),l=String(t.authMode??(t.keyOptional?`local`:`key`)),u=Be(t.name,t),d=u?t.liveModels!==!1:!1,f=sS(t.upstreamHttpVersion),[p,m]=(0,X.useState)(t.adapter),[h,g]=(0,X.useState)(t.baseUrl),[_,v]=(0,X.useState)(t.defaultModel??``),[y,b]=(0,X.useState)(l),[x,S]=(0,X.useState)(t.apiKeyTransport??`x-api-key`),[C,w]=(0,X.useState)(t.note??``),[T,E]=(0,X.useState)(t.allowPrivateNetwork??!1),[D,O]=(0,X.useState)(t.preserveResponsesReasoningContent===!0),[k,A]=(0,X.useState)(d),[j,M]=(0,X.useState)(f),[N,P]=(0,X.useState)(!1),[F,I]=(0,X.useState)(null),[L,R]=(0,X.useState)(t.codexAccountMode??`pool`),[z,B]=(0,X.useState)(!1),[V,H]=(0,X.useState)(null),[U,W]=(0,X.useState)(),[ee,te]=(0,X.useState)(r===void 0?`idle`:`loading`),[ne,G]=(0,X.useState)(()=>`custom`),[K,re]=(0,X.useState)(t.requestPacing?.enabled===!0),[q,ie]=(0,X.useState)({keySelection:t.requestPacing?.keySelection,keys:t.requestPacing?.keys}),[oe,se]=(0,X.useState)(()=>cS(t.requestPacing?.requestsPerMinute)),[ce,le]=(0,X.useState)(()=>cS(t.requestPacing?.minIntervalMs)),[ue,J]=(0,X.useState)(()=>cS(t.requestPacing?.maxConcurrentRequests)),[de,fe]=(0,X.useState)(()=>({...t.requestPacing?.models??{}})),[pe,me]=(0,X.useState)(``),[he,ge]=(0,X.useState)(``),[_e,ve]=(0,X.useState)(``),[ye,be]=(0,X.useState)(``),[xe,Se]=(0,X.useState)(null);(0,X.useEffect)(()=>{m(t.adapter),g(t.baseUrl),v(t.defaultModel??``),b(String(t.authMode??(t.keyOptional?`local`:`key`))),S(t.apiKeyTransport??`x-api-key`),w(t.note??``),E(t.allowPrivateNetwork??!1),O(t.preserveResponsesReasoningContent===!0),A(d),M(f),re(t.requestPacing?.enabled===!0),ie({keySelection:t.requestPacing?.keySelection,keys:t.requestPacing?.keys}),se(cS(t.requestPacing?.requestsPerMinute)),le(cS(t.requestPacing?.minIntervalMs)),J(cS(t.requestPacing?.maxConcurrentRequests)),fe({...t.requestPacing?.models??{}}),I(null),H(null),queueMicrotask(()=>G(Pb(U,t.baseUrl)))},[t.adapter,t.baseUrl,t.defaultModel,t.authMode,t.apiKeyTransport,t.keyOptional,t.note,t.allowPrivateNetwork,t.preserveResponsesReasoningContent,d,f,t.requestPacing,U]),(0,X.useEffect)(()=>{R(t.codexAccountMode??`pool`)},[t.codexAccountMode]),(0,X.useEffect)(()=>{if(r===void 0)return;let e=!1,n=t.name,i=t.baseUrl;return fetch(`${r}/api/provider-presets`).then(e=>Bn(e)).then(t=>{if(e)return;if(!t){W(void 0),te(`error`);return}let r=(t.providers??[]).find(e=>e.id===n)?.baseUrlChoices;W(r),te(`ready`),G(Pb(r,i))}).catch(()=>{e||(W(void 0),te(`error`))}),()=>{e=!0}},[r,t.name]),(0,X.useEffect)(()=>{if(r===void 0)return;let n=!0,i=!1,a=()=>{if(i)return;i=!0;let a=e(1e4);fetch(`${r}/api/provider-request-pacing?name=${encodeURIComponent(t.name)}`,{signal:a.signal}).then(e=>Bn(e)).then(e=>{n&&e&&Se(e)}).catch(()=>void 0).finally(()=>{a.clear(),i=!1})};a();let o=Ru(a,2e3);return()=>{n=!1,o()}},[r,t.name]);let Ce=(0,X.useMemo)(()=>({enabled:K,...q,...lS(oe)===void 0?{}:{requestsPerMinute:lS(oe)},...uS(ce)===void 0?{}:{minIntervalMs:uS(ce)},...uS(ue)===void 0?{}:{maxConcurrentRequests:uS(ue)},...Object.keys(de).length>0?{models:de}:{}}),[q,ue,ce,K,de,oe]),we=!ke(t.name)&&Ib({adapter:p,baseUrl:h,authMode:y}),Ee=we&&D!==(t.preserveResponsesReasoningContent===!0),De=Ee||p.trim()!==t.adapter||h.trim()!==t.baseUrl||_.trim()!==(t.defaultModel??``)||y!==String(t.authMode??(t.keyOptional?`local`:`key`))||p.trim()===`anthropic`&&y===`key`&&x!==(t.apiKeyTransport??`x-api-key`)||C.trim()!==(t.note??``)||T!==(t.allowPrivateNetwork??!1)||k!==d||p.trim()===`cursor`&&j!==f,Oe=dS(Ce)!==dS(t.requestPacing),Ae=De||Oe;(0,X.useEffect)(()=>(a?.(Ae),()=>a?.(!1)),[Ae,a]);let je=(0,X.useMemo)(()=>{let e=new Set(n);return _.trim()&&e.add(_.trim()),t.defaultModel&&e.add(t.defaultModel),[...e].sort((e,t)=>e.localeCompare(t))},[n,_,t.defaultModel]),Me=(0,X.useMemo)(()=>{let e=[...aS];return p&&!e.includes(p)&&e.unshift(p),e},[p]),Ne=ke(t.name),Pe=ee===`ready`&&!!(U&&U.length>0),Fe=p.trim()===`anthropic`&&y===`key`,Ie=t.name===`openai`?Bb(t):`invalid`,Le=Ie===`ready`||Ie===`disabled`,Re=Ne&&ee!==`error`,ze=async()=>{if(!i)return I({ok:!1,text:s(`pws.updatesUnavailable`)}),!1;if(z)return!1;let e=Pe?Fb(U,ne,h):h.trim();if(!p.trim()||!e)return I({ok:!1,text:s(`pws.adapterBaseRequired`)}),!1;P(!0),I(null);try{if(ue.trim()!==``&&uS(ue)===void 0)return I({ok:!1,text:s(`pws.pacingCapInvalid`)}),!1;if(Object.entries(q.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 I({ok:!1,text:s(`pws.keyLimitInvalid`)}),!1;if(K&&!Ce.requestsPerMinute&&!Ce.minIntervalMs&&!Ce.maxConcurrentRequests&&!Ce.models&&!Ce.keys&&Ce.keySelection!==`round-robin`)return I({ok:!1,text:s(`pws.pacingRuleRequired`)}),!1;let n=Oe&&!De,r=n?{requestPacing:Ce}:{adapter:p.trim(),baseUrl:e,defaultModel:_.trim(),authMode:y,note:C.trim(),allowPrivateNetwork:T,...Oe?{requestPacing:Ce}:{}};n||(u&&k!==(t.liveModels!==!1)&&(r.liveModels=k),Ee&&(r.preserveResponsesReasoningContent=D),p.trim()===`cursor`&&j!==f&&(r.upstreamHttpVersion=j===`http1.1`?`http1.1`:null),Fe?r.apiKeyTransport=x:t.apiKeyTransport!==void 0&&(r.apiKeyTransport=``));let a=await i(t.name,r);return I(a.ok?{ok:!0,text:s(`pws.settingsSaved`)}:{ok:!1,text:a.error||s(`prov.saveFailed`)}),a.ok}finally{P(!1)}},Ve=(0,X.useRef)(ze);(0,X.useEffect)(()=>{Ve.current=ze}),(0,X.useEffect)(()=>{if(o)return o(()=>Ve.current()),()=>o(null)},[o]);let He=async e=>{if(!(z||N||e===L)){if(!i)H({ok:!1,text:s(`pws.updatesUnavailable`)});else{B(!0),H(null);try{let t=await i(`openai`,{codexAccountMode:e});t.ok?(R(e),H({ok:!0,text:s(`pws.accountModeSaved`)})):H({ok:!1,text:t.error||s(`pws.accountModeFailed`)})}catch{H({ok:!1,text:s(`pws.accountModeFailed`)})}finally{B(!1)}}}},Ue=async e=>{await Nu({message:s(`pws.accountModeConfirm`)})&&await He(e)},We=()=>{m(t.adapter),g(t.baseUrl),v(t.defaultModel??``),b(l),S(t.apiKeyTransport??`x-api-key`),w(t.note??``),E(t.allowPrivateNetwork??!1),A(d),O(t.preserveResponsesReasoningContent===!0),M(f),I(null),re(t.requestPacing?.enabled===!0),se(cS(t.requestPacing?.requestsPerMinute)),ie({keySelection:t.requestPacing?.keySelection,keys:t.requestPacing?.keys}),le(cS(t.requestPacing?.minIntervalMs)),J(cS(t.requestPacing?.maxConcurrentRequests)),fe({...t.requestPacing?.models??{}}),G(Pb(U,t.baseUrl))},Ge=(e,t)=>{switch(e){case`token-plan`:return s(`modal.endpoint.tokenPlan`);case`payg`:return s(`modal.endpoint.payAsYouGo`);case`custom`:return s(`modal.endpoint.custom`);default:return t}},Ke=()=>{let e=pe.trim(),t=lS(he),n=uS(_e),r=uS(ye);ye.trim()!==``&&r===void 0?I({ok:!1,text:s(`pws.pacingCapInvalid`)}):!e||t===void 0&&n===void 0&&r===void 0||(fe(i=>({...i,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n},...r===void 0?{}:{maxConcurrentRequests:r}}})),me(``),ge(``),ve(``),be(``))};return(0,Z.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,Z.jsx)(ae,{style:{width:12,height:12}}),` `,s(`pws.providerId`)]}),(0,Z.jsx)(`input`,{className:`input`,value:t.name,readOnly:!0,disabled:!0})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.adapter`)}),Ne?(0,Z.jsx)(`input`,{className:`input`,value:p,readOnly:!0,disabled:!0}):(0,Z.jsx)($,{fullWidth:!0,label:s(`modal.adapter`),value:p,onChange:m,options:Me.map(e=>({value:e,label:e}))})]}),(0,Z.jsx)(rS,{apiBase:r,providerName:t.name,savedAdapter:t.adapter,draftAdapter:p.trim(),refreshKey:`${t.baseUrl}|${t.authMode??``}`}),Pe?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.endpoint`)}),(0,Z.jsx)($,{fullWidth:!0,label:s(`modal.endpoint`),value:ne,onChange:e=>{G(e),g(Nb(U,e,h))},options:U.map(e=>({value:e.id,label:Ge(e.id,e.label)}))})]}),ne===`custom`&&(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.baseUrl`)}),(0,Z.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),placeholder:s(`modal.baseUrlPlaceholder`)})]})]}):(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.baseUrl`)}),(0,Z.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),readOnly:Re,disabled:Re})]}),p.trim()===`cursor`&&(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.cursorTransport`)}),(0,Z.jsx)($,{fullWidth:!0,label:s(`pws.cursorTransport`),value:j,onChange:e=>M(e),options:[{value:`http2`,label:s(`pws.cursorTransportHttp2`)},{value:`http1.1`,label:s(`pws.cursorTransportHttp1`)}]}),(0,Z.jsx)(`span`,{className:`pwi-settings-hint`,children:s(`pws.cursorTransportDesc`)})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.cell.defaultModel`)}),je.length>0?(0,Z.jsx)($,{fullWidth:!0,label:s(`pws.cell.defaultModel`),value:_,onChange:v,options:[{value:``,label:s(`pws.defaultModelNone`)},...je.map(e=>({value:e,label:e}))]}):(0,Z.jsx)(`input`,{className:`input`,value:_,onChange:e=>v(e.target.value),placeholder:s(`pws.optionalPlaceholder`)})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.authMode`)}),Ne?(0,Z.jsx)(`input`,{className:`input`,value:Te(t,s),readOnly:!0,disabled:!0}):(0,Z.jsx)($,{fullWidth:!0,label:s(`pws.authMode`),value:y,onChange:b,options:[{value:`key`,label:s(`modal.badge.apiKey`)},{value:`forward`,label:s(`pws.auth.chatgptPassthrough`)},{value:`oauth`,label:s(`modal.badge.oauth`)},{value:`local`,label:s(`modal.badge.local`)}]})]}),Le&&(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`codexAuth.accountModeTitle`)}),(0,Z.jsx)($,{fullWidth:!0,label:s(`codexAuth.accountModeTitle`),value:L,disabled:z||N,onChange:e=>{let t=e;t!==L&&Ue(t)},options:[{value:`pool`,label:s(`codexAuth.accountModePool`)},{value:`direct`,label:s(`codexAuth.accountModeDirect`)}]}),(0,Z.jsx)(`span`,{className:`pwi-settings-hint`,children:s(L===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),z&&(0,Z.jsx)(`span`,{className:`muted text-label`,children:s(`pws.accountSwitching`)}),V&&(0,Z.jsx)(`span`,{role:V.ok?`status`:`alert`,className:V.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:V.text})]}),Fe&&(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.apiKeyTransport`)}),(0,Z.jsx)($,{fullWidth:!0,label:s(`modal.apiKeyTransport`),value:x,onChange:e=>S(e),options:[{value:`x-api-key`,label:s(`modal.apiKeyTransportNative`)},{value:`bearer`,label:s(`modal.apiKeyTransportBearer`)}]})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.note`)}),(0,Z.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:C,onChange:e=>w(e.target.value),rows:2})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:T,onChange:e=>E(e.target.checked)}),(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.allowPrivateNetwork`)})]}),we&&(0,Z.jsx)(Jb,{checked:D,onChange:O}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:k,disabled:!u,onChange:e=>A(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.liveModels`)}),(0,Z.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:s(`pws.liveModelsDesc`)})]})]}),(0,Z.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,Z.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{id:`pwi-pacing-title`,children:s(`pws.pacingTitle`)}),(0,Z.jsx)(`p`,{children:s(`pws.pacingDesc`)})]}),(0,Z.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:K,onChange:e=>re(e.target.checked)}),` `,s(`pws.pacingEnabled`)]})]}),(0,Z.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingRpm`)}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:oe,onChange:e=>se(e.target.value),placeholder:`38`})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingDelay`)}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ce,onChange:e=>le(e.target.value),placeholder:`1600`})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingConcurrency`)}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ue,onChange:e=>J(e.target.value),placeholder:`8`})]})]}),(0,Z.jsx)(`p`,{className:`pwi-settings-hint`,children:s(`pws.pacingSlowerWins`)}),(0,Z.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:xe?.queued??0}),` `,s(`pws.pacingQueued`)]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsxs)(`strong`,{children:[xe?.nextSlotInMs??0,` ms`]}),` `,s(`pws.pacingNextSlot`)]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:xe?.lastModelId??s(`pws.pacingNone`)}),` `,s(`pws.pacingLastModel`)]})]}),y!==`oauth`&&y!==`forward`&&(0,Z.jsx)(iS,{value:q,onChange:ie,status:xe?.keys}),(0,Z.jsx)(`h4`,{children:s(`pws.pacingModelOverrides`)}),(0,Z.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingModel`)}),(0,Z.jsx)(`input`,{className:`input`,list:`pacing-models-${t.name}`,value:pe,onChange:e=>me(e.target.value)}),(0,Z.jsx)(`datalist`,{id:`pacing-models-${t.name}`,children:n.map(e=>(0,Z.jsx)(`option`,{value:e},e))})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingRpm`)}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:he,onChange:e=>ge(e.target.value)})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingDelay`)}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:_e,onChange:e=>ve(e.target.value)})]}),(0,Z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Z.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingConcurrency`)}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ye,onChange:e=>be(e.target.value)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ke,children:s(`pws.pacingAdd`)})]}),Object.entries(de).length>0&&(0,Z.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(de).map(([e,t])=>(0,Z.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)(`span`,{children:[t.requestsPerMinute===void 0?void 0:`${t.requestsPerMinute} ${s(`pws.pacingRpmUnit`)}`,t.minIntervalMs===void 0?void 0:`${t.minIntervalMs} ms`,t.maxConcurrentRequests===void 0?void 0:`${t.maxConcurrentRequests} ${s(`pws.pacingCapUnit`)}`].filter(e=>e!==void 0).join(` · `)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>fe(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":s(`pws.pacingRemoveModel`,{model:e}),children:s(`pws.pacingRemove`)})]},e))})]}),Ae&&(0,Z.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:s(`pws.settingsUnsavedBar`)}),(0,Z.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:We,disabled:N,children:s(`pws.discardSettings`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void ze(),disabled:N||z,children:s(N?`pws.saving`:`pws.saveSettings`)})]})]}),F&&(0,Z.jsx)(`div`,{role:F.ok?`status`:`alert`,className:F.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:F.text})]})}function pS({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=c();return(0,Z.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,Z.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,Z.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,Z.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function mS({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=c();return(0,Z.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,Z.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,Z.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,Z.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function hS({item:e,preset:t,usageTotals:n,modelUsage:r,quotaReport:i,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:l,modelRevision:u,modelRowsReady:d,onOpenModels:f,onOpenConnect:p,onCreateJevAuto:m,modelsLoading:h,modelsLoadFailed:g,onRetryModels:_,oauthEmail:v,onDeselect:y,apiBase:b,oauth:x,accounts:S,accountLoadState:C,accountsFocusToken:w=0,accountsFocusProvider:T=null,settingsFocusToken:E=0,settingsFocusProvider:D=null,switchingAccountId:O,pausingAccountId:k,keys:A,busyProvider:j,loginHint:M,authHandlers:N,onCodexActiveNeedsReauthChange:P,codexController:F,onUpdateProvider:I,isDefault:L,onRemoveProvider:R,onSetDisabled:z,onSetDefault:B,onRefreshQuota:V}){let H=c(),[U,W]=(0,X.useState)(`overview`),[ee,te]=(0,X.useState)(!1),[ne,G]=(0,X.useState)(null),[K,re]=(0,X.useState)(!1),q=(0,X.useRef)(null),[ie,ae]=(0,X.useState)(0),[se,ce]=(0,X.useState)(0),[le,ue]=(0,X.useState)(0),J=(0,X.useCallback)(e=>{q.current=e},[]),fe=e.disabled===!0,me=(0,X.useMemo)(()=>Ie(e),[e]),he=(0,X.useMemo)(()=>pe(e),[e]),_e=(0,X.useMemo)(()=>Dm(e),[e]),ve=_e===`oauth-accounts`?S?.find(e=>e.active):_e===`api-keys`?A?.find(e=>e.active):void 0,ye=T===e.name?w:0,be=de(e.name,e),xe=JSON.stringify([be?F?.activeId??``:``,be?(F?.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]),A?.find(e=>e.active)?.id??``,(A??[]).map(e=>[e.id,e.active,e.disabled===!0]),x?.loggedIn===void 0?``:String(x.loggedIn),x?.needsReauth===void 0?``:String(x.needsReauth),v??``]),Se=ah(e,b,xe,a,le);U!==`overview`&&Se.completionProbe?.status===`testing`&&Se.clearIfTesting();let Ce=(0,X.useMemo)(()=>I?async(e,t)=>{let n=await I(e,t),r=Object.keys(t).some(e=>e!==`note`&&e!==`setDefault`);return n.ok&&r&&ue(e=>e+1),n}:void 0,[I]),we=(0,X.useMemo)(()=>{if(!N)return;let e=()=>ue(e=>e+1);return{...N,async onAddApiKey(t,n){let r=await N.onAddApiKey(t,n);return r&&e(),r},...N.onNativeLoginSettled?{async onNativeLoginSettled(t,n){await N.onNativeLoginSettled?.(t,n),n===`added`&&e()}}:{}}},[N]),Te=(0,X.useMemo)(()=>[{id:`overview`,label:H(`pws.tab.overview`)},{id:`models`,label:H(`pws.tab.models`)},{id:`usage`,label:H(`pws.tab.usage`)},..._e?[{id:`accounts`,label:H(_e===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:H(`pws.tab.settings`)}],[_e,H]),Ee=(0,X.useCallback)(e=>{ee&&U===`settings`&&e!==`settings`?G(e):W(e)},[U,ee]);ye!==ie&&(!ye||_e)&&(ae(ye),ye&&_e&&(ee&&U===`settings`?G(`accounts`):W(`accounts`)));let De=D===e.name?E:0;De!==se&&(ce(De),De&&W(`settings`));let Oe=(0,X.useCallback)(()=>{ee&&U===`settings`?G(`deselect`):y()},[ee,U,y]),ke=(0,X.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%Te.length;else if(e.key===`ArrowLeft`)n=(t-1+Te.length)%Te.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=Te.length-1;else return;e.preventDefault(),Ee(Te[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[Ee,Te]),Ae=`pws-tab-${U}`,je=`pws-panel-${U}`,Me=Ge(e.name,H);return(0,Z.jsxs)(`div`,{className:`pws-detail`,children:[(0,Z.jsx)(`div`,{className:`pws-detail-head`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:Oe,children:[(0,Z.jsx)(St,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),H(`pws.allProviders`)]})}),(0,Z.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,Z.jsx)(oe,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,Z.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,Z.jsxs)(`h2`,{className:`pws-detail-title`,children:[Me,Me!==e.name&&(0,Z.jsx)(`code`,{className:`pws-detail-id`,children:e.name}),he&&(0,Z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:H(`modal.badge.local`)}),!he&&me&&(0,Z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:H(`modal.badge.free`)})]})}),(0,Z.jsxs)(`div`,{className:`pws-detail-actions`,children:[!L&&!fe&&B&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>B(e.name),children:H(`prov.setDefault`)}),R&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>R(e.name),"aria-label":H(`pws.removeConfirmTitle`),title:H(`pws.removeConfirmTitle`),children:(0,Z.jsx)(ge,{style:{width:15,height:15},"aria-hidden":`true`})}),z&&(0,Z.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,Z.jsx)(`span`,{className:`pws-detail-toggle-label`,children:H(`pws.enabledLabel`)}),(0,Z.jsx)(kn,{on:!fe,onClick:()=>z(e.name,!fe),disabled:L,label:H(`pws.enabledLabel`)})]})]})]}),(0,Z.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:Te.map((e,t)=>(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":U===e.id,tabIndex:U===e.id?0:-1,className:`pws-detail-tab${U===e.id?` pws-detail-tab--active`:``}`,onClick:()=>Ee(e.id),onKeyDown:e=>ke(e,t),children:e.label},e.id))}),(0,Z.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:je,"aria-labelledby":Ae,tabIndex:0,children:[U===`overview`&&(0,Z.jsx)(oh,{item:e,preset:t,apiBase:b,connectionIdentity:xe,probeController:Se,availableModels:a,selectedModels:s,modelRows:l,modelRowsReady:d,modelsLoading:h,modelsLoadFailed:g,onRetryModels:_,onOpenAccounts:_e?()=>Ee(`accounts`):void 0,onOpenModelsTab:()=>Ee(`models`),onOpenModels:f,onOpenConnect:p,usageTotals:n,quotaReport:i,currentQuotaReading:ve,onRefreshQuota:V,oauthEmail:v,oauth:x,onEditSettings:()=>Ee(`settings`),onViewUsage:()=>Ee(`usage`),onCreateJevAuto:m,onUpdateProvider:Ce,reauthBusy:j===e.name,onCancelLogin:N?.onCancelLogin?()=>void N.onCancelLogin?.(e.name):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);N?.onReauth(e.name,n?.id)}else Ee(`accounts`)}:void 0}),U===`models`&&(0,Z.jsx)(fh,{item:e,apiBase:b,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:l,modelRevision:u,modelRowsReady:d,onOpenModels:f,modelsLoading:h,modelsLoadFailed:g,needsReauth:(S??[]).some(e=>e.active&&e.needsReauth)||x?.needsReauth===!0,onRetryModels:_,onOpenAccounts:_e?()=>Ee(`accounts`):void 0},e.name),U===`usage`&&(0,Z.jsx)(mh,{item:e,usageTotals:n,quotaReport:i,currentQuotaReading:ve,quotaIdentity:xe,modelUsage:r,...V?{onRefreshQuota:V}:{}}),U===`accounts`&&(0,Z.jsx)(Mb,{item:e,apiBase:b,oauth:x,accounts:S,keys:A,accountLoadState:C,switchingAccountId:O,pausingAccountId:k,busy:j===e.name,loginHint:M,authHandlers:we,onUpdateProvider:Ce,onCodexActiveNeedsReauthChange:P,codexController:F}),U===`settings`&&(0,Z.jsx)(fS,{item:e,apiBase:b,availableModels:a,onUpdateProvider:Ce,onDirtyChange:te,onRegisterSave:J},e.name)]}),ne&&(0,Z.jsx)(mS,{saving:K,onCancel:()=>{K||G(null)},onDiscard:()=>{if(K)return;let e=ne;G(null),te(!1),e===`deselect`?y():W(e)},onSave:()=>{(async()=>{if(!K){re(!0);try{if(!(await q.current?.()??!1))return;let e=ne;G(null),te(!1),e===`deselect`?y():e&&W(e)}finally{re(!1)}}})()}})]})}var gS=new Set([`anthropic`,`anthropic2`,`google-antigravity`,`meta-muse`]),_S=new Set([`github-copilot`,`cursor`,`zed`]);function vS(e){let t=e.trim().toLowerCase();return gS.has(t)?`high`:_S.has(t)?`elevated`:null}function yS(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function bS(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function xS(e,t){let n=e.trim().toLowerCase();return n===`anthropic`||n===`anthropic2`?{title:`oauthTos.anthropicTitle`,body:`oauthTos.anthropicBody`,conditions:`oauthTos.anthropicConditions`,saferPath:`oauthTos.anthropicSaferPath`,acknowledge:`oauthTos.anthropicAcknowledge`,continue:`oauthTos.anthropicContinue`}:{title:yS(t),body:bS(t),conditions:null,saferPath:n===`google-antigravity`?`oauthTos.saferPath`:null,acknowledge:`oauthTos.acknowledge`,continue:`oauthTos.continue`}}function SS(e,t){return t===void 0?e:e.map(e=>({...e,active:e.id===t}))}function CS(e,t){let n=new Map(t.map(e=>[e.id,e]));return ES(e,t,!1).map(e=>TS(e)?{...e,quotaPending:n.get(e.id)?.quotaPending??!1,quotaUnavailable:n.get(e.id)?.quotaMode===e.quotaMode?n.get(e.id)?.quotaUnavailable??!1:!1,quotaFailure:e.quotaMode===`probe`&&n.get(e.id)?.quotaMode===e.quotaMode&&n.get(e.id)?.quotaUnavailable?nl(n.get(e.id)?.quotaFailure):void 0}:e)}function wS(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=ES([t],[e],!0)[0];return{...e,quota:r.quota,quotaPending:r.quotaPending,quotaUnavailable:r.quotaUnavailable,quotaFailure:r.quotaFailure}})}var TS=e=>e.quotaMode===`probe`||e.quotaMode===`passive`;function ES(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=TS(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?nl(e.quotaFailure):void 0}})}function DS(e,t){let n=t&&new Map(t.map(e=>[e.id,e.quotaMode]));return e.map(e=>TS(e)&&(!n||n.get(e.id)===e.quotaMode)?{...e,quotaUnavailable:!0,quotaPending:!1,quotaFailure:void 0}:e)}function OS(e,t=!1){let n={};for(let[t,r]of Object.entries(e))kh(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function kS(t){let{apiBase:n,t:r,config:i,aliveRef:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,codexActiveNeedsReauth:u}=t,[d,f]=(0,X.useState)({}),[p,m]=(0,X.useState)({}),[h,g]=(0,X.useState)({}),_=Object.values(h)[0]??null,v=e=>g(e?{[e.provider]:e}:{}),[y,b]=(0,X.useState)({}),x=Object.values(y)[0]??null,[S,C]=(0,X.useState)({}),[w,T]=(0,X.useState)({}),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(``),A=(0,X.useRef)({}),j=(0,X.useRef)({}),M=(0,X.useRef)({}),N=(0,X.useRef)(new Map),P=(0,X.useRef)(new Set),F=(0,X.useRef)(new Map),I=(0,X.useRef)(new Map),L=(0,X.useRef)(!0),R=(0,X.useRef)(n);(0,X.useEffect)(()=>{let e=A.current,t=P.current,r=j.current,i=M.current,a=N.current,o=F.current,s=I.current;L.current=!0;let c=R.current!==n;return R.current=n,c&&Promise.resolve().then(()=>{L.current&&R.current===n&&(f({}),b({}),g({}),T({}),m({}))}),()=>{L.current=!1;for(let t of Object.keys(e))e[t]+=1;for(let e of Object.keys(r))r[e]+=1;for(let e of Object.keys(i))i[e]+=1;a.clear(),o.clear(),s.clear();for(let e of t)e.abort();t.clear()}},[n]);let z=(0,X.useRef)(null),B=(0,X.useRef)(null),V=(0,X.useCallback)(async(t,n)=>{let r=e(2e4),i=()=>r.controller.abort();n?.aborted&&i(),n?.addEventListener(`abort`,i,{once:!0}),P.current.add(r.controller);try{let e=await fetch(t,{signal:r.signal});if(!e.ok)throw Error(String(e.status));let n=await e.json();if(r.signal.aborted)throw Error(`Quota roster deadline exceeded`);return n}finally{r.clear(),n?.removeEventListener(`abort`,i),P.current.delete(r.controller)}},[]),H=(0,X.useCallback)(async(e,t=!1)=>{if(!a.current||!L.current||R.current!==n)return!1;let r=[...new Set(e)];return m(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=(A.current[r]??0)+1;A.current[r]=i;let o=(j.current[r]??0)+1;j.current[r]=o;let s=()=>a.current&&L.current&&R.current===n&&A.current[r]===i,c=()=>s()&&j.current[r]===o,l=`${n}/api/oauth/accounts?provider=${encodeURIComponent(e)}`;try{let i=await V(l);if(!Array.isArray(i.accounts))throw Error(`Invalid account roster`);if(!s())return!1;let o=SS(i.accounts,i.activeAccountId);if(f(t=>c()?{...t,[e]:{activeAccountId:i.activeAccountId??null,accounts:ES(o,t[e]?.accounts??[],!1)}}:t),m(t=>c()?{...t,[e]:`ready`}:t),!o.some(TS))return!0;let u=async()=>{let s=(M.current[r]??0)+1;M.current[r]=s;let u=()=>a.current&&L.current&&R.current===n&&M.current[r]===s;try{let n=await V(`${l}"a=1${t?`&refresh=1`:``}`);if(!Array.isArray(n.accounts))throw Error(`Invalid account quota roster`);if(!u())return!1;let r=SS(n.accounts,n.activeAccountId);return f(t=>u()?c()?{...t,[e]:{activeAccountId:n.activeAccountId===void 0?i.activeAccountId??null:n.activeAccountId,accounts:ES(r,t[e]?.accounts??[],!0)}}:{...t,[e]:{...t[e],accounts:wS(t[e]?.accounts??[],r)}}:t),!r.filter(e=>e.paused!==!0&&TS(e)).some(e=>e.quotaUnavailable===!0)}catch{return u()&&f(t=>u()&&t[e]?{...t,[e]:{...t[e],accounts:DS(t[e].accounts,o.filter(e=>e.paused!==!0))}}:t),!1}};return t?await u():(u(),!0)}catch{return c()&&(m(t=>c()?{...t,[e]:`error`}:t),f(t=>c()&&t[e]?{...t,[e]:{...t[e],accounts:DS(t[e].accounts)}}:t)),!1}}))).every(Boolean)},[a,n,V]),U=(0,X.useCallback)(async(e,t=!1)=>!a.current||!L.current||R.current!==n?!1:(await Promise.all([...new Set(e)].map(async e=>{let r=`key:${e}`,i=(A.current[r]??0)+1;A.current[r]=i;let o=(j.current[r]??0)+1;j.current[r]=o;let s=()=>a.current&&L.current&&R.current===n&&A.current[r]===i,c=()=>s()&&j.current[r]===o,l=`${n}/api/providers/keys?name=${encodeURIComponent(e)}`,u=()=>(c()&&T(t=>c()?{...t,[e]:DS(t[e]??[])}:t),!1);try{let i=await V(l);if(!Array.isArray(i.keys))throw Error(`Invalid key roster`);if(!s())return!1;let o=SS(i.keys,i.activeId);if(T(t=>c()?{...t,[e]:ES(o,t[e]??[],!1)}:t),!o.some(TS))return!0;let u=async()=>{let i=(M.current[r]??0)+1;M.current[r]=i;let s=()=>a.current&&L.current&&R.current===n&&M.current[r]===i;try{let n=await V(`${l}"a=1${t?`&refresh=1`:``}`);if(!Array.isArray(n.keys))throw Error(`Invalid key quota roster`);if(!s())return!1;let r=SS(n.keys,n.activeId);return T(t=>s()?{...t,[e]:c()?ES(r,t[e]??[],!0):wS(t[e]??[],r)}:t),!r.filter(e=>e.disabled!==!0&&TS(e)).some(e=>e.quotaUnavailable===!0)}catch{return s()&&T(t=>s()?{...t,[e]:DS(t[e]??[],o.filter(e=>e.disabled!==!0&&TS(e)))}:t),s()&&!o.some(e=>e.disabled!==!0&&TS(e))}};return t?await u():(u(),!0)}catch{return u()}}))).every(Boolean),[n,a,V]),W=(0,X.useCallback)(async(e,t)=>{if(!a.current||!L.current||R.current!==n||t?.aborted)return!1;let r=e?[e]:Object.entries(i?.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(N.current.has(i))return!1;let o=(j.current[i]??0)+1;j.current[i]=o;let s=()=>a.current&&L.current&&R.current===n&&!t?.aborted&&j.current[i]===o&&!N.current.has(i);try{if(r===`oauth`){let r=await V(`${n}/api/oauth/accounts?provider=${encodeURIComponent(e)}`,t);if(!Array.isArray(r.accounts)||!s())return!1;let i=SS(r.accounts,r.activeAccountId);f(t=>s()?{...t,[e]:{activeAccountId:r.activeAccountId===void 0?i.find(e=>e.active)?.id??null:r.activeAccountId,accounts:CS(i,t[e]?.accounts??[])}}:t),m(t=>s()?{...t,[e]:`ready`}:t)}else{let r=await V(`${n}/api/providers/keys?name=${encodeURIComponent(e)}`,t);if(!Array.isArray(r.keys)||!s())return!1;let i=SS(r.keys,r.activeId);T(t=>s()?{...t,[e]:CS(i,t[e]??[])}:t)}return!0}catch{return!1}}))).every(Boolean)},[a,n,i,V]),ee=(e,t)=>{let n=`${t===`oauth`?`oauth`:`key`}:${e}`;return A.current[n]=(A.current[n]??0)+1,j.current[n]=(j.current[n]??0)+1,n},te=async(e,t)=>!a.current||!L.current||R.current!==n?!1:(ee(e,`oauth`),f(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}),H([e])),ne=async(e,t)=>{if(t.active||t.needsReauth||t.paused||I.current.has(e)||F.current.has(e)||N.current.has(`oauth:${e}`))return;let i={provider:e,accountId:t.id};I.current.set(e,i),g(t=>({...t,[e]:i}));let s=ee(e,`oauth`),u=Symbol();N.current.set(s,u);let d=()=>a.current&&L.current&&R.current===n&&N.current.get(s)===u,p=se(e,t);try{let i=await fetch(`${n}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:t.id})});if(!d())return;if(!i.ok){o(r(`prov.accountSwitchFail`),!1);return}let a=await i.json().catch(()=>({}));if(!d())return;ee(e,`oauth`);let u=a.activeAccountId===void 0?t.id:a.activeAccountId;f(t=>t[e]?{...t,[e]:{...t[e],activeAccountId:u,accounts:SS(t[e].accounts,u)}}:t),N.current.delete(s);let m=await W({provider:e,kind:`oauth`});if(await Promise.all([c(),l(!0)]),!m){o(r(`pws.accountsLoadFailed`),!1);return}o(r(`prov.accountSwitched`,{email:p}),!0)}catch{d()&&o(r(`prov.accountSwitchFail`),!1)}finally{d()&&(ee(e,`oauth`),N.current.delete(s),W({provider:e,kind:`oauth`})),I.current.get(e)===i&&(I.current.delete(e),a.current&&g(t=>{let n={...t};return delete n[e],n}))}},G=async(t,i,s)=>{let c=`oauth:${t}`;if(I.current.has(t)||F.current.has(t)||N.current.has(c))return!1;let l=ee(t,`oauth`),u=Symbol();N.current.set(l,u);let d=()=>a.current&&L.current&&R.current===n&&N.current.get(l)===u,p=se(t,i);try{let r=e(2e4);P.current.add(r.controller);let a;try{let e=await fetch(`${n}/api/oauth/accounts/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:r.signal,body:JSON.stringify({provider:t,accountId:i.id,threshold:s})});if(!e.ok)throw Error(`account threshold write failed`);if(a=await e.json(),r.signal.aborted)throw Error(`account threshold deadline exceeded`)}finally{r.clear(),P.current.delete(r.controller)}let o=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100;if(!a||a.autoSwitchThresholdOverride!==null&&!o(a.autoSwitchThresholdOverride)||!o(a.autoSwitchThreshold)||!o(a.effectiveAutoSwitchThreshold))throw Error(`invalid threshold response`);return d()?(ee(t,`oauth`),f(e=>{let n=e[t];return n?{...e,[t]:{...n,accounts:n.accounts.map(e=>e.id===i.id?{...e,autoSwitchThresholdOverride:a.autoSwitchThresholdOverride,autoSwitchThreshold:a.autoSwitchThreshold,effectiveAutoSwitchThreshold:a.effectiveAutoSwitchThreshold}:e)}}:e}),!0):!1}catch{return d()&&o(r(`accountPool.autoSwitchUpdateFailed`,{email:p}),!1),!1}finally{d()&&(ee(t,`oauth`),N.current.delete(l),W({provider:t,kind:`oauth`}))}},K=async(e,t,i)=>{if(I.current.has(e)||F.current.has(e)||N.current.has(`oauth:${e}`))return;let s={provider:e,accountId:t.id};F.current.set(e,s),b(t=>({...t,[e]:{...s,paused:i}}));let u=ee(e,`oauth`),p=Symbol();N.current.set(u,p);let m=()=>a.current&&L.current&&R.current===n&&N.current.get(u)===p,h=se(e,t),g;try{let a=await fetch(`${n}/api/oauth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:t.id,paused:i})});if(!m())return;if(!a.ok){o(r(i?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:h}),!1);return}if(g=await a.json().catch(()=>({})),!m())return;ee(e,`oauth`);let s=g.activeAccountId===void 0?d[e]?.activeAccountId??null:g.activeAccountId;f(n=>{let r=n[e];if(!r)return n;let a=r.accounts.map(e=>e.id===t.id?{...e,paused:i}:e);return{...n,[e]:{activeAccountId:s,accounts:SS(a,s)}}}),N.current.delete(u)}catch{m()&&o(r(i?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:h}),!1);return}finally{m()&&(ee(e,`oauth`),N.current.delete(u),W({provider:e,kind:`oauth`})),F.current.get(e)===s&&(F.current.delete(e),a.current&&b(t=>{let n={...t};return delete n[e],n}))}if(a.current&&L.current&&R.current===n){o(r(i?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`,{email:h}),!0);try{let t=await W({provider:e,kind:`oauth`});g.activeAccountChanged&&await Promise.all([c(),l(!0)]),t||o(r(`pws.accountsLoadFailed`),!1)}catch{a.current&&L.current&&o(r(`pws.accountsLoadFailed`),!1)}}},re=async(e,t)=>{if(t.active&&!t.disabled||N.current.has(`key:${e}`))return;let i=ee(e,`api-key`),s=Symbol();N.current.set(i,s);let c=()=>a.current&&L.current&&R.current===n&&N.current.get(i)===s,u=!1;try{if(t.disabled){let i=await fetch(`${n}/api/providers/keys/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:t.id,paused:!1})});if(!c())return;if(!i.ok){o(r(`prov.keySwitchFail`),!1);return}u=!0}let i=await fetch(`${n}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:t.id})});if(!c())return;if(!i.ok){let e=await i.json().catch(()=>({}));c()&&o(u?r(`prov.keyResumedSwitchFailed`):e.error||r(`prov.keySwitchFail`),!1);return}let a=await i.json().catch(()=>({}));if(!c())return;ee(e,`api-key`);let s=a.activeId===void 0?t.id:a.activeId;T(t=>t[e]?{...t,[e]:SS(t[e],s)}:t),o(r(`prov.keySwitched`,{key:t.label??t.masked}),!0),l(!0)}catch{c()&&o(r(u?`prov.keyResumedSwitchFailed`:`prov.keySwitchFail`),!1)}finally{c()&&(ee(e,`api-key`),N.current.delete(i),W({provider:e,kind:`api-key`}))}},q=async(e,t)=>{await Nu({message:r(`prov.keyRemoveConfirm`,{key:t.label??t.masked}),confirmLabel:r(`common.remove`),tone:`danger`})&&(await fetch(`${n}/api/providers/keys?name=${encodeURIComponent(e)}&id=${encodeURIComponent(t.id)}`,{method:`DELETE`})).ok&&(o(r(`prov.keyRemoved`,{key:t.label??t.masked}),!0),U(Object.keys(w)),s(),l(!0))},ie=async(e,t)=>{let i=t.trim();if(!i)return!1;try{let t=await fetch(`${n}/api/providers/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,key:i})});if(!t.ok){let e=await t.json().catch(()=>({}));return o(e.error||r(`prov.keyAddFail`),!1),!1}return o(r(`prov.keyAdded`,{name:e}),!0),D(null),await Promise.all([U(Object.keys(w).includes(e)?Object.keys(w):[...Object.keys(w),e]),s(),l(!0)]),!0}catch{return o(r(`prov.keyAddFail`),!1),!1}},ae=async e=>{await ie(e,O)&&k(``)},oe=async(e,t,i,a)=>{let s=await Pu({message:r(`prov.aliasPrompt`),initialValue:a??``,maxLength:80,validate:e=>Gh(e,r)});if(s===null)return;let c=s.trim(),l=await fetch(t===`oauth`?`${n}/api/oauth/accounts/alias`:`${n}/api/providers/keys/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t===`oauth`?{provider:e,accountId:i,alias:c}:{name:e,id:i,alias:c})});if(l.ok)t===`oauth`?await H([e]):await U(Object.keys(w).includes(e)?Object.keys(w):[...Object.keys(w),e]),o(r(`prov.aliasSaved`),!0);else{let e=await l.json().catch(()=>({}));o(e.error||r(`prov.aliasSaveFailed`),!1)}},se=(e,t)=>Om(d[e]?.accounts??[t],t,r,km(e)&&Am(e,i?.providers[e])),ce=async(e,t)=>{let i=se(e,t);if(await Nu({message:r(`prov.accountRemoveConfirm`,{email:i}),confirmLabel:r(`common.remove`),tone:`danger`}))try{if(!(await fetch(`${n}/api/oauth/accounts?provider=${encodeURIComponent(e)}&id=${encodeURIComponent(t.id)}`,{method:`DELETE`})).ok){o(r(`prov.accountRemoveFail`,{email:i}),!1);return}o(r(`prov.accountRemoved`,{email:i}),!0),await H([e]),await Promise.all([c(),l(!0)])}catch{o(r(`prov.accountRemoveFail`,{email:i}),!1)}},le=(0,X.useMemo)(()=>i?Object.entries(i.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[i]);(0,X.useEffect)(()=>{if(le.length===0)return;let e=`${n}:${le.join(`,`)}`;z.current!==e&&(z.current=e,Promise.resolve().then(()=>{H(le)}))},[n,H,le]);let ue=(0,X.useMemo)(()=>i?Object.entries(i.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[i]);return(0,X.useEffect)(()=>{if(ue.length===0)return;let e=`${n}:${ue.join(`,`)}`;B.current!==e&&(B.current=e,Promise.resolve().then(()=>{U(ue)}))},[n,U,ue]),{accountSets:d,accountLoadStates:p,switchingAccount:_,pausingAccount:x,switchingAccounts:h,pausingAccounts:y,openAccounts:S,keyPools:w,addingKeyFor:E,newKeyValue:O,setAccountSets:f,setAccountLoadStates:m,setSwitchingAccount:v,setOpenAccounts:C,setKeyPools:T,setAddingKeyFor:D,setNewKeyValue:k,fetchAccountSets:H,fetchKeyPools:U,refreshAccountRosters:W,switchAccount:ne,pauseAccount:K,setAccountPoolThreshold:te,setAccountThreshold:G,switchApiKey:re,removeApiKey:q,addApiKeyValue:ie,addApiKey:ae,editCredentialAlias:oe,removeAccount:ce,oauthCardProviders:le,keyCardProviders:ue,activeAccountNeedsReauth:(0,X.useMemo)(()=>OS(d,u),[d,u])}}var AS=new Set([`hasApiKey`,`hasHeaders`,`xaiResponsesOptInState`,`initialModelSelection`]);function jS(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))AS.has(e)||(n[e]=structuredClone(r));return[e,n]}))}}function MS(e){let{apiBase:t,config:n,notify:r,fetchConfig:i,fetchProviderQuotas:a,onSaved:o,t:s}=e,[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),b=(0,X.useRef)(!1);(0,X.useEffect)(()=>{n&&!b.current&&d(JSON.stringify(jS(n),null,2))},[n]);let x=(0,X.useCallback)(async()=>{_(!0);let e;try{e=JSON.parse(u)}catch{return r(s(`prov.invalidJson`),!1),_(!1),!1}try{let n=JSON.parse(m),c=await fetch(`${t}/api/providers`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({baseline:n,next:e})});if(!c.ok){let e=await c.json().catch(()=>({}));return r(e.error||s(`prov.saveFailed`),!1),!1}r(s(`prov.saved`),!0),l(!1),p(!1),b.current=!1,y(!1),h(JSON.stringify(e,null,2)),i(),a(!0);let u=Object.keys(e.providers).filter(e=>!Object.hasOwn(n.providers,e));return o(u),!0}catch{return r(s(`prov.saveFailed`),!1),!1}finally{_(!1)}},[t,u,i,a,m,r,o,s]),S=(0,X.useCallback)(()=>{let e=n?JSON.stringify(jS(n),null,2):u;h(e),d(e),y(!1),p(!0),b.current=!0},[n,u]),C=(0,X.useCallback)(()=>{y(!1),p(!1),b.current=!1;let e=n?JSON.stringify(jS(n),null,2):m;h(e),d(e)},[n,m]);return{editing:c,setEditing:l,draft:u,setDraft:d,jsonEditorOpen:f,jsonBaseline:m,jsonSaving:g,jsonLeaveOpen:v,jsonEditorOpenRef:b,saveConfig:x,openJsonEditor:S,discardJsonEditor:C,requestCloseJsonEditor:(0,X.useCallback)(()=>{f&&u!==m?y(!0):C()},[C,u,m,f]),restoreJsonEditor:(0,X.useCallback)(()=>{d(m)},[m]),jsonIsDirty:f&&u!==m,setJsonLeaveOpen:y}}var NS=186e4;function PS(e,t,n){return e?Math.max(n,Math.ceil(NS/t)):n}var FS={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`},IS=e=>FS[e]??e;function LS({apiBase:e,t,aliveRef:n,accountSets:r,setAccountSets:i,setBusy:a,setStatus:o,setLoginInfo:s,setOauthStatus:c,notify:l,fetchConfig:u,fetchOauth:d,fetchAccountSets:f,fetchProviderQuotas:p,bumpModelsRefresh:m,onLoginSettled:h}){let g=(0,X.useRef)(null);g.current===null&&(g.current=new Map);let _=(0,X.useRef)(new Map),v=(0,X.useCallback)(e=>{let t=(g.current.get(e)??0)+1;return g.current.set(e,t),t},[]),y=(0,X.useCallback)(t=>Qy(e,t),[e]),b=(0,X.useCallback)(async e=>{let t=Object.keys(r);await f(new Set(t).has(e)?t:[...t,e])},[r,f]),x=(0,X.useCallback)(()=>{u(),p(!0),m()},[u,p,m]),S=(0,X.useCallback)(async(e,r)=>{if(n.current){r===`added`&&h?.(e);try{await b(e)}catch{}n.current&&(r===`added`?l(t(`prov.loginOk`,{provider:IS(e),cmd:`ocx sync`}),!0):l(r===`ended`?t(`kiroLogin.ended`):t(`prov.loginError`,{provider:IS(e),error:t(`kiroLogin.failed`)}),!1),x())}},[n,h,b,l,t,x]);return(0,X.useEffect)(()=>{let e=e=>{let t=[..._.current];_.current.clear();for(let[n,r]of t)g.current.get(n)===r&&v(n),e&&(a(e=>e===n?null:e),s(e=>e?.provider===n?null:e)),y(n)},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[v,y,a,s]),{cancelLoginOAuth:(0,X.useCallback)(async e=>{let r=v(e);_.current.delete(e),await y(e),n.current&&g.current.get(e)===r&&(a(t=>t===e?null:t),s(t=>t?.provider===e?null:t),l(t(`prov.loginCancelled`,{provider:IS(e)}),!1))},[n,v,y,l,a,s,t]),loginOAuth:async(u,d=!1,f)=>{let p=v(u);_.current.set(u,p);let m=f?.trim()||void 0;a(u),o(``),s(null);try{let a=await $y(e,u,()=>{if(n.current&&g.current.get(u)===p)return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:u,...rg(),...d||m?{addAccount:!0}:{},...m?{accountId:m,reauth:!0}:{}})})});if(!a||g.current.get(u)!==p||!n.current)return;if(!a.ok){let e=await a.json().catch(()=>({}));if(!n.current||g.current.get(u)!==p)return;l(e.error||t(`prov.loginFailStart`,{provider:IS(u)}),!1);return}let o=await a.json();if(!n.current||g.current.get(u)!==p)return;let f=ag(o.browserLaunch);(o.url||o.instructions||o.deviceCode)&&s({provider:u,url:o.url,instructions:o.instructions,deviceCode:o.deviceCode,browserLaunch:f});let _=r[u]?.accounts.length??0,v=!1,S=!!o.deviceCode;for(let r=0;r<PS(S,2e3,150)&&n.current&&g.current.get(u)===p;r++){if(await new Promise(e=>setTimeout(e,2e3)),g.current.get(u)!==p||!n.current)return;let r=await fetch(`${e}/api/oauth/status?provider=${u}`).catch(()=>null),a=r?await Bn(r)??null:null;if(!n.current||g.current.get(u)!==p)return;if(!a)continue;if(a.error){c(e=>({...e,[u]:a})),l(/cancel/i.test(a.error)?t(`prov.loginCancelled`,{provider:IS(u)}):t(`prov.loginError`,{provider:IS(u),error:a.error}),!1),s(null),v=!0;break}let o=a.accounts?.length??0;if(d||m?o>_||a.done===!0:a.loggedIn||a.done===!0){c(e=>({...e,[u]:a}));let e=m?a.accounts?.find(e=>e.id===m):a.accounts?.find(e=>e.active)??a.accounts?.find(e=>e.id===a.activeAccountId);if(m&&!e){l(t(`prov.loginError`,{provider:IS(u),error:t(`prov.reauthAccountMissing`)}),!1),s(null),v=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:IS(u),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),v=!0;break}if(a.accounts){let e=a.accounts.find(e=>e.active)?.id??null;i(t=>t[u]?t:{...t,[u]:{activeAccountId:a.activeAccountId??e,accounts:a.accounts}})}if(s(null),h?.(u),await b(u),!n.current||g.current.get(u)!==p)return;d&&!m&&o<=_?l(t(`prov.loginSameAccount`,{provider:IS(u)}),!1):l(t(`prov.loginOk`,{provider:IS(u),cmd:`ocx sync`}),!0),x(),v=!0;break}a.hint&&(a.hint.deviceCode&&(S=!0),s({provider:u,url:a.hint.url,instructions:a.hint.instructions,deviceCode:a.hint.deviceCode,browserLaunch:f}))}if(!v&&g.current.get(u)===p&&n.current){if(await y(u),!n.current||g.current.get(u)!==p)return;l(t(`prov.loginTimeout`,{provider:IS(u)}),!1),s(null)}}catch{if(g.current.get(u)===p){if(await y(u),!n.current||g.current.get(u)!==p)return;l(t(`prov.loginRequestFail`,{provider:IS(u)}),!1)}}finally{_.current.get(u)===p&&_.current.delete(u),n.current&&g.current.get(u)===p&&a(null)}},logoutOAuth:async n=>{v(n),a(e=>e===n?null:e),s(e=>e?.provider===n?null:e);try{if(!(await fetch(`${e}/api/oauth/logout?provider=${encodeURIComponent(n)}`,{method:`POST`})).ok){l(t(`prov.logoutFail`,{provider:IS(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:IS(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:IS(n)}),!1)}},onNativeLoginSettled:S}}async function RS(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function zS(e){let t=e.dependentShadowIntercept;return!t||typeof t.model!=`string`||t.enabled!==!0?null:{model:t.model,enabled:!0}}function BS(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 typeof e.error==`string`&&e.error.trim()?e.error.trim():n}}function VS({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,refreshCodexAccount:u}){let d=(0,X.useCallback)(async e=>{a(e)},[a]),f=(0,X.useCallback)(async u=>{let d=u;if(!d||n.current)return;n.current=!0,a(null);let f=t(`prov.removeFail`,{name:d});try{let n=await fetch(`${e}/api/providers?name=${encodeURIComponent(d)}`,{method:`DELETE`});if(n.ok){let e=await n.json().catch(()=>({})),a=typeof e.defaultProvider==`string`?e.defaultProvider:null,u=zS(e);u?o(t(`prov.removedShadowTarget`,{name:d,model:u.model}),!1,`warn`):o(a?t(`prov.removedDefault`,{name:d,defaultProvider:a}):t(`prov.removed`,{name:d}),!0),r===d&&i(null),s(),c(),l(!0)}else o(BS(await n.json().catch(()=>({})),t,f),!1)}catch{o(f,!1)}finally{n.current=!1}},[e,s,c,l,o,n,a,i,t,r]),p=(0,X.useCallback)(async(n,r)=>{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:r})});if(!i.ok){o(await RS(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}let a=zS(await i.json().catch(()=>({})));a?o(t(`prov.disabledShadowTarget`,{name:n,model:a.model}),!1,`warn`):o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),m=(0,X.useCallback)(async(n,r)=>{try{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok)return{ok:!1,error:await RS(i,t(`prov.updateFail`))};let a=await i.json().catch(()=>({}));if(await s(),Object.hasOwn(r,`codexAccountMode`)){let e=[l(!0)];u&&e.push(Promise.resolve(u())),await Promise.all(e)}let o=a.xaiResponsesOptInState;return{ok:!0,...o===!0||o===!1||o===`mixed`?{xaiResponsesOptInState:o}:{}}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,l,u,t]);return{removeProvider:d,confirmRemoveProvider:f,setProviderDisabled:p,setDefaultProvider:(0,X.useCallback)(async n=>{try{let r=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({setDefault:!0})});return r.ok?(o(t(`prov.setDefaultSuccess`,{name:n}),!0),await s(),!0):(o(BS(await r.json().catch(()=>({})),t,t(`prov.setDefaultFail`,{name:n})),!1),!1)}catch{return o(t(`prov.setDefaultFail`,{name:n}),!1),!1}},[e,s,o,t]),updateProvider:m}}function HS({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){let c=(0,X.useRef)(0);return(0,X.useEffect)(()=>()=>{c.current+=1},[e]),{fetchConfig:(0,X.useCallback)(async()=>{let r=++c.current;try{let t=await zn(await fetch(`${e}/api/config`));if(r!==c.current)return`superseded`;if(!t)throw Error(`config response missing`);return n(t??null),s&&t&&Nd(s,t),`applied`}catch{return r===c.current?(a(t(`prov.loadConfigFail`),!1),`failed`):`superseded`}},[e,s,a,n,t]),fetchOauth:(0,X.useCallback)(async()=>{try{let t=(await zn(await fetch(`${e}/api/oauth/providers`)))?.providers??[];r(t);let n=await Promise.all(t.map(async t=>{let n=await fetch(`${e}/api/oauth/status?provider=${encodeURIComponent(t)}`).catch(()=>null);return[t,n?await Bn(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,X.useCallback)(async(e=!1)=>{o(e)},[o])}}function US({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=c(),a=(0,X.useId)(),o=(0,X.useId)(),s=(0,X.useId)(),l=(0,X.useRef)(null),u=(0,X.useRef)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),h=vS(e);(0,X.useEffect)(()=>{let e=l.current;e&&!e.open&&e.showModal()},[]);let g=(0,X.useCallback)(e=>{e.preventDefault(),n()},[n]);if(!h)return null;let _=xS(e,h);return(0,Z.jsxs)(`dialog`,{ref:l,"aria-labelledby":a,"aria-describedby":_.conditions?`${o} ${s}`:o,className:`modal-overlay`,onCancel:g,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,Z.jsx)(`h3`,{id:a,children:i(_.title,{provider:t})}),(0,Z.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Z.jsx)(at,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Z.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(_.body,{provider:t})})]}),_.conditions&&(0,Z.jsx)(`p`,{id:s,className:`modal-desc`,style:{marginTop:12},children:i(_.conditions)}),_.saferPath&&(0,Z.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(_.saferPath)}),(0,Z.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,Z.jsx)(`span`,{className:`text-label`,children:i(_.acknowledge)})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!d||p,onClick:()=>{d&&!u.current&&(u.current=!0,m(!0),r())},children:i(_.continue)})]})]})]})}function WS(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}function GS({row:e,status:t,busyProvider:n,loginHint:r,paste:i,onLogin:a,onCancelLogin:o,onLogout:s,onManage:l}){let u=c(),d=n===e.id,f=!!t?.loggedIn,p=f?t?.email??e.statusLabel??u(`modal.accountLoggedIn`):t?.error??e.statusLabel??u(`modal.accountLoggedOut`),m=WS(e,n,r);return(0,Z.jsxs)(`div`,{className:`list-row provider-catalog-account-row${m?` provider-catalog-account-row--waiting`:``}`,children:[(0,Z.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,Z.jsx)(oe,{name:e.id,cls:`provider-icon provider-icon-sm`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`title`,children:e.label}),(0,Z.jsx)(`div`,{className:`sub`,children:p})]}),(0,Z.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,Z.jsxs)(Z.Fragment,{children:[f&&(0,Z.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:u(`modal.accountManage`)}),a&&(0,Z.jsx)(`button`,{type:`button`,className:f?`btn btn-ghost`:`btn btn-primary`,disabled:d,onClick:()=>{d||a(e.id)},children:u(d?`codexAuth.enablingOpenai`:f?`modal.accountAdd`:`modal.accountLogin`)})]}):f?(0,Z.jsxs)(Z.Fragment,{children:[l&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>l(e.id),children:u(`modal.accountManage`)}),a&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{d||a(e.id,!0)},children:u(d?`prov.waitingBrowser`:`modal.accountAdd`)}),d&&o&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:u(`common.cancel`)}),s&&!d&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>s(e.id),children:u(`modal.accountLogout`)})]}):d?o&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:u(`common.cancel`)}):a&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>a(e.id),children:u(`modal.accountLogin`)})})]}),m&&r&&(0,Z.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 KS=[`accounts`,`free`,`local`,`paid`],qS={accounts:`modal.tab.accounts`,free:`modal.tab.free`,local:`modal.tab.local`,paid:`modal.tab.paid`},JS={},YS=[],XS={};function ZS({presets:e,usageRank:t=JS,presetsLoading:n=!1,initialTier:r=`free`,query:i,onQueryChange:a,onSelectPreset:o,onSelectCustom:s,onShowNote:l,accountRows:u=YS,accountStatus:d=XS,busyProvider:f=null,loginHint:p=null,paste:m,onLogin:h,onCancelLogin:g,onLogout:_,onManage:v}){let y=c(),[b,x]=(0,X.useState)(r),S=(0,X.useId)(),C=e=>`${S}-${e}`,w=(0,X.useRef)(null),T=i.trim().length>0;(0,X.useEffect)(()=>{w.current&&(w.current.scrollTop=0)},[b,T]);let E=(0,X.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),D=(0,X.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,X.useMemo)(()=>Lm(Gm(D)),[D]),k=O[b],A=(0,X.useMemo)(()=>T?Hm(u,i,f):u,[u,i,T,f]),j=(0,X.useMemo)(()=>{let e=KS.filter(e=>e!==`accounts`);return T?e.map(e=>({tier:e,rows:Vm(Um(O[e].filter(e=>Bm(e,i)),A),i)})):b===`accounts`?[]:[{tier:b,rows:k}]},[T,b,k,O,i,A]),M=(0,X.useMemo)(()=>({...Object.fromEntries(j.map(e=>[e.tier,e.rows.length])),accounts:A.length}),[j,A]),N=KS.reduce((e,t)=>e+(M[t]??0),0),P=KS.filter(e=>(M[e]??0)>0),F=T?N:b===`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,f||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,Z.jsxs)(`h4`,{id:C(e),"data-catalog-group":e,className:`provider-catalog-group-head`,tabIndex:-1,children:[(0,Z.jsx)(`span`,{children:y(qS[e])}),(0,Z.jsx)(`span`,{className:`provider-catalog-group-count`,children:t})]}),z=e=>{let t=he(e),n=t?(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:y(`modal.badge.subscriptionCli`)}):e.codexAccountMode===`direct`?(0,Z.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,Z.jsx)(`span`,{className:`badge badge-accent`,children:y(`modal.badge.pool`)}):e.auth===`oauth`?(0,Z.jsx)(`span`,{className:`badge badge-accent`,children:y(`modal.badge.oauth`)}):e.auth===`forward`?(0,Z.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.codexLogin`)}):e.auth===`local`?(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:y(`modal.badge.local`)}):e.keyOptional?null:(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:y(`modal.badge.apiKey`)}),r=(e.freeTier||e.keyOptional)&&e.auth===`key`&&!t?(0,Z.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.free`)}):null,i=e.sponsor?(0,Z.jsx)(`span`,{className:`badge badge-accent provider-catalog-sponsor`,title:e.sponsorUrl,children:y(`modal.badge.sponsor`)}):null;return(0,Z.jsxs)(Z.Fragment,{children:[i,r,n]})};return(0,Z.jsxs)(`div`,{className:`provider-catalog`,children:[(0,Z.jsx)(`input`,{className:`input provider-catalog-search`,type:`search`,value:i,onChange:e=>a(e.target.value),onKeyDown:L,placeholder:y(`modal.search`),"aria-label":y(`modal.search`)}),T?(0,Z.jsx)(`div`,{className:`provider-catalog-tabs provider-catalog-tabs--chips`,children:KS.map(e=>(0,Z.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:[y(qS[e]),(0,Z.jsx)(`span`,{className:`provider-catalog-chip-count`,children:M[e]??0})]},e))}):(0,Z.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:KS.map(e=>(0,Z.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":b===e,"aria-controls":S,className:`provider-catalog-tab${b===e?` active`:``}`,onClick:()=>x(e),children:y(qS[e])},e))}),!T&&b===`accounts`&&(0,Z.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:y(`modal.accountsHint`)}),(0,Z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:T?N===0?y(`modal.noMatch`):y(`modal.searchResults`,{count:N,tiers:P.map(e=>y(qS[e])).join(`, `)}):``}),(0,Z.jsxs)(`div`,{className:`provider-catalog-rows`,id:S,ref:w,children:[n&&F===0&&(0,Z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:y(`modal.catalogLoading`)}),(T||b===`accounts`)&&A.length>0&&(0,Z.jsxs)(X.Fragment,{children:[T&&R(`accounts`,A.length),A.map(e=>(0,Z.jsx)(GS,{row:e,status:d[e.id],busyProvider:f,loginHint:p,...m?{paste:m}:{},...h?{onLogin:h}:{},...g?{onCancelLogin:g}:{},..._?{onLogout:_}:{},...v?{onManage:v}:{}},e.id))]},`accounts`),j.map(e=>e.rows.length===0?null:(0,Z.jsxs)(X.Fragment,{children:[T&&R(e.tier,e.rows.length),e.rows.map(e=>(0,Z.jsxs)(`div`,{className:`provider-catalog-row-wrap`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>o(e),children:[(0,Z.jsx)(oe,{name:e.id,adapter:e.adapter,cls:`provider-icon provider-icon-sm`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`title`,children:e.label}),(0,Z.jsxs)(`div`,{className:`sub`,children:[(0,Z.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,Z.jsx)(`div`,{className:`provider-catalog-badges`,children:z(e)})]}),l&&Rm(e.note)&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn provider-catalog-note-more`,onClick:()=>l(e),children:y(`modal.noteMore`)})]},e.id))]},e.tier)),!n&&F===0&&(0,Z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:y(`modal.noMatch`)})]}),(0,Z.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,Z.jsx)(`div`,{style:{flex:1}}),!T&&b!==`accounts`&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:s,children:y(`modal.notListed`)})]})]})}function QS({providerId:e,label:t,adapter:n,note:r,onClose:i}){let a=c(),o=(0,X.useId)(),s=(0,X.useId)(),l=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=l.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[]);let u=(0,X.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Z.jsxs)(`dialog`,{ref:l,"aria-labelledby":o,"aria-describedby":s,className:`modal-overlay`,onCancel:u,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:i}),(0,Z.jsxs)(`div`,{className:`modal-card provider-note-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsxs)(`h3`,{id:o,className:`provider-note-title`,children:[(0,Z.jsx)(oe,{name:e,adapter:n,cls:`provider-icon provider-icon-sm`}),t]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":a(`common.close`),onClick:i,children:(0,Z.jsx)(We,{})})]}),(0,Z.jsxs)(`div`,{id:s,className:`provider-note-body`,children:[(0,Z.jsx)(`code`,{className:`chip`,children:n}),(0,Z.jsx)(`p`,{className:`modal-desc provider-note-text`,children:r})]}),(0,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:a(`common.close`)})})]})]})}function $S({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,oauthDeviceCode:o,oauthInstructions:s,oauthBrowserLaunch:l,manualCode:u,manualCodeBusy:d,manualCodeMsg:f,manualCodeOk:p,onRequestLogin:m,onCancelLogin:h,onUseApiKeyInstead:g,onManualCodeChange:_,onSubmitManualCode:v,onBack:y}){let b=c();return(0,Z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,Z.jsx)(`div`,{className:`muted text-control`,children:e.note??b(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>m(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,Z.jsx)(ae,{}),n?b(`modal.waitingBrowser`):b(`modal.logInWith`,{label:e.label})]}),!n&&(0,Z.jsx)(Wv,{})]}):(0,Z.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:b(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,Z.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,Z.jsx)($h,{hint:{url:a,deviceCode:o,instructions:s,browserLaunch:l},paste:{value:u,busy:d,disabled:!e.oauthProvider,message:f,ok:p,onChange:_,onSubmit:()=>{e.oauthProvider&&v(e.oauthProvider)}}}),(0,Z.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:g,children:b(`modal.useApiKeyInstead`)}),(0,Z.jsx)(`div`,{style:{flex:1}}),n&&e.oauthProvider&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>h(e.oauthProvider),children:b(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:y,children:b(`modal.back`)})]})]})}function eC({label:e,children:t}){return(0,Z.jsxs)(`label`,{style:{display:`block`},children:[(0,Z.jsx)(`span`,{className:`field-label`,children:e}),t]})}var tC=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`];function nC(e){return e&&!tC.includes(e)?[e,...tC]:tC}function rC({preset:e,form:t,endpointChoice:n,error:r,saving:i,dup:a,isCustom:o,isLocal:s,isReservedForward:l,presetDescription:u,onFormChange:d,onEndpointChoiceChange:f,onSubmit:p,onUseOauthLogin:m,onBack:h}){let g=c(),_=he(t);return(0,Z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!l&&!o&&!s&&!e.keyOptional&&e.note&&(0,Z.jsxs)(`details`,{className:`setup-guide`,children:[(0,Z.jsx)(`summary`,{children:g(`modal.setupGuide`)}),(0,Z.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,Z.jsxs)(`li`,{children:[g(`modal.setupStep1Prefix`),` `,(0,Z.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:g(`modal.setupDashboardLink`,{label:e.label})}),` `,g(`modal.setupStep1Suffix`)]}),(0,Z.jsx)(`li`,{children:g(`modal.setupStep2`)}),(0,Z.jsx)(`li`,{children:g(`modal.setupStep3`)})]}),e.note&&(0,Z.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,Z.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:g(`modal.baseUrlPlaceholderHint`)})]}),(0,Z.jsx)(eC,{label:g(`modal.providerName`),children:(0,Z.jsx)(`input`,{className:`input`,value:t.name,readOnly:l,onChange:e=>d({...t,name:e.target.value}),placeholder:g(`modal.namePlaceholder`)})}),a&&(0,Z.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:g(`modal.duplicateWarn`,{name:t.name.trim()})}),!l&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(eC,{label:g(`modal.adapter`),children:(0,Z.jsx)($,{fullWidth:!0,label:g(`modal.adapter`),value:t.adapter,onChange:e=>d({...t,adapter:e}),options:nC(t.adapter).map(e=>({value:e,label:e}))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(eC,{label:g(`modal.endpoint`),children:(0,Z.jsx)($,{fullWidth:!0,label:g(`modal.endpoint`),value:n,onChange:n=>{f(n),d({...t,baseUrl:Nb(e.baseUrlChoices,n,t.baseUrl)})},options:e.baseUrlChoices.map(e=>({value:e.id,label:e.id===`token-plan`?g(`modal.endpoint.tokenPlan`):e.id===`payg`?g(`modal.endpoint.payAsYouGo`):e.id===`custom`?g(`modal.endpoint.custom`):e.label}))})}),n===`custom`&&(0,Z.jsx)(eC,{label:g(`modal.baseUrl`),children:(0,Z.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>d({...t,baseUrl:e.target.value}),placeholder:g(`modal.baseUrlPlaceholder`)})})]}):(0,Z.jsx)(eC,{label:g(`modal.baseUrl`),children:(0,Z.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>d({...t,baseUrl:e.target.value}),placeholder:g(`modal.baseUrlPlaceholder`)})}),!l&&(0,Z.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>d({...t,allowPrivateNetwork:e.target.checked})}),(0,Z.jsx)(`span`,{className:`muted text-control`,children:g(`modal.allowPrivateNetwork`)})]}),!l&&(t?.allowPrivateNetwork??!1)&&(0,Z.jsx)(`p`,{className:`muted text-hint`,children:g(`modal.allowPrivateNetworkHint`)})]}),o&&Ib(t)&&(0,Z.jsx)(Jb,{checked:t.preserveResponsesReasoningContent===!0,onChange:e=>d({...t,preserveResponsesReasoningContent:e})}),t.authMode===`forward`?(0,Z.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:u(e)}):t.authMode===`local`?(0,Z.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:g(`modal.localHint`)}):_?(0,Z.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,Z.jsx)(`strong`,{children:g(`modal.subscriptionCliTitle`)}),(0,Z.jsx)(`div`,{style:{marginTop:4},children:(0,Z.jsx)(N,{k:`modal.subscriptionCliWarning`,cmd:`claude -p`,vars:{apiProvider:ht}})})]}):e.keyOptional?(0,Z.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,Z.jsx)(`strong`,{children:g(`modal.freeTierTitle`)}),` — `,e.note??g(`modal.freeTierDefault`)]}):(0,Z.jsxs)(Z.Fragment,{children:[e.dashboardUrl&&(0,Z.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,Z.jsx)(Et,{style:{width:14,height:14}}),g(`modal.getApiKey`,{label:e.label}),(0,Z.jsx)(dt,{style:{width:13,height:13}})]}),(0,Z.jsx)(eC,{label:g(`modal.apiKey`),children:(0,Z.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>d({...t,apiKey:e.target.value}),placeholder:g(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,Z.jsx)(eC,{label:g(`modal.apiKeyTransport`),children:(0,Z.jsx)($,{fullWidth:!0,label:g(`modal.apiKeyTransport`),value:t.apiKeyTransport??`x-api-key`,onChange:e=>d({...t,apiKeyTransport:e===`bearer`?`bearer`:void 0}),options:[{value:`x-api-key`,label:g(`modal.apiKeyTransportNative`)},{value:`bearer`,label:g(`modal.apiKeyTransportBearer`)}]})})]}),!l&&(0,Z.jsx)(eC,{label:g(`modal.defaultModel`),children:(0,Z.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>d({...t,defaultModel:e.target.value}),placeholder:g(`modal.defaultModelPlaceholder`)})}),r&&(0,Z.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,Z.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:i,children:g(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:m,children:g(`modal.useOauthLogin`)}),(0,Z.jsx)(`div`,{style:{flex:1}}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:h,children:g(`modal.back`)})]})]})}var iC=2e3;function aC({apiBase:e,t,aliveRef:n,onAdded:r}){let i=(0,X.useRef)(new Map),a=(0,X.useRef)(new Map),o=(0,X.useCallback)(e=>{let t=(i.current.get(e)??0)+1;return i.current.set(e,t),t},[]),s=(0,X.useCallback)(t=>Qy(e,t),[e]);return(0,X.useEffect)(()=>{let e=e=>{let t=[...a.current];a.current.clear();for(let[n,r]of t)o(n),e&&(r.setOauthBusy(!1),r.setOauthUrl(``,n),r.setOauthMsg(``)),s(n)},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[o,s]),{cancelLoginOAuth:(0,X.useCallback)(async(e,r,c=e)=>{let l=o(e);a.current.delete(e),await s(e),n.current&&i.current.get(e)===l&&(r.setOauthBusy(!1),r.setOauthUrl(``,e),r.setOauthMsgTone(`warn`),r.setOauthMsg(t(`prov.loginCancelled`,{provider:c})))},[n,o,s,t]),loginOAuth:(0,X.useCallback)(async(c,l)=>{let{setOauthBusy:u,setOauthMsg:d,setOauthMsgTone:f,setOauthUrl:p,setManualCode:m,setManualCodeMsg:h,setManualCodeOk:g}=l,_=o(c),v=()=>i.current.get(c)===_;a.current.set(c,l),u(!0),d(``),f(`ok`),p(``,c),m(``),h(``),g(!0);try{let i=await $y(e,c,()=>{if(n.current&&v())return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:c,...rg()})})});if(!i||!n.current||!v())return;if(!i.ok){a.current.delete(c);let e=await i.json().catch(()=>({}));if(!n.current||!v())return;f(`warn`),d(e.error===`unknown oauth provider`?t(`modal.oauthComingSoonShort`):e.error||t(`modal.loginFailStart`));return}let o=await i.json();if(!n.current||!v())return;p(o.url??``,c,o.deviceCode,o.instructions,ag(o.browserLaunch)),o.url||o.deviceCode?d(t(`modal.waitingLogin`)):d(o.instructions||t(`modal.loggingIn`));let l=!!o.deviceCode;for(let i=0;i<PS(l,iC,100);i++){if(await new Promise(e=>setTimeout(e,iC)),!n.current||!v())return;let i=await fetch(`${e}/api/oauth/status?provider=${c}`).catch(()=>null),o=i?await Bn(i):null;if(!n.current||!v())return;if(o?.error){a.current.delete(c),f(`warn`),d(t(`modal.loginError`,{error:o.error}));return}if(o?.loggedIn){a.current.delete(c),d(``),r(c);return}let s=o?.hint;s&&(s.deviceCode&&(l=!0),p(s.url??``,c,s.deviceCode,s.instructions),d(s.url||s.deviceCode?t(`modal.waitingLogin`):s.instructions||t(`modal.loggingIn`)))}if(await s(c),!n.current||!v())return;a.current.delete(c),f(`warn`),d(t(`modal.loginTimeout`))}catch{v()&&await s(c),v()&&a.current.delete(c),n.current&&v()&&(f(`warn`),d(t(`modal.networkError`)))}finally{n.current&&v()&&(u(!1),p(``,c))}},[n,e,o,s,r,t]),submitManualCode:(0,X.useCallback)(async(r,i,a,o)=>{let s=i.trim();if(!s||a)return;let{setManualCodeBusy:c,setManualCode:l,setManualCodeOk:u,setManualCodeMsg:d}=o;c(!0),d(``);try{let i=await fetch(`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:r,input:s})});if(!n.current)return;if(!i.ok){let e=await i.json().catch(()=>({}));u(!1),d(t(`prov.pasteFail`,{error:e.error||i.statusText}));return}l(``),u(!0),d(t(`prov.pasteOk`))}catch{n.current&&(u(!1),d(t(`modal.networkError`)))}finally{n.current&&c(!1)}},[n,e,t])}}function oC(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 sC(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 cC({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:l,accountLoginHint:u=null,onAccountLogin:d,onAccountCancelLogin:f,onAccountLogout:p,onAccountManage:m,onOpen:h}){let g=c(),_=(0,X.useMemo)(()=>[{id:`custom`,label:g(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[g]),[v,y]=(0,X.useReducer)(sC,a,e=>oC(e,g(`modal.customProvider`))),b=(0,X.useRef)(!0),x=(0,X.useRef)(null),S=(0,X.useRef)(null),[C,w]=(0,X.useState)(null),[T,E]=(0,X.useState)(``),D=dn(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),O=dn(`add-provider-presets:${e}`,[e],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}),k=dn(Hr(e),[e],async t=>await Vr(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4}),A=D.data??[],j=O.data??_,M=O.loading,N=Object.fromEntries((k.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:P,form:F,saving:I,error:L,oauthBusy:R,oauthMsg:z,oauthMsgTone:B,oauthUrl:V,oauthUrlProvider:H,oauthDeviceCode:U,oauthInstructions:W,oauthBrowserLaunch:ee,manualCode:te,manualCodeBusy:ne,manualCodeMsg:G,manualCodeOk:K,endpointChoice:re,oauthTosPending:q}=v;(0,X.useEffect)(()=>{b.current=!0,x.current=document.activeElement,h?.();let e=S.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()=>{b.current=!1,x.current?.focus()}},[]),(0,X.useEffect)(()=>{let e=e=>{let t=!q&&!C;e.key===`Escape`&&t&&(T?E(``):n())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,q,C,T]);let ie=e=>{let t=Hb(e);return t?g(t):e.note},ae=e=>{let t=Pb(e.baseUrlChoices,e.baseUrl);y({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?Nb(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},oe=async()=>{if(!F)return;let t=P?Vb(P):!1,n=P?.baseUrlChoices?.length?Fb(P.baseUrlChoices,re,F.baseUrl):F.baseUrl.trim();if(!t&&!F.name.trim()){y({type:`set-error`,error:g(`modal.nameRequired`)});return}if(!t&&!n){y({type:`set-error`,error:g(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){y({type:`set-error`,error:g(`modal.baseUrlPlaceholderError`)});return}let i={...F,baseUrl:n},a;try{a=Wb(P??{id:`custom`},i)}catch{y({type:`set-error`,error:g(`modal.invalidPreset`)});return}y({type:`set-saving`,saving:!0}),y({type:`set-error`,error:``});try{let t=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(!t.ok){let e=await t.json().catch(()=>({}));y({type:`set-error`,error:e.error||g(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{y({type:`set-error`,error:g(`modal.networkError`)})}finally{y({type:`set-saving`,saving:!1})}},{cancelLoginOAuth:se,loginOAuth:ce,submitManualCode:le}=aC({apiBase:e,t:g,aliveRef:b,onAdded:r}),ue={setOauthBusy:e=>y({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>y({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>y({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t,n,r,i)=>y({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r,browserLaunch:i}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:G,ok:e})},J=F?t.includes(F.name.trim())&&F.name.trim()!==``:!1,de=e=>{R||(vS(e)?y({type:`set-oauth-tos-pending`,providerId:e}):ce(e,ue))},fe=e=>{le(e,te,ne,{setManualCodeBusy:e=>y({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:G,ok:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e})})},pe=P?.id===`custom`,me=F?.authMode===`local`,he=P?Vb(P):!1;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":g(`modal.add`),className:`modal-overlay`,children:(0,Z.jsxs)(`div`,{ref:S,className:`modal-card`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{children:P?g(`modal.addNamed`,{label:P.label}):g(`modal.add`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":g(`common.close`),onClick:n,children:(0,Z.jsx)(We,{})})]}),!P&&(0,Z.jsx)(Ur,{data:k.data}),P?F&&(P.auth===`oauth`&&F.authMode===`oauth`?(0,Z.jsx)($S,{preset:P,oauthSupported:A,oauthBusy:R,oauthMsg:z,oauthMsgTone:B,oauthUrl:H===P.oauthProvider?V:``,oauthDeviceCode:H===P.oauthProvider?U:``,oauthInstructions:H===P.oauthProvider?W:``,oauthBrowserLaunch:H===P.oauthProvider?ee:void 0,manualCode:te,manualCodeBusy:ne,manualCodeMsg:G,manualCodeOk:K,onRequestLogin:de,onCancelLogin:e=>{se(e,ue,P.label)},onUseApiKeyInstead:()=>{R&&P.oauthProvider&&se(P.oauthProvider,ue,P.label),y({type:`use-api-key-instead`,form:{...F,authMode:`key`}})},onManualCodeChange:e=>y({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{fe(e)},onBack:()=>{R&&P.oauthProvider&&se(P.oauthProvider,ue,P.label),y({type:`back`})}}):(0,Z.jsx)(rC,{preset:P,form:F,endpointChoice:re,error:L,saving:I,dup:J,isCustom:pe,isLocal:me,isReservedForward:he,presetDescription:ie,onFormChange:e=>y({type:`set-form`,form:e}),onEndpointChoiceChange:e=>y({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{oe()},onUseOauthLogin:()=>y({type:`use-oauth-login`,form:{...F,authMode:`oauth`}}),onBack:()=>y({type:`back`})})):(0,Z.jsx)(ZS,{presets:j,usageRank:N,presetsLoading:M,initialTier:i,query:T,onQueryChange:E,onSelectPreset:e=>ae(e),onSelectCustom:()=>ae(_[0]),onShowNote:e=>w(e),accountRows:o,accountStatus:s,busyProvider:l,onLogin:d,onCancelLogin:f,onLogout:p,onManage:m,loginHint:u,paste:{value:te,busy:ne,message:G,ok:K,onChange:e=>y({type:`set-manual-code`,code:e}),onSubmit:e=>{fe(e)}}})]})}),q&&(0,Z.jsx)(US,{providerId:q,providerLabel:P?.label??q,onCancel:()=>y({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=q;e&&(y({type:`set-oauth-tos-pending`,providerId:null}),ce(e,ue))}},q),C?.note&&(0,Z.jsx)(QS,{providerId:C.id,label:C.label,adapter:C.adapter,note:C.note,onClose:()=>w(null)},C.id)]})}function lC({apiBase:e,config:t,adding:n,modelsNotice:r,addIntent:i,busy:a,addModalAccountRows:o,accountLoginStatus:s,accountLoginHint:c,removeConfirmName:l,removeDefaultProvider:u,codexLoginOpen:d,jsonLeaveOpen:f,jsonSaving:p,oauthTosPending:m,onCloseAdd:h,onAdded:g,onAccountLogin:_,onAccountCancelLogin:v,onAccountLogout:y,onAccountManage:b,onOpenAdd:x,onCloseCodexLogin:S,onCodexAdded:C,onCancelRemove:w,onConfirmRemove:T,onCancelJsonLeave:E,onDiscardJson:D,onSaveJson:O,onCancelOauthTos:k,onContinueOauthTos:A}){return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(Lv,{...r}),n&&(0,Z.jsx)(cC,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:i?.tier,initialCustom:i?.custom,onClose:h,onAdded:g,accountRows:o,accountStatus:s,accountBusy:a,accountLoginHint:c??null,onAccountLogin:_,onAccountCancelLogin:v,onAccountLogout:y,onAccountManage:b,onOpen:x}),d&&(0,Z.jsx)(ug,{apiBase:e,onClose:S,onAdded:C}),l&&(0,Z.jsx)(pS,{providerName:l,defaultProviderName:u,onCancel:w,onConfirm:T}),f&&E&&D&&O&&(0,Z.jsx)(mS,{saving:p??!1,onCancel:E,onDiscard:D,onSave:O}),m&&(0,Z.jsx)(US,{providerId:m.provider,providerLabel:IS(m.provider),onCancel:k,onContinue:A},`${m.provider}:${m.addAccount?`add`:`login`}`)]})}function uC(e,t,n){return[...zb(e.providers).map(e=>({id:e,label:Ge(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:IS(e),kind:`oauth`}))]}function dC(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(!km(t)||!Am(t,e.providers[t]))continue;let i={...r};delete i.email,n[t]=i}return n}function fC(e,t){let[n,r]=(0,X.useState)({apiBase:e,notice:null});n.apiBase!==e&&r({apiBase:e,notice:null});let i=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{i.current=null},[e]);let a=(0,X.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,X.useCallback)(()=>{i.current=null,r(e=>({...e,notice:null}))},[]),s=(0,X.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 pC=new Set([`home`,`setup`,`advanced`,`dashboard`,`startup`,`providers`,`models`,`subagents`,`advisor`,`logs`,`usage`,`storage`,`remote`,`remote-workspace`,`codex-set`,`integrations`,`claude`]);function mC(e){let t=hn(mn(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`:pC.has(n)?n:`home`}function hC(e){let t=mn(e);return TC(t).replaceTo??t}var gC=[`dashboard/providers`,`dashboard/models`],_C=[`models/combos`,`models/routing`,`models/compatibility`],vC=`models/combos/jev-auto`;function yC(e){let t=e?.trim();return t&&t!==`jev`?`${vC}?${new URLSearchParams({decisionProvider:t})}`:vC}function bC(e){let{path:t,query:n}=hn(mn(e));if(t!==`models/combos/jev-auto`)return;let r=new URLSearchParams(n).get(`decisionProvider`)?.trim();return r&&r!==`jev`?r:null}var xC=`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(`.`),SC=[`providers`,`models/compatibility`,vC],CC=`providers?provider=anthropic&tab=accounts`;function wC(e,t){return e===t||t===`claude`&&[`claude/code`,`claude/desktop`].includes(e)||t===`logs`&&e===`logs/debug`||t===`usage`&&e===`usage/companion`||t===`codex-set`&&(e===`codex-set/prompt`||e===`codex-set/desktop`)||t===`models`&&(_C.includes(e)||e===`models/combos/jev-auto`)||t===`dashboard`&&(e===`dashboard/update`||gC.includes(e))||t===`integrations`&&xC.includes(e)}function TC(e){let{path:t,query:n}=hn(e);if(n||t!==e){let e=TC(t);return e.replaceTo===null&&SC.includes(t)?e:{page:e.page,replaceTo:e.replaceTo??t}}let r=mC(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:CC}:e===`claude/settings`?{page:`claude`,replaceTo:`claude/code`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:wC(e,r)?{page:r,replaceTo:null}:{page:r,replaceTo:r}}var EC=`models/compatibility`,DC=`providers`,OC=200,kC={inbound:``,upstream:``};function AC(e){return e!==void 0&&sx(e)?e:``}function jC(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?`${EC}?${n}`:EC}function MC(e,t){let n=hn(hC(e));return n.path===t?new URLSearchParams(n.query):null}function NC(e=window.location.hash){let t=MC(e,EC);if(!t)return null;let n=t.get(`inbound`),r=t.get(`upstream`);return{inbound:sx(n)?n:``,upstream:sx(r)?r:``}}function PC(e){return`${DC}?${new URLSearchParams({provider:e}).toString()}`}function FC(e){return`${DC}?${new URLSearchParams({provider:e,tab:`accounts`}).toString()}`}function IC(e=window.location.hash){return MC(e,`providers`)?.get(`tab`)===`accounts`?`accounts`:`settings`}function LC(e=window.location.hash){let t=MC(e,`providers`)?.get(`provider`)?.trim()??``;return t&&t.length<=OC?t:null}function RC(e){_n(jC(e))}function zC(e){_n(PC(e))}function BC(e,t=window){let n=FC(e);mn(t.location.hash)===n?t.dispatchEvent(new t.Event(`hashchange`)):_n(n,t)}function VC(e,t,n,r){let[i,a]=(0,X.useState)(()=>({name:LC(),tab:IC(),seq:0})),[o,s]=(0,X.useState)(null),c=(0,X.useRef)(t);if((0,X.useEffect)(()=>{let e=()=>a(e=>({name:LC(),tab:IC(),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`}),e?e(i.name):n(i.name)}return(0,X.useEffect)(()=>{let e=c.current;if(c.current=t,e===t)return;let n=LC();n&&o?.seq===i.seq&&i.name===n&&(t===null?e===n:t!==n)&&gn(DC)},[o,i,t]),o?.tab===`settings`?{token:o.seq+1,provider:o.provider}:{token:0,provider:null}}function HC(e){let[t,n]=(0,X.useState)({epoch:0,force:!1}),r=(0,X.useRef)(0),i=(0,X.useRef)(!0),a=(0,X.useRef)(new Map),o=(0,X.useCallback)(()=>{for(let e of a.current.values())e.resolve(!1);a.current.clear()},[]);(0,X.useEffect)(()=>(i.current=!0,()=>{i.current=!1,o()}),[e,o]);let s=(0,X.useCallback)((e=!1)=>{o();let t=++r.current;return i.current&&n({epoch:t,force:e}),t},[o]),c=(0,X.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,X.useCallback)((e,t)=>c(t,`report`,e),[c]),beginQuotaRefresh:(0,X.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 UC(e,t,n){let r=(0,X.useRef)(n);(0,X.useLayoutEffect)(()=>{r.current=n});let i=(0,X.useRef)(()=>{});return(0,X.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(`
|
|
5
|
+
`))}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;s.set(t,e.revision),c.set(t,{provider:e.provider,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(`
|
|
6
|
+
`))!==-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,X.useCallback)(()=>i.current(),[])}function WC({apiBase:e}){let t=c(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,X.useState)(()=>kd(n)),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(`err`),[m,h]=(0,X.useState)(0),[g,_]=(0,X.useState)([]),[v,y]=(0,X.useState)({}),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(0),[P,F]=(0,X.useState)(null),[I,L]=(0,X.useState)({token:0,provider:null}),R=(0,X.useRef)(!0),z=(0,X.useRef)(null),B=(0,X.useRef)(!1),V=(0,X.useCallback)((e,t=!0,n)=>{l(e),d(t),p(n??(t?`ok`:`err`)),h(e=>e+1)},[]),H=(0,X.useCallback)(()=>{l(``),d(!1),p(`err`)},[]),U=(0,X.useCallback)(e=>{e.validationPending||e.catalogRefreshPending?(l(t(e.validationPending?`pws.healthLabel.validationPending`:`codexAuth.catalogRefreshPending`)),d(!1),p(`warn`),h(e=>e+1)):V(t(`codexAuth.accountAdded`),!0)},[V,t]);(0,X.useEffect)(()=>(R.current=!0,()=>{R.current=!1}),[]),(0,X.useEffect)(()=>{if(!s||!u)return;let e=window.setTimeout(H,4500);return()=>window.clearTimeout(e)},[s,u,m,H]);let W=(0,X.useCallback)(e=>{o(!1),D(null),T(e),L(t=>({token:t.token+1,provider:e}))},[]),ee=VC(r?Object.keys(r.providers):null,w,T,W),te=dn(`add-provider-presets:${e}`,[e],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});dn(Hr(e),[e],async t=>await Vr(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4});let{quotaRefresh:ne,invalidateProviderQuotas:G,settleQuotaRefresh:K,beginQuotaRefresh:re}=HC(e),{fetchConfig:q,fetchOauth:ie,fetchProviderQuotas:ae}=HS({apiBase:e,t,setConfig:i,setOauthProviders:_,setOauthStatus:y,notify:V,invalidateProviderQuotas:G,configCacheKey:n}),oe=(0,X.useCallback)(async()=>{await q()},[q]),se=fC(e,q),ce=se.open,le=(0,X.useCallback)(e=>{W(e),ce(e,!1)},[W,ce]),ue=Jg(e),J=ue.activeNeedsReauth,fe=(0,X.useMemo)(()=>{let e=ue.accounts;if(e.length===0&&ue.loadState===`loading`)return v;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{...v,openai:{loggedIn:i,...a?{email:a}:{},...J?{needsReauth:!0}:{}}}},[v,ue.accounts,ue.loadState,J]),{accountSets:pe,setAccountSets:me,accountLoadStates:he,switchingAccounts:ge,pausingAccounts:_e,keyPools:ve,fetchAccountSets:ye,fetchKeyPools:xe,refreshAccountRosters:Se,oauthCardProviders:Ce,keyCardProviders:we,switchAccount:Te,pauseAccount:Ee,setAccountPoolThreshold:De,setAccountThreshold:Oe,switchApiKey:ke,removeApiKey:Ae,addApiKeyValue:je,editCredentialAlias:Me,removeAccount:Ne,activeAccountNeedsReauth:Pe}=kS({apiBase:e,t,config:r,oauthStatus:fe,aliveRef:R,notify:V,fetchConfig:oe,fetchOauth:ie,fetchProviderQuotas:ae,codexActiveNeedsReauth:J}),Fe=(0,X.useCallback)(e=>e&&!(e.kind===`oauth`?Ce:we).includes(e.provider)?Promise.resolve(!0):Se(e),[Se,Ce,we]),Ie=UC(e,r!==null,Fe),Le=JSON.stringify([e,Ce.toSorted(),we.toSorted()]),Re=(0,X.useRef)(null);dn(`provider-rosters:${Le}`,[Le],async e=>Re.current===Le?(Ie(),Se(void 0,e)):(Re.current=Le,!0),{enabled:r!==null,pollMs:3e4});let{draft:ze,setDraft:Be,jsonEditorOpen:Ve,jsonSaving:He,jsonLeaveOpen:Ue,saveConfig:We,openJsonEditor:Ge,discardJsonEditor:Ke,requestCloseJsonEditor:qe,restoreJsonEditor:Je,jsonIsDirty:Ye,setJsonLeaveOpen:Xe}=MS({apiBase:e,config:r,notify:V,fetchConfig:oe,fetchProviderQuotas:ae,onSaved:e=>{e.length&&(e.length===1&&T(t=>t??e[0]),se.open(e,!0)),N(e=>e+1)},t}),Ze=(0,X.useCallback)(e=>{let t=r?.providers[e],n=t?.authMode,i=t&&de(e,t)?()=>ue.load(!0,{validatePending:!0}):n===`oauth`?()=>ye([e],!0):n===`forward`||n===`local`?void 0:()=>xe([e],!0);return re(i)},[r,ue,ye,xe,re]),Qe=(0,X.useCallback)(()=>re(),[re]);(0,X.useEffect)(()=>{z.current!==e&&(z.current=e,Promise.resolve().then(()=>{oe(),ie()}))},[e,oe,ie]);let $e=()=>N(e=>e+1),{cancelLoginOAuth:et,loginOAuth:tt,logoutOAuth:nt,onNativeLoginSettled:rt}=LS({apiBase:e,t,aliveRef:R,accountSets:pe,setAccountSets:me,setBusy:x,setStatus:l,setLoginInfo:C,setOauthStatus:y,notify:V,fetchConfig:oe,fetchOauth:ie,fetchAccountSets:ye,fetchProviderQuotas:ae,bumpModelsRefresh:$e,onLoginSettled:le}),it=(0,X.useRef)(rt);(0,X.useEffect)(()=>{it.current=rt},[rt]),(0,X.useEffect)(()=>lb(e,e=>{it.current(`kiro`,e).catch(()=>{})}),[e]);let{removeProvider:at,confirmRemoveProvider:ot,setProviderDisabled:st,setDefaultProvider:ct,updateProvider:lt}=VS({apiBase:e,t,removeBusyRef:B,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:V,fetchConfig:oe,fetchOauth:ie,fetchProviderQuotas:ae,refreshCodexAccount:()=>ue.load(!0)}),ut=(e,t=!1,n)=>{b!==e&&(vS(e)?F({provider:e,addAccount:t,...n?{accountId:n}:{}}):tt(e,t,n))};if(!r)return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`page-head`,children:(0,Z.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,Z.jsx)(An,{tone:f,onDismiss:H,dismissLabel:t(`common.close`),children:s}):(0,Z.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,Z.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,Z.jsx)(`div`,{className:`providers-workspace-main`,children:(0,Z.jsxs)(`p`,{className:`muted`,children:[(0,Z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let dt=uC(r,g,t),ft=dC(r,fe),Y=e=>r.providers[e]?.authMode===`forward`,pt=async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=Bb(n);if(i===`invalid`){V(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await qb(e,i),await oe()}catch(e){e instanceof Kb?V(t(e.i18nKey),!1):V(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{R.current&&x(e=>e===`openai`?null:e)}}j(!0)}else Y(n)?j(!0):(r.providers[n]?.authMode===`oauth`||g.includes(n))&&ut(n,i)},mt=e=>{W(e)},ht={onLogin:ut,onNativeLoginSettled:rt,onCancelLogin:et,onLogout:nt,onReauth:(e,t)=>ut(e,!0,t),onSwitchAccount:Te,onPauseAccount:Ee,onAccountPoolThreshold:De,onAccountThreshold:Oe,onRemoveAccount:Ne,onRetryAccounts:async e=>{await ye([e])},onAddApiKey:je,onSwitchApiKey:ke,onRemoveApiKey:Ae,onEditAlias:Me,onRefreshQuota:Ze};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`page-head`,children:[(0,Z.jsx)(`h2`,{children:t(`nav.providers`)}),(0,Z.jsx)(`div`,{className:`row`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,Z.jsx)(be,{}),t(`prov.add`)]})})]}),s&&(0,Z.jsx)(An,{tone:f,onDismiss:H,dismissLabel:t(`common.close`),children:s}),(0,Z.jsx)(Tm,{onRemoveProvider:at,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:Ge,jsonEditor:{open:Ve,draft:ze,isDirty:Ye,onDraftChange:Be,onSave:()=>We(),onClose:qe,onRestore:Je},jsonSaving:He,modelsRefreshToken:M,fetchDiscovery:!0,onModelsSettled:se.modelsSettled,activeAccountNeedsReauth:Pe,quotaRefreshEpoch:ne.epoch,quotaForceRefresh:ne.force,onQuotaRefreshSettled:K,onRefreshAllQuotas:Qe,detail:(t,n)=>{let i=ft[t.name]??v[t.name];return(0,Z.jsx)(hS,{item:t,preset:Nm(t,te.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:()=>_n(`models`),onOpenConnect:()=>_n(`integrations`),onCreateJevAuto:dl(t)?()=>_n(yC(t.name)):void 0,modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:i?.email,onDeselect:()=>T(null),apiBase:e,oauth:i,accounts:pe[t.name]?.accounts??[],keys:ve[t.name]??[],accountLoadState:he[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:I.token,accountsFocusProvider:I.provider,settingsFocusToken:ee.token,settingsFocusProvider:ee.provider,switchingAccountId:ge[t.name]?.accountId??null,pausingAccountId:_e[t.name]?.accountId??null,busyProvider:b,loginHint:S,authHandlers:ht,onRefreshQuota:()=>Ze(t.name),isDefault:t.name===r.defaultProvider,onRemoveProvider:at,onSetDisabled:st,onSetDefault:e=>{ct(e)},onUpdateProvider:lt,codexController:ue},t.name)}}),(0,Z.jsx)(lC,{apiBase:e,config:r,adding:a,modelsNotice:se.notice?{provider:se.notice.context.provider,initialRegistration:se.notice.context.initialRegistration,catalogRefreshPending:se.notice.context.catalogRefreshPending,loading:se.notice.loading,failed:se.notice.failed,providerKnown:se.notice.context.providers.every(e=>!!r.providers[e]),selection:se.notice.context.providers.length===1?r.providers[se.notice.context.provider]?.initialModelSelection:se.notice.context.providers.some(e=>r.providers[e]?.initialModelSelection?.status===`pending`)?{status:`pending`}:void 0,onClose:se.close,onOpenModels:()=>{se.close(),_n(`models`)},onRetry:()=>{let e=se.notice.context;se.open(e.providers,e.initialRegistration,e.catalogRefreshPending),$e()}}:null,addIntent:E,busy:b,addModalAccountRows:dt,accountLoginStatus:ft,accountLoginHint:S,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Ue,jsonSaving:He,oauthTosPending:P,onCloseAdd:()=>{b&&et(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),H(),T(t=>t??e),se.open(e,!r.providers[e]),oe(),ie(),ae(!0),$e()},onAccountLogin:pt,onAccountCancelLogin:e=>{et(e)},onAccountLogout:e=>{nt(e)},onAccountManage:mt,onOpenAdd:ie,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),U(e),e.validationPending||(T(e=>e??`openai`),se.open(`openai`,!r.providers.openai,e.catalogRefreshPending)),oe(),ie(),ae(!0),$e()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{ot(O)},onCancelJsonLeave:()=>{He||Xe(!1)},onDiscardJson:Ke,onSaveJson:()=>{We()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),tt(e.provider,e.addAccount,e.accountId))}})]})}function GC(e){let{t}=a();return e.state===`stale`?(0,Z.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,Z.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:e.controller.restarting,onClick:()=>{e.controller.restart()},children:e.controller.restarting?t(`dash.codexRestarting`):t(`dash.codexRestart`)})]}):null}function KC(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim().length>0)}function qC(e){return e===null||e===`alphabetical`||e===`provider`||e===`most-used`}function JC(e){if(typeof e!=`object`||!e)return!1;let t=e;return KC(t.pickerOrder)&&qC(t.pickerOrderMode)}function YC(e){if(!JC(e))return!1;let t=e;return KC(t.pickerAvailable)&&(!(`chosen`in t)||Array.isArray(t.chosen)&&t.chosen.every(e=>typeof e==`string`))}function XC(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 ZC(e){let t=e.indexOf(`/`);return t<0?[``,e]:[e.slice(0,t),e.slice(t+1)]}var QC=(e,t)=>e.localeCompare(t,`en`);function $C(e,t){let[n,r]=ZC(e),[i,a]=ZC(t);return QC(n,i)||QC(r,a)}function ew(e,t,n=[],r=[]){if(e==="default")return null;let i=[...new Set(t)];if(e===`alphabetical`)return i.sort((e,t)=>QC(ZC(e)[1],ZC(t)[1])||$C(e,t));if(e===`provider`)return i.sort($C);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)||$C(e,t))}function tw(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=ew(n,e);if(r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n]))return n}return`custom`}function nw(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 rw(e,t,n){return JSON.stringify([e,t,n.pickerAvailable,n.chosen??null,n.pickerOrder,n.pickerOrderMode])}function iw(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 aw(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(!iw(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=nw(e.pickerOrder,n,t);return{fixed:o,order:[...new Set([...o,...s,...n])]}}function ow(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 sw(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 cw=`application/x-ocx-picker-order`,lw=0;function uw(){let e=++lw;if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return`${e}:${crypto.randomUUID()}`}catch{}return`picker-${Date.now().toString(36)}-${e}`}function dw({apiBase:t,active:n,identities:r,onAccepted:i,onBusyChange:a}){let o=c(),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),w=(0,X.useRef)({generation:0,flight:null,drag:null}),[T,E]=(0,X.useState)({apiBase:t,active:n,onBusyChange:a}),D=JSON.stringify(r.map(({provider:e,id:t,namespaced:n})=>[e,t,n])),O=(0,X.useRef)(D);(0,X.useLayoutEffect)(()=>{O.current=D},[D]);let k=s!==null&&s.identities!==D,A=!n||f||!s||m!==null||k,j=s!==null&&JSON.stringify(u)!==JSON.stringify(s.order),M=(0,X.useCallback)(()=>{w.current.drag=null,x(null),C(null)},[]);(T.apiBase!==t||T.active!==n||T.onBusyChange!==a)&&(E({apiBase:t,active:n,onBusyChange:a}),l(null),d([]),h(null),_(!1),p(!1));let[N,P]=(0,X.useState)({disabled:A,snapshot:s,identitySignature:D});(N.disabled!==A||N.snapshot!==s||N.identitySignature!==D)&&(P({disabled:A,snapshot:s,identitySignature:D}),x(null),C(null)),(0,X.useLayoutEffect)(()=>{let e=w.current;return e.generation++,()=>{e.generation++,e.flight?.controller.abort(),e.flight?.clear(),e.flight=null,e.drag=null,a(!1)}},[t,n,a]),(0,X.useLayoutEffect)(()=>{w.current.drag=null},[A,s,D]);let F=async o=>{if(!n||w.current.flight||o&&(A||!j))return;let c=w.current.generation,f=e(15e3);w.current.flight=f,p(!0),a(!0),_(!1),M();let m=()=>w.current.generation===c&&w.current.flight===f,g=()=>m()&&!f.signal.aborted&&O.current===D;try{let e=await fetch(`${t}/api/subagent-models`,{signal:f.signal});if(!g())return;let n=await zn(e);if(!g())return;if(!YC(n))throw Error(`Invalid picker settings`);let a=rw(t,c,n);if(o&&(!s||a!==s.signature||D!==s.identities)){h(`models.pickerOrder.changed`);return}let p=aw(n,r);if(!p){h(n.pickerOrder.some(e=>!e.includes(`/`))?`models.pickerOrder.nativeLocked`:n.chosen===void 0?`models.pickerOrder.unknownChosen`:`models.pickerOrder.catalogRequired`);return}if(!o){l({...p,signature:a,identities:D}),d(p.order),h(null),y(``);return}let m=await fetch(`${t}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:f.signal,body:JSON.stringify({pickerOrder:u,pickerOrderMode:null})});if(!g())return;let _=await zn(m);if(!g())return;if(!JC(_)||!(`ok`in _)||_.ok!==!0)throw Error(`Invalid picker receipt`);d(_.pickerOrder),h(`models.pickerOrder.savedReload`),i({pickerOrder:_.pickerOrder,pickerOrderMode:_.pickerOrderMode,catalogRefresh:`catalogRefresh`in _?_.catalogRefresh:void 0})}catch{m()&&O.current===D&&_(!0)}finally{f.clear(),m()&&(w.current.flight=null,p(!1),a(!1))}},I=(0,X.useEffectEvent)(async()=>{let e=w.current,t=e.generation;await Promise.resolve(),n&&e.generation===t&&F(!1)});(0,X.useEffect)(()=>{n&&I()},[t,n,a]);let L=(e,t)=>{A||(d(t),y(o(`models.pickerOrder.position`,{model:e,position:t.indexOf(e)+1,total:t.length})),M())},R=new Set(u),z=new Set(s?.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(cw)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,C(t))};return(0,Z.jsxs)(`section`,{className:`picker-order-editor`,"aria-label":o(`models.pickerOrder.custom`),"aria-busy":f,children:[(0,Z.jsx)(`p`,{className:`muted text-label`,children:o(`models.pickerOrder.editorHint`)}),(m||k)&&(0,Z.jsx)(`p`,{role:`alert`,children:o(m??`models.pickerOrder.changed`)}),g&&(0,Z.jsx)(`p`,{role:`alert`,children:o(`models.pickerOrder.requestFailed`)}),s&&u.length===0&&(0,Z.jsx)(`p`,{children:o(`models.pickerOrder.empty`)}),(0,Z.jsx)(`ol`,{className:`picker-order-list`,children:u.map((e,t)=>{let n=z.has(e);return(0,Z.jsxs)(`li`,{className:`picker-order-row${b===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(cw)&&B(n.id)&&B(e)&&(t.preventDefault(),L(n.id,ow(u,n.id,e,s?.fixed??[]))),M()},onDragEnd:M,children:[(0,Z.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,disabled:A||n,draggable:!A&&!n,"aria-label":o(`models.pickerOrder.dragModel`,{model:e}),onDragStart:t=>{if(!B(e)){t.preventDefault();return}let n=uw();w.current.drag={id:e,token:n},x(e),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(cw,n)},children:(0,Z.jsx)(Xe,{width:14,height:14,"aria-hidden":`true`})}),(0,Z.jsx)(`code`,{className:`picker-order-name`,children:e}),n&&(0,Z.jsx)(`span`,{className:`muted text-caption`,children:o(`models.pickerOrder.featured`)}),(0,Z.jsxs)(`span`,{className:`picker-order-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:A||n||t===0||z.has(u[t-1]),"aria-label":o(`models.pickerOrder.upModel`,{model:e}),onClick:()=>L(e,sw(u,e,-1,s?.fixed??[])),children:(0,Z.jsx)(pt,{width:14,height:14,"aria-hidden":`true`})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:A||n||t===u.length-1||z.has(u[t+1]),"aria-label":o(`models.pickerOrder.downModel`,{model:e}),onClick:()=>L(e,sw(u,e,1,s?.fixed??[])),children:(0,Z.jsx)(Je,{width:14,height:14,"aria-hidden":`true`})})]})]},e)})}),(0,Z.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:v}),(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:A||!j,onClick:()=>void F(!0),children:o(f?`models.pickerOrder.applying`:`models.pickerOrder.saveDraft`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!n||f,onClick:()=>void F(!1),children:o(`models.pickerOrder.reloadDraft`)})]})]})}function fw({apiBase:t,onSaved:n}){let r=c(),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),h=(0,X.useRef)(!0),g=(0,X.useRef)(!1),_=(0,X.useRef)(0),v=(0,X.useCallback)(async()=>{if(g.current)return;let n=++_.current,r=e(15e3);try{let e=await fetch(`${t}/api/settings`,{signal:r.signal});if(!e.ok)throw Error(`load`);let i=await e.json();if(g.current||n!==_.current)return;if(typeof i.fastRows!=`boolean`)throw Error(`shape`);h.current=i.fastRows,a(i.fastRows),s(!0),f(!1)}catch{!g.current&&n===_.current&&f(!0)}finally{r.clear()}},[t]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{v()},0),t=Ru(()=>{v()},3e4);return()=>{window.clearTimeout(e),t()}},[v]);let y=(0,X.useCallback)(async()=>{if(g.current||!o)return;let i=h.current,c=!i;h.current=c,a(c),g.current=!0,u(!0),m(null),_.current+=1;let l=e(15e3);try{let e=await zn(await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({fastRows:c}),signal:l.signal}))??{};if(e.ok!==!0||typeof e.fastRows!=`boolean`)throw Error(`unconfirmed`);h.current=e.fastRows,a(e.fastRows),s(!0),f(!1),m(e.catalogRefreshPending===!0?{tone:`warn`,message:r(`models.fastRows.refreshHint`)}:{tone:`ok`,message:r(e.fastRows?`models.fastRows.enabled`:`models.fastRows.disabled`)}),n?.()}catch{let o=e(15e3);try{let e=await fetch(`${t}/api/settings`,{signal:o.signal});if(!e.ok)throw Error(`reconcile`);let n=await e.json();if(typeof n.fastRows!=`boolean`)throw Error(`shape`);h.current=n.fastRows,a(n.fastRows),s(!0),f(!1),m(n.fastRows===c?{tone:`warn`,message:r(`models.fastRows.refreshHint`)}:{tone:`err`,message:r(`models.fastRows.updateFailed`)})}catch{h.current=i,a(i),m({tone:`err`,message:r(`models.fastRows.updateFailed`)})}finally{o.clear(),n?.()}}finally{l.clear(),g.current=!1,u(!1)}},[t,o,n,r]),b=d&&!o;return(0,Z.jsxs)(`div`,{className:`card card-row fast-rows-card`,"aria-busy":l||!o&&!b||void 0,children:[(0,Z.jsxs)(`div`,{className:`fast-rows-copy`,children:[(0,Z.jsx)(`strong`,{children:r(`models.fastRows.title`)}),(0,Z.jsx)(`div`,{className:`card-sub`,role:b?`status`:void 0,children:r(b?`models.fastRows.loadFailed`:o?`models.fastRows.desc`:`common.loading`)}),o&&d&&(0,Z.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:r(`models.fastRows.loadFailed`)})]}),(0,Z.jsxs)(`div`,{className:`fast-rows-controls`,children:[d&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{v()},disabled:l,children:r(`common.retry`)}),o&&(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${i?`on`:``}`,onClick:()=>{y()},disabled:l,"aria-pressed":i,"aria-label":r(`models.fastRows.title`),title:r(`models.fastRows.title`),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]}),p&&(0,Z.jsx)(`div`,{className:`fast-rows-feedback is-${p.tone}`,role:p.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:p.message})]})}function pw({showOrderEditor:e,onSaved:t,...n}){return(0,Z.jsxs)(Z.Fragment,{children:[e&&(0,Z.jsx)(dw,{...n},n.apiBase),(0,Z.jsx)(fw,{apiBase:n.apiBase,onSaved:t})]})}var mw={operator:`models.displayNameSourceOperator`,provider:`models.displayNameSourceProvider`,fallback:`models.displayNameSourceFallback`};function hw({model:e,saving:t,requestError:n,currentNamePending:r=!1,mutationOutcomeUnknown:i=!1,onRetry:a,onEdit:o,onSave:s,onReset:l,onClose:u}){let d=c(),f=(0,X.useRef)(null),p=(0,X.useRef)(null),m=(0,X.useRef)(null),h=(0,X.useRef)(t),g=(0,X.useId)(),_=(0,X.useId)(),v=(0,X.useId)(),[y,b]=(0,X.useState)(e),[x,S]=(0,X.useState)(e.displayNameOverride??``),[C,w]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=f.current;return e&&!e.open&&e.showModal(),p.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,X.useEffect)(()=>{let e=h.current&&!t&&!!n;h.current=t,e&&(i?m.current?.focus():p.current?.focus())},[n,t,i]),y!==e&&(b(e),S(e.displayNameOverride??``),w(null));let T=C?d(C):null,E=T??n,D=e.displayNameSource?mw[e.displayNameSource]:`models.displayNameSourceFallback`,O=()=>{t||u()};return(0,Z.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":g,onCancel:e=>{e.preventDefault(),O()},children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,disabled:t,onClick:O}),(0,Z.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=Af(x);w(n),n||s(x.trim())},children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:g,children:d(`models.displayNameTitle`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:O,children:d(`common.close`)})]}),(0,Z.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:d(`models.displayNameModelId`)}),(0,Z.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Z.jsxs)(`div`,{className:`model-display-name-current`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:d(`models.displayNameCurrent`)}),(0,Z.jsx)(`strong`,{children:r?d(`models.displayNameCurrentUnavailable`):e.displayName??e.namespaced}),!r&&(0,Z.jsx)(`span`,{className:`models-chip muted text-caption`,children:d(D)})]}),(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${g}-input`,children:d(`models.displayNameField`)}),(0,Z.jsx)(`input`,{ref:p,id:`${g}-input`,className:`input`,value:x,maxLength:129,placeholder:d(`models.displayNamePlaceholder`),"aria-describedby":`${_}${E?` ${v}`:``}`,"aria-invalid":T?!0:void 0,disabled:t||i,onChange:e=>{t||i||(o?.(),S(e.target.value),w(null))}}),(0,Z.jsx)(`p`,{id:_,className:`muted small`,children:d(`models.displayNameHelp`,{model:e.namespaced})}),E&&(0,Z.jsx)(`p`,{id:v,className:`model-display-name-error`,role:`alert`,children:E}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||i||!e.displayNameOverride,onClick:()=>{!t&&!i&&l()},children:d(`models.displayNameReset`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:t,onClick:O,children:d(`common.cancel`)}),(0,Z.jsx)(`button`,{ref:m,type:`submit`,className:`btn btn-primary btn-sm`,disabled:t||i&&!a,children:d(t?`common.saving`:a?`common.retry`:`common.save`)})]})]})]})}var gw=[`input`,`output`,`cacheRead`,`cacheWrite`],_w={input:``,output:``,cacheRead:``,cacheWrite:``},vw={..._w,threshold:``,comparison:`gt`},yw=Symbol(`invalid model cost`),bw={input:`customInput`,output:`customOutput`,cacheRead:`customCacheRead`,cacheWrite:`customCacheWrite`};function xw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sw(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function Cw(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=1e6}function ww(e){return xw(e)&&Sw(e,gw)&&gw.every(t=>Cw(e[t]))}function Tw(e){if(e!==void 0){if(!xw(e))return yw;if(!(e.mode===`automatic`&&Sw(e,[`mode`])))return e.mode===`flat`&&Sw(e,[`mode`])?{mode:`flat`}:e.mode!==`custom`||!Number.isSafeInteger(e.thresholdTokens)||Number(e.thresholdTokens)<=0||!Sw(e,[`mode`,`thresholdTokens`,`comparison`,`rates`])||e.comparison!==`gt`&&e.comparison!==`gte`||!ww(e.rates)?yw:{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 Ew(e){if(!xw(e)||!Sw(e,Object.hasOwn(e,`promptLengthPricing`)?[...gw,`promptLengthPricing`]:gw)||!gw.every(t=>Cw(e[t])))return yw;let t=Tw(e.promptLengthPricing);if(t===yw)return yw;let n=Object.fromEntries(gw.map(t=>[t,e[t]]));return t===void 0?n:{...n,promptLengthPricing:t}}function Dw(e,t){if(!gw.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&&gw.every(e=>n.rates[e]===r.rates[e]):!1}function Ow(e,t){if(t===null)return e===null;let n=Ew(e);return n!==yw&&Dw(n,t)}var kw=e=>Object.fromEntries(gw.map(t=>[t,String(e[t])]));function Aw(e){if(!e)return{rates:_w,mode:`automatic`,custom:vw};let t=e.promptLengthPricing;return!t||t.mode===`flat`?{rates:kw(e),mode:t?.mode??`automatic`,custom:vw}:{rates:kw(e),mode:`custom`,custom:{...kw(t.rates),threshold:String(t.thresholdTokens),comparison:t.comparison}}}var jw=e=>e.trim()===``?0:Number(e);function Mw(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:jw(e.cacheRead),cacheWrite:jw(e.cacheWrite)},a=gw.find(e=>!Cw(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:jw(n.cacheRead),cacheWrite:jw(n.cacheWrite)},c=gw.find(e=>!Cw(s[e]));return c?{field:bw[c]}:{cost:{...i,promptLengthPricing:{mode:`custom`,thresholdTokens:Number(o),comparison:n.comparison,rates:s}}}}var Nw={input:`pricing.override.input`,output:`pricing.override.output`,cacheRead:`pricing.override.cacheRead`,cacheWrite:`pricing.override.cacheWrite`},Pw=6e4;function Fw({model:t,apiBase:n,onRefresh:r,onClose:i}){let a=c(),o=(0,X.useId)(),s=(0,X.useId)(),l=(0,X.useId)(),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)({}),p=(0,X.useRef)(null),m=(0,X.useRef)(null),h=(0,X.useRef)(!1),[g,_]=(0,X.useState)(`loading`),[v,y]=(0,X.useState)(_w),[b,x]=(0,X.useState)(`automatic`),[S,C]=(0,X.useState)(vw),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)(!1),M=`${n}/api/providers/${encodeURIComponent(t.provider)}/model-costs`,N=g===`saving`||g===`refreshing`,P=g!==`ready`,F=(0,X.useCallback)((n=!1)=>{if(m.current)return;let r=e(Pw);m.current=r,fetch(M,{signal:r.signal,cache:`no-store`}).then(async e=>{let i=await zn(e);if(r.signal.throwIfAborted(),!xw(i)||i.provider!==t.provider||!xw(i.modelCosts))throw Error(`invalid model-costs response`);let a=Object.hasOwn(i.modelCosts,t.id)?i.modelCosts[t.id]:void 0,o=a===void 0?void 0:Ew(a);if(o===yw)throw Error(`invalid model cost`);if(m.current!==r)return;let s=Aw(o);y(s.rates),x(s.mode),C(s.custom),T(o!==void 0),D(null),k(null),j(n),_(`ready`)}).catch(()=>{m.current===r&&(_(n?`unknown`:`loadFailed`),D(n?`pricing.override.recoveryFailed`:`pricing.override.loadFailed`))}).finally(()=>{r.clear(),m.current===r&&(m.current=null)})},[M,t.id,t.provider,C,D,k,x]);(0,X.useEffect)(()=>{let e=u.current;return e&&!e.open&&e.showModal(),F(),()=>{m.current?.controller.abort(),m.current?.clear(),m.current=null,e?.open&&e.close()}},[F]),(0,X.useEffect)(()=>{g===`ready`?d.current?.focus():(g===`unknown`||g===`loadFailed`||g===`refreshFailed`)&&p.current?.focus()},[g]);let I=async n=>{if(m.current||(n===void 0?g!==`refreshFailed`:g!==`ready`))return;let a=e(Pw);m.current=a,_(n===void 0?`refreshing`:`saving`),h.current=!0,D(null),k(null);let o=n===void 0;try{if(n!==void 0){let e=await zn(await fetch(M,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:t.id,cost:n}),signal:a.signal}));a.signal.throwIfAborted();let r=xw(e)?e.cost:void 0;if(!xw(e)||e.ok!==!0||e.provider!==t.provider||e.modelId!==t.id||!Ow(r,n))throw Error(`invalid model-costs receipt`);if(m.current!==a)return;o=!0,_(`refreshing`)}if(!await r(a.signal))throw Error(`catalog refresh failed`);a.signal.throwIfAborted(),m.current===a&&i()}catch{if(m.current!==a)return;_(o?`refreshFailed`:`unknown`),D(o?`pricing.override.refreshFailed`:`pricing.override.outcomeUnknown`)}finally{a.clear(),m.current===a&&(m.current=null,h.current=!1)}},L=()=>{h.current||i()};return(0,Z.jsxs)(`dialog`,{ref:u,className:`modal-overlay`,"aria-labelledby":`${o}-title`,onCancel:e=>{e.preventDefault(),L()},children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":a(`pricing.override.close`),disabled:N,onClick:L}),(0,Z.jsxs)(`form`,{className:`modal-card model-display-name-dialog model-price-dialog`,role:`document`,noValidate:!0,"aria-busy":g===`loading`||N,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),m.current)return;if(g===`unknown`||g===`loadFailed`){_(`loading`),D(null),F(g===`unknown`);return}if(g===`refreshFailed`){I(void 0);return}if(P)return;let t=Object.entries(f.current).find(([,e])=>e.validity.badInput)?.[0],n=Mw(v,b,S,t);`field`in n?(k(n.field),D(n.field===`threshold`||n.field.startsWith(`custom`)?`pricing.override.customInvalid`:`pricing.override.invalid`),f.current[n.field]?.focus()):I(n.cost)},children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:`${o}-title`,children:a(`pricing.override.title`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:N,onClick:L,children:a(`pricing.override.close`)})]}),(0,Z.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:a(`pricing.override.modelId`)}),(0,Z.jsx)(`code`,{className:`mono text-control`,children:t.namespaced})]}),(0,Z.jsxs)(`div`,{className:`model-price-body`,children:[(0,Z.jsx)(`p`,{id:s,className:`muted small`,children:a(`pricing.override.help`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:a(`pricing.override.promptHelp`)}),g===`loading`&&(0,Z.jsx)(`p`,{role:`status`,className:`muted small`,children:a(`pricing.override.loading`)}),(0,Z.jsx)(`div`,{className:`model-price-rates-grid`,children:gw.map(e=>(0,Z.jsxs)(`div`,{className:`model-price-rate-field`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-${e}`,children:a(Nw[e])}),(0,Z.jsx)(`input`,{ref:t=>{t?f.current[e]=t:delete f.current[e],e===`input`&&(d.current=t)},id:`${o}-${e}`,className:`input`,type:`number`,min:0,max:1e6,step:`any`,inputMode:`decimal`,value:v[e],disabled:P,required:e===`input`||e===`output`,"aria-describedby":`${s}${E?` ${l}`:``}`,"aria-invalid":O===e||void 0,onChange:t=>{if(P||m.current)return;let n=t.target.value;y(t=>({...t,cacheRead:t.cacheRead||`0`,cacheWrite:t.cacheWrite||`0`,[e]:n})),D(null),k(null)}})]},e))}),(0,Z.jsxs)(`fieldset`,{className:`model-price-mode`,children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:a(`pricing.override.promptTitle`)}),[`automatic`,`flat`,`custom`].map(e=>(0,Z.jsxs)(`label`,{className:`model-price-mode-option`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`${o}-mode`,value:e,checked:b===e,disabled:P,onChange:()=>{x(e),D(null),k(null)}}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:a(`pricing.override.mode${e[0].toUpperCase()}${e.slice(1)}`)}),(0,Z.jsx)(`small`,{className:`muted`,children:a(`pricing.override.mode${e[0].toUpperCase()}${e.slice(1)}Help`)})]})]},e))]}),b===`custom`&&(0,Z.jsxs)(`section`,{className:`model-price-band`,"aria-labelledby":`${o}-custom-title`,children:[(0,Z.jsx)(`h4`,{id:`${o}-custom-title`,className:`model-price-band-title`,children:a(`pricing.override.bandTitle`)}),(0,Z.jsxs)(`div`,{className:`model-price-custom-controls`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-threshold`,children:a(`pricing.override.threshold`)}),(0,Z.jsx)(`input`,{ref:e=>{e?f.current.threshold=e:delete f.current.threshold},id:`${o}-threshold`,className:`input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:S.threshold,disabled:P,"aria-describedby":`${s}${E?` ${l}`:``}`,"aria-invalid":O===`threshold`||void 0,onChange:e=>{C(t=>({...t,threshold:e.target.value})),D(null),k(null)}})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-comparison`,children:a(`pricing.override.comparison`)}),(0,Z.jsx)($,{id:`${o}-comparison`,label:a(`pricing.override.comparison`),value:S.comparison,disabled:P,portal:!1,describedBy:s,options:[{value:`gt`,label:a(`pricing.override.comparisonGt`)},{value:`gte`,label:a(`pricing.override.comparisonGte`)}],onChange:e=>C(t=>({...t,comparison:e}))})]})]}),(0,Z.jsx)(`p`,{id:`${o}-custom-help`,className:`muted small`,children:a(`pricing.override.bandHelp`)}),(0,Z.jsx)(`div`,{className:`model-price-rates-grid`,children:gw.map(e=>(0,Z.jsxs)(`div`,{className:`model-price-rate-field`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-custom-${e}`,children:a(Nw[e])}),(0,Z.jsx)(`input`,{ref:t=>{let n=bw[e];t?f.current[n]=t:delete f.current[n]},id:`${o}-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":`${s}${E?` ${l}`:``}`,"aria-invalid":O===bw[e]||void 0,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),D(null),k(null)}})]},`custom-${e}`))})]})]}),A&&(0,Z.jsx)(`p`,{role:`status`,className:`muted small`,children:a(`pricing.override.recovered`)}),E&&(0,Z.jsx)(`p`,{id:l,className:`model-display-name-error`,role:`alert`,children:a(E)}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P||!w,onClick:()=>void I(null),children:a(`pricing.override.reset`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:N,onClick:L,children:a(`pricing.override.cancel`)}),(0,Z.jsx)(`button`,{ref:p,type:`submit`,className:`btn btn-primary btn-sm`,disabled:g===`loading`||N,children:a(N?`pricing.override.saving`:g===`unknown`||g===`loadFailed`?`pricing.override.reload`:g===`refreshFailed`?`pricing.override.refresh`:`pricing.override.save`)})]})]})]})}var Iw=[`text`,`image`,`audio`],Lw=[`100000`,`128000`,`200000`,`256000`,`352000`,`500000`,`1000000`],Rw=6e4;function zw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bw(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 Vw(e){return e.toSorted().join(`,`)}function Hw(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 Uw({row:t,apiBase:n,onRefresh:r,onFeedback:i,onClose:a}){let o=c(),s=(0,X.useId)(),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),[f]=(0,X.useState)(()=>Bw(t)),[p,m]=(0,X.useState)(`ready`),[h,g]=(0,X.useState)(()=>f.contextWindow),[_,v]=(0,X.useState)(()=>f.contextWindow!==``&&!Lw.includes(f.contextWindow)),[y,b]=(0,X.useState)(()=>[...f.modalities]),[x,S]=(0,X.useState)(()=>f.reasoning),[C,w]=(0,X.useState)(()=>[...f.ladder]),[T,E]=(0,X.useState)(()=>f.defaultEffort),[D,O]=(0,X.useState)(null),k=p===`saving`||p===`restoring`,A=p===`unknown`||p===`saved-stale`;(0,X.useEffect)(()=>{let e=l.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&typeof t.focus==`function`&&t.focus()}},[]),(0,X.useEffect)(()=>{A&&u.current?.focus()},[A]);let j=async()=>{let n=e(Rw);d.current=n;try{if(!await r(n.signal)||(n.signal.throwIfAborted(),d.current!==n))return;i(!0,o(`models.settingsReloaded`,{model:t.namespaced})),a()}catch{}finally{n.clear(),d.current===n&&(d.current=null)}},M=e=>{if(S(e),!e||C.length>0)return;let n=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts:void 0;w(n&&n.length>0?[...n]:[...jf])},N=(e,t)=>{w(n=>t?[...n,e]:n.filter(t=>t!==e)),!t&&T===e&&E(``)},P=()=>{k||a()},F=async(s,c)=>{let l=e(Rw);d.current=l,m(c?`restoring`:`saving`),O(null);let u=!1,f=!1;try{let e=await fetch(n+`/api/model-settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t.provider,modelId:t.id,...s}),signal:l.signal});if(e.status>=400&&e.status<500)throw f=!0,Error(`model settings rejected`);let p=await zn(e);if(l.signal.throwIfAborted(),!zw(p)||p.ok!==!0||p.provider!==t.provider||p.modelId!==t.id||typeof p.changed!=`boolean`||typeof p.hasOverrides!=`boolean`||typeof p.saved!=`boolean`||p.saved!==p.changed||!zw(p.catalogRefresh)||![`committed`,`skipped`,`failed`].includes(String(p.catalogRefresh.status)))throw Error(`invalid model-settings receipt`);if(d.current!==l)return;if(u=!0,!p.changed){i(!0,o(c&&!p.hasOverrides?`models.settingsNothingToRestore`:`models.settingsNoChange`,{model:t.namespaced})),a();return}let m=p.catalogRefresh,h=m.status===`failed`||m.status===`skipped`&&m.retryable===!0;if(!await r(l.signal))throw Error(`catalog refresh failed`);if(l.signal.throwIfAborted(),d.current!==l)return;h?i(!1,o(`models.settingsSavedCodexStale`,{model:t.namespaced})):c?i(!0,o(`models.settingsRestored`,{model:t.namespaced})):i(!0,o(`models.settingsSaved`,{model:t.namespaced})),a()}catch{if(d.current!==l)return;if(f){m(`ready`),O(`models.settingsRejected`);return}m(u?`saved-stale`:`unknown`),O(u?`models.settingsRefreshFailed`:`models.settingsSaveFailed`)}finally{l.clear(),d.current===l&&(d.current=null)}},I=()=>{if(p!==`ready`)return;let e=Hw(h);if(e===void 0){O(`models.contextInvalid`);return}let t=f,n={};h.trim()!==t.contextWindow&&(n.contextWindow=e),Vw(y)!==Vw(t.modalities)&&(n.inputModalities=y.length>0?[...y]:null);let r=x?Vw(C):``;(x!==t.reasoning||r!==Vw(t.ladder))&&(n.reasoningEfforts=x?[...C]:null);let i=x&&C.includes(T)?T:``;i!==t.defaultEffort&&(n.defaultReasoningEffort=i||null),Object.keys(n).length===0?a():F(n,!1)},L=async()=>{p===`ready`&&await Nu({message:o(`models.settingsRestoreConfirm`,{model:t.namespaced}),confirmLabel:o(`models.settingsRestore`),tone:`danger`})&&F({contextWindow:null,inputModalities:null,reasoningEfforts:null,defaultReasoningEffort:null},!0)},R=Array.isArray(t.inputModalities)?t.inputModalities.join(`, `):``,z=Array.isArray(t.inputModalities)?t.inputModalities.filter(e=>Iw.includes(e)):[];return(0,Z.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":s+`-title`,onCancel:e=>{e.preventDefault(),P()},children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,disabled:k,onClick:P}),(0,Z.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,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:s+`-title`,children:o(`models.settingsTitle`,{model:t.namespaced})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k,onClick:P,children:o(`common.close`)})]}),D&&(0,Z.jsx)(Q,{tone:p===`saved-stale`?`warn`:`err`,children:o(D)}),(0,Z.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Z.jsxs)(`div`,{className:`text-label models-field`,children:[o(`models.customFieldModelId`),(0,Z.jsx)(`code`,{className:`mono text-control`,children:t.namespaced})]}),(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[o(`models.customFieldContext`),(0,Z.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Z.jsx)($,{value:_?Lf:h,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:Lf,label:o(`models.custom`)}],onChange:e=>{e===`custom`?v(!0):(v(!1),g(e))},disabled:k,label:o(`models.customFieldContext`),portal:!1}),_&&(0,Z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:h,onChange:e=>g(e.target.value),disabled:k,placeholder:o(`models.customPlaceholder`),"aria-label":o(`models.customFieldContext`)})]}),t.contextWindowDeclared===void 0&&(0,Z.jsx)(`span`,{className:`muted text-caption`,children:o(`models.settingsContextInherit`,{value:t.contextWindow?String(t.contextWindow):o(`models.settingsContextUnknown`)})})]}),(0,Z.jsxs)(`div`,{className:`text-label models-field`,children:[o(`models.customFieldModalities`),(0,Z.jsx)(`div`,{className:`row models-field-row`,children:Iw.map(e=>(0,Z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:y.includes(e),onChange:t=>{let n=t.target.checked;b(t=>{if(!n)return t.filter(t=>t!==e);let r=t.length>0?t:z;return[...new Set([...r,e])]})},disabled:k}),(0,Z.jsx)(`span`,{className:`text-control`,children:e})]},e))}),y.length===0&&(0,Z.jsx)(`span`,{className:`muted text-caption`,children:o(`models.settingsModalitiesInherit`,{modalities:R||o(`models.settingsModalitiesUnknown`)})})]}),(0,Z.jsxs)(`div`,{className:`text-label models-field`,children:[o(`models.customFieldReasoning`),(0,Z.jsx)(`div`,{className:`row models-field-row`,children:(0,Z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>M(e.target.checked),disabled:k}),(0,Z.jsx)(`span`,{className:`text-control`,children:o(`models.customFieldReasoningOverride`)})]})}),x&&(0,Z.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:jf.map(e=>(0,Z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:C.includes(e),onChange:t=>N(e,t.target.checked),disabled:k}),(0,Z.jsx)(`span`,{className:`text-control`,children:o(`models.reasoningEffort.`+e)})]},e))})]}),x&&(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[o(`models.settingsDefaultEffort`),(0,Z.jsx)(`div`,{className:`row models-field-row`,children:(0,Z.jsx)($,{value:T,options:[{value:``,label:`—`},...C.map(e=>({value:e,label:o(`models.reasoningEffort.`+e)}))],onChange:E,disabled:k,label:o(`models.settingsDefaultEffort`),portal:!1})})]})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[A&&(0,Z.jsx)(`button`,{ref:u,type:`button`,className:`btn btn-ghost`,onClick:()=>void j(),children:o(`models.settingsReload`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,title:o(`models.settingsRestoreHint`),disabled:k||A,onClick:()=>void L(),children:o(`models.settingsRestore`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:P,disabled:k,children:o(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:k||A,children:o(k?`models.customSaving`:`models.customApply`)})]})]})]})}var Ww=[`current`,`stale`,`unknown`,`not_running`],Gw=[`fresh`,`stale`,`not_running`,`unknown`],Kw=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function qw(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function Jw(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&Gw.includes(t.stateBefore)&&typeof t.code==`string`&&Kw.includes(t.code)&&qw(t.requested)&&qw(t.stopped)&&qw(t.surviving)&&qw(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`||!qw(n.stopped)||!qw(n.surviving)||n.relaunch!==`started`&&n.relaunch!==`skipped`||n.reason!==void 0&&typeof n.reason!=`string`||n.pickerState!==void 0&&(typeof n.pickerState!=`string`||!Ww.includes(n.pickerState))||n.relaunch===`started`&&n.surviving.length>0)return!1}return!0}function Yw(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&Gw.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var Xw={state:null,runningCount:0};async function Zw(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 Xw;let i=await r.json().catch(()=>null);return Yw(i)?{state:i.state,runningCount:i.runningCount}:Xw}catch{return Xw}}var Qw=3e4;function $w(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function eT(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=Qw,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:$w(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:$w(e)?s():o()}}return Jw(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function tT(e){return e===`stopped`||e===`nothing_running`}function nT(e,t){let{t:n}=a(),[r,i]=(0,X.useState)(!1),o=(0,X.useRef)(!0),s=(0,X.useRef)(t.onSettled),c=(0,X.useRef)(t.report),l=(0,X.useRef)(e),u=(0,X.useRef)(null);return(0,X.useEffect)(()=>{s.current=t.onSettled,c.current=t.report},[t.onSettled,t.report]),(0,X.useEffect)(()=>(l.current=e,()=>{u.current?.abort(),u.current=null}),[e]),(0,X.useEffect)(()=>(o.current=!0,()=>{o.current=!1,u.current?.abort(),u.current=null}),[]),{restarting:r,restart:(0,X.useCallback)(async()=>{let t=new AbortController;u.current?.abort(),u.current=t;let r=await Nu({message:n(`dash.codexRestartConfirm`),confirmLabel:n(`dash.codexRestart`),tone:`danger`,signal:t.signal});if(u.current===t&&(u.current=null),!r||!o.current||l.current!==e)return null;i(!0);let a=await eT(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(o.current&&i(!1),!a.ok)return c.current(a.message,`err`),null;let d=a.result;return d.code===`stopped`?c.current(n(`dash.codexRestartDone`,{count:String(d.stopped.length)}),`ok`):d.code===`nothing_running`?c.current(n(`dash.codexRestartNothing`),`ok`):d.code===`enumeration_unavailable`?c.current(n(`dash.codexRestartUnknown`),`warn`):c.current(n(`dash.codexRestartPartial`,{count:String(d.surviving.length)}),`warn`),o.current&&tT(d.code)&&s.current?.(d.code),d.code},[e,n])}}async function rT(e,t,{apiBase:n,t:r,reloadAliases:i,publishFeedback:a}){let o=await Pu({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 iT(e,t,n,{apiBase:r,t:i,reloadAliases:a,publishFeedback:o}){let s=await Pu({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 aT={"gpt-5.6-sol":J,"gpt-5.6-terra":wt,"gpt-5.6-luna":st,"gpt-daybreak-blue-latest":J,"daybreak-blue-latest":J,"daybreak-red-latest":ae},oT={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function sT(e){return e.slice(e.lastIndexOf(`/`)+1)}function cT(e){return aT[e]??aT[sT(e)]??null}function lT(e){let t=cT(e);return t?(0,X.createElement)(`span`,{className:`model-label`},(0,X.createElement)(t,{style:oT,"aria-hidden":!0}),e):e}function uT(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var dT=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),fT=new Set([`unparseable`,`not-regular-file`,`foreign-edit`,`unowned-key`,`blocked-container`,`unresolvable-path`]);function pT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mT(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function hT(e){if(!pT(e)||e.clientId!==`aside`||!mT(e.profileId)||typeof e.current!=`boolean`||typeof e.enabled!=`boolean`||!dT.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&&!fT.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 gT(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!pT(n)||!mT(n.profileId)||typeof n.ok!=`boolean`||n.state!==void 0&&!dT.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 _T=[`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 vT(e){return e.clientId===`kilo`&&!!e.lastOpId&&(e.reason===`candidate-conflict`||e.state===`unsafe`&&!!e.candidateFailurePath&&e.candidateFailurePath!==e.configPath)}var yT=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`superseded_store`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),bT=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),xT=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),ST=[`apply`,`overwrite`,`disable`,`restore`],CT=[`add`,`replace`,`remove`,`snapshot`,`ownership`,`journal`],wT=[`none`,`unowned`,`foreign-edit`,`drift`],TT=new Set([`version`,`clientId`,`operation`,`state`,`foreignEdit`,`changes`,`fingerprint`,`canApply`,`willChange`,`refusalReason`,`supersededReason`,`missingStoreDocument`,`profileId`]),ET=new Set([`owned-config-file`,`unestablished-schema`,`missing-store`]),DT=/^[\x20-\x7e]{1,64}$/,OT=new Set([`kind`,`path`]),kT=new Set([`$snapshot`,`$ownership`,`$journal`]),AT=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`]),jT=256;function MT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NT(e,t){return Object.keys(e).every(e=>t.has(e))}function PT(e){return kT.has(e)||AT.has(e)}function FT(){return new RT(502,{code:`invalid_integration_preview_response`})}function IT(e){if(!MT(e)||!NT(e,TT)||e.version!==1||!_T.includes(e.clientId)||!ST.includes(e.operation)||!xT.has(String(e.state))||!wT.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>jT||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&&!yT.has(String(e.refusalReason))||e.supersededReason!==void 0&&(e.refusalReason!==`superseded_store`||typeof e.supersededReason!=`string`||!ET.has(e.supersededReason))||e.missingStoreDocument!==void 0&&(e.supersededReason!==`missing-store`||typeof e.missingStoreDocument!=`string`||!DT.test(e.missingStoreDocument)))throw FT();let t=[],n=-1,r=``,i=new Map;for(let a of e.changes){if(!MT(a)||!NT(a,OT)||!CT.includes(a.kind)||typeof a.path!=`string`||!PT(a.path))throw FT();let e=CT.indexOf(a.kind);if(e<n||e===n&&a.path<=r)throw FT();let o=a.kind,s=i.get(o)??new Set;if(s.has(a.path))throw FT();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 FT();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 LT(e){return!MT(e)||!yT.has(String(e.reason))?!1:typeof e.error==`string`&&bT.has(String(e.code))&&_T.includes(e.clientId)&&xT.has(String(e.state))&&typeof e.message==`string`}var RT=class extends Error{refusal;status;body;stalePlan;constructor(e,t){let n=LT(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 zT(e){return e instanceof RT&&e.status===404&&e.body.code===`integration_operation_not_found`}async function BT(e){let t;try{t=await e.json()}catch{return{}}return MT(t)?t.code===`integration_preview_stale`?{code:t.code,plan:IT(t.plan)}:t:{}}async function VT(e){if(!e.ok)throw new RT(e.status,await BT(e));let t=await Bn(e);if(t==null)throw new RT(e.status,{});return t}function HT(e){return e instanceof RT&&e.body.code===`integration_preview_unavailable`}function UT(e){return{operation:e.operation,planFingerprint:e.fingerprint}}function WT(e){if(!Number.isSafeInteger(e)||e<0)throw new RT(400,{code:`invalid_aside_profile`});return`/api/client-integrations/aside/profiles/${e}`}function GT(e,t){if(t!==void 0){if(e!==`aside`)throw new RT(400,{code:`invalid_aside_profile`});return WT(t)}return e===`aside`?`/api/client-integrations/aside/profiles`:`/api/client-integrations/${encodeURIComponent(e)}`}function KT(e,t){if(e===void 0)return``;let n=`profile=${encodeURIComponent(e)}`;return t?`client=hermes&${n}`:n}function qT(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}${t}`:e}function JT(){return new RT(502,{code:`invalid_hermes_profile_response`})}async function YT(e,t){return VT(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function XT(e,t,n,r,i){let a=await VT(await fetch(`${e}${qT(GT(t,r),KT(i,!1))}`,{signal:n}));if(i!==void 0&&(t!==`hermes`||a.hermesProfile!==i))throw JT();if(r!==void 0){let e=hT(a);if(!e||e.profileId!==r)throw new RT(502,{code:`invalid_aside_profile_response`});return e}return a}async function ZT(e,t,n,r,i){if(r!==void 0&&t!==`aside`)throw new RT(400,{code:`invalid_aside_profile`});if(i!==void 0&&t!==`hermes`)throw new RT(400,{code:`invalid_hermes_profile`});let a=t===`aside`?`${GT(t,r)}/journal`:qT(`/api/client-integrations/journal${t?`?client=${encodeURIComponent(t)}`:``}`,KT(i,!1)),o=await VT(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 RT(502,{code:`invalid_aside_profile_response`});return o}async function QT(e,t,n,r,i,a,o){let s=i===void 0?qT(`/api/client-integrations/preview`,KT(o,!0)):`${WT(i)}/preview`,c={...i===void 0?{clientId:t}:{},operation:n,...t===`droid`&&a!==void 0?{droidReasoningDefaults:a}:{}},l=IT(await VT(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 FT();return l}async function $T(e,t,n=!1,r,i,a){let o=i===void 0?qT(`/api/client-integrations/restore/preview`,KT(a,!0)):`${WT(i)}/preview`,s=i===void 0?{opId:t,confirmDrift:n}:{operation:`restore`,opId:t,confirmDrift:n},c=IT(await VT(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 FT();return c}async function eE(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 RT(400,{code:`invalid_hermes_profile`});let u=r?a?`overwrite`:`apply`:`disable`,d;try{d=await VT(await fetch(`${e}${qT(GT(t,o),KT(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 RT&&e.stalePlan&&(e.stalePlan.clientId!==t||e.stalePlan.operation!==u||e.stalePlan.profileId!==o)?FT():e}let f=d.results===void 0?void 0:gT(d.results);if(t===`aside`&&d.results!==void 0&&(!f||d.ok!==f.every(e=>e.ok)))throw new RT(502,{code:`invalid_aside_profile_response`});if(d.ok!==!0)throw new RT(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 RT(502,{code:`invalid_aside_profile_response`});return{...d,...f?{results:f}:{}}}async function tE(e,t){let{opId:n,confirmDrift:r=!1,signal:i,profileId:a,binding:o,hermesProfile:s}=t,c;try{c=await VT(await fetch(`${e}${a===void 0?qT(`/api/client-integrations/restore`,KT(s,!0)):`${WT(a)}/restore`}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:n,confirmDrift:r,...o}),signal:i}))}catch(e){throw e instanceof RT&&e.stalePlan&&(e.stalePlan.operation!==`restore`||e.stalePlan.profileId!==a)?FT():e}if(a!==void 0&&c.profileId!==a)throw new RT(502,{code:`invalid_aside_profile_response`});return c}async function nE(e,t,n,r,i){let a=await VT(await fetch(`${e}${qT(r===void 0?`/api/client-integrations/journal`:`${WT(r)}/journal`,KT(i,!0))}${i===void 0?`?`:`&`}opId=${encodeURIComponent(t)}`,{method:`DELETE`,signal:n}));if(r!==void 0&&a.profileId!==r)throw new RT(502,{code:`invalid_aside_profile_response`});return a}async function rE(e){try{let t=await e;return t.ok?await Bn(t)??null:null}catch{return null}}async function iE(e,t){let n=await rE(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 aE(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await Bn(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function oE(e,t){let n=await rE(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 sE(e,t){let n=await rE(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 cE(e,t){let n=await rE(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var lE=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),uE=new Set([`native_integration_refused`,`native_integration_failed`]),dE=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function fE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pE(e){return fE(e)?typeof e.error==`string`&&uE.has(String(e.code))&&lE.has(String(e.clientId))&&dE.has(String(e.reason))&&typeof e.message==`string`:!1}var mE=class extends Error{refusal;status;body;constructor(e,t){let n=pE(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 hE(e){try{let t=await e;return t.ok?await Bn(t)??null:null}catch{return null}}async function gE(e){try{let t=await e.json();return fE(t)?t:{}}catch{return{}}}async function _E(e){if(!e.ok)throw new mE(e.status,await gE(e));let t=await Bn(e);if(t==null)throw new mE(e.status,{});return t}function vE(e,t){return hE(fetch(`${e}/api/native-integrations`,{signal:t}))}async function yE(e,t,n,r){return _E(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var bE={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 xE(e){return e instanceof RT?e.refusal:null}function SE(e){return e instanceof mE?e.refusal:null}function CE(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var wE=new Set([`non_loopback`]);function TE(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 EE(e,t,n,r){let i=SE(t);if(i)return TE(e,i,r);let a=xE(t);if(!a){if(t instanceof RT&&`results`in t.body&&t.body.results?.length){let n=t.body.results.filter(e=>!e.ok).map(t=>{let n=DE(e,t);return`${e(`integrations.aside.profile`,{id:String(t.profileId)})}: ${n}`});return[e(`integrations.aside.partial`),...n].join(`
|
|
7
|
+
`)}let r=bE[t instanceof RT?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}return OE(e,a)}function DE(e,t){return OE(e,{clientId:`aside`,message:t.message??t.reason,reason:t.refusalReason??t.reason,snapshotPath:t.snapshotPath,residual:t.residual})}function OE(e,t){let n=wE.has(t.reason??``)?e(CE(t.reason),{client:t.clientId}):t.message||e(CE(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(CE(t.reason))} ${n}`:n}var kE=(e,t,n)=>JSON.stringify([e,t,n]),AE=new Map;function jE(t,n){let[r,i]=(0,X.useState)({apiBase:t,overrides:AE,pending:!1});r.apiBase!==t&&i({apiBase:t,overrides:AE,pending:!1});let a=r.apiBase===t?r.overrides:AE,o=r.apiBase===t&&r.pending,s=(0,X.useRef)(n);(0,X.useLayoutEffect)(()=>{s.current=n});let c=(0,X.useRef)(null);(0,X.useLayoutEffect)(()=>{let e={active:!0,running:!1,queue:[],readVersion:0,bounded:null};return c.current=e,s.current.onBusy(!1),()=>{e.active=!1,e.queue.length=0,e.bounded?.controller.abort(),e.bounded?.clear()}},[t]);let l=async n=>{let r=null;for(;n.active;){for(;n.active&&n.queue.length>0;){let i=n.queue.shift(),a=e(6e4);n.bounded=a;try{let e=await Cf(t,i.scope,i.provider,i.targets,i.enabled,fetch,a.signal);if(n.active){if(!e.ok)r=`models.saveFailed`;else{let t=await e.json().catch(()=>void 0);n.active&&s.current.onResponse(t)}}}catch{if(!n.active)return;r=`models.networkError`}finally{a.clear(),n.bounded=null}}if(!n.active)return;let a=n.readVersion,o=!1,c=e(6e4);n.bounded=c;try{o=await s.current.refresh(c.signal)}catch{}finally{c.clear(),n.bounded=null}if(!n.active)return;if(!(n.queue.length||a!==n.readVersion)){n.running=!1,i({apiBase:t,overrides:AE,pending:!1}),s.current.onBusy(!1),s.current.onSettled(r??(o?null:`models.networkError`));return}}};return{pending:o,overrides:a,enqueue:(e,n,r,a)=>{let o=c.current;o?.active&&(o.queue.push({scope:e,provider:n,targets:r,enabled:a}),o.readVersion++,s.current.onQueued(),i(e=>{let i=new Map(e.apiBase===t?e.overrides:AE);for(let e of r)i.set(kE(n,e.id,e.native===!0),a);return{apiBase:t,overrides:i,pending:!0}}),o.running||(o.running=!0,s.current.onBusy(!0),l(o)))},isRunning:()=>c.current?.running===!0,visible:(e,t,n,r)=>a.get(kE(e,t,n))??r}}function ME({className:e,style:t}){return(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function NE({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,Z.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,Z.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,Z.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,Z.jsx)(ME,{})},t))]})}function PE({children:e,busy:t=!0,live:n=!0,className:r}){return(0,Z.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,Z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{children:e})]})}var FE=class extends X.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,Z.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,Z.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,Z.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,Z.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,Z.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}};function IE(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 LE(e,t){return e.length!==0&&e.every(e=>{let n=IE(e,t);return n===`vision`||n===`sidecar`})}function RE(e,t){if(!LE(e,t))return[];let n=new Set,r=[];for(let i of e){if(IE(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 zE(e,t){return e.filter(e=>IE(e,t)===`blocked`).map(e=>({provider:e.provider.trim(),model:e.model.trim()}))}function BE(e,t,n,r){if(t===`invalidSessionPin`)return e(`cws.err.invalidSessionPin`,{min:rl,max:il});if(t===`invalidDecisionTimeout`)return e(`cws.err.invalidDecisionTimeout`,{min:ol,max:sl});if(t===`invalidDecisionProvider`){let t=cu(n.decisionProvider,r)??`missing`;return e(`cws.err.invalidDecisionProvider`,{name:n.decisionProvider??``,reason:e(Sl[t])})}return e(`cws.err.${t}`)}function VE(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function HE(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function UE(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 WE(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||UE(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 GE=`max-[939px]:[grid-column:3/-1]`;function KE({value:e,onChange:t,disabled:n}){let r=c();return(0,Z.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:_l.map(i=>(0,Z.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(vl[i])},i))})}function qE({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=c(),o=i??gl,s=t!==null&&!o.includes(t);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)($,{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,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function JE({targets:e,models:t,imageInput:n,reasoningEffortMode:r,visionEnabled:i,disabled:a,onChange:o}){let s=c(),l=LE(e,t),u=zE(e,t),d=l&&n!==`disabled`,f=RE(e,t),p=l?f.length>0&&n!==`disabled`?s(`cws.capability.imageInputSidecarHint`,{models:f.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}):s(`cws.capability.imageInputHint`):u.length>0?s(`cws.capability.imageInputBlockedHint`,{models:u.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}):s(`cws.capability.imageInputUnavailable`);return(0,Z.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":s(`cws.capabilities`),children:[(0,Z.jsx)(`span`,{className:`field-label`,children:s(`cws.capabilities`)}),(0,Z.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`cwi-capability-label`,children:s(`cws.capability.imageInput`)}),(0,Z.jsx)(`p`,{className:`muted cwi-capability-hint`,children:p}),f.length>0&&d&&i===!1?(0,Z.jsxs)(`p`,{className:`cwi-capability-hint cwi-capability-hint--warn`,children:[s(`cws.capability.imageInputSidecarDisabled`,{models:f.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>_n(`dashboard`),children:s(`nav.dashboard`)})]}):null]}),(0,Z.jsx)(kn,{on:d,onClick:()=>{l&&o({imageInput:n===`auto`?`disabled`:`auto`})},disabled:a||!l,label:s(`cws.capability.imageInput`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`cwi-capability-label`,children:s(`cws.capability.adaptiveEffort`)}),(0,Z.jsx)(`p`,{className:`muted cwi-capability-hint`,children:s(`cws.capability.adaptiveEffortHint`)})]}),(0,Z.jsx)(kn,{on:r===`adaptive`,onClick:()=>{o({reasoningEffortMode:r===`adaptive`?`strict`:`adaptive`})},disabled:a,label:s(`cws.capability.adaptiveEffort`)})]})]})}function YE({targets:e,strategy:t,providers:n,models:r,capabilityModels:i=r,providerQuotaStates:a,onChange:o}){let s=c(),l=VE(n),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),m=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,h=(t,n)=>{o(e.map((e,r)=>r===t?{...e,...n}:e))},g=(t,n)=>{o(e.map((e,r)=>{if(r!==t)return e;let{reasoningEfforts:i,modelProfile:a,...o}=e;return{...o,...n}}))},_=(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,Z.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((c,v)=>{let y=n.find(e=>e.name===c.provider),b=y&&!l.some(e=>e.name===c.provider)?[...l,y]:l,x=WE(r,c.provider,n),S=c.model&&!x.includes(c.model)?[c.model,...x]:x,C=!c.provider,w=u===v,T=f===v&&u!==null&&u!==v,E=a[c.provider.trim()]??`unknown`,D=i.find(e=>e.provider===c.provider&&e.id===c.model)?.reasoningEfforts,O=D===void 0?void 0:new Set(D),k=O===void 0?void 0:gl.filter(e=>O.has(e)),A=new Set(k??[]),j=k===void 0?[]:c.reasoningEfforts===void 0?k:c.reasoningEfforts.filter(e=>A.has(e)),M=new Set(j);return(0,Z.jsxs)(`div`,{className:`cwi-target-entry`,children:[(0,Z.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=>{u!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,f!==v&&p(v))},onDrop:e=>{e.preventDefault(),u!==null&&_(u,v),d(null),p(null)},onDragEnd:()=>{d(null),p(null)},children:[(0,Z.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":s(`cws.target.drag`),title:s(`cws.target.drag`),onDragStart:e=>{d(v),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(v))},children:(0,Z.jsx)(Xe,{width:14,height:14,"aria-hidden":`true`})}),(0,Z.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===0,"aria-label":s(`cws.target.moveUp`),onClick:()=>_(v,v-1),children:(0,Z.jsx)(pt,{width:14,height:14,"aria-hidden":`true`})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===e.length-1,"aria-label":s(`cws.target.moveDown`),onClick:()=>_(v,v+1),children:(0,Z.jsx)(Je,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Z.jsx)($,{fullWidth:!0,className:GE,value:c.provider,label:s(`cws.target.provider`),onChange:e=>{let t=WE(r,e,n)[0]??``;g(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:Ge(e.name,s)}):Ge(e.name,s)}))]}),(0,Z.jsx)($,{fullWidth:!0,className:GE,value:c.model,disabled:C,label:s(`cws.target.model`),onChange:e=>g(v,{provider:c.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,Z.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:c.weight??1,"aria-label":s(`cws.target.weight`),onChange:e=>{let t=HE(e.target.value,1,1e4);t!==void 0&&h(v,{weight:t})}}),(0,Z.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${E}`,"aria-label":s(`cws.quota.${E}`),children:s(`cws.quota.${E}`)}),(0,Z.jsx)(`div`,{className:`cwi-target-actions`,children:(0,Z.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,Z.jsx)(ge,{width:14,height:14})})})]}),t===`jev`&&(0,Z.jsxs)(`div`,{className:`cwi-jev-target-meta`,children:[v===m&&(0,Z.jsx)(`span`,{className:`chip`,children:s(`cws.jev.failOpen`)}),k===void 0?(0,Z.jsx)(`span`,{className:`muted`,children:s(`cws.jev.effortsUnknown`)}):k.length===0?(0,Z.jsx)(`span`,{className:`muted`,children:s(`cws.jev.effortsNone`)}):(0,Z.jsxs)(`fieldset`,{className:`cwi-jev-efforts`,children:[(0,Z.jsx)(`legend`,{children:s(`cws.jev.allowedEfforts`)}),k.map(e=>{let t=M.has(e);return(0,Z.jsxs)(`label`,{className:`cwi-jev-effort`,children:[(0,Z.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),h(v,{reasoningEfforts:k.filter(e=>n.has(e))})}}),(0,Z.jsx)(`span`,{children:e})]},e)})]}),(0,Z.jsxs)(`label`,{className:`cwi-field`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:s(`cws.jev.modelProfile`)}),(0,Z.jsx)(`textarea`,{className:`input`,rows:3,maxLength:512,value:c.modelProfile??``,placeholder:s(`cws.jev.modelProfilePlaceholder`),onChange:e=>h(v,{modelProfile:e.target.value})}),(0,Z.jsx)(`span`,{className:`muted`,children:s(`cws.jev.modelProfileHint`)})]})]})]},c.clientKey??`${c.provider}:${c.model}`)}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>o([...e,El()]),children:[(0,Z.jsx)(be,{width:14,height:14}),` `,s(`cws.target.add`)]})]})}var XE=[`typesafe`,`systemone`,`model`],ZE={typesafe:`cws.jev.method.typesafe`,systemone:`cws.jev.method.systemone`,model:`cws.jev.method.model`};function QE({idPrefix:e,apiBase:t,combo:n,combos:r,providers:i,models:a,decisionProvider:o,decisionModel:s,decisionTimeoutMs:l,sessionPin:u,disabled:d,onChange:f}){let p=c(),m=pl({decisionProvider:o,decisionModel:s}),h=u!=null&&!al(u),g=(0,X.useMemo)(()=>lu(i,o).filter(e=>e.id!==null),[i,o]),_=g.find(e=>e.id===o?.trim()),{id:v,alias:y,model:b}=n,x=(0,X.useMemo)(()=>hl(a,i,r,{id:v,alias:y,model:b}),[a,i,r,v,y,b]),[S,C]=(0,X.useState)(null),w=(0,X.useRef)(null),T=`${m}\0${o??``}\0${s??``}\0${l??``}`,E=S?.key===T?S.result:null,D=e+`-decision-model-options`;(0,X.useEffect)(()=>()=>{w.current?.abort(),w.current=null},[T]);let O=e=>{e!==m&&f(e===`typesafe`?{decisionProvider:null,decisionModel:null}:e===`systemone`?{decisionProvider:g.find(e=>!e.issue)?.id??g[0]?.id??``,decisionModel:null}:{decisionProvider:null,decisionModel:x[0]??``})},k=m===`typesafe`||m===`systemone`&&!!_&&!_.issue||m===`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()}:{},...m===`systemone`&&o?{decisionProvider:o.trim()}:{},...m===`model`&&s?{decisionModel:s.trim()}:{},...l===null?{}:{decisionTimeoutMs:l}})});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,Z.jsxs)(`fieldset`,{className:`cwi-field cwi-jev-decision`,"aria-describedby":`${e}-decision-method-hint`,children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:p(`cws.jev.decisionMethod`)}),(0,Z.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":p(`cws.jev.decisionMethod`),children:XE.map(t=>(0,Z.jsx)(`button`,{type:`button`,id:`${e}-decision-method-${t}`,className:`btn btn-sm ${m===t?`btn-primary`:`btn-ghost`}`,"aria-pressed":m===t,disabled:d,onClick:()=>O(t),children:p(ZE[t])},t))}),(0,Z.jsxs)(`p`,{id:`${e}-decision-method-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[m===`typesafe`&&p(`cws.jev.decisionServiceDefaultHint`),m===`systemone`&&g.length===0&&p(`cws.jev.method.systemoneEmpty`)]}),m===`systemone`&&g.length>0&&(0,Z.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Z.jsx)(`label`,{htmlFor:`${e}-decision-provider`,children:p(`cws.jev.decisionService`)}),(0,Z.jsx)($,{id:`${e}-decision-provider`,fullWidth:!0,value:o?.trim()??``,disabled:d,describedBy:_?.issue?e+`-decision-provider-hint `+e+`-decision-provider-issue`:e+`-decision-provider-hint`,invalid:_?.issue!==void 0,onChange:e=>f({decisionProvider:e,decisionModel:null}),options:[..._?[]:[{value:``,label:`—`,disabled:!0}],...g.map(e=>({value:e.id,label:e.issue?`${e.id} (${p(Sl[e.issue])})`:e.id,disabled:e.issue!==void 0&&e.id!==_?.id}))]}),(0,Z.jsxs)(`p`,{id:`${e}-decision-provider-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[p(`cws.jev.decisionServiceHint`),_?.baseUrl&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`code`,{children:_.baseUrl})]})]}),_?.issue&&(0,Z.jsx)(`p`,{id:`${e}-decision-provider-issue`,className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:p(`cws.err.invalidDecisionProvider`,{name:_.id??``,reason:p(Sl[_.issue])})})]}),m===`model`&&(0,Z.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Z.jsx)(`label`,{htmlFor:`${e}-decision-model`,children:p(`cws.jev.decisionModel`)}),(0,Z.jsx)(`input`,{id:`${e}-decision-model`,className:`input mono`,list:D,value:s??``,maxLength:512,spellCheck:!1,autoComplete:`off`,placeholder:`ollama/qwen3:4b`,disabled:d,"aria-describedby":`${e}-decision-model-hint`,onChange:e=>f({decisionModel:e.target.value,decisionProvider:null})}),(0,Z.jsx)(`datalist`,{id:D,children:x.map(e=>(0,Z.jsx)(`option`,{value:e},e))}),(0,Z.jsx)(`p`,{id:`${e}-decision-model-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:p(`cws.jev.decisionModelHint`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Z.jsx)(`label`,{htmlFor:`${e}-decision-timeout`,children:p(`cws.jev.decisionTimeout`)}),(0,Z.jsx)(`input`,{id:`${e}-decision-timeout`,className:`input mono`,type:`number`,inputMode:`numeric`,min:ol,max:sl,step:1,placeholder:String(cl),value:l??``,disabled:d,"aria-describedby":`${e}-decision-timeout-hint`,onChange:e=>{if(e.target.value===``){f({decisionTimeoutMs:null});return}let t=Number(e.target.value);Number.isFinite(t)&&f({decisionTimeoutMs:t})}}),(0,Z.jsx)(`p`,{id:`${e}-decision-timeout-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.jev.decisionTimeoutHint`,{default:cl,min:ol,max:sl})})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Z.jsxs)(`label`,{htmlFor:`${e}-session-pin`,children:[(0,Z.jsx)(`input`,{id:`${e}-session-pin`,type:`checkbox`,checked:u!=null,disabled:d,"aria-describedby":`${e}-session-pin-hint`,onChange:e=>f({sessionPin:e.target.checked?{ttlMs:rl}:null})}),` `,p(`cws.jev.sessionPin`)]}),(0,Z.jsx)(`p`,{id:`${e}-session-pin-hint`,className:`muted text-label`,children:p(`cws.jev.sessionPinHint`,{min:rl,max:il})}),u!=null&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`label`,{htmlFor:`${e}-session-pin-ttl`,children:p(`cws.jev.sessionPinTtl`)}),(0,Z.jsx)(`input`,{id:`${e}-session-pin-ttl`,className:`input mono`,type:`number`,inputMode:`numeric`,min:6e4,max:864e5,step:1,value:u.ttlMs||``,disabled:d,"aria-invalid":h||void 0,"aria-describedby":h?`${e}-session-pin-hint ${e}-session-pin-error`:`${e}-session-pin-hint`,onChange:e=>{if(e.target.value===``){f({sessionPin:{ttlMs:0}});return}let t=Number(e.target.value);f({sessionPin:{ttlMs:Number.isFinite(t)?t:0}})}}),h&&(0,Z.jsx)(`p`,{id:`${e}-session-pin-error`,className:`notice-err text-label`,role:`alert`,children:p(`cws.err.invalidSessionPin`,{min:6e4,max:864e5})})]})]}),(0,Z.jsxs)(`div`,{className:`cwi-jev-decision-test`,style:{display:`flex`,gap:8,alignItems:`center`,flexWrap:`wrap`,marginTop:8},children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||!k||E?.state===`running`,onClick:()=>{A()},children:E?.state===`running`?p(`cws.jev.testing`):p(`cws.jev.test`)}),(0,Z.jsxs)(`span`,{className:`muted`,role:`status`,"aria-live":`polite`,style:{fontSize:12,overflowWrap:`anywhere`},children:[E===null&&p(`cws.jev.testHint`),E?.state===`done`&&(E.ok?p(`cws.jev.testOk`,{ms:E.latencyMs,backend:p(fl[E.backend]??`cws.jev.backend.unknown`)}):p(`cws.jev.testFailOpen`,{gate:E.gate,ms:E.latencyMs})),E?.state===`error`&&p(`cws.jev.testError`,{error:E.message})]})]})]})}var $E=[];function eD({apiBase:e,combos:t=$E,existingIds:n,existingAliases:r,providerMap:i,providerQuotaStates:a,providers:o,models:s,capabilityModels:l=s,initialDraft:u,onClose:d,onSubmit:f}){let p=c(),m=(0,X.useRef)(null),[h,g]=(0,X.useState)(()=>u?{...u,targets:u.targets.map(e=>({...e}))}:au()),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(``),x=(0,X.useMemo)(()=>{let e=new Map;for(let t of l)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[l]),S=(0,X.useMemo)(()=>Cl(h.targets,x,h.reasoningEffortMode??`strict`),[h.targets,x,h.reasoningEffortMode]),C=$l(h.targets,a,i)===`exhausted`,w=u?.strategy===`jev`,T=w&&(n.includes(h.id.trim())||!!h.alias?.trim()&&r.includes(h.alias.trim()));(0,X.useEffect)(()=>{let e=m.current;e&&!e.open&&e.showModal()},[]);let E=(0,X.useCallback)(()=>{_||d()},[_,d]),D=(0,X.useCallback)(e=>{e.preventDefault(),E()},[E]),O=async()=>{let e=iu(h,{existingIds:n,existingAliases:r,combos:t,isCreate:!0,providers:i});if(e){b(BE(p,e,h,i));return}v(!0),b(``);let a=h.id.trim(),o=h.alias?.trim()||null;try{let e=await f({...h,id:a,alias:o,model:Pl(a,o)});if(!e.ok){b(e.error||p(`cws.saveFailed`));return}}finally{v(!1)}};return(0,Z.jsxs)(`dialog`,{ref:m,className:`modal-overlay`,"data-combo-preset":w?`jev-auto`:void 0,"aria-labelledby":`cwi-add-title`,onCancel:D,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":p(`common.close`),tabIndex:-1,onClick:E}),(0,Z.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,Z.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:p(`cws.addTitle`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:E,disabled:_,"aria-label":p(`common.close`),children:(0,Z.jsx)(We,{width:16,height:16})})]}),(0,Z.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:p(w?`cws.jev.setupHint`:`cws.addSubtitle`)}),y&&(0,Z.jsx)(Q,{tone:`err`,children:y}),T&&(0,Z.jsx)(Q,{tone:`err`,children:p(`cws.jev.exists`)}),C&&(0,Z.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:p(`cws.quota.allExhausted`)}),(0,Z.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-new-id`,children:p(`cws.field.id`)}),(0,Z.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:h.id,disabled:_,onChange:e=>g(t=>({...t,id:e.target.value,model:Pl(e.target.value,t.alias)}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.idInternalHint`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:p(`cws.field.alias`)}),(0,Z.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:h.alias??``,placeholder:p(`cws.field.aliasPlaceholder`),disabled:_,onChange:e=>g(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:Pl(t.id,e.target.value)}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.aliasHint`)}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.idHint`,{model:h.id.trim()?Pl(h.id,h.alias):`…`})})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:p(`cws.strategy`)}),(0,Z.jsx)(KE,{value:h.strategy,disabled:_,onChange:e=>g(t=>({...t,strategy:e}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(yl[h.strategy])})]}),h.strategy===`jev`&&(0,Z.jsx)(QE,{idPrefix:`cwi-new`,apiBase:e,combo:h,combos:t,providers:o,models:s,decisionProvider:h.decisionProvider??null,decisionModel:h.decisionModel??null,decisionTimeoutMs:h.decisionTimeoutMs??null,sessionPin:h.sessionPin,disabled:_,onChange:e=>g(t=>({...t,...e}))}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:p(`cws.field.defaultEffort`)}),(0,Z.jsx)(qE,{id:`cwi-new-effort`,value:h.defaultEffort,disabled:_,allowedEfforts:S,onChange:e=>g(t=>({...t,defaultEffort:e}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.defaultEffortHint`)})]}),h.strategy===`round-robin`&&(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:p(`cws.field.stickyLimit`)}),(0,Z.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:h.stickyLimit,disabled:_,onChange:e=>{let t=HE(e.target.value,1,100);t!==void 0&&g(e=>({...e,stickyLimit:t}))}}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.stickyLimitHint`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:p(`cws.targets`)}),(0,Z.jsx)(YE,{targets:h.targets,strategy:h.strategy,providers:o,models:s,capabilityModels:l,providerQuotaStates:a,onChange:e=>g(t=>({...t,targets:e}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(bl[h.strategy])})]}),(0,Z.jsx)(JE,{targets:h.targets,models:l,imageInput:h.imageInput??`auto`,reasoningEffortMode:h.reasoningEffortMode??`strict`,disabled:_,onChange:e=>g(t=>({...t,...e}))})]}),(0,Z.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:E,disabled:_,children:p(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{O()},disabled:_||C||T,children:p(_?`common.saving`:`cws.create`)})]})]})]})}function tD(e){return e===null?`—`:`${Math.round(e*100)}%`}function nD(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 rD({apiBase:e,comboId:t,active:n}){let{t:r,locale:i}=a(),[o,s]=(0,X.useState)(`30d`),c=(0,X.useCallback)(async n=>{let r=new URLSearchParams({jev:`1`,comboId:t,range:o}),i=await fetch(`${e}/api/usage?${r}`,{signal:n});if(!i.ok)throw Error(String(i.status));return i.json()},[e,t,o]),l=Fd(`ocx.jev-stats.v1:${e}:${t}:${o}`,[e,t,o],c,{isEmpty:e=>e.summary.decisions===0,enabled:n,pollMs:3e4,pauseWhenHidden:!0,deadlineMs:6e4}),{state:u}=l,d=u.data;return n?(0,Z.jsxs)(`section`,{className:`jev-stats`,"aria-busy":u.refreshing,children:[(0,Z.jsxs)(`div`,{className:`jev-stats-toolbar`,children:[(0,Z.jsx)(`div`,{className:`segmented jev-stats-ranges`,role:`group`,"aria-label":r(`cws.jev.stats.range`),children:[`7d`,`30d`,`all`].map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm ${o===e?`btn-primary`:`btn-ghost`}`,"aria-pressed":o===e,onClick:()=>s(e),children:r(e===`all`?`usage.range.available`:`usage.range.${e}`)},e))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>l.refresh(),children:r(`cws.jev.stats.refresh`)})]}),u.showSkeleton&&(0,Z.jsx)(NE,{label:r(`cws.jev.stats.loading`),rows:4}),u.showError&&(0,Z.jsx)(Q,{tone:`err`,children:r(`cws.jev.stats.loadFailed`)}),d&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ur,{data:d}),(d.historyTruncated||d.entriesTruncated)&&(0,Z.jsx)(Q,{tone:`warn`,children:r(`cws.jev.stats.historyIncomplete`)}),d.error&&(0,Z.jsx)(Q,{tone:`err`,children:r(`cws.jev.stats.loadFailed`)}),d.summary.decisions===0?(0,Z.jsxs)(`div`,{className:`jev-stats-empty`,children:[(0,Z.jsx)(`h3`,{children:r(`cws.jev.stats.emptyTitle`)}),(0,Z.jsx)(`p`,{className:`muted`,children:r(`cws.jev.stats.emptyBody`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`jev-stats-cards`,children:[(0,Z.jsxs)(`div`,{className:`stat`,children:[(0,Z.jsx)(`div`,{className:`muted`,children:r(`cws.jev.stats.decisions`)}),(0,Z.jsx)(`div`,{className:`stat-value`,children:d.summary.decisions.toLocaleString(i)}),(0,Z.jsx)(`div`,{className:`muted text-caption`,children:r(`cws.jev.stats.appliedAndFailOpen`,{applied:d.summary.appliedDecisions,failOpen:d.summary.failOpenDecisions})})]}),(0,Z.jsxs)(`div`,{className:`stat`,children:[(0,Z.jsx)(`div`,{className:`muted`,children:r(`cws.jev.stats.modelTokens`)}),(0,Z.jsx)(`div`,{className:`stat-value`,children:Ue(d.summary.modelTotalTokens,i)}),(0,Z.jsx)(`div`,{className:`muted text-caption`,children:r(`cws.jev.stats.measuredAttempts`,{measured:d.summary.measuredModelAttempts,total:d.summary.modelAttempts})})]}),(0,Z.jsxs)(`div`,{className:`stat`,children:[(0,Z.jsx)(`div`,{className:`muted`,children:r(`cws.jev.stats.decisionTokens`)}),(0,Z.jsx)(`div`,{className:`stat-value`,children:Ue(d.summary.decisionTotalTokens,i)}),(0,Z.jsx)(`div`,{className:`muted text-caption`,children:r(`cws.jev.stats.measuredDecisions`,{measured:d.summary.decisionUsageReported,total:d.summary.decisions})})]})]}),(0,Z.jsxs)(`div`,{className:`jev-stats-facts`,children:[(0,Z.jsx)(`span`,{children:r(`cws.jev.stats.successful`,{count:d.summary.successfulRequests})}),(0,Z.jsx)(`span`,{children:r(d.summary.requestsWithModelFallback===1?`cws.jev.stats.fallbackOne`:`cws.jev.stats.fallbackMany`,{count:d.summary.requestsWithModelFallback})}),(0,Z.jsx)(`span`,{children:r(`cws.jev.stats.averageLatency`,{value:nD(d.summary.averageLatencyMs,i)})}),(0,Z.jsx)(`span`,{children:r(`cws.jev.stats.averageConfidence`,{value:tD(d.summary.averageConfidence)})})]}),(0,Z.jsx)(`div`,{className:`jev-stats-gates`,"aria-label":r(`cws.jev.stats.gates`),children:d.gates.map(e=>(0,Z.jsxs)(`span`,{className:`chip`,children:[e.gate,`: `,e.decisions]},e.gate))}),d.backends&&d.backends.length>0&&(0,Z.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Z.jsxs)(`table`,{className:`jev-stats-table`,"aria-label":r(`cws.jev.stats.backends`),children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:r(`cws.jev.stats.backend`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.decisions`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.applied`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.latency`)})]})}),(0,Z.jsx)(`tbody`,{children:d.backends.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:r(fl[e.backend]??`cws.jev.backend.unknown`)}),(0,Z.jsx)(`td`,{className:`num mono`,children:e.decisions.toLocaleString(i)}),(0,Z.jsx)(`td`,{className:`num mono`,children:e.applied.toLocaleString(i)}),(0,Z.jsx)(`td`,{className:`num mono`,children:nD(e.averageLatencyMs,i)})]},e.backend))})]})}),(0,Z.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Z.jsxs)(`table`,{className:`jev-stats-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:r(`cws.jev.stats.model`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.picks`)}),(0,Z.jsx)(`th`,{children:r(`cws.jev.stats.efforts`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.attempts`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.input`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.output`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.reasoning`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.cacheReadWrite`)}),(0,Z.jsx)(`th`,{className:`num`,children:r(`cws.jev.stats.total`)})]})}),(0,Z.jsx)(`tbody`,{children:d.models.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:e.overflow?(0,Z.jsx)(`div`,{children:r(`cws.jev.stats.otherModels`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`mono`,children:e.model}),(0,Z.jsx)(`div`,{className:`muted text-caption`,children:Ge(e.provider,r)})]})}),(0,Z.jsxs)(`td`,{className:`num mono`,children:[e.picks,(0,Z.jsx)(`span`,{className:`jev-stats-cell-note`,children:r(`cws.jev.stats.appliedAndFailOpen`,{applied:e.appliedPicks,failOpen:e.failOpenPicks})})]}),(0,Z.jsx)(`td`,{children:e.efforts.length>0?e.efforts.map(e=>`${e.effort??r(`cws.jev.stats.noEffort`)} × ${e.picks}`).join(`, `):`—`}),(0,Z.jsxs)(`td`,{className:`num mono`,children:[e.attempts,(0,Z.jsxs)(`span`,{className:`jev-stats-cell-note`,children:[e.measuredAttempts,` `,r(`cws.jev.stats.measuredShort`)]})]}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.inputTokens,i)}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.outputTokens,i)}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.reasoningTokens,i)}),(0,Z.jsxs)(`td`,{className:`num mono`,children:[Ue(e.cacheReadTokens,i),` / `,Ue(e.cacheWriteTokens,i)]}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.totalTokens,i)})]},e.overflow?`__jev_stats_overflow__`:`${e.provider}\0${e.model}`))})]})}),(0,Z.jsx)(`p`,{className:`muted text-caption jev-stats-footnote`,children:r(`cws.jev.stats.tokenFootnote`)})]})]})]}):null}var iD={passthrough:`api.plan.disposition.passthrough`,translated:`api.plan.disposition.translated`,degraded:`api.plan.disposition.degraded`,unsupported:`api.plan.disposition.unsupported`},aD={passthrough:`badge-green`,translated:`badge-accent`,degraded:`badge-amber`,unsupported:`badge-muted`};function oD({effects:e,unknownFeatures:t}){let n=c();return e.length===0&&t.length===0?(0,Z.jsx)(`p`,{className:`muted small`,children:n(`api.plan.noFeatures`)}):(0,Z.jsxs)(`ul`,{className:`protocol-feature-list`,children:[e.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`code`,{children:e.feature}),(0,Z.jsx)(`span`,{className:`badge ${aD[e.disposition]}`,children:n(iD[e.disposition])})]},e.feature)),t.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:n(`api.plan.disposition.unknown`)})]},e))]})}var sD=[`responses`,`chat`,`messages`],cD={native:`api.plan.mode.native`,translated:`api.plan.mode.translated`,"legacy-bridge":`api.plan.mode.legacyBridge`,blocked:`api.plan.mode.blocked`},lD={native:`badge-green`,translated:`badge-accent`,"legacy-bridge":`badge-amber`,blocked:`badge-muted`},uD={preserved:`api.plan.fidelity.preserved`,degraded:`api.plan.fidelity.degraded`,unknown:`api.plan.fidelity.unknown`},dD={direct:`api.plan.routeKind.direct`,combo:`api.plan.routeKind.combo`,policy:`api.plan.routeKind.policy`,unknown:`api.plan.routeKind.unknown`},fD=` → `;function pD({path:e}){let t=c();return e.length>0?(0,Z.jsx)(`code`,{children:e.join(fD)}):(0,Z.jsx)(`span`,{className:`muted`,children:t(`api.plan.noPath`)})}function mD({features:e}){let t=c();return e.length===0?(0,Z.jsx)(`span`,{className:`muted`,children:t(`api.plan.none`)}):(0,Z.jsx)(`span`,{className:`protocol-plan-chips`,children:e.map(e=>(0,Z.jsx)(`code`,{className:`chip`,children:e},e))})}function hD({plan:e}){let t=c();return(0,Z.jsxs)(`div`,{className:`protocol-plan-result`,"aria-live":`polite`,children:[(0,Z.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.overallMode`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`span`,{className:`badge ${lD[e.mode]}`,children:t(cD[e.mode])})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.routeKind`)}),(0,Z.jsx)(`dd`,{children:t(dD[e.routeKind])})]}),e.reasonCodes.length>0&&(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`span`,{className:`protocol-plan-chips`,children:e.reasonCodes.map(e=>(0,Z.jsx)(`code`,{className:`chip`,children:e},e))})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.guaranteed`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(mD,{features:e.guaranteedFeatures})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.partial`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(mD,{features:e.partialFeatures})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.policyRevision`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`code`,{children:e.policyRevision})})]})]}),e.candidates.length===0?(0,Z.jsx)(`p`,{className:`muted small`,children:t(`api.plan.noCandidates`)}):(0,Z.jsx)(`ol`,{className:`protocol-plan-candidates`,children:e.candidates.map(n=>(0,Z.jsxs)(`li`,{className:`protocol-plan-candidate`,children:[(0,Z.jsxs)(`div`,{className:`protocol-plan-candidate-head`,children:[(0,Z.jsxs)(`code`,{children:[n.provider,`/`,n.model]}),(0,Z.jsx)(`span`,{className:`badge ${lD[n.mode]}`,children:t(cD[n.mode])}),!n.eligible&&n.mode!==`blocked`&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:t(`api.plan.ineligible`)})]}),(0,Z.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.requestPath`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(pD,{path:n.requestPath})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.responsePath`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(pD,{path:n.responsePath})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.fidelity`)}),(0,Z.jsx)(`dd`,{children:t(uD[n.fidelity])})]}),n.reasonCodes.length>0&&(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`span`,{className:`protocol-plan-chips`,children:n.reasonCodes.map(e=>(0,Z.jsx)(`code`,{className:`chip`,children:e},e))})})]})]}),(0,Z.jsx)(oD,{effects:n.featureEffects,unknownFeatures:n.unknownFeatures}),(0,Z.jsxs)(`div`,{className:`protocol-plan-links`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>zC(n.provider),children:t(`protocolLinks.providerSettings`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>RC({inbound:e.inbound,upstream:AC(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]})]},`${n.provider}/${n.model}`))})]})}function gD({apiBase:e,models:t,protocolLabel:n}){let r=c(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`chat`),[l,u]=(0,X.useState)(()=>new Set),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(!1),y=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>y.current?.abort(),[]);let b=i||t[0]?.id||``,x=(0,X.useMemo)(()=>hx.filter(e=>vx[e].includes(o)),[o]),S=e=>{s(e),u(t=>new Set([...t].filter(t=>vx[t].includes(e))))},C=(e,t)=>{u(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},w=async()=>{if(!b||p)return;y.current?.abort();let t=new AbortController;y.current=t,m(!0),g(!1);try{let n=await Gx(e,{model:b,inbound:o,features:[...l]},t.signal);if(t.signal.aborted)return;n.kind===`unavailable`?(v(!0),f(null)):n.kind===`error`?g(!0):f(n.plan)}catch{}finally{y.current===t&&m(!1)}};return(0,Z.jsxs)(`div`,{className:`panel api-panel protocol-plan-panel`,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:r(`api.plan.title`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:r(`api.plan.description`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:r(`api.plan.modeNote`)}),_?(0,Z.jsx)(`p`,{className:`muted small`,children:r(`api.plan.unavailable`)}):t.length===0?(0,Z.jsx)(`p`,{className:`muted small`,children:r(`api.plan.noModels`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`protocol-plan-form`,children:[(0,Z.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Z.jsx)(`span`,{className:`muted small`,children:r(`api.plan.model`)}),(0,Z.jsx)($,{fullWidth:!0,label:r(`api.plan.model`),value:b,onChange:a,options:t.map(e=>({value:e.id,label:e.id}))})]}),(0,Z.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Z.jsx)(`span`,{className:`muted small`,children:r(`api.plan.inbound`)}),(0,Z.jsx)($,{fullWidth:!0,label:r(`api.plan.inbound`),value:o,onChange:e=>S(e),options:sD.map(e=>({value:e,label:n(e)}))})]})]}),(0,Z.jsxs)(`fieldset`,{className:`protocol-plan-features`,children:[(0,Z.jsx)(`legend`,{className:`muted small`,children:r(`api.plan.features`)}),x.map(e=>(0,Z.jsxs)(`label`,{className:`protocol-plan-feature`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l.has(e),onChange:t=>C(e,t.target.checked)}),(0,Z.jsx)(`code`,{children:e})]},e))]}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:!b||p,onClick:()=>{w()},children:r(p?`api.plan.previewing`:`api.plan.preview`)})}),h&&(0,Z.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:r(`api.plan.failed`)}),d&&(0,Z.jsx)(hD,{plan:d})]})]})}function _D({apiBase:e,model:t,dirty:n}){let r=c(),[i,a]=(0,X.useState)(`responses`),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),h=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>h.current?.abort(),[]);let g=(0,X.useMemo)(()=>hx.filter(e=>vx[e].includes(i)),[i]),_=async()=>{if(l)return;h.current?.abort();let n=new AbortController;h.current=n,u(!0),f(!1);try{let r=await Gx(e,{model:t,inbound:i,features:g},n.signal);if(n.signal.aborted)return;r.kind===`unavailable`?m(!0):r.kind===`error`?f(!0):s(r.plan)}catch{}finally{h.current===n&&u(!1)}};return p?null:(0,Z.jsxs)(`section`,{className:`pwi-section combo-protocol-plan`,"aria-labelledby":`cws-plan-title`,children:[(0,Z.jsx)(`h3`,{id:`cws-plan-title`,className:`pwi-section-title`,children:r(`cws.plan.title`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:r(`cws.plan.description`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:r(`api.plan.modeNote`)}),n&&(0,Z.jsx)(`p`,{className:`muted small`,role:`status`,children:r(`cws.plan.savedOnly`)}),(0,Z.jsx)(`div`,{className:`protocol-plan-form`,children:(0,Z.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Z.jsx)(`span`,{className:`muted small`,children:r(`api.plan.inbound`)}),(0,Z.jsx)($,{fullWidth:!0,label:r(`api.plan.inbound`),value:i,onChange:e=>{a(e),s(null)},options:Yb.map(e=>({value:e,label:Qx(e,r)}))})]})}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:l,onClick:()=>{_()},children:r(l?`api.plan.previewing`:`cws.plan.run`)})}),d&&(0,Z.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:r(`api.plan.failed`)}),o&&o.inbound===i&&(0,Z.jsx)(hD,{plan:o})]})}var vD=[`config`,`about`],yD=[`config`,`stats`,`about`],bD=e=>`cws-detail-tab-${e}`,xD=e=>`cws-detail-panel-${e}`,SD=[];function CD({apiBase:e,baseline:t,combos:n=SD,isCreate:r=!1,otherIds:i,otherAliases:a,providerMap:o,providerQuotaStates:s,providers:l,models:u,capabilityModels:d=u,visionEnabled:f,onBack:p,onSaved:m,onRequestRemove:h,onSave:g,onDirtyChange:_}){let v=c(),[y,b]=(0,X.useState)(`config`),x=!r&&t.strategy===`jev`?yD:vD,S=(0,X.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(),b(x[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[x]),[C,w]=(0,X.useState)(t),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(!1),j=!nu(C,t),M=$l(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,X.useMemo)(()=>{let e=new Map;for(let t of d)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[d]),F=(0,X.useMemo)(()=>Cl(C.targets,P,C.reasoningEffortMode??`strict`),[C.targets,P,C.reasoningEffortMode]),I=(0,X.useCallback)(e=>{let n=e(C);w(n),_(!nu(n,t))},[C,t,_]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{w(t),O(null),b(`config`),_(!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=iu(C,{existingIds:i,existingAliases:a,combos:n,isCreate:r,providers:o});if(e){O({ok:!1,text:BE(v,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:Pl(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 g(u,r,d);if(!e.ok){O({ok:!1,text:e.error||v(`cws.saveFailed`)});return}O({ok:!0,text:r?v(`cws.created`,{model:u.model}):v(`cws.saved`)}),m(u)}finally{E(!1)}},z=r?C.id.trim()?Pl(C.id,C.alias):v(`cws.addTitle`):t.model;return(0,Z.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,Z.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[p&&(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:p,"aria-label":v(`cws.backToAll`),children:[(0,Z.jsx)(St,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),v(`cws.allCombos`)]}),(0,Z.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:z}),!r&&(0,Z.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{L()},title:v(`cws.copyModel`),children:v(k?`cws.copied`:`cws.copyModel`)}),(0,Z.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!r&&h&&(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:h,children:[(0,Z.jsx)(ge,{width:14,height:14}),` `,v(`common.remove`)]}),(0,Z.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:v(T?`common.saving`:r?`cws.create`:`common.save`)})]})]}),D&&(0,Z.jsx)(Q,{tone:D.ok?`ok`:`err`,children:D.text}),M&&(0,Z.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:v(`cws.quota.allExhausted`)}),(0,Z.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":v(`cws.tabsLabel`),children:x.map((e,t)=>(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:bD(e),"aria-selected":y===e,"aria-controls":xD(e),tabIndex:y===e?0:-1,className:`btn btn-sm ${y===e?`btn-primary`:`btn-ghost`}`,onClick:()=>b(e),onKeyDown:e=>S(e,t),children:v(e===`config`?`cws.tab.config`:e===`stats`?`cws.jev.stats.tab`:`cws.tab.about`)},e))}),(0,Z.jsxs)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:xD(`config`),"aria-labelledby":bD(`config`),hidden:y!==`config`,children:[(0,Z.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:v(`cws.field.id`)}),(0,Z.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:C.id,disabled:T,onChange:e=>I(t=>({...t,id:e.target.value,model:Pl(e.target.value,t.alias)}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:r?v(`cws.field.idInternalHint`):v(`cws.field.idHintEdit`,{model:Pl(C.id,C.alias)})})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:v(`cws.field.alias`)}),(0,Z.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:C.alias??``,placeholder:Nl(C.id.trim()||`…`),disabled:T,onChange:e=>I(t=>Fl(t,e.target.value))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.aliasHint`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,Z.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:C.nativeAlias,disabled:T,onChange:e=>I(t=>({...t,nativeAlias:e.target.checked}))}),` `,v(`cws.field.nativeAlias`)]}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.nativeAliasHint`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:v(`cws.field.displayName`)}),(0,Z.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,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.displayNameHint`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:v(`cws.strategy`)}),(0,Z.jsx)(KE,{value:C.strategy,disabled:T,onChange:e=>I(t=>({...t,strategy:e}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(yl[C.strategy])})]}),C.strategy===`jev`&&(0,Z.jsx)(QE,{idPrefix:`cwi-edit`,apiBase:e,combo:C,combos:n,providers:l,models:u,decisionProvider:C.decisionProvider??null,decisionModel:C.decisionModel??null,decisionTimeoutMs:C.decisionTimeoutMs??null,sessionPin:C.sessionPin,disabled:T,onChange:e=>I(t=>({...t,...e}))}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-effort`,children:v(`cws.field.defaultEffort`)}),(0,Z.jsx)(qE,{id:`cwi-effort`,value:C.defaultEffort,disabled:T,allowedEfforts:F,onChange:e=>I(t=>({...t,defaultEffort:e}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.defaultEffortHint`)})]}),C.strategy===`round-robin`&&(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`cwi-sticky`,children:v(`cws.field.stickyLimit`)}),(0,Z.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:C.stickyLimit,disabled:T,onChange:e=>{let t=HE(e.target.value,1,100);t!==void 0&&I(e=>({...e,stickyLimit:t}))}})]}),(0,Z.jsxs)(`div`,{className:`cwi-field`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:v(`cws.targets`)}),(0,Z.jsx)(YE,{targets:C.targets,strategy:C.strategy,providers:l,models:u,capabilityModels:d,providerQuotaStates:s,onChange:e=>I(t=>({...t,targets:e}))}),(0,Z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(bl[C.strategy])})]}),(0,Z.jsx)(JE,{targets:C.targets,models:d,imageInput:C.imageInput??`auto`,reasoningEffortMode:C.reasoningEffortMode??`strict`,visionEnabled:f,disabled:T,onChange:e=>I(t=>({...t,...e}))})]}),!r&&e!==void 0&&(0,Z.jsx)(_D,{apiBase:e,model:t.model,dirty:j})]}),!r&&t.strategy===`jev`&&(0,Z.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:xD(`stats`),"aria-labelledby":bD(`stats`),hidden:y!==`stats`,children:(0,Z.jsx)(rD,{apiBase:e??``,comboId:t.id,active:y===`stats`})}),(0,Z.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:xD(`about`),"aria-labelledby":bD(`about`),hidden:y!==`about`,tabIndex:0,children:(0,Z.jsxs)(`section`,{className:`pwi-section`,children:[(0,Z.jsx)(`h3`,{className:`pwi-section-title`,children:v(`cws.aboutTitle`)}),(0,Z.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:v(`cws.aboutBody`)})]})})]})}function wD({model:e,onCancel:t,onConfirm:n}){let r=c(),i=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,X.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,Z.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,Z.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,Z.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,Z.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function TD({onKeep:e,onDiscard:t}){let n=c(),r=(0,X.useRef)(null);(0,X.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]);let i=(0,X.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,Z.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,Z.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,Z.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,Z.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function ED(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 DD({combos:e,cataloguedComboIds:t,providerMap:n,providerQuotaStates:r,providers:i,onSelect:a,onAdd:o}){let s=c(),l=Gl(e),u=eu(e,{cataloguedComboIds:t,providers:n,providerQuotaStates:r}),d=e.flatMap(e=>{let t=uu(e,i);return t?[{item:e,decision:t}]:[]});return(0,Z.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,Z.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,Z.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:s(`cws.overviewTitle`)}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:o,children:[(0,Z.jsx)(be,{width:14,height:14}),` `,s(`cws.add`)]})]}),(0,Z.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:s(`cws.overviewBlurb`)}),(0,Z.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,Z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Z.jsx)(`strong`,{children:e.length}),(0,Z.jsx)(`span`,{children:s(`cws.count.total`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Z.jsx)(`strong`,{children:l.failover.length}),(0,Z.jsx)(`span`,{children:s(`cws.count.failover`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Z.jsx)(`strong`,{children:l.roundRobin.length}),(0,Z.jsx)(`span`,{children:s(`cws.count.roundRobin`)})]}),(0,Z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Z.jsx)(`strong`,{children:l.other.length}),(0,Z.jsx)(`span`,{children:s(`cws.count.other`)})]})]}),(0,Z.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.howTitle`),children:[(0,Z.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.howTitle`)}),(0,Z.jsx)(`p`,{className:`muted`,style:{margin:0},children:s(`cws.howBody`)})]}),d.length>0&&(0,Z.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.jev.decisionServicesTitle`),children:[(0,Z.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.jev.decisionServicesTitle`)}),(0,Z.jsx)(`div`,{className:`cwi-attention-list`,children:d.map(({item:e,decision:t})=>(0,Z.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,Z.jsx)(`code`,{className:`chip`,children:e.model}),t.model?(0,Z.jsxs)(`span`,{children:[s(`cws.jev.method.model`),`: `,(0,Z.jsx)(`code`,{children:t.model})]}):(0,Z.jsx)(`span`,{children:t.provider??s(`cws.jev.decisionServiceDefault`)}),t.baseUrl&&(0,Z.jsx)(`code`,{className:`muted`,style:{overflowWrap:`anywhere`},children:t.baseUrl}),(0,Z.jsx)(`span`,{className:`muted`,children:t.timeoutMs===null?s(`cws.jev.decisionTimeoutDefaultShort`):s(`cws.jev.decisionTimeoutShort`,{ms:t.timeoutMs})}),(0,Z.jsx)(St,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},e.id))})]}),u.length>0&&(0,Z.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.attentionTitle`),children:[(0,Z.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.attentionTitle`)}),(0,Z.jsx)(`div`,{className:`cwi-attention-list`,children:u.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>a(e.id),children:[(0,Z.jsx)(at,{width:14,height:14,"aria-hidden":`true`}),(0,Z.jsx)(`code`,{className:`chip`,children:e.model}),(0,Z.jsx)(`span`,{className:`muted`,children:ED(e.reason,s)}),(0,Z.jsx)(St,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function OD({apiBase:e,combos:t,providerQuotaStates:n,providers:r,models:i,capabilityModels:a=i,cataloguedComboIds:o,visionEnabled:s,loading:l,onRefresh:u,onSave:d,onRemove:f,onAdd:p,adding:m,addIntent:h,addDecisionProvider:g,onCloseAdd:_,onCreated:v}){let y=c(),b=(0,X.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,X.useState)(``),[C,w]=(0,X.useState)(null),[T,E]=(0,X.useState)(void 0),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),j=(0,X.useMemo)(()=>au(),[]),M=(0,X.useMemo)(()=>t.some(e=>e.id===`jev-auto`||e.alias===`jev-auto`),[t]),N=(0,X.useMemo)(()=>new Set(r.filter(e=>!e.disabled&&!e.hiddenFromPicker&&e.adapter!==`jev-decision`).map(e=>e.name)),[r]),P=(0,X.useMemo)(()=>{if(h!==`jev-auto`)return;let e=r.length===0||cu(g,b)===null;return su(i,N,e?g:null)},[g,h,N,i,b,r.length]),F=(0,X.useMemo)(()=>Kl(t,x),[t,x]),I=(0,X.useMemo)(()=>Gl(F),[F]),L=(0,X.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,X.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,X.useCallback)(e=>{e!==R&&(V?E(e):(w(e),A(null)))},[R,V]),te=()=>{T!==void 0&&(w(T),A(null),H(!1),E(void 0))},ne=()=>E(void 0),G=T!==void 0&&V,K=!l&&t.length===0&&!m;return(0,Z.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,Z.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":y(`cws.railAria`),children:[(0,Z.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`combos-workspace-rail-title`,children:y(`nav.combos`)}),(0,Z.jsx)(`div`,{className:`combos-workspace-rail-count`,children:t.length})]}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{K?document.getElementById(`cwi-edit-id`)?.focus():p()},"aria-label":y(`cws.add`),children:[(0,Z.jsx)(be,{width:14,height:14}),` `,y(`cws.add`)]})]}),(0,Z.jsxs)(`div`,{className:`cwi-jev-quick-action`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>p(`jev-auto`),disabled:M,title:y(M?`cws.jev.exists`:`cws.jev.setupHint`),children:[(0,Z.jsx)(Le,{width:14,height:14}),` `,y(`cws.jev.create`)]}),M&&(0,Z.jsx)(`span`,{className:`muted`,children:y(`cws.jev.exists`)})]}),t.length>0&&(0,Z.jsx)(`div`,{className:`cwi-search-row`,children:(0,Z.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,Z.jsx)(ze,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,Z.jsx)(`input`,{className:`input cwi-search-input`,value:x,onChange:e=>S(e.target.value),placeholder:y(`cws.searchPlaceholder`),"aria-label":y(`cws.searchPlaceholder`)})]})}),(0,Z.jsx)(`div`,{className:`combos-workspace-rail-list`,children:F.length===0&&t.length>0?(0,Z.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:y(`cws.noSearchResults`)}):(0,Z.jsx)(Z.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,Z.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,Z.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,Z.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),y(n),(0,Z.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,Z.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,Z.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,Z.jsx)(Le,{width:16,height:16})}),(0,Z.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,Z.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?y(`cws.targetCountOne`):y(`cws.targetCount`,{count:e.targets.length})}),(0,Z.jsx)(St,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,Z.jsx)(`div`,{className:`combos-workspace-main`,children:B&&z?(0,Z.jsx)(CD,{apiBase:e,baseline:B,combos:t.filter(e=>e.id!==B.id),otherIds:U,otherAliases:W,providerMap:b,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)),u()},onRequestRemove:()=>O(B.id),onSave:d,onDirtyChange:H},B.id):K?(0,Z.jsx)(CD,{apiBase:e,baseline:j,isCreate:!0,otherIds:[],otherAliases:[],providerMap:b,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,visionEnabled:s,onSaved:e=>{H(!1),w(e.id),A(null),v(e.id)},onSave:d,onDirtyChange:H},`first-combo`):(0,Z.jsx)(DD,{combos:t,cataloguedComboIds:o,providerMap:b,providerQuotaStates:n,providers:r,onSelect:e=>ee(e),onAdd:p})}),m&&(0,Z.jsx)(eD,{apiBase:e,combos:t,existingIds:t.map(e=>e.id),existingAliases:L,providerMap:b,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,initialDraft:P,onClose:_,onSubmit:async e=>{let t=await d(e,!0);return t.ok&&(_(),v(e.id),w(e.id),A(null)),t}},`${h??`blank`}:${P?.decisionProvider??``}`),D&&(0,Z.jsx)(wD,{model:t.find(e=>e.id===D)?.model??Nl(D),onCancel:()=>O(null),onConfirm:()=>{(async()=>{let e=await f(D);O(null),e.ok&&(R===D&&(w(null),A(null)),u())})()}}),G&&(0,Z.jsx)(TD,{onKeep:ne,onDiscard:te})]})}function kD(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function AD(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function jD(e){return jd(e)?.data??null}function MD(e){return jd(e)?.cachedAt??null}function ND({apiBase:e,active:t=!0,onCountChange:n}){let r=c(),i=`ocx.combos.workspace.v2:${e}`,a=(0,X.useMemo)(()=>jD(i),[i]),[o,s]=(0,X.useState)(a??null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(()=>bC(window.location.hash)===void 0?null:`jev-auto`),[h,g]=(0,X.useState)(()=>bC(window.location.hash)??null),_=(0,X.useCallback)(()=>{m(null),g(null),bC(window.location.hash)!==void 0&&gn(`models/combos`)},[]),v=(e,t)=>{u(e),f(t)};(0,X.useEffect)(()=>{if(!l||!d)return;let e=window.setTimeout(()=>{u(``),f(!1)},5e3);return()=>window.clearTimeout(e)},[l,d]);let y=(0,X.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=Wl(o),f=c.providers??{},p=Re(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 Md(i,y),s(y),y},[e,i]),b=Fd(i,[e],y,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:MD(i),staleAfterMs:6e4,enabled:t}),{state:x}=b,[S,C]=(0,X.useState)(void 0);(0,X.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,X.useState)(()=>Date.now()),E=(0,X.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=Fd(`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=Ql(O,w),A=Zl(O,w);(0,X.useEffect)(()=>{if(!t)return;let e=()=>T(Date.now()),n=window.setTimeout(e,A===void 0?0:Math.max(0,A-Date.now())),r=Pt(()=>{Nt()||e()});return()=>{window.clearTimeout(n),r()}},[t,e,D.data,D.lastAttemptOk,A]);let j=x.data??o??void 0,M=j?.combos??[];(0,X.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(ru(t,{...i?{renameFrom:i}:{},...t.imageInput===`disabled`?{}:{visionSidecarTargets:RE(t.targets,F)}}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=kD(o);if(!a.ok||s||!AD(o)){let e=s||r(`cws.saveFailed`);return v(e,!1),{ok:!1,error:e}}return b.refresh(),v(i?r(`cws.renamed`,{from:Nl(i),to:t.model}):n?r(`cws.created`,{model:t.model}):r(`cws.saved`),!0),{ok:!0}}catch{let e=r(`cws.saveFailed`);return v(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=kD(i);if(!n.ok||a||!AD(i)){let e=a||r(`cws.removeFailed`);return v(e,!1),{ok:!1,error:e}}return b.refresh(),v(r(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=r(`cws.removeFailed`);return v(e,!1),{ok:!1,error:e}}};if(x.showSkeleton&&!j)return(0,Z.jsx)(NE,{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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Q,{tone:`err`,children:e}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>b.refresh(),children:r(`common.retry`)})]})}return(0,Z.jsxs)(`div`,{className:`combos-workspace-shell`,children:[l&&(0,Z.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Z.jsx)(Q,{tone:d?`ok`:`err`,children:l})}),x.showError&&(0,Z.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Z.jsx)(Q,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,Z.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":x.refreshing,children:[(0,Z.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:x.refreshing?r(`common.loading`):``}),(0,Z.jsx)(OD,{apiBase:e,combos:M,providerQuotaStates:k,providers:N,models:P,capabilityModels:F,cataloguedComboIds:I,visionEnabled:S,loading:!1,onRefresh:()=>{b.refresh(),D.refresh()},onSave:L,onRemove:R,onAdd:(e=`blank`)=>m(e),adding:p!==null,addIntent:p??void 0,addDecisionProvider:h,onCloseAdd:_,onCreated:()=>b.refresh()})]})]})}var PD=0;function FD(){return PD+=1,`candidate-${PD}`}function ID(e,t){return{provider:e,model:t,key:FD()}}function LD(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 RD(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:LD(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 zD={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},BD={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function VD(e){return e===!0?`true`:e===!1?`false`:``}function HD(e){return e===void 0?``:String(e)}function UD(e=``,t=``){return{id:``,alias:``,candidates:[ID(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...zD},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...BD},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function WD(e){let t=RD(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:FD()})),require:{minContextWindow:HD(e.require.minContextWindow),minQuotaHeadroom:HD(e.require.minQuotaHeadroom),tools:VD(e.require.tools),imageInput:VD(e.require.imageInput),structuredOutput:VD(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:VD(e.require.localOnly),remoteAllowed:VD(e.require.remoteAllowed),encryptedCodexTasks:VD(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:HD(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:HD(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function GD(e){let t=e.trim();return t?Number(t):void 0}function KD(e){if(e===`true`)return!0;if(e===`false`)return!1}function qD(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function JD(e,t,n){let r=qD({minContextWindow:GD(e.require.minContextWindow),minQuotaHeadroom:GD(e.require.minQuotaHeadroom),tools:KD(e.require.tools),imageInput:KD(e.require.imageInput),structuredOutput:KD(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:KD(e.require.localOnly),remoteAllowed:KD(e.require.remoteAllowed),encryptedCodexTasks:KD(e.require.encryptedCodexTasks)}),i=GD(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?qD({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:GD(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=qD({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 YD(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 XD(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function ZD(e,t){return e.filter(e=>e.provider===t)}var QD={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`}},$D=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],eO=[`reasoningEffort`,`serviceTier`],tO={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},nO=Object.keys(tO),rO=[`latency`,`health`,`cost`,`quota`],iO=[`capability`,`health`,`quota`,`cost`],aO=[`allow`,`penalize`,`exclude`],oO=[`allow`,`exclude`];function sO(e){return`${e.evidenceLayer}:${e.suiteId}`}function cO(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function lO(e){let t=new Set,n=[];for(let r of e){if(!cO(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=sO(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 uO(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function dO(e,t){return e===void 0?t:`${Math.round(e)}ms`}function fO(e,t){return e==null?t:`${Math.round(e*100)}%`}function pO(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 mO(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 hO(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>cO(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&cO(e.require)&&cO(e.optimize)&&cO(e.limits)&&cO(e.unknownEvidence):!1).map(e=>{let t=RD(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function gO(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 _O(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 vO({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=a(),o=QD[r],s=i(`routing.unavailable`),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)({}),[g,_]=(0,X.useState)([]),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(!1),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(null),[R,z]=(0,X.useState)(``),[B,V]=(0,X.useState)(!1),[H,U]=(0,X.useState)([]),[W,ee]=(0,X.useState)(!1),te=(0,X.useRef)(null),ne=(0,X.useRef)(0),G=(0,X.useRef)(null),K=(0,X.useRef)(!0),re=(0,X.useCallback)(()=>{K.current=!1,G.current?.abort(),ne.current++},[]),q=(0,X.useRef)(0),ie=(0,X.useCallback)((e,t)=>{T({message:e,ok:t})},[]);(0,X.useEffect)(()=>{if(!w?.ok)return;let e=window.setTimeout(()=>T(null),5e3);return()=>window.clearTimeout(e)},[w]);let ae=(0,X.useCallback)(()=>{q.current+=1,L(null),z(``),V(!1)},[]),oe=(0,X.useCallback)(e=>{te.current=e,x(e),C(e?WD(e):null),T(null),ae()},[ae]),se=(0,X.useCallback)(async t=>{if(!K.current)return;G.current?.abort();let n=new AbortController;G.current=n;let{signal:r}=n,i=++ne.current;y(``);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!==ne.current)return;let y=hO(u),b=te.current,S=_O(y,b?.id??null,t),w=m.providers??{},T=Object.entries(w).filter(([,e])=>e.disabled!==!0).map(([e])=>e).sort((e,t)=>e<t?-1:+(e>t)),E=Object.fromEntries(Object.entries(w).filter(([,e])=>e.disabled!==!0&&typeof e.defaultModel==`string`).map(([e,t])=>[e,t.defaultModel.trim()]));te.current=S,l(y),x(S),C(S?WD(S):null),d(f),p(T),h(E),_(gO(g)),v&&Array.isArray(v.scenarios)?(U(lO(v.scenarios)),ee(!1)):(U([]),ee(!0)),(!b||!S||b.id!==S.id||b.revision!==S.revision)&&ae()}catch(e){if(i!==ne.current||r.aborted)return;y(e instanceof Error?e.message:String(e))}finally{G.current===n&&(G.current=null)}},[e,ae]);(0,X.useEffect)(()=>{if(!t){re();return}K.current=!0;let e=window.setTimeout(()=>void se(),0);return()=>{window.clearTimeout(e),re()}},[t,re,se]),(0,X.useEffect)(()=>{n?.(c.length)},[n,c.length]);let ce=f[0]??``,le=m[ce]??ZD(g,ce)[0]?.id??``,ue=()=>{te.current=null,x(null),C(UD(ce,le)),T(null),ae()},J=()=>{b?(C(WD(b)),T(null)):oe(c[0]??null)},de=async()=>{if(S&&!E){D(!0),T(null);try{let t=JD(S,b?`update`:`create`,b?.revision),n=await fetch(`${e}/api/routing-profiles`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await Bn(n);if(!n.ok){let e=await n.json().catch(()=>null);ie(YD(e)??i(`routing.loadFailed`),!1);return}if(!XD(r)){ie(YD(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{D(!1)}}},fe=async()=>{if(b&&!E&&await Nu({message:i(`routing.removeConfirm`,{id:b.id}),confirmLabel:i(`common.remove`),tone:`danger`})){D(!0),T(null);try{let t=await fetch(`${e}/api/routing-profiles?id=${encodeURIComponent(b.id)}`,{method:`DELETE`}),n=await Bn(t);if(!t.ok){let e=await t.json().catch(()=>null);ie(YD(e)??i(`routing.loadFailed`),!1);return}if(!XD(n)){ie(YD(n)??i(`routing.loadFailed`),!1);return}te.current=null,await se(),ie(i(`common.ok`),!0)}catch(e){ie(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},pe=(e,t,n)=>{C(r=>{if(!r)return r;let i=r.candidates.map((r,i)=>i===e?t===`provider`?{...r,provider:n,model:m[n]??ZD(g,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},me=()=>{C(e=>e&&{...e,candidates:[...e.candidates,ID(ce,le)]})},he=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},ge=async()=>{if(!b)return;let t=++q.current;V(!0),L(null),z(``);try{let n={},r=O.trim()?Number(O.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),A&&(n.toolsRequired=!0),M&&(n.imageInputRequired=!0),P&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:b.id,evidence:n})});if(t!==q.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==q.current)return;z(YD(e)??i(`routing.dryRunError`,{status:a.status}));return}let o=await a.json();if(t!==q.current)return;L(o)}catch(e){if(t!==q.current)return;z(e instanceof Error?e.message:String(e))}finally{t===q.current&&V(!1)}},_e=S?.candidates.map(e=>ZD(g,e.provider))??[],ve=aO.map(e=>({value:e,label:i(`routing.unknownEvidence.${e}`)}));return(0,Z.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,Z.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:ue,children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void se(),children:i(`common.retry`)})]}),v?(0,Z.jsxs)(Q,{tone:`err`,children:[i(`routing.loadFailed`),`: `,v]}):null,w?(0,Z.jsx)(Q,{tone:w.ok?`ok`:`err`,children:w.message}):null,c.length>0?(0,Z.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:c.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>oe(e),"aria-pressed":b?.id===e.id,children:(0,Z.jsxs)(`div`,{className:`card-badges`,children:[(0,Z.jsx)(`strong`,{children:e.id}),(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,Z.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),de()},children:[(0,Z.jsxs)(`div`,{className:`page-head`,children:[(0,Z.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,b?.model??(0,Z.jsx)(`code`,{children:`policy/…`})]}),b?(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,b.revision]}):null]}),(0,Z.jsxs)(`div`,{className:`model-grid`,children:[(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:`id`}),(0,Z.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:`alias`}),(0,Z.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,Z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,Z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[S.candidates.map((e,t)=>{let n=[...new Set([e.provider,...f])].filter(Boolean),r=`routing-model-options-${t}`;return(0,Z.jsxs)(`div`,{className:`model-card`,children:[(0,Z.jsxs)(`div`,{className:`model-grid`,children:[(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:`provider`}),(0,Z.jsx)($,{fullWidth:!0,required:!0,value:e.provider,onChange:e=>pe(t,`provider`,e),options:[{value:``,label:i(`routing.none`),disabled:!0},...n.map(e=>({value:e,label:e}))]})]}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:`model`}),(0,Z.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>pe(t,`model`,e.target.value)}),(0,Z.jsx)(`datalist`,{id:r,children:_e[t]?.map(e=>(0,Z.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S.candidates.length===1,onClick:()=>he(t),"aria-label":i(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:i(`common.remove`)})]},e.key)}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:me,children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,Z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,Z.jsxs)(`div`,{className:`model-grid`,children:[nO.map(e=>(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:tO[e].min,max:tO[e].max,step:tO[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),eO.map(e=>(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),$D.map(e=>(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)($,{fullWidth:!0,value:S.require[e],onChange:t=>C(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,Z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,Z.jsx)(`div`,{className:`model-grid`,children:rO.map(e=>(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,required:!0,value:S.optimize[e],onChange:t=>C(n=>n&&{...n,optimize:{...n.optimize,[e]:t.target.value}})})]},e))})]}),(0,Z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,value:S.limits.maxEstimatedCostUsd,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,maxEstimatedCostUsd:e.target.value}})})]}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:`onUnknownCost`}),(0,Z.jsx)($,{fullWidth:!0,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e}}),options:oO.map(e=>({value:e,label:i(`routing.unknownEvidence.${e}`)}))})]})]}),(0,Z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,Z.jsx)(`div`,{className:`model-grid`,children:iO.map(e=>(0,Z.jsxs)(`label`,{className:`field-label`,children:[(0,Z.jsx)(`code`,{children:e}),(0,Z.jsx)($,{fullWidth:!0,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t}}),options:ve})]},e))})]}),(0,Z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,Z.jsxs)(`label`,{className:`checkbox`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:S.compatibility.enabled,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),i(`routing.compatibility.enabled`)]}),S.compatibility.enabled?(0,Z.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,Z.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),W?(0,Z.jsx)(`div`,{style:{marginTop:6},children:(0,Z.jsx)(Q,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,H.length>0?(0,Z.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:H.map(e=>(0,Z.jsxs)(`label`,{className:`checkbox`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:uO(S.compatibility.requiredSuites,e),onChange:t=>C(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,Z.jsxs)(`span`,{children:[e.suiteId,` `,(0,Z.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,Z.jsx)($,{fullWidth:!0,value:S.compatibility.minStatus,onChange:e=>C(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,Z.jsxs)(`label`,{className:`field-label`,children:[o.maxEvidenceAgeMs,(0,Z.jsx)(`input`,{className:`input`,type:`number`,min:0,value:S.compatibility.maxEvidenceAgeMs,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,maxEvidenceAgeMs:e.target.value}})})]}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[o.unknownEvidence,(0,Z.jsx)($,{fullWidth:!0,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e}}),options:ve})]}),(0,Z.jsxs)(`label`,{className:`field-label`,children:[o.degradedEvidence,(0,Z.jsx)($,{fullWidth:!0,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e}}),options:ve})]})]}):null]}),(0,Z.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,Z.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:i(E?`common.saving`:`common.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:J,children:i(`common.cancel`)}),b?(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void fe(),children:i(`common.remove`)}):null]})]}):null,b&&(0,Z.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Z.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,Z.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,Z.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),ae()}})]}),(0,Z.jsxs)(`label`,{className:`checkbox`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),ae()}}),i(`routing.dryRunTools`)]}),(0,Z.jsxs)(`label`,{className:`checkbox`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),ae()}}),i(`routing.dryRunImage`)]}),(0,Z.jsxs)(`label`,{className:`checkbox`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),ae()}}),i(`routing.dryRunStructured`)]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||B,onClick:()=>void ge(),children:i(`routing.dryRunRun`)}),R?(0,Z.jsx)(Q,{tone:`err`,children:R}):null,I?(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:i(`routing.candidate`)}),(0,Z.jsx)(`th`,{children:i(`routing.eligible`)}),(0,Z.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,Z.jsx)(`th`,{children:i(`routing.costCap`)}),(0,Z.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,Z.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,Z.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,Z.jsx)(`td`,{children:e.exclusions.map(e=>mO(e.code,i)).join(`, `)||i(`routing.none`)}),(0,Z.jsx)(`td`,{children:pO(e.cost?.capOutcome,i,s)}),(0,Z.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):s})]},`${e.provider}/${e.model}`))})]}):null]}),c.length>0&&(0,Z.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Z.jsx)(`h3`,{children:i(`routing.analytics`)}),u?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`card-badges`,children:[(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,u.totalRequests]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,fO(u.successRate,s)]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,fO(u.fallbackRate,s)]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,dO(u.durationMs.p50,s)]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,dO(u.durationMs.p95,s)]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,dO(u.durationMs.p99,s)]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,u.cooldownTriggeringFailures]}),(0,Z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,u.confidence??s]}),u.historyTruncated?(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:i(`routing.candidate`)}),(0,Z.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,Z.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,Z.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,Z.jsx)(`tbody`,{children:u.breakdown.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,Z.jsx)(`td`,{children:e.requests}),(0,Z.jsx)(`td`,{children:fO(e.successRate,s)}),(0,Z.jsx)(`td`,{children:dO(e.p50DurationMs,s)})]},`${e.provider}/${e.model}`))})]})]}):(0,Z.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var yO=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],bO=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],xO=[`present`,`corrupt`,`purged_unavailable`];function SO(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function CO(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function wO(e){return e===null||typeof e==`string`}function TO(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function EO(e){if(!SO(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(!TO(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function DO(e){return!SO(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!yO.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`||!bO.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!CO(e.scenarioManifestDigests)||!wO(e.claimSourceDigest)||!CO(e.contributingEventIds)||!CO(e.contradictingEventIds)||!CO(e.notes)?null:e}function OO(e){return!SO(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(DO).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function kO(e){return!SO(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>SO(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function AO(e){return!SO(e)||!SO(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function jO(e){return!SO(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!yO.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`||!wO(e.exclusionReason)?null:e}function MO(e){return!SO(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(jO).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function NO(e){if(!SO(e)||!SO(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`||!wO(t.exclusionReason)?null:t}function PO(e){if(!SO(e)||!SO(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!xO.includes(t.status)||!wO(t.artifactClass)||!wO(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!wO(t.lastError)?null:t}function FO(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 IO(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function LO(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:IO()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function RO(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function zO(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function BO(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 VO(e){if(!e)return{};let t=typeof e.inboundProtocol==`string`?px(e.inboundProtocol):void 0,n=typeof e.upstreamProtocol==`string`?px(e.upstreamProtocol):void 0;return{...t?{inbound:t}:{},...n?{upstream:n}:{}}}function HO(e){return e.inbound!==``||e.upstream!==``}function UO(e,t){return!HO(t)||!(!e||t.inbound&&e.inbound!==t.inbound||t.upstream&&e.upstream!==t.upstream)}function WO(e,t,n){return HO(n)?e.filter(e=>UO(t.get(e.subjectId),n)):e}function GO(e,t){return HO(e)?t.some(e=>yO.some(t=>e.byLayer[t].length>0))?`evidence`:`unverified`:`any`}function KO(){let e=c();return t=>t?Qx(t,e):e(`compatProtocol.anyProtocol`)}function qO({value:e,onChange:t}){let n=c(),r=KO(),i=[{value:``,label:n(`lab.filter.all`)},...Yb.map(e=>({value:e,label:r(e)}))];return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`lab-filter-inbound`,children:n(`compatProtocol.filter.inbound`)}),(0,Z.jsx)($,{id:`lab-filter-inbound`,value:e.inbound,options:i,onChange:n=>t({...e,inbound:n}),label:n(`compatProtocol.filter.inbound`),portal:!1})]}),(0,Z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`lab-filter-upstream`,children:n(`compatProtocol.filter.upstream`)}),(0,Z.jsx)($,{id:`lab-filter-upstream`,value:e.upstream,options:i,onChange:n=>t({...e,upstream:n}),label:n(`compatProtocol.filter.upstream`),portal:!1})]})]})}function JO({filter:e,evidence:t,resolution:n}){let r=c(),i=KO();if(!HO(e))return null;let a=r(`compatProtocol.pair`,{inbound:i(e.inbound),upstream:i(e.upstream)});return(0,Z.jsxs)(`div`,{className:`lab-protocol-status`,"data-pair-evidence":n.loading?`loading`:t,children:[n.loading?(0,Z.jsx)(`p`,{className:`muted small`,role:`status`,children:r(`compatProtocol.loading`)}):t===`unverified`?(0,Z.jsx)(`p`,{className:`lab-protocol-unverified`,role:`status`,children:r(`compatProtocol.unverified`,{pair:a})}):null,n.unresolved>0&&!n.loading&&(0,Z.jsx)(`p`,{className:`muted small`,children:r(`compatProtocol.unresolved`,{count:n.unresolved})}),(0,Z.jsx)(`p`,{className:`muted small`,children:r(`compatProtocol.axisNote`)})]})}var YO=50,XO=200,ZO=6,QO=200;async function $O(e,t,n){return zn(await fetch(`${e}${t}`,{signal:n}))}function ek(e,t){let n=new URLSearchParams({limit:String(YO)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var tk=class extends Error{};function nk(){return new tk}function rk(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw nk()}function ik(e){if(!SO(e)||!Array.isArray(e.verdicts))throw nk();let t=OO(e);if(t.verdicts.length!==e.verdicts.length)throw nk();return rk(e,t.hasMore,t.nextCursor),t}function ak(e){if(!SO(e)||!Array.isArray(e.subjects))throw nk();let t=kO(e);if(t.subjects.length!==e.subjects.length)throw nk();return rk(e,t.hasMore,t.nextCursor),t}function ok(e){if(!SO(e)||!Array.isArray(e.observations))throw nk();let t=MO(e);if(t.observations.length!==e.observations.length)throw nk();return rk(e,t.hasMore,t.nextCursor),t}async function sk(e,t){let n=EO(await $O(e,`/api/lab/status`,t));if(!n)throw nk();return n}async function ck(e,t,n,r){return ik(await $O(e,`/api/lab/verdicts?${ek({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function lk(e,t,n){return ak(await $O(e,`/api/lab/subjects?${ek({},t)}`,n))}async function uk(e){let t=[],n=new Set,r;for(let i=0;i<XO;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 tk;n.add(a),r=a}return{rows:t,truncated:!0}}async function dk(e,t){return uk(async n=>{let r=await lk(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function fk(e,t,n){let r=AO(await $O(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw nk();return r}async function pk(e,t,n,r){return ok(await $O(e,`/api/lab/observations?${ek({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function mk(e,t,n){return uk(async r=>{let i=await pk(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function hk(e,t,n){let r=NO(await $O(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw nk();return r}async function gk(e,t,n){let r=PO(await $O(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw nk();return r}function _k(e){if(!SO(e)||e.verificationStatus!==`not_verification`||!SO(e.summary))throw nk();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 nk();return{verificationStatus:`not_verification`,summary:t}}async function vk(e,t,n){return _k(await $O(e,`/api/lab/production-signals?${ek({subjectId:t})}`,n))}function yk(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function bk(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function xk(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Sk(e){if(!SO(e)||!yk(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(!SO(n)||!yk(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!bk(n.bundleId)||!bk(n.publisherKeyId)||!xk(n.activeRecordCount)||!xk(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 Ck(e,t){let n=Sk(await $O(e,`/api/lab/public/community`,t));if(!n)throw nk();return n}async function wk(e,t,n){let[r,i]=await Promise.all([sk(e,n),Ck(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([ck(e,t,void 0,n),dk(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function Tk(e,t,n,r){return ck(e,t,n,r)}async function Ek(e,t,n,r){let i=e.slice(0,QO),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 Dk(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=BO(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([fk(e,t.subjectId,n),mk(e,a,n),Ek(r,ZO,n,t=>hk(e,t,n)),Ek(i,ZO,n,t=>gk(e,t,n)),vk(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 Ok=6,kk=2e3,Ak=`
|
|
8
|
+
`,jk=new Map;function Mk(e,t){return JSON.stringify([e,t])}function Nk(e,t){for(jk.set(e,t);jk.size>kk;){let e=jk.keys().next().value;if(e===void 0)break;jk.delete(e)}}var Pk={pairs:new Map,loading:!1,unresolved:0};function Fk(e,t,n){let[,r]=(0,X.useState)(0),i=n?t.slice(0,200):[],a=i.filter(t=>!jk.has(Mk(e,t))).join(Ak);if((0,X.useEffect)(()=>{if(!a)return;let t=new AbortController,n=a.split(Ak);return Promise.all(Array.from({length:Math.min(Ok,n.length)},async()=>{for(let r=n.shift();r!==void 0;r=n.shift())try{let n=await fk(e,r,t.signal);Nk(Mk(e,r),VO(n))}catch{if(t.signal.aborted)return;Nk(Mk(e,r),null)}})).then(()=>{t.signal.aborted||r(e=>e+1)}),()=>t.abort()},[e,a]),!n)return Pk;let o=new Map,s=Math.max(0,t.length-200);for(let t of i){let n=jk.get(Mk(e,t));n?o.set(t,n):n===null&&(s+=1)}return{pairs:o,loading:a.length>0,unresolved:s}}var Ik={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},Lk={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},Rk={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`},zk={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function Bk(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 Vk({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,Z.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,Z.jsx)(`span`,{children:n}),(0,Z.jsx)(`span`,{className:`suite`,children:t})]}):(0,Z.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,Z.jsx)(`span`,{children:n}),(0,Z.jsx)(`span`,{className:`suite`,children:t})]})}function Hk({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,Z.jsx)(`span`,{className:`muted`,children:`-`}):(0,Z.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,Z.jsx)(Vk,{verdict:e.verdict,caption:e.suiteId,label:t(Rk[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function Uk({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:zO(r.builtAtMs,n)}),(0,Z.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,Z.jsxs)(`div`,{className:`lab-status-card`,children:[(0,Z.jsx)(`span`,{className:`label`,children:e.label}),(0,Z.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function Wk({community:e,locale:n}){if(!e||e.evidence.length===0)return null;let r=e.evidence.reduce((e,t)=>e+t.activeRecordCount,0),i=e.evidence.reduce((e,t)=>e+t.revokedRecordCount,0);return(0,Z.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,Z.jsx)(`h3`,{className:`lab-matrix-title`,children:t(n,`community.title`)}),(0,Z.jsx)(`p`,{className:`muted`,children:t(n,`community.notLocalVerdict`)}),(0,Z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:t(n,`community.bundles`)}),(0,Z.jsx)(`dd`,{children:e.evidence.length})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:t(n,`community.activeRecords`)}),(0,Z.jsx)(`dd`,{children:r})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:t(n,`community.revokedRecords`)}),(0,Z.jsx)(`dd`,{children:i})]})]})]})}function Gk({verdict:e,detail:n,loading:r,error:i,t:a,locale:o,onClose:s}){let c=new Set([...e.contributingEventIds,...e.contradictingEventIds]).size;return(0,Z.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":a(`lab.detailTitle`),children:[(0,Z.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,Z.jsx)(`h3`,{children:RO(e.subjectId)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:a(`lab.detailClose`)})]}),(0,Z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.col.layer`)}),(0,Z.jsx)(`dd`,{children:a(Ik[e.evidenceLayer])})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.col.suite`)}),(0,Z.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.col.verdict`)}),(0,Z.jsx)(`dd`,{children:a(Rk[e.verdict])})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.col.asOf`)}),(0,Z.jsx)(`dd`,{children:zO(e.asOf,o)})]})]}),r&&(0,Z.jsx)(PE,{busy:!0,children:a(`common.loading`)}),i&&(0,Z.jsx)(Q,{tone:`err`,children:i}),n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Z.jsx)(`h4`,{children:a(`lab.detailSubject`)}),(0,Z.jsx)(`p`,{className:`mono`,children:n.subject.subjectKind})]}),n.production&&(0,Z.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,Z.jsx)(`h4`,{children:a(`lab.production.title`)}),(0,Z.jsx)(`p`,{className:`muted`,children:a(`lab.production.notVerification`)}),(0,Z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.production.attempts`)}),(0,Z.jsx)(`dd`,{children:n.production.summary.recentProductionAttempts})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.production.successes`)}),(0,Z.jsx)(`dd`,{children:n.production.summary.recentSuccessfulAttempts})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.production.routeErrors`)}),(0,Z.jsx)(`dd`,{children:n.production.summary.recentRouteErrorSignals})]}),n.production.summary.lastObservedProductionAttempt!==void 0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:a(`lab.production.lastObserved`)}),(0,Z.jsx)(`dd`,{children:zO(n.production.summary.lastObservedProductionAttempt,o)})]})]})]}),n.observations.length>0&&(0,Z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Z.jsx)(`h4`,{children:a(`lab.detailObservations`)}),(0,Z.jsx)(`ul`,{className:`lab-detail-list`,children:n.observations.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,Z.jsx)(`span`,{children:e.outcome}),(0,Z.jsx)(`span`,{className:`muted`,children:zO(e.completedAt,o)})]},e.eventId))})]}),(n.events.length>0||c>0)&&(0,Z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Z.jsxs)(`h4`,{children:[a(`lab.detailEvents`),n.events.length<c?` (${n.events.length}/${c})`:``]}),(0,Z.jsx)(`ul`,{className:`lab-detail-list`,children:n.events.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,Z.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),n.artifacts.length>0&&(0,Z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Z.jsx)(`h4`,{children:a(`lab.detailArtifacts`)}),(0,Z.jsx)(`ul`,{className:`lab-detail-list`,children:n.artifacts.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{className:`mono`,title:e.digest,children:RO(e.digest)}),(0,Z.jsx)(`span`,{children:e.artifactClass??`-`}),(0,Z.jsx)(`span`,{children:t(o,zk[e.status])})]},e.digest))})]})]})]})}function Kk({apiBase:e,active:n=!0,onCountChange:r}){let{t:i,locale:o}=a(),[s,c]=(0,X.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[l,u]=(0,X.useState)(()=>NC()??kC),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(null),T=(0,X.useRef)(null),E=(0,X.useRef)(null),D=(0,X.useRef)(null),O=(0,X.useMemo)(()=>FO(s),[s]),k=JSON.stringify(O),A=(0,X.useCallback)(t=>wk(e,O,t),[e,O]),j=Fd(`lab-matrix:${e}:${k}`,[e,k],A,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:n,pauseWhenHidden:!0}),M=(0,X.useCallback)(()=>{T.current?.abort(),T.current=null,f(null),m(null),g(!1)},[]),N=(0,X.useCallback)(()=>{D.current=null,E.current?.abort(),E.current=null,v(null),b(null),w(null),S(!1)},[]);(0,X.useEffect)(()=>{T.current?.abort()},[j.data]),(0,X.useEffect)(()=>()=>{T.current?.abort(),E.current?.abort()},[]);let P=(0,X.useCallback)(e=>{N(),M(),c(e)},[N,M]),F=(0,X.useCallback)(e=>{N(),u(e),n&&gn(jC(e))},[n,N]);(0,X.useEffect)(()=>{let e=()=>{let e=NC();e&&u(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 I=d!==null&&d.baseData===j.data&&d.queryKey===k?d:null,L=p!==null&&p.baseData===j.data&&p.queryKey===k?p.message:null,R=(0,X.useMemo)(()=>{if(!n||!j.data?.status.projectionAvailable)return null;let e=j.data.status.verdictCount;return typeof e==`number`?e:j.data.verdicts.length+(I?.verdicts.length??0)},[n,j.data,I]);(0,X.useEffect)(()=>{r?.(R)},[r,R]);let z=(0,X.useMemo)(()=>j.data?[...j.data.verdicts,...I?.verdicts??[]]:[],[j.data,I]),B=(0,X.useMemo)(()=>j.data?LO(z,j.data.subjects):[],[z,j.data]),V=HO(l),H=Fk(e,(0,X.useMemo)(()=>B.map(e=>e.subjectId),[B]),n&&V),U=(0,X.useMemo)(()=>WO(B,H.pairs,l),[l,H.pairs,B]),W=(0,X.useMemo)(()=>{if(!V)return z;let e=new Set(U.map(e=>e.subjectId));return z.filter(t=>e.has(t.subjectId))},[z,U,V]),ee=GO(l,U),te=(0,X.useCallback)(async()=>{let t=I?.nextCursor??j.data?.nextCursor,n=j.data;if(!t||!n||h)return;T.current?.abort();let r=new AbortController;T.current=r;let a=k;m(null),g(!0);try{let i=await Tk(e,O,t,r.signal);if(r.signal.aborted)return;f(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...i.verdicts],nextCursor:i.nextCursor,hasMore:i.hasMore}})}catch(e){r.signal.aborted||m({baseData:n,queryKey:a,message:Bk(e,i(`lab.loadFailed`))})}finally{T.current===r&&(T.current=null,g(!1))}},[e,h,O,k,j.data,i,I]),ne=(0,X.useCallback)(async t=>{if(!n)return;E.current?.abort();let r=new AbortController;E.current=r,D.current=t.projectionKey,v(t),b(null),w(null),S(!0);try{let n=await Dk(e,t,r.signal);!r.signal.aborted&&D.current===t.projectionKey&&b(n)}catch(e){!r.signal.aborted&&D.current===t.projectionKey&&w(Bk(e,i(`lab.detailLoadFailed`)))}finally{E.current===r&&(E.current=null,!r.signal.aborted&&D.current===t.projectionKey&&S(!1))}},[n,e,i]),G=j.refresh,K=(0,X.useCallback)(()=>{N(),M(),G({forceLoading:!0})},[N,G,M]),re=n?_:null,q=I?I.hasMore:j.data?.hasMore??!1,ie=[{value:``,label:i(`lab.filter.all`)},...yO.map(e=>({value:e,label:i(Ik[e])}))],ae=[{value:``,label:i(`lab.filter.all`)},...bO.map(e=>({value:e,label:i(Rk[e])}))],oe=[{value:``,label:i(`lab.filter.all`)},...(j.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${RO(e.subjectId)} · ${e.subjectKind}`}))];if(j.state.showSkeleton)return(0,Z.jsx)(NE,{label:i(`lab.loading`),rows:5});let se=j.state.showError?Bk(j.error,i(`lab.loadFailed`)):null,ce=j.data?.status,le=ce&&!ce.projectionAvailable,ue=ce?.projectionIncompatible===!0;return(0,Z.jsxs)(`div`,{className:`lab-page`,children:[(0,Z.jsx)(`div`,{className:`lab-toolbar`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:K,disabled:j.refreshing,children:[(0,Z.jsx)(Mt,{}),i(`lab.refresh`)]})}),j.refreshing&&!j.state.showSkeleton&&(0,Z.jsx)(PE,{busy:!0,live:!se,children:i(`common.loading`)}),se&&(0,Z.jsx)(Q,{tone:`err`,children:se}),ue&&(0,Z.jsx)(Q,{tone:`err`,children:i(`lab.projectionIncompatible`)}),le&&!ue&&(0,Z.jsx)(Nn,{title:i(`lab.projectionUnavailable`)}),le&&!ue&&(0,Z.jsx)(JO,{filter:l,evidence:`unverified`,resolution:{loading:!1,unresolved:0}}),j.data&&(0,Z.jsx)(Wk,{community:j.data.community,locale:o}),j.data&&ce?.projectionAvailable&&!ue&&(0,Z.jsxs)(`div`,{className:`lab-layout`,children:[(0,Z.jsxs)(`div`,{className:`lab-main`,children:[(0,Z.jsx)(Uk,{data:j.data,t:i,locale:o}),(0,Z.jsxs)(`div`,{className:`lab-filters`,children:[(0,Z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:i(`lab.filter.layer`)}),(0,Z.jsx)($,{id:`lab-filter-layer`,value:s.layer,options:ie,onChange:e=>P(t=>({...t,layer:e})),label:i(`lab.filter.layer`),portal:!1})]}),(0,Z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:i(`lab.filter.verdict`)}),(0,Z.jsx)($,{id:`lab-filter-verdict`,value:s.verdict,options:ae,onChange:e=>P(t=>({...t,verdict:e})),label:i(`lab.filter.verdict`),portal:!1})]}),(0,Z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Z.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:i(`lab.filter.subject`)}),(0,Z.jsx)($,{id:`lab-filter-subject`,value:s.subjectQuery,options:oe,onChange:e=>P(t=>({...t,subjectQuery:e})),label:i(`lab.filter.subject`),portal:!1})]}),(0,Z.jsx)(qO,{value:l,onChange:F})]}),(0,Z.jsx)(JO,{filter:l,evidence:ee,resolution:H}),U.length===0?(0,Z.jsx)(Nn,{title:i(`lab.empty`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Z.jsx)(`h3`,{className:`lab-matrix-title`,children:i(`lab.matrixTitle`)}),(0,Z.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Z.jsxs)(`table`,{className:`lab-matrix`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:i(`lab.col.subject`)}),(0,Z.jsx)(`th`,{children:i(`lab.subjectKind`)}),yO.map(e=>(0,Z.jsx)(`th`,{children:i(Lk[e])},e))]})}),(0,Z.jsx)(`tbody`,{children:U.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`subject`,title:e.subjectId,children:RO(e.subjectId)}),(0,Z.jsx)(`td`,{className:`kind`,children:e.subjectKind||t(o,`subjectKindUnknown`)}),yO.map(t=>(0,Z.jsx)(`td`,{children:(0,Z.jsx)(Hk,{rows:e.byLayer[t],t:i,selectedKey:re?.projectionKey??null,onSelect:e=>{ne(e)}})},t))]},e.subjectId))})]})})]}),(0,Z.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Z.jsx)(`h3`,{className:`lab-matrix-title`,children:i(`lab.verdictsTitle`)}),(0,Z.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Z.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:i(`lab.col.subject`)}),(0,Z.jsx)(`th`,{children:i(`lab.col.layer`)}),(0,Z.jsx)(`th`,{children:i(`lab.col.suite`)}),(0,Z.jsx)(`th`,{children:i(`lab.col.verdict`)}),(0,Z.jsx)(`th`,{children:i(`lab.col.asOf`)})]})}),(0,Z.jsx)(`tbody`,{children:W.map(e=>{let n=re?.projectionKey===e.projectionKey;return(0,Z.jsxs)(`tr`,{className:n?`selected`:``,children:[(0,Z.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":n,"aria-label":t(o,`selectVerdict`,{subject:RO(e.subjectId)}),onClick:()=>{ne(e)},children:RO(e.subjectId)})}),(0,Z.jsx)(`td`,{children:i(Ik[e.evidenceLayer])}),(0,Z.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(Vk,{verdict:e.verdict,caption:e.suiteId,label:i(Rk[e.verdict])})}),(0,Z.jsx)(`td`,{children:zO(e.asOf,o)})]},e.projectionKey)})})]})})]}),L&&(0,Z.jsx)(Q,{tone:`err`,children:L}),q&&(0,Z.jsx)(`div`,{className:`lab-load-more`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:h,onClick:()=>{te()},children:i(h?`common.loading`:`lab.loadMore`)})})]})]}),re&&(0,Z.jsx)(Gk,{verdict:re,detail:y,loading:x,error:C,t:i,locale:o,onClose:N})]})]})}var qk=[`catalog`,`combos`,`routing`,`compatibility`];function Jk(e){return e===`catalog`?`models`:`models/${e}`}function Yk(e=window.location.hash){let t=hn(mn(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 Xk(e){_n(Jk(e))}function Zk(e){return`models-tab-${e}`}function Qk(e){return`models-panel-${e}`}var $k={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function eA({tab:e,onSelect:t,meta:n}){let r=c(),i=(0,X.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=qk.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+qk.length)%qk.length:t.key===`ArrowRight`?r=(n+1)%qk.length:t.key===`Home`?r=0:t.key===`End`&&(r=qk.length-1),r!==null&&(t.preventDefault(),a(qk[r]))};return(0,Z.jsx)(`div`,{className:`page-tabs models-page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:qk.map(t=>{let s=t===e,c=n?.[t];return(0,Z.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:Zk(t),"aria-selected":s,"aria-controls":Qk(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r($k[t]),c?(0,Z.jsx)(`span`,{className:`section-tab-meta tabular-nums`,children:c}):null]},t)})})}function tA({summary:e,apiBase:t,onSaved:n}){let r=c(),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),l=e?.fastOptIn?.enabled;if(o&&l!==o.from&&s(null),!e?.fastOptIn)return null;let u=e.fastOptIn.enabled,d=o&&o.from===u?o.value:u,f=async o=>{if(!(i||o===d)){a(!0);try{await zn(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:u}),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,Z.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:r(`models.fastProvider`)}),(0,Z.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":r(`models.fastProvider`),children:[!1,!0].map(e=>(0,Z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===e,className:`btn btn-sm${d===e?` btn-primary`:` btn-ghost`}`,disabled:i,onClick:()=>void f(e),children:r(e?`models.newPolicy_on`:`models.newPolicy_off`)},String(e)))}),(0,Z.jsx)(`span`,{className:`muted text-caption`,children:r(`models.fastProviderHint`)})]})}function nA(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 rA({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=c(),i=e&&t?.status===`failed`?t:void 0;return(0,Z.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Z.jsx)(q,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Z.jsxs)(`span`,{children:[i&&n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${Tf(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>_n(`providers`),children:r(`models.openProviderSettings`)})]})]})}function iA(){let e=c();return(0,Z.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Z.jsx)(q,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Z.jsxs)(`span`,{children:[`${e(`models.discoveryFailedDependency`,{control:e(`pws.liveModels`)})} `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>_n(`providers`),children:e(`models.openProviderSettings`)})]})]})}var aA=`ocx.models.settingsOpen.v1`;function oA(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function sA(e){try{return oA(e)?.getItem(aA)===`1`}catch{return!1}}function cA(e,t){try{oA(t)?.setItem(aA,e?`1`:`0`)}catch{}}var lA={default:`models.pickerOrder.default`,alphabetical:`models.pickerOrder.alphabetical`,provider:`models.pickerOrder.provider`,"most-used":`models.pickerOrder.mostUsed`,custom:`models.pickerOrder.custom`};function uA(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?Uf(t.windowValue):n});let i=lA[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 dA({title:e,attentionLabel:t,summary:n,warn:r,children:i,storage:a}){let[o,s]=(0,X.useState)(()=>sA(a)),[c,l]=(0,X.useState)(!1),u=o||r&&!c;return(0,Z.jsxs)(`details`,{className:`models-settings`,open:u,onToggle:e=>{let t=e.currentTarget.open;t!==u&&(s(t),!t&&r&&l(!0),cA(t,a))},children:[(0,Z.jsxs)(`summary`,{className:`models-settings-summary`,children:[(0,Z.jsx)(`span`,{className:`models-settings-title`,children:e}),r&&(0,Z.jsx)(`span`,{className:`models-settings-warn`,role:`img`,"aria-label":t,title:t}),(0,Z.jsx)(`span`,{className:`models-settings-state`,children:n.map(e=>(0,Z.jsxs)(`span`,{className:`models-settings-kv`,"data-item":e.id,children:[(0,Z.jsx)(`span`,{className:`models-settings-k`,children:e.label}),e.value&&(0,Z.jsx)(`span`,{className:`models-settings-v`,children:e.value})]},e.id))})]}),(0,Z.jsx)(`div`,{className:`models-settings-body`,children:i})]})}function fA({count:e,label:t}){return e===0?null:(0,Z.jsx)(`span`,{className:`models-chip mono text-caption models-custom-summary`,children:t})}function pA({text:e}){return(0,Z.jsx)(Pn,{content:e,side:`top`,maxWidth:360,children:(0,Z.jsxs)(`span`,{className:`models-info-hint`,children:[(0,Z.jsx)(q,{width:14,height:14,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:e})]})})}function mA({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,Z.jsxs)(`div`,{className:`models-control-row`,"aria-busy":n||void 0,children:[(0,Z.jsxs)(`span`,{className:o,children:[e,t?(0,Z.jsxs)(Z.Fragment,{children:[` `,t]}):null]}),(0,Z.jsx)(`div`,{className:`models-row-actions`,children:a})]})}function hA({shadowCall:e,saving:t,modelOptions:n,onSave:r}){let i=c(),a=i(`models.shadowCallInterceptHint`,{models:Un(e?.sourceModels)});return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(mA,{label:i(`models.shadowCallIntercept`),hint:(0,Z.jsx)(Pn,{content:a,side:`top`,maxWidth:320,children:(0,Z.jsx)(`span`,{style:{cursor:`help`},"aria-label":a,children:(0,Z.jsx)(q,{width:13,height:13,"aria-hidden":`true`})})}),busy:!e,children:[(0,Z.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:i(`models.shadowCallOriginal`,{models:qn(e?.sourceModels,i(`shadowCall.memoryLabel`))})}),(0,Z.jsx)(kn,{on:e?.enabled??!1,onClick:()=>r({enabled:!e?.enabled}),disabled:!e||t,label:i(`models.shadowCallIntercept`)}),(0,Z.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Z.jsx)($,{value:e?.model??``,options:n,onChange:e=>r({model:e}),disabled:!e||t||!e.enabled,label:i(`models.shadowCallIntercept`)})})]}),(0,Z.jsx)(pd,{className:`models-shadow-sources`,options:e?.sourceModelOptions,sourceModels:e?.sourceModels,disabled:!e?.enabled,saving:t,onChange:e=>r({sourceModels:e})})]})}function gA(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 _A({connected:e,catalogSyncedAt:t}){let{locale:n,t:r}=a(),i=gA(t,n),o=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 o.push({id:`loaded`,chip:r(`models.delivery.chip.loaded`),title:r(`models.delivery.loaded.title`),body:r(`models.delivery.loaded.body`)}),(0,Z.jsxs)(`details`,{className:`models-delivery`,children:[(0,Z.jsxs)(`summary`,{children:[(0,Z.jsx)(`span`,{className:`models-delivery-title`,children:r(`models.delivery.title`)}),(0,Z.jsx)(`span`,{className:`models-delivery-flow`,children:o.map(e=>e.chip).join(` → `)})]}),(0,Z.jsx)(`ol`,{className:`models-delivery-steps`,children:o.map(e=>(0,Z.jsxs)(`li`,{"data-step":e.id,children:[(0,Z.jsx)(`strong`,{children:e.title}),(0,Z.jsx)(`p`,{children:e.body})]},e.id))}),(0,Z.jsx)(`p`,{className:`models-delivery-hint`,children:r(`models.delivery.hint`)})]})}function vA(t,n,r){let[i,a]=(0,X.useState)({apiBase:t,data:null,saving:!1}),o=i.apiBase===t?i.data:null,s=i.apiBase===t&&i.saving,c=(0,X.useRef)({read:null,write:null,generation:0,apiBase:t});(0,X.useLayoutEffect)(()=>{let e=c.current;return e.apiBase=t,e.generation++,()=>{e.generation++,e.read?.controller.abort(),e.read?.clear(),e.read=null,e.write?.controller.abort(),e.write?.clear(),e.write=null}},[t]);let l=(0,X.useCallback)(async({reconcile:n=!1}={})=>{let r=c.current;if(r.write&&!n)return null;r.read?.controller.abort(),r.read?.clear();let i=e(15e3),o=r.generation;r.read=i;try{let e=await Bn(await fetch(`${t}/api/auto-review-settings`,{signal:i.signal}));return!e||typeof e.enabled!=`boolean`||typeof e.model!=`string`?null:!i.signal.aborted&&r.apiBase===t&&r.generation===o&&r.read===i&&(!r.write||n)?(a({apiBase:t,data:e,saving:r.write!==null}),e):null}catch{return null}finally{i.clear(),r.read===i&&(r.read=null)}},[t]);return{data:o,saving:s,load:l,save:(0,X.useCallback)(async i=>{let u=c.current;if(!o||s||u.apiBase!==t||u.write)return;let d=o,f=e(15e3);u.write=f;let p=++u.generation;u.read?.controller.abort(),u.read?.clear(),u.read=null,a({apiBase:t,data:{...d,...i},saving:!0});try{let e=await zn(await fetch(`${t}/api/auto-review-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:f.signal,body:JSON.stringify(i)}),n(`models.saveFailed`));if(!e||e.ok!==!0||typeof e.enabled!=`boolean`||typeof e.model!=`string`)throw Error(n(`models.saveFailed`));if(u.apiBase!==t||u.generation!==p)return;a({apiBase:t,data:{enabled:e.enabled,model:e.model},saving:!0}),(!e.catalogRefresh||e.catalogRefresh.status!==`committed`)&&r(!1,n(`codexAuth.catalogRefreshPending`))}catch(e){if(u.apiBase===t&&u.generation===p){let i=await l({reconcile:!0});if(u.apiBase!==t||u.generation!==p)return;a({apiBase:t,data:i??d,saving:!0}),r(!1,e instanceof Error&&e.message?e.message:n(`models.saveFailed`))}}finally{f.clear(),u.write===f&&(u.write=null),u.apiBase===t&&u.generation===p&&a(e=>e.apiBase===t?{...e,saving:!1}:e)}},[t,o,s,n,r,l])}}function yA({apiBase:t,publishFeedback:n,t:r}){let[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!1);return{shadowCall:i,shadowCallSaving:o,loadShadowCall:(0,X.useCallback)(async()=>{let n=e(15e3);try{let e=await Bn(await fetch(`${t}/api/shadow-call-settings`,{signal:n.signal}));e&&a(e)}catch{}finally{n.clear()}},[t]),saveShadowCall:async e=>{if(!i||o)return;let c=i;s(!0),a({...i,...e});try{let i=await fetch(`${t}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!i.ok){a(c),n(!1,r(Mf((await i.json().catch(()=>null))?.code)));return}let o=await i.json().catch(()=>null);o&&typeof o.enabled==`boolean`&&a(o)}catch{a(c),n(!1,r(`models.networkError`))}finally{s(!1)}}}}function bA({text:e,children:t}){let n=c(),[r,i]=(0,X.useState)(!1),a=(0,X.useId)(),o=(0,X.useRef)(null),s=(0,X.useRef)(null);return(0,X.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,Z.jsxs)(`div`,{ref:o,className:`ui-v2 relative`,children:[(0,Z.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:Y(`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,Z.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,Z.jsxs)(`div`,{id:a,role:`region`,"aria-label":n(`modelsV2.about`),hidden:!r,className:Y(`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,Z.jsx)(`p`,{className:`m-0`,children:e}),t]})]})}function xA({name:e,className:t}){let n=xt(e),r=$e(n);return(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`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,Z.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,Z.jsx)(`img`,{src:n,alt:``,className:`block size-3.5 object-contain`}):(0,Z.jsx)(`span`,{className:`text-[11px] leading-none font-semibold uppercase`,children:e.slice(0,1)})})}function SA({items:e,all:t,selected:n,onSelect:r}){let i=c();return(0,Z.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":i(`nav.models`),children:[(0,Z.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,Z.jsx)(`span`,{className:`models-workspace-rail-title`,children:i(`models.workspace.providers`)}),(0,Z.jsx)(`span`,{className:`models-workspace-rail-count`,children:e.length})]}),(0,Z.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,Z.jsx)(CA,{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,Z.jsx)(CA,{provider:e.provider,label:Ge(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 CA({provider:e,label:t,meta:n,ratio:r,current:i,onClick:a}){return(0,Z.jsxs)(`button`,{type:`button`,className:Y(`models-workspace-rail-row`,i&&`models-workspace-rail-row--selected`),onClick:a,"aria-current":i?`true`:void 0,children:[e?(0,Z.jsx)(xA,{name:e}):(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`models-rail-all-mark`}),(0,Z.jsx)(`span`,{className:`models-workspace-rail-name`,children:t}),(0,Z.jsx)(`span`,{className:`models-workspace-rail-meta`,children:n}),(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`models-rail-meter`,children:(0,Z.jsx)(`span`,{style:{width:`${Math.round(r*100)}%`}})})]})}var wA={catalog:[`modelsV2.ledeCatalog`,`models.subtitle`],combos:[`modelsV2.ledeCombos`,`models.subtitle.combos`],routing:[`models.subtitle.routing`],compatibility:[`models.subtitle.compatibility`]};function TA({apiBase:t,restartEpoch:n=0,connected:r=!1,catalogSyncedAt:i,reportRestart:a}){let[o,s]=(0,X.useState)(null),l=(0,X.useRef)(!0);(0,X.useEffect)(()=>(l.current=!0,()=>{l.current=!1}),[]);let u=(0,X.useRef)(null),d=(0,X.useRef)(0),f=(0,X.useRef)(t),p=(0,X.useCallback)(()=>{d.current++,u.current?.controller.abort(),u.current?.clear(),u.current=null},[]),m=(0,X.useCallback)(async()=>{if(!l.current||f.current!==t)return;p();let n=d.current,r=e(15e3);u.current=r;try{let e=await Zw(t,{signal:r.signal});if(r.signal.aborted||!l.current||f.current!==t||n!==d.current||u.current!==r)return;s(e.state)}finally{r.clear(),u.current===r&&(u.current=null)}},[t,p]),{restarting:h,restart:g}=nT(t,{onSettled:()=>{m()},report:a});(0,X.useEffect)(()=>(f.current=t,s(null),m(),p),[t,p,m,n]);let[_,v]=(0,X.useState)(Yk),[y,b]=(0,X.useState)(()=>new Set([Yk()])),x=(0,X.useCallback)(e=>{v(e),b(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,X.useEffect)(()=>{let e=()=>x(Yk());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[x]);let S=(0,X.useCallback)(e=>{Xk(e),x(e)},[x]),C=_===`catalog`,[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(null),A=c(),j=`ocx.models.catalog.v1:${t}`,M=(0,X.useMemo)(()=>kd(j),[j]),[N,P]=(0,X.useState)(()=>M?.models??[]),[F,I]=(0,X.useState)(()=>M?.providers??[]),[L,R]=(0,X.useState)(()=>new Set(M?.disabled??[])),[z,B]=(0,X.useState)(()=>M?.selectedModels??null),[V,H]=(0,X.useState)({}),[U,W]=(0,X.useState)({}),[te,ne]=(0,X.useState)({}),[G,K]=(0,X.useState)(()=>M?.contextCaps??{}),[re,ie]=(0,X.useState)(()=>M?.contextCapValues??{}),[ae,oe]=(0,X.useState)(()=>M?.contextCapValue??35e4),se=`${j}:picker-order`,ce=(0,X.useMemo)(()=>{let e=kd(se);return YC(e)?e:void 0},[se]),[le,ue]=(0,X.useState)(null),[J,de]=(0,X.useState)(!1),fe=(0,X.useRef)(null),pe=(0,X.useRef)(0),me=Fd(se,[t],(0,X.useCallback)(async e=>{let n=await zn(await fetch(`${t}/api/subagent-models`,{signal:e}));if(!YC(n))throw Error(`picker settings payload missing`);if(e.aborted)throw Error(`picker settings request aborted`);return Nd(se,n),n},[t,se]),{isEmpty:()=>!1,enabled:C,deadlineMs:15e3,initialData:ce}),he=me.state.data,ge=le??tw(he?.pickerAvailable??[],he?.pickerOrder??[],he?.pickerOrderMode);(0,X.useLayoutEffect)(()=>(pe.current++,ue(null),de(!1),()=>{pe.current++,fe.current?.controller.abort(),fe.current?.clear(),fe.current=null}),[t,C]),(0,X.useLayoutEffect)(()=>{C&&le===null&&ge===`custom`&&ue(`custom`)},[C,le,ge]);let[_e,ve]=(0,X.useState)(``),[ye,be]=(0,X.useState)(!1),[xe,Se]=(0,X.useState)({}),[Ce,we]=(0,X.useState)({}),Te=qf(),[Ee,De]=(0,X.useState)(()=>Te??new Set),ke=(0,X.useRef)(Te===null),[Ae,je]=(0,X.useState)(``),[Me,Ne]=(0,X.useState)([]),[Pe,Fe]=(0,X.useState)(!1),[Ie,Le]=(0,X.useState)(0),Re=(0,X.useCallback)((e,t)=>{Fe(e),je(t),Le(e=>e+1)},[]),{data:ze,saving:Be,load:Ve,save:He}=vA(t,A,Re);(0,X.useEffect)(()=>{C||Ve()},[t,C,Ve]),(0,X.useEffect)(()=>{if(!Ae)return;let e=setTimeout(()=>je(``),Pe?6e3:8e3);return()=>clearTimeout(e)},[Ae,Pe,Ie]);let[Ue,We]=(0,X.useState)(!1),Ke=(0,X.useRef)(!1),qe=(0,X.useRef)(!1),Je=(0,X.useRef)(0),Ye=(0,X.useRef)(!1),Xe=jE(t,{onQueued:()=>{++Je.current,je(``)},onBusy:e=>{++Je.current,Ye.current=!1,qe.current=e,Ke.current=e,We(e)},onResponse:e=>{let t=gf(e);t!==void 0&&Ne(t)},refresh:e=>_r(!0,e),onSettled:e=>{Fe(!e),je(A(e??`models.applied`))}}),Qe=(e,t,n,r,i)=>Xe.visible(t,n,r,Sf(e,t,n,r,i)),[$e,et]=(0,X.useState)(null),[tt,nt]=(0,X.useState)({}),[rt,it]=(0,X.useState)(null),[ot,st]=(0,X.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[ct,lt]=(0,X.useState)(!1),[dt,ft]=(0,X.useState)(null),[Y,pt]=(0,X.useState)(!0),[mt,ht]=(0,X.useState)(!1),[gt,_t]=(0,X.useState)(``),vt=(0,X.useRef)(!1),yt=(0,X.useRef)(0),bt=(0,X.useRef)(0),[xt,Ct]=(0,X.useState)(``),[wt,Tt]=(0,X.useState)(!1),[Et,Dt]=(0,X.useState)(!1),[Ot,kt]=(0,X.useState)(null),[At,jt]=(0,X.useState)(!1),[Nt,Pt]=(0,X.useState)(null),[Ft,It]=(0,X.useState)(null),Lt=(0,X.useRef)(null),[Rt,zt]=(0,X.useState)(null),[Bt,Vt]=(0,X.useState)(!1),[Ht,Ut]=(0,X.useState)(null),[Wt,Gt]=(0,X.useState)(null),[Kt,qt]=(0,X.useState)(!1),Jt=(0,X.useRef)(null),Yt=(0,X.useRef)(!1);(0,X.useEffect)(()=>()=>{Jt.current?.controller.abort(),Jt.current?.clear(),Jt.current=null},[]);let Xt=(0,X.useRef)(null),Zt=(0,X.useCallback)(async e=>{let n=await Bn(await fetch(`${t}/api/aliases`,{signal:e}));n&&!e?.aborted&&st(n)},[t]);(0,X.useEffect)(()=>{let e=new AbortController;return Zt(e.signal),()=>e.abort()},[Zt]);let Qt={apiBase:t,t:A,reloadAliases:Zt,publishFeedback:Re},$t=e=>rT(e,ot.providers[e]??``,Qt),en=(e,t)=>iT(e,t,ot.models[e]?.[t]?.alias??``,Qt),tn=async(e,n)=>{(await fetch(`${t}/api/default-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e,...n?{provider:n}:{}})})).ok&&await Zt()},[nn,rn]=(0,X.useState)(`add`),[an,on]=(0,X.useState)(``),[sn,cn]=(0,X.useState)(``),[ln,un]=(0,X.useState)(``),[dn,fn]=(0,X.useState)(``),[mn,hn]=(0,X.useState)(``),[gn,_n]=(0,X.useState)(!1),[vn,yn]=(0,X.useState)([`text`]),[bn,xn]=(0,X.useState)(!1),[Sn,Cn]=(0,X.useState)([]),wn=(0,X.useRef)(!1),[Tn,En]=(0,X.useState)(!1),[Dn,On]=(0,X.useState)(``),[An,jn]=(0,X.useState)(null),[Mn,Fn]=(0,X.useState)([]),[In,Ln]=(0,X.useState)(``),[Rn,Vn]=(0,X.useState)(``),[Hn,Un]=(0,X.useState)({}),[Wn,Gn]=(0,X.useState)({contextWindow:null,modelContextWindows:{}}),[Kn,qn]=(0,X.useState)(new Set),[Jn,Yn]=(0,X.useState)(!1),[Xn,Zn]=(0,X.useState)(!1),[Qn,$n]=(0,X.useState)(``),[er,tr]=(0,X.useState)(null),nr=(0,X.useRef)(null),{shadowCall:rr,shadowCallSaving:ir,loadShadowCall:ar,saveShadowCall:or}=yA({apiBase:t,publishFeedback:Re,t:A}),[sr,cr]=(0,X.useState)(null);(0,X.useEffect)(()=>()=>{nr.current&&clearTimeout(nr.current)},[]);let lr=(0,X.useMemo)(()=>Gf(N,L,z??{},A),[N,L,z,A]),ur=(0,X.useMemo)(()=>{let e=new Set(lr.map(e=>e.value));return Cr(N.filter(t=>e.has(t.namespaced)),rr?.model,rr?.sourceModels)},[N,rr?.model,rr?.sourceModels,lr]),dr=(0,X.useMemo)(()=>[{value:``,label:`—`},...Kf(lr,N,ze?.model)],[N,lr,ze?.model]),fr=(0,X.useCallback)(async()=>{if(vt.current)return;let n=++yt.current,r=bt.current,i=()=>n===yt.current&&r===bt.current,a=e(15e3);try{let e=await fetch(`${t}/api/v2`,{signal:a.signal});if(!i())return;if(!(e.headers.get(`content-type`)??``).includes(`application/json`)){et(null);return}let n=await Bn(e);if(!i())return;if(!n||typeof n.enabled!=`boolean`){et(null);return}et({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`,keepNativeChatGptOnV1:n.keepNativeChatGptOnV1===!0})}catch{i()&&et(null)}finally{a.clear(),pt(!1)}},[t]),pr=(0,X.useCallback)(async e=>{let n=Je.current,[r,i,a,o]=await Promise.all([fetch(`${t}/api/models`,{signal:e}),fetch(`${t}/api/provider-context-caps`,{signal:e}),fetch(`${t}/api/providers`,{signal:e}),bf(t,fetch,e)]),[s,c,l]=await Promise.all([zn(r),zn(i),zn(a)]);if(s===void 0||c===void 0||l===void 0)throw Error(`models payload missing`);if(e.aborted)throw Error(`models request aborted`);let u=Wf(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===Je.current&&Nd(j,p),p},[t,j]),mr=(0,X.useCallback)(e=>{let t=nA(e.models,e.providers);cr(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),P(e.models),I(e.providers),R(new Set(e.disabled)),B(e.selectedModels),oe(e.contextCapValue),K(e.contextCaps),ie(e.contextCapValues??e.contextCaps)},[]),hr=Fd(j,[t],async e=>{let t=Je.current,n=await pr(e);if(e.aborted)throw Error(`models request aborted`);return!qe.current&&t===Je.current&&mr(n),n},{isEmpty:()=>!1,pollMs:1e4,initialData:M??void 0,enabled:C,deadlineMs:6e4}),gr=hr.state,_r=(0,X.useCallback)(async(e=!1,t)=>{if(Ye.current&&!e)return!1;Ye.current=!0;let n=++Je.current;try{let e=await pr(t??new AbortController().signal);return wf(n,Je.current)?(mr(e),pn(j,e),me.refresh(),!0):!1}catch{return!1}finally{wf(n,Je.current)&&(Ye.current=!1)}},[mr,j,pr,me.refresh]),vr=(0,X.useCallback)(()=>{let e=Xt.current;Pt(null),Ut(null),Gt(null),qt(!1),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)},[]),yr=(0,X.useCallback)(()=>{Yt.current||vr()},[vr]),br=(0,X.useCallback)(async n=>{let r=Nt;if(!r||Yt.current)return;let i=e(6e4);Jt.current=i,Yt.current=!0,Vt(!0),Ut(null);let a=Wt?.confirmed===!0&&(n===void 0||n===Wt.value),o=n===void 0,s=n===void 0;try{if(n!==void 0){let e=await fetch(`${t}/api/providers/${encodeURIComponent(r.provider)}/model-display-names`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:r.id,displayName:n}),signal:i.signal}),c=e.ok?await zn(e,A(`models.displayNameSaveFailed`)):await e.json();if(i.signal.throwIfAborted(),!c||typeof c!=`object`||Array.isArray(c)||!e.ok&&c.saved!==!0&&typeof c.error!=`string`)throw Error(A(`models.displayNameSaveFailed`));o=!0;let l=e.ok||c.saved===!0;if(a||=l,l){let e=c.displayNameOverride===null?void 0:c.displayNameOverride??n??void 0,t={displayName:c.displayName??e,displayNameOverride:e,displayNameSource:c.displayNameSource??(e?`operator`:void 0)};P(e=>e.map(e=>e.namespaced===r.namespaced?{...e,...t}:e)),Pt({...r,...t}),qt(t.displayName===void 0)}if(!e.ok)throw Error(c.error||A(`models.displayNameSaveFailed`));s=!0}if(!await _r(!0,i.signal))throw Error(A(`models.loadFail`));i.signal.throwIfAborted(),Re(!0,A(a?n===null||n===void 0&&Wt?.value===null?`models.displayNameResetDone`:`models.displayNameSaved`:`models.displayNameReloaded`)),vr()}catch(e){if(Jt.current!==i)return;let t=!o||i.signal.aborted;t&&!a&&qt(!0),Gt(a||t||s?{value:s||t?void 0:n,confirmed:a}:null),Ut(a?A(`models.displayNameSavedRefreshFailed`):t||s?A(`models.displayNameOutcomeUnknown`):e instanceof Error&&e.message?e.message:A(`models.displayNameSaveFailed`))}finally{i.clear(),Jt.current===i&&(Jt.current=null,Yt.current=!1,Vt(!1))}},[t,Nt,Wt,vr,_r,Re,A]);(0,X.useEffect)(()=>{if(!C)return;let e=window.setTimeout(()=>{ar(),Ve(),fr(),Gr(),Kr()},0),t=Ru(()=>{vt.current||fr()},1e4);return()=>{window.clearTimeout(e),t()}},[C,ar,Ve,fr]);let xr=(0,X.useMemo)(()=>nA(N,F),[N,F]),Sr=N.length>0||gr.data!==void 0,wr=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;jn(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)]));Vn(r),Un(i),Gn({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),qn(new Set),Yn(!1),$n(``)},Tr=e=>{Ln(e)},Er=async()=>{if(!An)return;let e=Yf(Rn);if(!xr.find(e=>e.provider===An)){$n(A(`models.contextSaveFailed`));return}if(Jn&&e===void 0){$n(A(`models.contextInvalid`));return}let n=Object.create(null);for(let e of Kn){let t=Yf(uT(Hn,e)??``);if(t===void 0){$n(A(`models.contextInvalid`));return}t!==(uT(Wn.modelContextWindows,e)??null)&&(n[e]=t)}let r=Jn&&e!==Wn.contextWindow;if(!r&&Object.keys(n).length===0)jn(null),Re(!0,A(`models.contextUnchanged`));else{Zn(!0),$n(``);try{let i={};r&&(i.contextWindow=e),Object.keys(n).length>0&&(i.modelContextWindows=n),await zn(await fetch(`${t}/api/providers?name=${encodeURIComponent(An)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),A(`models.contextSaveFailed`))}catch(e){$n(e instanceof Error?e.message:A(`models.contextSaveFailed`));return}finally{Zn(!1)}jn(null),Re(!0,A(`models.contextSaved`)),await _r(!0)}};(0,X.useEffect)(()=>{if(!ke.current||xr.length===0)return;ke.current=!1;let e=new Set(xr.map(e=>e.provider));De(e),Jf(e)},[xr]);let Dr=(0,X.useMemo)(()=>z?N.filter(e=>Qe(z,e.provider,e.id,e.native===!0,L.has(e.namespaced))).length:0,[L,N,z,Xe.overrides]),Or=(0,X.useMemo)(()=>({catalog:Sr?A(`models.active`,{active:Dr,total:N.length}):void 0,combos:w===null?void 0:String(w),routing:E===null?void 0:String(E),compatibility:O===null?void 0:String(O)}),[Sr,w,O,Dr,N.length,E,A]),kr=async(e,t,n,r)=>{(!Ke.current||Xe.isRunning())&&Xe.enqueue(e,t,n,r)},Ar=async e=>{We(!0),Ke.current=!0,je(``);let n=G[e]===void 0;try{let r=await fetch(`${t}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,enabled:n})});try{let e=await zn(r,A(`models.capSaveFailed`));K(e?.caps??{}),ie(e?.values??e?.caps??{}),Fe(!0),je(A(`models.capApplied`)),await _r(!0)}catch(e){Fe(!1),je(e instanceof Error?e.message:A(`models.capSaveFailed`))}}catch{Fe(!1),je(A(`models.networkError`))}finally{We(!1),Ke.current=!1}},jr=e=>{De(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Jf(n),n})},Nr=e=>{De(()=>{let t=e?new Set(xr.map(e=>e.provider)):new Set;return Jf(t),t})},Fr=async e=>{We(!0),Ke.current=!0,je(``);try{let n=await fetch(`${t}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});try{let e=await zn(n,A(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&oe(e.value),K(e?.caps??{}),ie(e?.values??e?.caps??{}),Fe(!0),je(A(`models.capApplied`)),await _r(!0)}catch(e){Fe(!1),je(e instanceof Error?e.message:A(`models.capSaveFailed`))}}catch{Fe(!1),je(A(`models.networkError`))}finally{We(!1),Ke.current=!1}},Ir=(0,X.useMemo)(()=>{let e=xr.filter(e=>!e.native);return e.length>0&&e.every(e=>G[e.provider]===ae)&&Object.keys(G).every(e=>G[e]===ae)},[xr,G,ae]),Lr=e=>{!Number.isSafeInteger(e)||e<=0||Fr(Ir?{value:e,setAll:!0}:{value:e})},Rr=(e,t)=>{if(t===`custom`){Se(t=>({...t,[e]:!0})),we(t=>({...t,[e]:String(G[e]??re[e]??ae)}));return}Se(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==G[e]&&Fr({provider:e,enabled:!0,value:n})},zr=e=>{let t=Number((Ce[e]??``).replace(/[_,\s]/g,``));!Number.isSafeInteger(t)||t<=0?Re(!1,A(`models.capSaveFailed`)):(Se(t=>({...t,[e]:!1})),Fr({provider:e,enabled:!0,value:t}))},Br=e=>{if(e===`custom`){be(!0),ve(String(ae));return}be(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==ae&&Lr(t)},Vr=()=>{let e=Number(_e.replace(/[_,\s]/g,``));!Number.isSafeInteger(e)||e<=0?Re(!1,A(`models.capSaveFailed`)):(be(!1),Lr(e))},Hr=()=>{Fr({setAll:!Ir})},Ur=async e=>{if($e&&!vt.current){ht(!0),vt.current=!0,bt.current++,_t(``),je(``);try{let n=await fetch(`${t}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});try{let e=await zn(n,A(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Fe(!1),je(A(`models.saveFailed`));return}et({enabled:e.enabled,agentsMaxThreadsConflict:e.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof e.maxConcurrentThreadsPerSession==`number`?e.maxConcurrentThreadsPerSession:null,multiAgentMode:e.multiAgentMode===`v1`||e.multiAgentMode===`v2`?e.multiAgentMode:`default`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),Fe(!0),je(A(`models.v2Applied`)),_t((e.warnings??[]).join(` `))}catch(e){Fe(!1),je(e instanceof Error?e.message:A(`models.saveFailed`))}}catch{Fe(!1),je(A(`models.networkError`))}finally{ht(!1),vt.current=!1}}},Wr=async e=>{$e&&$e.multiAgentMode!==e&&(e===`v1`?await Ur({multiAgentMode:`v1`}):kt(e))},Gr=async()=>{try{let n=e(15e3),r=await Bn(await fetch(`${t}/api/model-presets`,{signal:n.signal}));nt(r?.providers??{})}catch{nt({})}},Kr=async()=>{try{let e=await fetch(`${t}/api/model-discovery`);it(await Bn(e)??null)}catch{it(null)}},qr=async(e,n)=>{await Bn(await fetch(`${t}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:e,provider:n??null})})),await Promise.all([Kr(),_r()])},Jr=async(n,r,i)=>{if((!i||await Nu({message:A(`models.presetConfirmReplace`,{count:String(i.presetCount)}),tone:`danger`}))&&!qe.current){qe.current=!0,ft(n),We(!0),Ke.current=!0;try{let i=e(3e4),a=await zn(await fetch(`${t}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:n,mode:r}),signal:i.signal}),A(`models.saveFailed`));if(!a)throw Error(A(`models.saveFailed`));if(a.fallback===`preset-empty`)Re(!1,A(`models.presetEmpty`,{provider:n}));else{let e=gf(a);e!==void 0&&Ne(e),Re(!0,r===`all`?A(`models.presetClearedToast`,{provider:n}):A(`models.presetAppliedToast`,{provider:n,count:String(a.selected?.length??0)}))}await Promise.all([Gr(),_r()])}catch(e){Re(!1,e instanceof Error?e.message:String(e))}finally{ft(null),We(!1),Ke.current=!1,qe.current=!1}}},Yr=async e=>{$e&&$e.keepNativeChatGptOnV1!==e&&await Ur({keepNativeChatGptOnV1:e})},Xr=$e?.maxConcurrentThreadsPerSession==null?null:Bf($e.maxConcurrentThreadsPerSession,$e.enabled),Zr=async e=>{if(!$e||vt.current)return;let n=Vf(e,$e.enabled);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(n))Re(!1,A(`models.v2ThreadsInvalid`));else if(Xr!==e){ht(!0),vt.current=!0,bt.current++,_t(``),je(``);try{let e=await fetch(`${t}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let t=await zn(e,A(`models.saveFailed`));if(!t||typeof t.enabled!=`boolean`){Fe(!1),je(A(`models.saveFailed`));return}et({enabled:t.enabled,agentsMaxThreadsConflict:t.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof t.maxConcurrentThreadsPerSession==`number`?t.maxConcurrentThreadsPerSession:null,multiAgentMode:t.multiAgentMode===`v1`||t.multiAgentMode===`v2`?t.multiAgentMode:`default`,keepNativeChatGptOnV1:t.keepNativeChatGptOnV1===!0}),Fe(!0),je(A(`models.v2ThreadsApplied`)),Tt(!1)}catch(e){Fe(!1),je(e instanceof Error?e.message:A(`models.saveFailed`))}}catch{Fe(!1),je(A(`models.networkError`))}finally{ht(!1),vt.current=!1}}},Qr=e=>{e===`custom`?(Tt(!0),Ct(String(Xr??``))):(Tt(!1),Zr(Number(e)))},$r=(e,t)=>{nr.current&&clearTimeout(nr.current),nr.current=setTimeout(()=>{tr({namespaced:e,rect:t.getBoundingClientRect()})},300)},ei=(e,t)=>{nr.current&&clearTimeout(nr.current),tr({namespaced:e,rect:t.getBoundingClientRect()})},ti=()=>{nr.current&&clearTimeout(nr.current),nr.current=setTimeout(()=>tr(null),120)},ni=()=>{nr.current&&clearTimeout(nr.current)},ri=async(e,n,r,i,a,o)=>{En(!0),On(``);try{let s=await fetch(`${t}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,modelId:n,displayName:r,contextWindow:i,inputModalities:a,reasoningEfforts:o})});try{await zn(s,A(`models.customSaveFailed`)),jt(!1),Re(!0,A(`models.customAdded`)),await _r(!0)}catch(e){On(e instanceof Error?e.message:A(`models.customSaveFailed`))}}catch{On(A(`models.networkError`))}finally{En(!1)}},ii=async(e,n)=>{En(!0),On(``);try{let r=await fetch(`${t}/api/custom-models/${encodeURIComponent(e)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await zn(r,A(`models.customSaveFailed`)),jt(!1),Re(!0,A(`models.customUpdated`)),await _r(!0)}catch(e){On(e instanceof Error?e.message:A(`models.customSaveFailed`))}}catch{On(A(`models.networkError`))}finally{En(!1)}},ai=async(e,n)=>{if(await Nu({message:A(`models.customDeleteConfirm`,{name:n}),confirmLabel:A(`common.delete`),tone:`danger`}))try{(await fetch(`${t}/api/custom-models/${encodeURIComponent(e)}`,{method:`DELETE`})).ok?(Re(!0,A(`models.customDeleted`)),await _r(!0)):Re(!1,A(`models.customSaveFailed`))}catch{Re(!1,A(`models.networkError`))}},oi=gr.data??M,si=gr.kind===`failed-cold`?gr.error instanceof Error?gr.error.message:A(`models.loadFail`):null,ci=gr.showSkeleton&&!oi,li=z??{},ui=e=>{let{provider:n,rows:r,nativeProviderGroup:i,liveModels:a,discovery:o}=e,s=Ee.has(n),c=e=>Qe(li,n,e.id,e.native===!0,L.has(e.namespaced)),l=U[n]===!0,u=Ef(r),d=Of(l,r),f=Df(r,d),p=f.filter(c).length,m=rt?.recentArrivals[n]??[],h=new Set(m.map(e=>e.id)),g=G[n]!==void 0,_=G[n]??re[n]??ae,v=e.nativeProviderGroup?Ff:Nf,y=e.nativeProviderGroup?If:Pf,b=a&&o?.status===`failed`?o:void 0,x=(V[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),j=!D||f.every(e=>!c(e)),M=e=>{D&&!O&&kr(`provider`,n,f.map(e=>({id:e.id,native:e.native===!0})),e)},N=(()=>{let e=tt[n];if(!e)return null;let t=Ue||dt!==null,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":A(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,Z.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:Ue||t||O,onClick:t=>{t.stopPropagation(),Jr(n,r,r===`preset`&&e.mode===`custom`?e:void 0)},children:A(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,Z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:A(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,Z.jsx)(`span`,{className:`muted mono text-label`,children:A(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:A(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})();return(0,Z.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,Z.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>jr(n),"aria-expanded":!s,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,Z.jsx)(St,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,Z.jsx)(xA,{name:n}),(0,Z.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:ee(n)}),ot.providers[n]&&(0,Z.jsx)(`span`,{className:`models-chip mono text-caption`,children:ot.providers[n]}),i&&(0,Z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:A(`models.nativeGroupLabel`)}),b&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:Tf(A,b),children:A(`models.discoveryFailedBadge`)}),(0,Z.jsx)(`span`,{className:`muted mono text-label models-provider-count`,children:A(`models.active`,{active:p,total:f.length})}),m.length>0&&(0,Z.jsx)(`span`,{className:`models-chip mono text-caption`,children:A(`models.newCount`,{count:m.length})}),s&&g&&(0,Z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:A(`models.contextCappedValue`,{value:Uf(_)})})]}),(0,Z.jsxs)(`div`,{className:`row models-provider-actions`,children:[N,(0,Z.jsxs)(`div`,{className:`models-bulk`,role:`group`,"aria-label":A(`modelsV2.bulkLabel`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Ue&&!Xe.pending||k||O,onClick:()=>M(!0),children:A(`models.allOn`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Ue&&!Xe.pending||j||O,onClick:()=>M(!1),children:A(`models.allOff`)})]})]}),!s&&(0,Z.jsxs)(`div`,{className:`row models-provider-actions models-provider-tools`,role:`group`,"aria-label":A(`modelsV2.providerTools`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm models-alias-edit`,"aria-label":A(`models.editProviderAlias`),title:A(`models.editProviderAlias`),onClick:()=>void $t(n),children:(0,Z.jsx)(Oe,{style:{width:14,height:14}})}),(0,Z.jsx)(kn,{on:ot.defaults.providers[n]??ot.defaults.global,onClick:()=>void tn(!(ot.defaults.providers[n]??ot.defaults.global),n),label:A(`models.useDefaultAliases`),showLabel:!0}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),rn(`add`),on(n),cn(``),un(``),fn(``),hn(``),_n(!1),yn([`text`]),xn(!1),Cn([]),wn.current=!1,On(``),jt(!0)},"aria-haspopup":`dialog`,children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,A(`models.customAdd`)]}),(0,Z.jsxs)(`div`,{className:`models-cap-cluster`,children:[(0,Z.jsx)(kn,{on:g,onClick:()=>Ar(n),disabled:Ue,label:A(`models.contextCapLabel`),showLabel:!0}),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)($,{value:xe[n]?`custom`:String(_),options:[...!y.has(_)&&!xe[n]?[{value:String(_),label:Uf(_)}]:[],...v.map(e=>({value:String(e),label:Uf(e)})),{value:`custom`,label:A(`models.custom`)}],onChange:e=>Rr(n,e),disabled:Ue||!g,label:A(`models.capValue`,{value:Uf(_)}),title:A(`models.contextCapLabel`)}),g&&xe[n]&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:A(`models.customPlaceholder`),value:Ce[n]??``,onChange:e=>we(t=>({...t,[n]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&zr(n)},disabled:Ue,"aria-label":A(`models.customPlaceholder`)}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>zr(n),disabled:Ue,className:`btn btn-ghost btn-sm`,children:A(`models.customApply`)})]})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>wr(e),"aria-haspopup":`dialog`,children:A(`models.contextSettings`)})]})]})]}),!s&&(0,Z.jsxs)(`div`,{className:`models-provider-body`,children:[i&&(0,Z.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:A(`models.nativeHint`)}),r.length===0&&(0,Z.jsx)(rA,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>0&&b&&(0,Z.jsx)(iA,{}),(r.length>30||u||!i&&rt)&&(0,Z.jsxs)(`div`,{className:`row models-provider-filters`,children:[r.length>30&&(0,Z.jsx)(`input`,{className:`input`,placeholder:A(`models.search`),value:V[n]??``,onChange:e=>H(t=>({...t,[n]:e.target.value})),"aria-label":A(`models.search`)}),u&&(0,Z.jsx)(kn,{on:l,onClick:()=>W(e=>({...e,[n]:!l})),label:A(`models.freeOnly`),showLabel:!0}),!i&&rt&&(0,Z.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:A(`models.newPolicyProvider`)}),(0,Z.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":A(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,Z.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 qr(e,n),children:A(`models.newPolicy_${e}`)},e))})]})]}),!i&&(0,Z.jsx)(tA,{summary:F.find(e=>e.name===n),apiBase:t,onSaved:(e,t)=>{Re(e,t),e&&_r(!0)}}),d&&f.length===0&&r.length>0&&(0,Z.jsx)(`p`,{className:`muted text-label`,role:`status`,children:A(`models.noFreeMatch`)}),T.map(e=>{let t=!c(e);return(0,Z.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>$r(e.namespaced,t.currentTarget),onMouseLeave:ti,onFocus:t=>ei(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tr(null)},children:[(0,Z.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Z.jsx)(kn,{on:!t,onClick:()=>void kr(`models`,n,[{id:e.id,native:e.native===!0}],t),disabled:Ue&&!Xe.pending||e.initialSelectionPending,label:e.native?e.id:e.namespaced}),(0,Z.jsxs)(`span`,{className:`models-model-main`,children:[ot.models[n]?.[e.id]&&(0,Z.jsx)(`strong`,{className:`mono text-control`,children:ot.models[n][e.id].alias}),(0,Z.jsxs)(`span`,{className:`models-model-identity`,children:[(0,Z.jsx)(`code`,{className:`mono text-control`,style:{color:t?`var(--faint)`:`var(--text)`,textDecoration:t?`line-through`:`none`},children:e.native?lT(e.id):e.namespaced}),!e.native&&e.displayName?.trim()&&e.displayName.trim()!==e.namespaced&&(0,Z.jsx)(`span`,{className:`models-model-friendly text-caption`,children:e.displayName.trim()})]}),e.initialSelectionPending&&(0,Z.jsx)(`span`,{className:`models-chip muted`,role:`status`,children:A(`models.initialSelectionPending`)}),e.quotaInactiveReason===`no_credit`&&(0,Z.jsx)(`span`,{className:`models-chip muted`,role:`status`,title:A(`models.inactiveNoCreditHint`),children:A(`models.inactiveNoCredit`)}),ot.models[n]?.[e.id]?.source===`builtin`&&(0,Z.jsx)(`span`,{className:`models-chip muted text-caption`,children:A(`models.aliasAuto`)}),e.custom&&(0,Z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:A(`models.customBadge`)}),!e.native&&e.provider!==`combo`&&e.manualPricing===!0&&(0,Z.jsx)(`span`,{className:`models-chip muted text-caption`,children:A(`pricing.override.badge`)}),!e.custom&&h.has(e.id)&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:A(`models.newBadge`)}),e.contextCapped&&(0,Z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:A(`models.contextCappedValue`,{value:Uf(e.contextCap??ae)})})]}),(0,Z.jsxs)(`span`,{className:`models-model-actions`,role:`group`,"aria-label":A(`modelsV2.modelActions`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":A(`models.editModelAlias`),title:A(`models.editModelAlias`),onClick:()=>void en(n,e.id),children:(0,Z.jsx)(Oe,{style:{width:13,height:13}})}),!e.native&&!e.custom&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":A(`models.displayNameActionLabel`,{model:e.namespaced}),onClick:t=>{Xt.current=t.currentTarget,Ut(null),Gt(null),qt(!1),Pt(e)},children:A(`models.displayNameAction`)}),!e.native&&e.provider!==`combo`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":A(`pricing.override.actionLabel`,{model:e.namespaced}),onClick:t=>{Lt.current=t.currentTarget,It(e)},children:A(`pricing.override.action`)}),!e.native&&!e.custom&&e.provider!==`combo`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":A(`models.settingsTitle`,{model:e.namespaced}),onClick:()=>zt(e),children:A(`models.customEdit`)})]})]}),er?.namespaced===e.namespaced&&(()=>{let n=er.rect,r=n.bottom+4,i=r+360>window.innerHeight;return(0,Z.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:ni,onMouseLeave:ti,children:[(0,Z.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,Z.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,Z.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:A(`models.customBadge`)}),(0,Z.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,Z.jsx)(`span`,{className:`model-tip-key`,children:A(`models.tipProvider`)}),(0,Z.jsx)(`span`,{className:`model-tip-val`,children:Ge(e.provider,A)}),(e.contextWindow||e.contextCap)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`model-tip-key`,children:A(`models.tipContext`)}),(0,Z.jsx)(`span`,{className:`model-tip-val`,children:Uf(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`model-tip-key`,children:A(`models.tipModalities`)}),(0,Z.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,Z.jsx)(`span`,{className:`model-tip-key`,children:A(`models.tipStatus`)}),(0,Z.jsx)(`span`,{className:`model-tip-val`,children:A(t?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,Z.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{rn(`edit`),on(e.provider),cn(e.customId),un(e.id),fn(e.displayName??``),hn(e.contextWindow?String(e.contextWindow):``),_n(!1),yn(e.inputModalities??[`text`]),xn(Array.isArray(e.reasoningEfforts)),Cn(e.reasoningEfforts??[]),wn.current=Array.isArray(e.reasoningEfforts),On(``),jt(!0),tr(null)},children:A(`models.customEdit`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{ai(e.customId,e.displayName??e.id).finally(()=>tr(null))},children:A(`models.customDelete`)})]})]})})()]},e.namespaced)}),E>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>ne(e=>({...e,[n]:w+60})),className:`btn btn-ghost btn-sm models-show-more`,children:A(`models.showMore`,{n:E})})]})]},n)},di=sr?xr.filter(e=>e.provider===sr):xr,fi=(e,t=!1)=>{let n={pickerOrder:e.pickerOrder,pickerOrderMode:e.pickerOrderMode,pickerAvailable:[]};pn(se,n),Nd(se,n),t&&ue(`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,A(i?`models.pickerOrder.saved`:`models.pickerOrder.pending`)),m()},pi=async()=>{if(fe.current||!he||me.state.showError||ge===`custom`)return;let n=pe.current,r=ge,i=he.pickerAvailable,a=e(15e3);fe.current=a,de(!0);let o=()=>pe.current===n&&fe.current===a,s=()=>o()&&!a.signal.aborted;try{let e=[];if(r===`most-used`){let n=await fetch(`${t}/api/usage?range=all&surface=all`,{signal:a.signal});if(!s())return;let r=await zn(n,A(`models.pickerOrder.usageFailed`));if(!s())return;if(r?.usageIncomplete===!0)throw Error(A(`models.pickerOrder.usageIncomplete`));if(!XC(r?.models))throw Error(A(`models.pickerOrder.usageFailed`));e=r.models}if(!s())return;let n=ew(r,i,e,N),o=await fetch(`${t}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:a.signal,body:JSON.stringify({pickerOrder:n,pickerOrderMode:r==="default"?null:r})});if(!s())return;let c=await zn(o,A(`models.saveFailed`));if(!JC(c)||!(`ok`in c)||c.ok!==!0)throw Error(A(`models.saveFailed`));if(!s())return;fi({pickerOrder:c.pickerOrder,pickerOrderMode:c.pickerOrderMode,catalogRefresh:`catalogRefresh`in c?c.catalogRefresh:void 0}),ue(null)}catch(e){o()&&Re(!1,e instanceof Error?e.message:A(`models.networkError`))}finally{a.clear(),o()&&(fe.current=null,de(!1))}},mi=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`models-control-top-row`,children:[rt&&(0,Z.jsx)(mA,{label:A(`models.newPolicyGlobal`),children:(0,Z.jsx)(kn,{on:rt.policy===`off`,onClick:()=>void qr(rt.policy===`off`?`on`:`off`),label:A(`models.newPolicyGlobal`)})}),(0,Z.jsxs)(mA,{label:A(`models.useDefaultAliasesGlobal`),children:[(0,Z.jsx)(kn,{on:ot.defaults.global,onClick:()=>void tn(!ot.defaults.global),label:A(`models.useDefaultAliasesGlobal`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>lt(e=>!e),children:A(`models.aliases`)})]}),(0,Z.jsx)(hA,{shadowCall:rr,saving:ir,modelOptions:ur,onSave:e=>void or(e)}),(0,Z.jsxs)(mA,{label:A(`models.autoReviewOverride`),hint:(0,Z.jsx)(Pn,{content:A(`models.autoReviewOverrideHint`),side:`top`,maxWidth:320,children:(0,Z.jsx)(`span`,{style:{cursor:`help`},"aria-label":A(`models.autoReviewOverrideHint`),children:`ⓘ`})}),busy:!ze,children:[(0,Z.jsx)(kn,{on:ze?.enabled??!1,onClick:()=>void He({enabled:!ze?.enabled}),disabled:!ze||Be,label:A(`models.autoReviewOverride`)}),(0,Z.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Z.jsx)($,{value:ze?.model??``,options:dr,onChange:e=>void He({model:e}),disabled:!ze||Be||!ze.enabled,label:A(`models.autoReviewOverride`)})})]}),(Y||$e)&&(0,Z.jsxs)(mA,{label:A(`models.v2Label`),children:[(0,Z.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":A(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Z.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 Wr(e),children:A(`models.v2Mode_${e}`)},e))}),(0,Z.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":A(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,Z.jsx)(q,{width:14,height:14,"aria-hidden":`true`})})]}),$e&&$e.multiAgentMode===`v2`&&(0,Z.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,Z.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,Z.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:A(`models.keepNativeOnV1`)}),(0,Z.jsx)(kn,{on:$e.keepNativeChatGptOnV1===!0,onClick:()=>void Yr(!$e.keepNativeChatGptOnV1),disabled:mt,label:A(`models.keepNativeOnV1`)}),(0,Z.jsx)(Pn,{content:A(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,Z.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":A(`models.keepNativeOnV1Hint`),children:(0,Z.jsx)(q,{width:13,height:13,"aria-hidden":`true`})})})]})}),Ot&&(0,Z.jsx)(Pr,{reason:`selection`,mode:Ot,docsUrl:Mr($e?.multiAgentSurfaceAdvisory)?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:mt,onContinue:()=>{let e=Ot;kt(null),Ur({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{kt(null),$e?.multiAgentMode!==`v1`&&Ur({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>kt(null)})]}),$e&&(0,Z.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[(0,Z.jsx)(`span`,{className:`muted text-control`,children:A(`models.v2ThreadsLabel`)}),(0,Z.jsx)($,{value:wt?`custom`:Xr===null?``:zf.has(Xr)?String(Xr):`custom`,options:[...Xr===null?[{value:``,label:A(`models.v2ThreadsDefault`)}]:[],...Xr!==null&&!zf.has(Xr)&&!wt?[{value:`custom`,label:String(Xr)}]:[],...Rf.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:A(`models.custom`)}],onChange:e=>Qr(e),disabled:mt,label:A(`models.v2ThreadsLabel`)}),wt&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:xt,onChange:e=>Ct(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Zr(Number(xt.replace(/[_,\s]/g,``)))},disabled:mt,"aria-label":A(`models.v2ThreadsLabel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:mt,onClick:()=>{Zr(Number(xt.replace(/[_,\s]/g,``)))},children:A(`models.v2ThreadsApply`)})]}),$e.enabled&&$e.agentsMaxThreadsConflict&&(0,Z.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:A(`models.v2Conflict`)}),gt&&(0,Z.jsx)(`span`,{className:`muted text-label`,children:gt})]}),(0,Z.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,Z.jsx)(`span`,{className:`muted text-control`,children:A(`models.contextCapLabel`)}),(0,Z.jsx)($,{value:ye?Lf:String(ae),options:[...!Pf.has(ae)&&!ye?[{value:String(ae),label:Uf(ae)}]:[],...Nf.map(e=>({value:String(e),label:Uf(e)})),{value:Lf,label:A(`models.custom`)}],onChange:e=>Br(e),disabled:Ue,label:A(`models.contextCapLabel`)}),ye&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:A(`models.customPlaceholder`),value:_e,onChange:e=>ve(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Vr()},disabled:Ue,"aria-label":A(`models.customPlaceholder`)}),(0,Z.jsx)(`button`,{type:`button`,onClick:Vr,disabled:Ue,className:`btn btn-ghost btn-sm`,children:A(`models.customApply`)})]}),(0,Z.jsx)(kn,{on:Ir,onClick:Hr,disabled:Ue,label:A(`models.setAll`)}),(0,Z.jsx)(pA,{text:A(`models.setAllHint`,{value:Uf(ae)})})]}),(0,Z.jsxs)(`div`,{className:`row models-cap-row`,"aria-busy":J||me.state.refreshing,children:[(0,Z.jsx)(`span`,{className:`muted text-control`,children:A(`models.pickerOrder.label`)}),(0,Z.jsx)($,{value:ge,options:[{value:`default`,label:A(`models.pickerOrder.default`)},{value:`alphabetical`,label:A(`models.pickerOrder.alphabetical`)},{value:`provider`,label:A(`models.pickerOrder.provider`)},{value:`most-used`,label:A(`models.pickerOrder.mostUsed`)},{value:`custom`,label:A(`models.pickerOrder.custom`)}],onChange:e=>ue(e),disabled:J||!he||me.state.showError,label:A(`models.pickerOrder.label`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void pi(),disabled:J||!he||me.state.showError||ge===`custom`||ge!=="default"&&he.pickerAvailable.length===0,children:A(J?`models.pickerOrder.applying`:`models.pickerOrder.apply`)}),me.state.showError&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{role:`alert`,children:A(`models.pickerOrder.loadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>me.refresh(),children:A(`models.pickerOrder.retry`)})]}),(0,Z.jsx)(pA,{text:A(`models.pickerOrder.hint`)})]}),(0,Z.jsx)(pw,{showOrderEditor:ge===`custom`,apiBase:t,active:C,identities:N,onBusyChange:de,onAccepted:e=>fi(e,!0),onSaved:()=>hr.refresh()}),ct&&(0,Z.jsxs)(`div`,{className:`card models-aliases-card`,"aria-label":A(`models.aliasesTable`),children:[(0,Z.jsx)(`div`,{className:`row group-head`,children:(0,Z.jsx)(`strong`,{children:A(`models.aliases`)})}),Object.entries(ot.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,Z.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Z.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,Z.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,Z.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?A(`models.aliasAuto`):A(`models.aliasUser`)}),n.stale&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:A(`models.aliasStale`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":A(`models.editModelAlias`),onClick:()=>void en(e,t),children:(0,Z.jsx)(Oe,{style:{width:13,height:13}})})]},`${e}/${t}`)))]})]}),hi=N.filter(e=>e.custom).length,gi=(0,Z.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Nr(!0),disabled:Ue,children:[(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`}),` `,A(`models.collapseAll`)]}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Nr(!1),disabled:Ue,children:[(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,A(`models.expandAll`)]}),(0,Z.jsx)(pA,{text:A(`models.orderHint`)}),(0,Z.jsx)(fA,{count:hi,label:A(`models.customSummary`,{count:hi})})]}),_i=(0,Z.jsx)(Z.Fragment,{children:xr.length===0&&(0,Z.jsx)(Nn,{icon:(0,Z.jsx)(Ze,{}),title:A(`models.noRouted`),children:A(`models.noRoutedHint`)})}),vi=(0,Z.jsxs)(Z.Fragment,{children:[Et&&(0,Z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":A(`models.v2Label`),onClick:()=>Dt(!1),onKeyDown:e=>{e.key===`Escape`&&Dt(!1)},children:(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{children:A(`models.v2Label`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Dt(!1),"aria-label":A(`common.close`),children:`×`})]}),(0,Z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:A(`models.v2Help`)}),(0,Z.jsx)(`div`,{className:`models-help-link`,children:(0,Z.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:A(`models.v2DocsLink`)})}),(0,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Dt(!1),children:A(`common.ok`)})})]})}),An&&(0,Z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":A(`models.contextSettings`),onClick:()=>{Xn||jn(null)},onKeyDown:e=>{e.key===`Escape`&&!Xn&&jn(null)},children:(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{children:A(`models.contextSettingsTitle`,{provider:Ge(An,A)})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>jn(null),disabled:Xn,"aria-label":A(`common.close`),children:`×`})]}),Qn&&(0,Z.jsx)(Q,{tone:`err`,children:Qn}),(0,Z.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:A(`models.contextHint`)}),(0,Z.jsxs)(`div`,{className:`models-context-fields`,children:[(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[A(`models.contextDefault`),(0,Z.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Rn,onChange:e=>{Vn(e.target.value),Yn(!0)},disabled:Xn,placeholder:A(`models.contextAutomatic`),autoFocus:!0})]}),Mn.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`text-label models-field`,children:[A(`models.contextModel`),(0,Z.jsx)($,{value:In,options:Mn.map(e=>({value:e,label:e})),onChange:Tr,disabled:Xn,label:A(`models.contextModel`)})]}),(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[A(`models.contextModelOverride`),(0,Z.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:uT(Hn,In)??``,onChange:e=>{Un(t=>({...t,[In]:e.target.value})),qn(e=>new Set(e).add(In))},disabled:Xn,placeholder:A(`models.contextAutomatic`)})]})]})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>jn(null),disabled:Xn,children:A(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Er(),disabled:Xn,children:A(Xn?`models.customSaving`:`models.customApply`)})]})]})}),At&&(0,Z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":A(`models.customAdd`),onClick:()=>{Tn||jt(!1)},onKeyDown:e=>{e.key===`Escape`&&!Tn&&jt(!1)},children:(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{children:A(nn===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:Ge(an,A)})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>jt(!1),disabled:Tn,"aria-label":A(`common.close`),children:`×`})]}),Dn&&(0,Z.jsx)(Q,{tone:`err`,children:Dn}),(0,Z.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[A(`models.customFieldModelId`),(0,Z.jsx)(`input`,{className:`input`,value:ln,onChange:e=>un(e.target.value),disabled:Tn,placeholder:A(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[A(`models.customFieldDisplayName`),(0,Z.jsx)(`input`,{className:`input`,value:dn,onChange:e=>fn(e.target.value),disabled:Tn,placeholder:A(`models.customFieldDisplayNamePlaceholder`)})]}),(0,Z.jsxs)(`label`,{className:`text-label models-field`,children:[A(`models.customFieldContext`),(0,Z.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Z.jsx)($,{value:gn?`custom`:mn,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:A(`models.custom`)}],onChange:e=>{e===`custom`?_n(!0):(_n(!1),hn(e))},disabled:Tn,label:A(`models.customFieldContext`)}),gn&&(0,Z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:mn,onChange:e=>hn(e.target.value),disabled:Tn,placeholder:A(`models.customPlaceholder`),"aria-label":A(`models.customFieldContext`)})]})]}),(0,Z.jsxs)(`div`,{className:`text-label models-field`,children:[A(`models.customFieldModalities`),(0,Z.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,Z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:vn.includes(e),onChange:t=>{yn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Tn}),(0,Z.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,Z.jsxs)(`div`,{className:`text-label models-field`,children:[A(`models.customFieldReasoning`),(0,Z.jsx)(`div`,{className:`row models-field-row`,children:(0,Z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:bn,onChange:e=>{if(xn(e.target.checked),e.target.checked&&!wn.current){wn.current=!0;let e=N.find(e=>e.provider===an&&e.id===ln),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;Cn(t??[...jf])}},disabled:Tn}),(0,Z.jsx)(`span`,{className:`text-control`,children:A(`models.customFieldReasoningOverride`)})]})}),bn&&(0,Z.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:jf.map(e=>(0,Z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Sn.includes(e),onChange:t=>{Cn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Tn}),(0,Z.jsx)(`span`,{className:`text-control`,children:A(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>jt(!1),disabled:Tn,children:A(`common.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Tn||!ln.trim(),onClick:()=>{let e=ln.trim(),t=dn.trim(),n=Yf(mn);if(n===void 0)On(A(`models.contextInvalid`));else if(nn===`add`){let r=bn?Sn:void 0;ri(an,e,t||void 0,n??void 0,vn.length>0?vn:void 0,r)}else ii(sn,{modelId:e,displayName:t,contextWindow:n,inputModalities:vn,reasoningEfforts:bn?Sn:null})},children:A(Tn?`models.customSaving`:nn===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),yi=(0,Z.jsxs)(`div`,{className:`models-workspace-shell`,children:[Ae&&(0,Z.jsxs)(`div`,{className:`action-toast notice ${Pe?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[Pe?(0,Z.jsx)(ut,{}):(0,Z.jsx)(at,{}),(0,Z.jsx)(`span`,{children:Ae})]}),gr.showError&&(0,Z.jsx)(Q,{tone:`err`,children:A(`models.loadFail`)}),Me.length>0&&(0,Z.jsx)(`div`,{className:`models-integration-warning`,children:(0,Z.jsxs)(Q,{tone:`warn`,children:[A(`models.integrationRefreshWarning`),(0,Z.jsx)(`ul`,{children:Me.map(e=>(0,Z.jsxs)(`li`,{children:[e.client,e.profileId===void 0?``:`:${e.profileId}`,`: `,OE(A,{clientId:e.client,message:e.reason===`integration_mutation_busy`?A(`integrations.error.busy`):e.reason,reason:e.refusalReason,snapshotPath:e.snapshotPath,residual:e.residual})]},`${e.client}:${e.profileId??`all`}`))})]})}),(0,Z.jsx)(dA,{title:A(`models.settingsPanel.title`),attentionLabel:A(`models.settingsPanel.attention`),warn:!!($e?.enabled&&$e.agentsMaxThreadsConflict)||gt!==``||me.state.showError,summary:uA(A,{multiAgentMode:$e?.multiAgentMode,v2Threads:Xr,keepNativeOnV1:$e?.keepNativeChatGptOnV1===!0,shadowEnabled:rr?.enabled===!0,shadowModel:rr?.model,windowOn:Ir,windowValue:ae,newModelsOff:rt?.policy===`off`,aliasesOn:ot.defaults.global,autoReviewEnabled:ze?.enabled===!0,autoReviewModel:ze?.model,pickerMode:tw(he?.pickerAvailable??[],he?.pickerOrder??[],he?.pickerOrderMode)}),children:mi}),(0,Z.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":Xe.pending||gr.refreshing||void 0,children:[(0,Z.jsx)(SA,{selected:sr,onSelect:cr,all:{active:Dr,total:N.length},items:xr.map(({provider:e,rows:t})=>({provider:e,total:t.length,active:t.filter(t=>Qe(li,e,t.id,t.native===!0,L.has(t.namespaced))).length}))}),(0,Z.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":A(`models.workspace.mainAria`),children:[gi,(0,Z.jsx)(`div`,{className:`models-provider-list`,children:di.map(e=>ui(e))}),xr.length===0&&_i]})]}),vi]});return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`page-head`,children:[(0,Z.jsxs)(`div`,{className:`ui-v2 flex min-w-0 flex-col gap-1`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:A(`nav.models`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[14px] leading-5 text-fg-muted`,children:A(wA[_][0])})]}),(0,Z.jsxs)(`div`,{className:`page-head-actions`,children:[wA[_][1]&&(0,Z.jsx)(bA,{text:A(wA[_][1]),children:_===`catalog`&&(0,Z.jsx)(_A,{connected:r,catalogSyncedAt:i})},_),(0,Z.jsxs)(lp,{variant:`outline`,size:`sm`,onClick:()=>{g()},disabled:h,children:[(0,Z.jsx)(`span`,{className:h?`inline-flex animate-spin`:`inline-flex`,children:(0,Z.jsx)(Mt,{"aria-hidden":`true`})}),A(h?`dash.codexRestarting`:`dash.codexRestart`)]})]})]}),(0,Z.jsx)(GC,{state:o,controller:{restarting:h,restart:g}}),(0,Z.jsx)(eA,{tab:_,onSelect:S,meta:Or}),(0,Z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Qk(`catalog`),"aria-labelledby":Zk(`catalog`),hidden:_!==`catalog`,children:(0,Z.jsx)(FE,{pageName:A(`models.tab.catalog`),title:A(`errorBoundary.title`),message:A(`errorBoundary.message`),detailsLabel:A(`errorBoundary.details`),reloadLabel:A(`errorBoundary.reload`),children:ci?(0,Z.jsx)(NE,{label:A(`models.loading`),rows:5}):si===null?yi:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Q,{tone:`err`,children:si}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>hr.refresh(),children:A(`common.retry`)})]})})}),(0,Z.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:Qk(`combos`),"aria-labelledby":Zk(`combos`),hidden:_!==`combos`,children:y.has(`combos`)&&(0,Z.jsx)(FE,{pageName:A(`models.tab.combos`),title:A(`errorBoundary.title`),message:A(`errorBoundary.message`),detailsLabel:A(`errorBoundary.details`),reloadLabel:A(`errorBoundary.reload`),children:(0,Z.jsx)(ND,{apiBase:t,active:_===`combos`,onCountChange:T})})}),(0,Z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Qk(`routing`),"aria-labelledby":Zk(`routing`),hidden:_!==`routing`,children:y.has(`routing`)&&(0,Z.jsx)(FE,{pageName:A(`models.tab.routing`),title:A(`errorBoundary.title`),message:A(`errorBoundary.message`),detailsLabel:A(`errorBoundary.details`),reloadLabel:A(`errorBoundary.reload`),children:(0,Z.jsx)(vO,{apiBase:t,active:_===`routing`,onCountChange:D})})}),(0,Z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Qk(`compatibility`),"aria-labelledby":Zk(`compatibility`),hidden:_!==`compatibility`,children:y.has(`compatibility`)&&(0,Z.jsx)(FE,{pageName:A(`models.tab.compatibility`),title:A(`errorBoundary.title`),message:A(`errorBoundary.message`),detailsLabel:A(`errorBoundary.details`),reloadLabel:A(`errorBoundary.reload`),children:(0,Z.jsx)(Kk,{apiBase:t,active:_===`compatibility`,onCountChange:k})})}),Nt&&(0,Z.jsx)(hw,{model:Nt,saving:Bt,requestError:Ht,currentNamePending:Kt,mutationOutcomeUnknown:Wt?.confirmed===!1,onRetry:Wt?()=>void br(Wt.value):void 0,onEdit:()=>Gt(null),onSave:e=>void br(e),onReset:()=>void br(null),onClose:yr}),Ft&&(0,Z.jsx)(Fw,{model:Ft,apiBase:t,onRefresh:e=>_r(!0,e),onClose:()=>{let e=Lt.current;It(null),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)}},`${t}/${Ft.namespaced}`),Rt&&(0,Z.jsx)(Uw,{row:Rt,apiBase:t,onRefresh:e=>_r(!0,e),onFeedback:Re,onClose:()=>zt(null)},`${t}/${Rt.namespaced}`)]})}function EA(e){return[...new Set(e.filter(e=>!e.disabled&&!e.initialSelectionPending).map(e=>e.namespaced))]}function DA({apiBase:e,value:t,disabled:n,onChange:r}){let i=c(),a=Fd(`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=EA(o.data??[]),l=t!==``&&!s.includes(t),u=[{value:``,label:i(`advisor.modelClear`)},...l?[{value:t,label:t}]:[],...s.map(e=>({value:e,label:e}))];return(0,Z.jsxs)(`div`,{"aria-busy":o.showSkeleton||o.refreshing,children:[(0,Z.jsx)($,{id:`advisor-model`,value:t,options:u,label:i(`advisor.model`),describedBy:`advisor-model-hint`,disabled:n||o.showSkeleton,onChange:r}),(0,Z.jsx)(`p`,{id:`advisor-model-hint`,className:`muted setting-hint`,children:i(`advisor.modelHint`)}),o.showSkeleton&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`common.loading`)}),o.showError&&!o.showSkeleton&&(0,Z.jsxs)(Q,{tone:`err`,children:[i(`advisor.modelsLoadFailed`),` `,(0,Z.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,Z.jsxs)(Q,{tone:`warn`,children:[i(`advisor.modelsEmpty`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:()=>a.refresh(),children:i(`common.retry`)})]}),!o.showSkeleton&&!o.showError&&l&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`advisor.modelUnavailable`)})]})}var OA={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 kA({entries:e}){let t=c();if(!e.length)return(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-1.5 px-6 py-10 text-center`,children:[(0,Z.jsx)(`span`,{className:`mb-1 grid size-9 place-items-center rounded-[10px] bg-surface text-fg-muted`,"aria-hidden":`true`,children:(0,Z.jsx)(xc,{icon:kc,size:18,strokeWidth:1.8})}),(0,Z.jsx)(`p`,{className:`m-0 text-[14px] font-medium text-fg`,children:t(`advisor.activity.empty`)}),(0,Z.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,Z.jsx)(`div`,{className:`max-h-[480px] overflow-auto rounded-[12px]`,children:(0,Z.jsxs)(`table`,{className:`pv2-table advisor-activity-table w-full border-collapse text-[13px] text-fg`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`border-b border-line`,children:[(0,Z.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.activity.started`)}),(0,Z.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.activity.trigger`)}),(0,Z.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.model`)}),(0,Z.jsx)(`th`,{scope:`col`,className:n,children:t(`advisor.effort`)}),(0,Z.jsx)(`th`,{scope:`col`,className:Y(n,`text-right`),children:t(`advisor.activity.tokens`)}),(0,Z.jsx)(`th`,{scope:`col`,className:Y(n,`text-right`),children:t(`advisor.activity.duration`)})]})}),(0,Z.jsx)(`tbody`,{className:`divide-y divide-line`,children:e.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:Y(r,`font-mono text-xs text-fg-muted tabular-nums`),children:(0,Z.jsx)(`time`,{dateTime:new Date(e.startedAt).toISOString(),children:new Date(e.startedAt).toLocaleTimeString()})}),(0,Z.jsx)(`td`,{className:r,children:(0,Z.jsxs)(`div`,{className:`flex flex-col items-start gap-1`,children:[(0,Z.jsx)(`span`,{children:t(`advisor.activity.trigger.${e.trigger}`)}),(0,Z.jsx)(`span`,{className:Y(`rounded-full px-2 py-0.5 text-[11px] font-semibold`,OA[e.status]),children:t(`advisor.activity.status.${e.status}`)})]})}),(0,Z.jsxs)(`td`,{className:r,children:[(0,Z.jsx)(`code`,{className:`font-mono text-xs text-fg`,children:e.advisorModel}),(0,Z.jsx)(`div`,{className:`mt-0.5`,children:(0,Z.jsx)(`code`,{className:`font-mono text-xs text-fg-subtle`,children:e.workerModel})})]}),(0,Z.jsx)(`td`,{className:r,children:(0,Z.jsxs)(`code`,{className:`font-mono text-xs`,children:[e.requestedEffort,` → `,e.effectiveEffort??t(`logs.tokens.unreported`)]})}),(0,Z.jsx)(`td`,{className:Y(r,`num text-right font-mono text-xs tabular-nums`),children:e.usage?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{title:t(`logs.tokens.input`),children:e.usage.inputTokens??`—`}),` / `,(0,Z.jsx)(`span`,{title:t(`logs.tokens.output`),children:e.usage.outputTokens??`—`})]}):(0,Z.jsx)(`span`,{className:`font-sans text-fg-subtle`,children:t(`logs.tokens.unreported`)})}),(0,Z.jsx)(`td`,{className:Y(r,`num text-right font-mono text-xs tabular-nums`),children:e.durationMs===null?`—`:(0,Z.jsxs)(Z.Fragment,{children:[e.durationMs,` ms`]})})]},e.id))})]})})}function AA({apiBase:e}){let t=c(),[n,r]=(0,X.useState)(!1),i=Fd(`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,Z.jsxs)(`section`,{"aria-labelledby":`advisor-activity-title`,className:`min-w-0 rounded-card bg-surface p-1`,children:[(0,Z.jsxs)(`header`,{className:`flex flex-col gap-0.5 px-4 pt-3 pb-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`h3`,{id:`advisor-activity-title`,className:`m-0 text-[15px] leading-5 font-semibold text-fg`,children:t(`advisor.activity.title`)}),(0,Z.jsx)(Ic,{label:t(`proxyV2.detailsFor`,{name:t(`advisor.activity.title`)}),expanded:n,controls:`advisor-activity-note`,onClick:()=>r(e=>!e)})]}),(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-[18px] text-fg-muted`,children:t(`proxyV2.activityLede`)}),(0,Z.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,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col rounded-[12px] bg-raised ring-1 ring-line`,children:[a.showSkeleton&&(0,Z.jsx)(`p`,{className:`m-0 px-4 py-6 text-[13px] text-fg-muted`,children:t(`common.loading`)}),a.showError&&(0,Z.jsx)(`div`,{className:`p-3`,children:(0,Z.jsxs)(Q,{tone:`err`,children:[t(`advisor.activity.failed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i.refresh(),children:t(`common.retry`)})]})}),a.data&&(0,Z.jsx)(kA,{entries:a.data.entries})]})]})}function jA({agreed:e,disabled:t,onChange:n}){let r=c();return(0,Z.jsxs)(`section`,{"aria-labelledby":`advisor-consent-title`,className:Y(`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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:Y(`grid size-7 shrink-0 place-items-center rounded-[8px]`,e?`bg-raised text-fg`:`bg-raised text-warning`),"aria-hidden":`true`,children:(0,Z.jsx)(xc,{icon:Mc,size:16,strokeWidth:1.8})}),(0,Z.jsx)(`h3`,{id:`advisor-consent-title`,className:`m-0 text-[15px] leading-5 font-semibold text-fg`,children:r(`proxyV2.consentTitle`)}),(0,Z.jsx)(`span`,{className:Y(`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,Z.jsxs)(`label`,{className:`flex cursor-pointer items-start gap-3 rounded-control bg-raised p-3 ring-1 ring-line`,children:[(0,Z.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,Z.jsx)(`span`,{className:`text-[13px] leading-[19px] text-fg`,children:r(`advisor.consent.label`)})]}),(0,Z.jsxs)(`details`,{className:`advisor-notices pv2-more`,children:[(0,Z.jsx)(`summary`,{children:r(`advisor.notices`)}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsx)(Q,{tone:`warn`,children:r(`advisor.costNote`)}),(0,Z.jsx)(Q,{tone:`warn`,children:r(`advisor.privacyNote`)}),(0,Z.jsx)(Q,{tone:`warn`,children:r(`advisor.disclosure`)})]})]})]})}var MA=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],NA=`w-[16rem] max-w-full max-[640px]:w-full`;function PA({apiBase:e,initial:t}){let n=c(),[r,i]=(0,X.useState)(t),[a,o]=(0,X.useState)(t),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(``),m=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{m.current!==null&&(clearTimeout(m.current),m.current=null)},[]);let h=(0,X.useCallback)(async()=>{m.current!==null&&(clearTimeout(m.current),m.current=null),d(!1),l(!0),p(``);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,...t.maxConsultationsPerTask===void 0?{}:{maxConsultationsPerTask:t.maxConsultationsPerTask},timeoutMs:t.timeoutMs,contextSharingConsent:t.contextSharingConsent})});if(!n.ok){let e=await n.json().catch(()=>null);p(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),d(!0),m.current=setTimeout(()=>{m.current=null,d(!1)},2500)}catch(e){p(e instanceof Error?e.message:String(e))}finally{l(!1)}},[e,a]),g=(0,X.useCallback)(e=>{p(``),o(t=>({...t,...e}))},[]),_=JSON.stringify(a)!==JSON.stringify(r),v=a.enabled&&a.model.trim()===``,y=a.enabled&&a.model.trim()!==``&&a.contextSharingConsent!==`v1`;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Fc,{id:`advisor-settings`,title:n(`proxyV2.advisorSettings`),children:[(0,Z.jsx)(Lc,{label:n(`advisor.enabled`),hint:n(`proxyV2.enabledHint`),inline:!0,control:(0,Z.jsxs)(`label`,{className:`toggle`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:a.enabled,disabled:s,"aria-label":n(`advisor.enabled`),onChange:e=>g({enabled:e.target.checked})}),(0,Z.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}),(0,Z.jsx)(Lc,{className:`advisor-model-row`,label:n(`advisor.model`),labelFor:`advisor-model`,control:(0,Z.jsx)(`div`,{className:NA,children:(0,Z.jsx)(DA,{apiBase:e,value:a.model,disabled:s,onChange:e=>g({model:e})})})}),(0,Z.jsx)(Lc,{label:n(`advisor.effort`),labelFor:`advisor-effort`,hint:n(`proxyV2.effortHint`),control:(0,Z.jsx)($,{id:`advisor-effort`,value:a.effort,disabled:s,fullWidth:!0,className:NA,options:MA.map(e=>({value:e,label:n(`models.reasoningEffort.${e}`)})),onChange:e=>g({effort:e})})}),(0,Z.jsx)(Lc,{label:n(`advisor.policy`),labelFor:`advisor-policy`,hint:n(`proxyV2.policyHint`),control:(0,Z.jsx)($,{id:`advisor-policy`,value:a.policy,disabled:s,fullWidth:!0,className:NA,options:[{value:`manual`,label:n(`advisor.policy.manual`)},{value:`preflight`,label:n(`advisor.policy.preflight`)},{value:`adaptive`,label:n(`advisor.policy.adaptive`)}],onChange:e=>g({policy:e})})}),a.policy===`adaptive`&&(0,Z.jsx)(Lc,{label:n(`advisor.taskLimit`),labelFor:`advisor-task-limit`,hint:n(`proxyV2.taskLimitHint`),details:n(`advisor.adaptiveNote`),control:(0,Z.jsx)($,{id:`advisor-task-limit`,value:String(a.maxConsultationsPerTask??3),disabled:s,fullWidth:!0,className:NA,options:[1,2,3].map(e=>({value:String(e),label:String(e)})),onChange:e=>g({maxConsultationsPerTask:Number(e)})})}),(0,Z.jsx)(Lc,{label:n(`advisor.timeout`),labelFor:`advisor-timeout`,hint:n(`proxyV2.timeoutHint`),control:(0,Z.jsx)(`input`,{id:`advisor-timeout`,className:Y(`input mono`,NA),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)&&g({timeoutMs:n})}})})]}),(0,Z.jsx)(jA,{agreed:a.contextSharingConsent===`v1`,disabled:s,onChange:e=>g({contextSharingConsent:e?`v1`:null})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[v&&(0,Z.jsx)(Q,{tone:`warn`,children:n(`advisor.warning.noModel`)}),y&&(0,Z.jsx)(Q,{tone:`warn`,children:n(`advisor.consent.required`)}),f&&(0,Z.jsx)(Q,{tone:`err`,children:f}),u&&(0,Z.jsx)(Q,{tone:`ok`,children:n(`advisor.saved`)}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-3`,children:[_&&!s&&(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted`,role:`status`,children:n(`proxyV2.unsaved`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!_||s,onClick:()=>void h(),children:n(s?`common.loading`:`advisor.save`)})]})]})]})}function FA({apiBase:e}){let t=c(),[n,r]=(0,X.useState)(!1),i=Fd(`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,Z.jsxs)(`div`,{className:`pv2-page flex max-w-[60rem] flex-col gap-5`,children:[(0,Z.jsxs)(`header`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:t(`nav.advisor`)}),(0,Z.jsx)(Ic,{label:t(`proxyV2.detailsFor`,{name:t(`nav.advisor`)}),expanded:n,controls:`advisor-about`,onClick:()=>r(e=>!e)})]}),(0,Z.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[14px] leading-[1.55] text-fg-muted`,children:t(`proxyV2.advisorLede`)}),(0,Z.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,Z.jsx)(Q,{tone:`warn`,children:t(`common.loading`)}),a.showError&&!a.showSkeleton&&(0,Z.jsxs)(Q,{tone:`err`,children:[t(`advisor.loadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i.refresh(),children:t(`common.retry`)})]}),a.data!==void 0&&(0,Z.jsx)(PA,{apiBase:e,initial:a.data.settings},i.hasSucceeded?`ready`:`cold`),(0,Z.jsx)(AA,{apiBase:e})]})}function IA(e){return(0,Z.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...e,children:[(0,Z.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9.5`}),(0,Z.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,Z.jsx)(`path`,{d:`M12 17h.01`})]})}function LA({label:e,children:t}){let n=c();return(0,Z.jsx)(`span`,{className:`inline-flex shrink-0 items-center text-fg-subtle transition-colors hover:text-fg-muted`,children:(0,Z.jsxs)(Pn,{content:t,side:`bottom`,maxWidth:380,children:[(0,Z.jsx)(IA,{width:15,height:15,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:n(`subagentsV2.moreAbout`,{label:e})})]})})}function RA({id:e,title:t,lede:n,meta:r,actions:i,below:a,children:o,className:s,headClassName:c,busy:l}){let u=(0,X.useId)();return(0,Z.jsxs)(`section`,{id:e,"aria-labelledby":u,"aria-busy":l,className:Y(`flex min-w-0 scroll-mt-[72px] flex-col rounded-[12px] bg-surface ring-1 ring-inset ring-line`,s),children:[(0,Z.jsxs)(`div`,{className:Y(`flex min-w-0 flex-wrap items-start gap-x-3 gap-y-2 px-4 pt-3.5 pb-3`,c),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[min(100%,15rem)] flex-1 flex-col gap-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(`h3`,{id:u,className:`m-0 truncate text-[14px] leading-5 font-semibold text-fg`,children:t}),r]}),n&&(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:n})]}),i&&(0,Z.jsx)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 max-sm:w-full`,children:i})]}),a&&(0,Z.jsx)(`div`,{className:`px-4 pb-3`,children:a}),o]})}function zA({children:e,className:t,as:n=`div`}){return(0,Z.jsx)(n,{className:Y(`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 BA({children:e,className:t}){return(0,Z.jsx)(`div`,{className:Y(`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 VA({label:e,hint:t,help:n,control:r,children:i,className:a}){return(0,Z.jsxs)(`div`,{className:Y(`flex min-w-0 flex-col gap-2 px-4 py-3.5`,a),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[min(100%,12rem)] flex-1 flex-col gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5 text-[14px] leading-5 font-medium text-fg`,children:[e,n]}),t&&(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:t})]}),r&&(0,Z.jsx)(`div`,{className:`flex max-w-full min-w-0 flex-wrap items-center justify-end gap-2`,children:r})]}),i]})}function HA({children:e}){return(0,Z.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 UA=Y(`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`),WA=`grid size-6 shrink-0 place-items-center rounded-[7px] text-[12px] font-medium tabular-nums ring-1 ring-inset`;function GA(e){let t=c(),[n,r]=(0,X.useState)(!1),i=(0,X.useId)();return{open:n,button:(0,Z.jsx)(`button`,{type:`button`,className:Y(UA,`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,Z.jsx)(IA,{"aria-hidden":`true`})}),panel:(e,t)=>(0,Z.jsx)(`div`,{id:i,hidden:!n,className:Y(`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 KA(e,t){let n=new Set(t);return[...new Set([...e.filter(e=>n.has(e)),...t])]}function qA({apiBase:e,roster:t,id:n,onForceChange:r}){let i=c(),a=GA(i(`sub.forceTitle`)),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(0),[y,b]=(0,X.useState)(null),x=d||y?.retry!==_||y.t!==i,S=(0,X.useRef)(!1),C=(0,X.useRef)(!1);(0,X.useEffect)(()=>{C.current=!0,S.current=!0;let t=new AbortController,n=!1;return(async()=>{try{let r=await zn(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),u(a.force??``),m(``)}catch{n||m(i(`sub.loadFail`))}finally{n||(S.current=!1,b({retry:_,t:i}))}})(),()=>{n=!0,C.current=!1,t.abort()}},[e,_,i]);async function w(t){if(!(!o||x||S.current)){S.current=!0,f(!0),m(``),g(!1);try{let n=await zn(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}),u(n?.force??l),g(!0),v(e=>e+1)}catch{C.current&&m(i(`sub.saveFailed`))}finally{S.current=!1,C.current&&f(!1)}}}let T=KA(t,o?.forceAvailable??[]),E=o?.force??l,D=T.includes(E),O=o?.forceStatus,k=o?o.force:void 0;(0,X.useEffect)(()=>{r?.(k)},[k,r]);let A=[o?.force&&(!D||O?.targetValid===!1)&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`sub.forceInvalid`)},`invalid`),o?.force&&O?.support===`unsupported`&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`sub.forceOld`)},`old`),o?.force&&(!O||O.support===`unknown`)&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`sub.forceUnknown`)},`unknown`),o?.force&&O?.settingsOverride&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`sub.forceOverride`)},`override`),o?.force&&O?.settingsReadable===!1&&(0,Z.jsx)(Q,{tone:`warn`,children:i(`sub.forceSettingsUnknown`)},`settings`),h&&(0,Z.jsx)(Q,{tone:`ok`,children:i(`sub.forceSaved`)},`saved`),p&&(0,Z.jsxs)(Q,{tone:`err`,children:[p,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:x,onClick:()=>v(e=>e+1),children:i(`common.retry`)})]},`error`)].filter(Boolean);return(0,Z.jsxs)(RA,{id:n,title:i(`sub.forceTitle`),lede:i(`subagentsV2.forceLede`),meta:a.button,actions:(0,Z.jsx)(kn,{on:!!o?.force,disabled:!o||x||!o.force&&!D,label:i(`sub.forceTitle`),onClick:()=>{w(o?.force?null:l)}}),below:a.panel((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:i(`sub.forceHelp`)}),(0,Z.jsx)(`p`,{children:i(`sub.forceScope`)})]})),children:[(0,Z.jsx)(zA,{children:(0,Z.jsxs)(`label`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3`,children:[(0,Z.jsx)(`span`,{className:`min-w-[min(100%,12rem)] flex-1 text-[14px] leading-5 font-medium text-fg`,children:i(`sub.forceModel`)}),(0,Z.jsx)($,{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):u(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,Z.jsx)(`div`,{className:`flex flex-col gap-2 px-4 py-3`,children:A})]})}var JA=Y(`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 YA({decrementLabel:e,incrementLabel:t,onDecrement:n,onIncrement:r,stepDisabled:i,unit:a,className:o,inputClassName:s,...c}){return(0,Z.jsxs)(`span`,{className:Y(`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,Z.jsx)(`button`,{type:`button`,className:Y(JA,`border-r border-line`),disabled:i,"aria-label":e,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Z.jsx)(lt,{"aria-hidden":`true`})}),(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center`,children:[(0,Z.jsx)(`input`,{type:`number`,...c,className:Y(`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,Z.jsx)(`span`,{className:`pr-2 font-mono text-[12px] text-fg-subtle select-none`,children:a})]}),(0,Z.jsx)(`button`,{type:`button`,className:Y(JA,`border-l border-line`),disabled:i,"aria-label":t,onMouseDown:e=>e.preventDefault(),onClick:r,children:(0,Z.jsx)(be,{"aria-hidden":`true`})})]})}var XA=[`maxConcurrentChildren`,`maxPhysicalSends`,`maxDistinctChildren`],ZA={maxConcurrentChildren:[`workflowBudget.maxConcurrentChildren`,`workflowBudget.maxConcurrentChildrenHint`],maxPhysicalSends:[`workflowBudget.maxPhysicalSends`,`workflowBudget.maxPhysicalSendsHint`],maxDistinctChildren:[`workflowBudget.maxDistinctChildren`,`workflowBudget.maxDistinctChildrenHint`]},QA=e=>typeof e==`number`&&Number.isInteger(e);function $A(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||!QA(t.windowMs))throw Error(`Missing workflow budget settings`);let i={values:{},defaults:{},bounds:{},windowMinutes:Math.round(t.windowMs/6e4)};for(let e of XA){let a=r[e];if(!QA(t[e])||!QA(n[e])||!a||!QA(a.min)||!QA(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 ej=e=>({maxConcurrentChildren:String(e.maxConcurrentChildren),maxPhysicalSends:String(e.maxPhysicalSends),maxDistinctChildren:String(e.maxDistinctChildren)});function tj(e,t){if(!/^\d+$/.test(e.trim()))return;let n=Number(e.trim());return n>=t.min&&n<=t.max?n:void 0}function nj({apiBase:e,id:t}){return(0,Z.jsx)(rj,{apiBase:e,id:t},e)}function rj({apiBase:t,id:n}){let r=c(),i=GA(r(`workflowBudget.title`)),[a,o]=(0,X.useState)(),[s,l]=(0,X.useState)({maxConcurrentChildren:``,maxPhysicalSends:``,maxDistinctChildren:``}),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(!1),_=(0,X.useRef)(null),v=(0,X.useCallback)(e=>{o(e),l(ej(e.values))},[]),y=(0,X.useCallback)(async()=>{if(_.current)return;let n=e(15e3);_.current=n,p(!1);try{let e=$A(await Qn(await fetch(t+`/api/workflow-budget/settings`,{signal:n.signal})));g.current&&_.current===n&&v(e)}catch{g.current&&_.current===n&&p(!0)}finally{n.clear(),_.current===n&&(_.current=null)}},[t,v]);(0,X.useEffect)(()=>{g.current=!0;let e=window.setTimeout(()=>{y()},0);return()=>{window.clearTimeout(e),g.current=!1,_.current?.controller.abort(),_.current?.clear(),_.current=null}},[y]);let b=a?Object.fromEntries(XA.map(e=>[e,tj(s[e],a.bounds[e])])):void 0,x=b!==void 0&&XA.every(e=>b[e]!==void 0),S=a!==void 0&&b!==void 0&&XA.some(e=>b[e]!==a.values[e]),C=a!==void 0&&XA.every(e=>a.values[e]===a.defaults[e]),w=async(n=!1)=>{if(_.current||a===void 0||!n&&(!x||b===void 0))return;let r=n||XA.every(e=>b?.[e]===a.defaults[e])?null:Object.fromEntries(XA.map(e=>[e,b?.[e]])),i=e(15e3);_.current=i,d(!0),h(null);try{let e=$A(await Qn(await fetch(t+`/api/workflow-budget/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:i.signal,body:JSON.stringify(r)})));g.current&&_.current===i&&(v(e),h(`saved`))}catch{g.current&&_.current===i&&h(`failed`)}finally{i.clear(),g.current&&_.current===i&&d(!1),_.current===i&&(_.current=null)}},T=u||a===void 0||f,E=(e,t)=>{l(n=>({...n,[e]:t})),h(null)};return(0,Z.jsxs)(RA,{id:n,title:r(`workflowBudget.title`),lede:r(`subagentsV2.budgetLede`),meta:i.button,busy:u||a===void 0&&!f,below:i.panel((0,Z.jsx)(`p`,{children:r(`workflowBudget.description`,{minutes:a?.windowMinutes??10})})),children:[f&&(0,Z.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,Z.jsx)(`span`,{className:`flex-1`,children:r(`workflowBudget.loadFailed`)}),(0,Z.jsx)(lp,{size:`sm`,variant:`outline`,onClick:()=>{y()},children:r(`common.retry`)})]}),(0,Z.jsx)(zA,{children:XA.map(e=>{let[t,n]=ZA[e],i=r(t),o=a?.bounds[e]??{min:0,max:0},c=a!==void 0&&b?.[e]===void 0,l=`workflow-budget-`+e+`-hint`;return(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[min(100%,12rem)] flex-1 flex-col gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5 text-[14px] leading-5 font-medium text-fg`,children:[i,(0,Z.jsx)(LA,{label:i,children:r(n)})]}),(0,Z.jsx)(`span`,{className:`text-[12px] leading-4 text-fg-subtle tabular-nums`,id:l,children:a&&r(`workflowBudget.range`,{default:a.defaults[e],min:o.min,max:o.max})}),c&&(0,Z.jsx)(`span`,{className:`text-[12px] leading-4 text-danger`,role:`alert`,children:r(`workflowBudget.invalid`,{min:o.min,max:o.max})})]}),(0,Z.jsx)(YA,{min:o.min,max:o.max,step:1,inputMode:`numeric`,value:s[e],readOnly:T,"aria-disabled":T,"aria-label":i,"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:r(`workflowBudget.increase`,{label:i}),decrementLabel:r(`workflowBudget.decrease`,{label:i}),onIncrement:()=>E(e,Ch(s[e],1,o.min,o.max)),onDecrement:()=>E(e,Ch(s[e],-1,o.min,o.max))})]},e)})}),(0,Z.jsxs)(BA,{className:`sticky bottom-0 z-[1] rounded-b-[12px] bg-surface`,children:[(0,Z.jsx)(`span`,{className:`mr-auto min-w-0`,"aria-live":`polite`,children:m===`failed`?(0,Z.jsx)(`span`,{className:`text-danger`,role:`alert`,children:r(`workflowBudget.saveFailed`)}):m===`saved`?(0,Z.jsx)(`span`,{className:`text-success`,role:`status`,children:r(`workflowBudget.saved`)}):(0,Z.jsx)(`span`,{className:S?`text-fg`:void 0,children:r(S?`subagentsV2.unsaved`:`subagentsV2.noChanges`)})}),(0,Z.jsx)(lp,{size:`sm`,variant:`ghost`,disabled:T||!S&&C,onClick:()=>{w(!0)},children:r(`workflowBudget.reset`)}),(0,Z.jsx)(lp,{size:`sm`,variant:`primary`,disabled:T||!S||!x,onClick:()=>{w()},children:r(`common.save`)})]})]})}var ij=`section`;function aj(e,t){return[e,ij,t].join(`-`)}function oj(e){return[e,ij,``].join(`-`)}var sj=1200;function cj({scope:e,items:t,ariaLabel:n,mobileReadingLine:r}){let[i,a]=(0,X.useState)(()=>r&&window.matchMedia(`(max-width: 760px)`).matches?r:72);(0,X.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,X.useState)(t[0]?.id??``),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useCallback)(()=>{c.current=null,l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=(0,X.useCallback)(()=>{u();let n=null,r=1/0;for(let a of t){let t=document.getElementById(aj(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,X.useEffect)(()=>()=>u(),[u]),(0,X.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(aj(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(aj(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(oj(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(aj(e,t));n&&(c.current=t,l.current!==null&&clearTimeout(l.current),l.current=setTimeout(d,sj),s(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,Z.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,Z.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===t.id,"aria-controls":aj(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,Z.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}var lj=1500,uj={fast:`integrations.lazycodexRoles.auto.tierFast`,standard:`integrations.lazycodexRoles.auto.tierStandard`,frontier:`integrations.lazycodexRoles.auto.tierFrontier`},dj={glance:`integrations.lazycodexRoles.auto.effortGlance`,measured:`integrations.lazycodexRoles.auto.effortMeasured`,thorough:`integrations.lazycodexRoles.auto.effortThorough`,exhaustive:`integrations.lazycodexRoles.auto.effortExhaustive`};function fj({apiBase:e,model:t,effort:n,available:r,saving:i,onAccept:a}){let o=c(),[s,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),g=e=>{let t=r.find(t=>t.namespaced===e);return t?He(`${t.provider}/${t.model}`,o):e},_=async()=>{d(!0),p(null);try{let t=await fetch(`${e}/api/injection-model/suggest`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({work:s.trim()})});h(await zn(t,o(`sub.suggest.failed`))??null)}catch(e){h(null),p(e instanceof Error&&e.message?e.message:o(`sub.suggest.failed`))}finally{d(!1)}},v=m?.proposal,y=!!v?.proposedModel&&v.proposedModel===t&&(v.proposedEffort??``)===n,b=u?o(`sub.suggest.running`):m?o(`sub.suggest.title`):``;return(0,Z.jsxs)(`div`,{className:`swi-suggest`,children:[(0,Z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:b}),(0,Z.jsx)(`label`,{className:`swi-suggest-label`,htmlFor:`swi-suggest-work`,children:o(`sub.suggest.label`)}),(0,Z.jsxs)(`div`,{className:`swi-suggest-input`,children:[(0,Z.jsx)(`textarea`,{id:`swi-suggest-work`,className:`input`,rows:2,maxLength:lj,value:s,placeholder:o(`sub.suggest.placeholder`),onChange:e=>l(e.target.value),disabled:u}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:u||i||s.trim()===``,onClick:()=>void _(),children:o(u?`sub.suggest.running`:`sub.suggest.submit`)})]}),f&&(0,Z.jsx)(Q,{tone:`err`,children:f}),m&&v&&(0,Z.jsxs)(`section`,{className:`swi-suggest-result`,"aria-label":o(`sub.suggest.title`),children:[(0,Z.jsxs)(`div`,{className:`swi-suggest-head`,children:[v.tier&&v.effortIntent&&(0,Z.jsx)(`span`,{className:`font-semibold`,children:o(`integrations.lazycodexRoles.auto.tierEffort`,{tier:o(uj[v.tier]),effort:o(dj[v.effortIntent])})}),(0,Z.jsx)(`span`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.sizedWith`,{model:m.sizingModel})})]}),m.sizingError&&(0,Z.jsx)(Q,{tone:`warn`,children:o(`integrations.lazycodexRoles.auto.sizingFailed`,{error:m.sizingError})}),v.status===`unsized`?(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.unsized`,{reason:v.reason??``})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`swi-suggest-change`,children:[(0,Z.jsxs)(`span`,{children:[v.model?g(v.model):o(`dash.injectionNone`),v.effort?` · ${v.effort}`:``]}),(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),v.proposedModel?(0,Z.jsxs)(`strong`,{children:[g(v.proposedModel),v.proposedEffort?` · ${v.proposedEffort}`:``]}):(0,Z.jsx)(`span`,{className:`muted`,children:o(`integrations.lazycodexRoles.auto.unassigned`,{reason:v.reason??``})})]}),v.rationale&&(0,Z.jsx)(`p`,{children:v.rationale}),v.moveUpIf&&(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.moveUp`,{text:v.moveUpIf})}),v.moveDownIf&&(0,Z.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.moveDown`,{text:v.moveDownIf})})]}),(0,Z.jsxs)(`div`,{className:`swi-suggest-actions`,children:[y?(0,Z.jsx)(`span`,{className:`swi-suggest-done`,children:o(`integrations.lazycodexRoles.auto.alreadySet`)}):v.status===`proposed`&&v.proposedModel&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:i,onClick:()=>a({model:v.proposedModel,effort:v.proposedEffort??null}),children:o(`sub.suggest.accept`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:i,onClick:()=>h(null),children:o(`integrations.lazycodexRoles.auto.discard`)})]})]})]})}function pj({apiBase:e,model:t,effort:n,efforts:r,available:i,guidanceEnabled:a,syncCodexDefaults:o,saving:s,onSave:l,ultraMode:u,ultraSaving:d,onUltraModeSave:f,ultraLoadFailed:p,onUltraModeRetry:m,fallback:h,fallbackPollMs:g,fallbackBusy:_,availableModels:v,onFallbackChange:y,onFallbackPollMsChange:b,onFallbackSave:x,id:S}){let C=c(),w=(u.hintText??``).trim().length>0,T=i.some(e=>e.namespaced===t&&(e.provider!==`openai`||e.namespaced!==e.model)),E=u.enabled||u.multiAgentMode!==`v1`&&!(u.multiAgentMode===`v2`&&u.keepNativeChatGptOnV1),D=!p&&u.loaded===!0&&T&&E,O=new Set(v),k=new Set(h),[A,j]=(0,X.useState)(()=>({pollMs:g,text:String(g)}));Object.is(A.pollMs,g)||j({pollMs:g,text:Number.isFinite(g)?String(g):``});let M=(0,X.useRef)(null),[N,P]=(0,X.useState)(!1),[F,I]=(0,X.useState)(()=>({models:h,rows:h.map((e,t)=>({model:e,id:t})),nextId:h.length})),L=F.rows;if(F.models!==h){let e=[...F.rows],t=F.nextId;L=h.map(n=>{let r=e.findIndex(e=>e.model===n);return r>=0?e.splice(r,1)[0]:{model:n,id:t++}}),I({models:h,rows:L,nextId:t})}let R=(0,X.useRef)(null);(0,X.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()},[h]);let z=Number.isInteger(g)&&g>=5e3&&g<=6e5,B=(e,t)=>{let n=[...h],r=e+t;if(_||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`},y(n)},V=e=>{let t=Number(e),n=e.trim()!==``&&Number.isFinite(t)?t:NaN;j({pollMs:n,text:e}),b(n)},H=C(`sub.fallbackPoll`);return(0,Z.jsx)(RA,{id:S,className:`swi-delegation`,title:C(`subagentsV2.delegationTitle`),children:(0,Z.jsxs)(zA,{children:[p&&(0,Z.jsx)(VA,{className:`swi-delegation-row`,label:C(`sub.ultraMode`),hint:(0,Z.jsx)(`span`,{className:`text-danger`,children:C(`sub.ultraModeLoadFail`)}),control:(0,Z.jsx)(lp,{size:`sm`,variant:`outline`,onClick:m,children:C(`common.retry`)})}),(0,Z.jsx)(VA,{className:`swi-delegation-row swi-delegation-model-row`,label:C(`sub.delegation.model`),hint:C(`subagentsV2.delegationShort`),help:(0,Z.jsx)(LA,{label:C(`sub.delegation.model`),children:C(`sub.delegation.modelHint`)}),control:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)($,{value:t,options:[{value:``,label:C(`dash.injectionNone`)},...i.map(e=>({value:e.namespaced,label:He(`${e.provider}/${e.model}`,C)}))],onChange:e=>l({model:e||null,effort:n||null}),disabled:s,label:C(`dash.injectionLabel`),align:`right`}),t&&r.length>0&&(0,Z.jsx)($,{value:n,options:[{value:``,label:C(`dash.injectionEffortNone`)},...r.map(e=>({value:e,label:e}))],onChange:e=>l({model:t||null,effort:e||null}),disabled:s,label:C(`dash.injectionEffortLabel`),align:`right`}),(0,Z.jsx)(lp,{size:`sm`,variant:N?`outline`:`ghost`,"aria-expanded":N,onClick:()=>P(e=>!e),children:C(`sub.suggest.button`)})]}),children:N&&(0,Z.jsx)(fj,{apiBase:e,model:t,effort:n,available:i,saving:s,onAccept:l})}),D&&(0,Z.jsx)(`div`,{className:`swi-delegation-row swi-v2-compatibility px-4 py-3`,role:`note`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 rounded-[8px] bg-warning-soft px-3 py-2.5 text-[13px] leading-5`,children:[(0,Z.jsx)(`div`,{className:`font-semibold text-warning`,children:C(`sub.v2Compatibility.title`)}),(0,Z.jsx)(`p`,{className:`m-0 text-fg-muted`,children:C(`sub.v2Compatibility.risk`)}),(0,Z.jsx)(`p`,{className:`m-0 text-fg-muted`,children:C(`sub.v2Compatibility.recoveryUnknown`)}),(0,Z.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,Z.jsx)(VA,{className:`swi-delegation-row swi-fallback-editor`,label:C(`sub.fallbackLabel`),hint:C(`sub.fallbackHint`),children:(0,Z.jsxs)(`div`,{className:`swi-fallback-controls flex min-w-0 flex-col gap-2`,ref:M,children:[h.length>0&&(0,Z.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:h.map((e,t)=>(0,Z.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,Z.jsx)(`span`,{className:Y(`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,Z.jsxs)(`span`,{className:`swi-fallback-model flex min-w-0 flex-1 flex-col`,children:[(0,Z.jsx)(`span`,{className:`swi-fallback-name truncate font-mono text-[13px] text-fg`,children:e}),!O.has(e)&&(0,Z.jsx)(`span`,{className:`text-[12px] text-warning`,children:C(`sub.fallbackUnavailable`)})]}),(0,Z.jsxs)(`span`,{className:`swi-fallback-actions flex shrink-0 items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,className:UA,"data-action":`up`,onClick:()=>B(t,-1),disabled:_||t===0,"aria-label":C(`sub.moveUp`,{m:e}),children:(0,Z.jsx)(pt,{})}),(0,Z.jsx)(`button`,{type:`button`,className:UA,"data-action":`down`,onClick:()=>B(t,1),disabled:_||t===h.length-1,"aria-label":C(`sub.moveDown`,{m:e}),children:(0,Z.jsx)(Je,{})}),(0,Z.jsx)(`button`,{type:`button`,className:Y(UA,`hover:bg-danger-soft hover:text-danger`),"data-action":`remove`,onClick:()=>{let e=h.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,h.length-2)),action:`remove`},y(e)},disabled:_,"aria-label":C(`sub.removeAria`,{m:e}),children:(0,Z.jsx)(We,{})})]})]},L[t].id))}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Z.jsx)($,{value:``,label:C(`sub.fallbackAdd`),options:[{value:``,label:C(`sub.fallbackAdd`)},...v.filter(e=>!k.has(e)).map(e=>({value:e,label:e}))],onChange:e=>{e&&!k.has(e)&&y([...h,e])},disabled:_}),(0,Z.jsxs)(`div`,{className:`ml-auto flex items-center gap-2 text-[13px] text-fg-muted`,children:[(0,Z.jsx)(`label`,{htmlFor:`subagent-fallback-poll-ms`,children:H}),(0,Z.jsx)(YA,{id:`subagent-fallback-poll-ms`,min:5e3,max:6e5,step:1e3,value:A.text,onChange:e=>V(e.currentTarget.value),disabled:_,"aria-invalid":!z,stepDisabled:_,unit:`ms`,inputClassName:`w-24`,decrementLabel:C(`workflowBudget.decrease`,{label:H}),incrementLabel:C(`workflowBudget.increase`,{label:H}),onDecrement:()=>V(Ch(A.text,-1e3,5e3,6e5)),onIncrement:()=>V(Ch(A.text,1e3,5e3,6e5))})]}),(0,Z.jsx)(lp,{size:`sm`,variant:`primary`,onClick:x,disabled:_||!z,children:C(`common.save`)})]}),!z&&(0,Z.jsx)(`div`,{className:`text-[12px] text-danger`,role:`alert`,children:C(`sub.fallbackPollInvalid`)})]})}),(0,Z.jsx)(VA,{className:`swi-delegation-row`,label:C(`dash.syncCodexSubagentDefaults`),hint:C(`subagentsV2.syncShort`),help:(0,Z.jsx)(LA,{label:C(`dash.syncCodexSubagentDefaults`),children:C(`dash.syncCodexSubagentDefaultsHint`)}),control:(0,Z.jsx)(`button`,{type:`button`,className:`switch ${o?`on`:``}`,onClick:()=>l({syncCodexSubagentDefaults:!o}),disabled:s||!t,"aria-label":C(`dash.syncCodexSubagentDefaults`),"aria-pressed":o,children:(0,Z.jsx)(`span`,{className:`knob`})})}),(0,Z.jsxs)(`details`,{className:`swi-advanced`,children:[(0,Z.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,Z.jsx)(St,{className:`size-4 shrink-0 text-fg-subtle transition-transform duration-200 [details[open]>summary>&]:rotate-90`,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`text-[14px] font-medium text-fg`,children:C(`sub.advanced`)}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-[13px] text-fg-subtle`,children:C(`subagentsV2.advancedHint`)})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col divide-y divide-line border-t border-line`,children:[(0,Z.jsx)(VA,{className:`swi-delegation-row`,label:C(`models.v2Label`),hint:(0,Z.jsxs)(Z.Fragment,{children:[C(`subagentsV2.surfaceShort`),` `,(0,Z.jsx)(`a`,{className:`text-highlight hover:underline`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,children:C(`models.v2DocsLink`)})]}),help:(0,Z.jsx)(LA,{label:C(`models.v2Label`),children:(0,Z.jsx)(`span`,{className:`whitespace-pre-line`,children:C(`models.v2Help`)})}),control:(0,Z.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":C(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":u.multiAgentMode===e,className:`btn btn-sm${u.multiAgentMode===e?` btn-primary`:` btn-ghost`}`,disabled:d||p,onClick:()=>{u.multiAgentMode!==e&&f({multiAgentMode:e})},children:C(`models.v2Mode_${e}`)},e))})}),(0,Z.jsx)(VA,{className:`swi-delegation-row`,label:C(`dash.multiAgentGuidance`),hint:C(`subagentsV2.guidanceShort`),help:(0,Z.jsx)(LA,{label:C(`dash.multiAgentGuidance`),children:C(`dash.multiAgentGuidanceHint`)}),control:(0,Z.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>l({multiAgentGuidanceEnabled:!a}),disabled:s,"aria-label":C(`dash.multiAgentGuidance`),"aria-pressed":a,children:(0,Z.jsx)(`span`,{className:`knob`})})}),(0,Z.jsx)(VA,{className:`swi-delegation-row`,label:C(`sub.ultraMode`),hint:u.multiAgentV2Enabled?C(`subagentsV2.ultraShort`):(0,Z.jsx)(`span`,{className:`text-warning`,children:C(`sub.ultraModeV2Required`)}),help:(0,Z.jsx)(LA,{label:C(`sub.ultraMode`),children:C(`sub.ultraModeHint`)}),control:(0,Z.jsx)(`button`,{type:`button`,className:`switch ${w?`on`:``}`,onClick:()=>{w?f({multiAgentModeHintText:null}):u.recommendation&&f({multiAgentModeHintText:u.recommendation.text})},disabled:s||d||!w&&(!u.multiAgentV2Enabled||!u.recommendation),"aria-label":C(`sub.ultraMode`),"aria-pressed":w,children:(0,Z.jsx)(`span`,{className:`knob`})})}),w&&(0,Z.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor flex flex-col gap-2 px-4 py-3.5`,children:(0,Z.jsx)(mj,{initialHint:u.hintText??``,disabled:s||d,onSave:f,preset:u.recommendation?.text??null,labels:{text:C(`sub.ultraModeText`),preset:C(`sub.ultraModePreset`),save:C(`common.save`)}},u.hintText)})]})]})]})})}function mj({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,X.useState)(e);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(lp,{size:`sm`,variant:`ghost`,onClick:()=>{r!==null&&o(r)},disabled:t||r===null,children:i.preset}),(0,Z.jsx)(lp,{size:`sm`,variant:`primary`,onClick:()=>{a.trim().length!==0&&n({multiAgentModeHintText:a})},disabled:t||a.trim().length===0,children:i.save})]})]})}function hj({available:e,fallbackAvailable:t,chosen:n,onToggle:r,onMove:i,fallback:a,fallbackPollMs:o,fallbackBusy:s,onFallbackChange:l,onFallbackPollMsChange:u,onFallbackSave:d,delegation:f,settingsExtra:p}){let m=c(),[h,g]=(0,X.useState)(``),_=(0,X.useMemo)(()=>new Set(n),[n]),v=n.length>=5,y=Math.max(0,5-n.length),b=(0,X.useMemo)(()=>{let t=h.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,h]),x=(0,X.useMemo)(()=>[{id:`featured`,label:m(`sub.featured`),meta:`${n.length}/5`},{id:`models`,label:m(`sub.models`),meta:String(b.length)},{id:`settings`,label:m(`sub.settings`)}],[m,n.length,b.length]);return(0,Z.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,Z.jsx)(cj,{scope:`subagents`,items:x,ariaLabel:m(`sub.sections`)}),(0,Z.jsxs)(`div`,{className:`subagents-workspace-root flex flex-col gap-4`,children:[(0,Z.jsx)(RA,{id:aj(`subagents`,`featured`),className:`subagents-workspace-section`,headClassName:`swi-featured-head`,title:(0,Z.jsx)(`span`,{className:`swi-featured-title`,children:m(`sub.featured`)}),meta:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(HA,{children:(0,Z.jsxs)(`span`,{className:`swi-featured-count`,children:[n.length,`/`,5]})}),(0,Z.jsx)(LA,{label:m(`sub.orderHintAria`),children:(0,Z.jsx)(N,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),lede:m(`subagentsV2.featuredLede`),children:(0,Z.jsxs)(zA,{as:`ol`,children:[n.map((e,t)=>(0,Z.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,Z.jsx)(`span`,{className:Y(WA,`bg-surface text-fg ring-line-strong`),children:t+1}),(0,Z.jsx)(`span`,{className:`swi-featured-name min-w-0 flex-1 truncate font-mono text-[13px] text-fg`,children:lT(e)}),(0,Z.jsxs)(`span`,{className:`swi-featured-actions flex shrink-0 items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,className:UA,onClick:()=>i(t,-1),disabled:t===0,"aria-label":m(`sub.moveUp`,{m:e}),children:(0,Z.jsx)(pt,{})}),(0,Z.jsx)(`button`,{type:`button`,className:UA,onClick:()=>i(t,1),disabled:t===n.length-1,"aria-label":m(`sub.moveDown`,{m:e}),children:(0,Z.jsx)(Je,{})}),(0,Z.jsx)(`button`,{type:`button`,className:Y(UA,`hover:bg-danger-soft hover:text-danger`),onClick:()=>r(e),"aria-label":m(`sub.removeAria`,{m:e}),children:(0,Z.jsx)(We,{})})]})]},e)),Array.from({length:y},(e,t)=>(0,Z.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,Z.jsx)(`span`,{className:Y(WA,`border border-dashed border-line-strong text-fg-subtle ring-0`),"aria-hidden":`true`,children:n.length+t+1}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n.length===0&&t===0?m(`sub.noneSelected`):m(`subagentsV2.emptySlot`)})]},`free-${t}`))]})}),(0,Z.jsx)(RA,{id:aj(`subagents`,`models`),className:`subagents-workspace-section`,title:m(`sub.workspace.allModels`),meta:(0,Z.jsx)(HA,{children:b.length}),lede:v?m(`sub.workspace.featuredFull`):m(`subagentsV2.modelsLede`,{max:5}),actions:(0,Z.jsxs)(`label`,{className:`relative flex w-full items-center sm:w-72`,children:[(0,Z.jsx)(ze,{className:`pointer-events-none absolute left-2.5 size-4 text-fg-subtle`,"aria-hidden":`true`}),(0,Z.jsx)(`input`,{className:`input w-full pl-8`,type:`search`,value:h,onChange:e=>g(e.target.value),placeholder:m(`sub.search`),"aria-label":m(`sub.search`)})]}),children:(0,Z.jsx)(zA,{as:`ul`,className:`max-h-[min(30rem,60vh)] overflow-y-auto`,children:b.length===0?(0,Z.jsx)(`li`,{className:`px-4 py-6 text-center text-[13px] text-fg-muted`,children:m(`sub.noModels`)}):b.map(e=>{let t=_.has(e),i=t?n.indexOf(e)+1:null,a=!t&&v;return(0,Z.jsxs)(`li`,{className:`flex min-h-11 min-w-0 items-center gap-3 py-1.5 pr-2 pl-3.5`,children:[(0,Z.jsx)(yt,{className:`size-4 shrink-0 text-fg-subtle`,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:Y(`min-w-0 flex-1 truncate font-mono text-[13px]`,t?`text-fg`:`text-fg-muted`),children:lT(e)}),i!==null&&(0,Z.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:m(`subagentsV2.rank`,{n:i})}),(0,Z.jsxs)(`button`,{type:`button`,className:Y(`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":m(t?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:t?m(`sub.workspace.removeFromFeatured`,{m:e}):v?m(`sub.workspace.featuredFull`):m(`sub.workspace.addToFeatured`,{m:e}),children:[t?(0,Z.jsx)(ut,{"aria-hidden":`true`}):(0,Z.jsx)(be,{"aria-hidden":`true`}),m(t?`subagentsV2.added`:`subagentsV2.add`)]})]},e)})})}),(0,Z.jsxs)(`section`,{id:aj(`subagents`,`settings`),className:`subagents-workspace-section flex flex-col gap-4`,"aria-label":m(`sub.settings`),children:[(0,Z.jsx)(pj,{id:aj(`subagents`,`delegation`),apiBase:f.apiBase,model:f.model,effort:f.effort,efforts:f.efforts,available:f.available,guidanceEnabled:f.guidanceEnabled,syncCodexDefaults:f.syncCodexDefaults,saving:f.saving,onSave:f.onSave,ultraMode:f.ultraMode,ultraSaving:f.ultraSaving,onUltraModeSave:f.onUltraModeSave,ultraLoadFailed:f.ultraLoadFailed,onUltraModeRetry:f.onUltraModeRetry,fallback:a,fallbackPollMs:o,fallbackBusy:s,availableModels:t??e,onFallbackChange:l,onFallbackPollMsChange:u,onFallbackSave:d}),p]})]})]})}function gj(e){let[t,n]=(0,X.useState)(!1),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)([]),[d,f]=(0,X.useState)([]),[p,m]=(0,X.useState)(!0),[h,g]=(0,X.useState)(!1),_=(0,X.useCallback)(e=>{let t=af(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,X.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await Qn(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,X.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 Qn(n))}catch{}finally{i(!1)}}},[e,_,r])}}function _j({chosen:e,max:t,firstModel:n,firstEffort:r,pin:i,onJump:a}){let o=c(),s=e[0];return(0,Z.jsxs)(`section`,{"aria-label":o(`subagentsV2.nowTitle`),className:`flex flex-col gap-2`,children:[(0,Z.jsx)(`h3`,{className:`m-0 text-[12px] font-medium text-fg-subtle`,children:o(`subagentsV2.nowTitle`)}),(0,Z.jsxs)(`div`,{className:`grid gap-3 md:grid-cols-3`,children:[(0,Z.jsx)(vj,{label:o(`subagentsV2.nowOrder`),value:s?lT(s):o(`subagentsV2.nowOrderNone`),mono:!!s,muted:!s,caption:o(`subagentsV2.nowOrderCaption`,{n:e.length,max:t}),onClick:()=>a(`featured`)}),(0,Z.jsx)(vj,{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,Z.jsx)(vj,{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 vj({label:e,value:t,caption:n,mono:r,muted:i,on:a,onClick:o}){let s=c();return(0,Z.jsxs)(`button`,{type:`button`,onClick:o,className:Y(`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,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-[12px] font-medium text-fg-subtle`,children:[a!==void 0&&(0,Z.jsx)(`span`,{className:Y(`size-1.5 shrink-0 rounded-full`,a?`bg-success`:`bg-fg-subtle`),"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e}),(0,Z.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,Z.jsx)(St,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,Z.jsx)(`span`,{className:Y(`truncate text-[16px] leading-6 font-semibold tracking-[-0.01em]`,r&&`font-mono text-[15px]`,i?`text-fg-muted`:`text-fg`),children:t}),(0,Z.jsx)(`span`,{className:`truncate text-[12px] text-fg-muted`,children:n})]})}var yj={enabled:!1,hintText:null,recommendation:null,multiAgentV2Enabled:!1,multiAgentMode:`default`};function bj(e){return kd(e)}function xj(e){document.getElementById(aj(`subagents`,e))?.scrollIntoView({behavior:`smooth`,block:`start`})}function Sj({apiBase:e}){let t=c(),n=`ocx.subagents.v1:${e}`,r=bj(n),[i,a]=(0,X.useState)(()=>r?.chosen??[]),[o,s]=(0,X.useState)(()=>r?.fallback??[]),[l,u]=(0,X.useState)(()=>r?.pollMs??6e4),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(()=>Array.isArray(r?.fallback)&&Number.isInteger(r?.pollMs)),[h,g]=(0,X.useState)(()=>r?.fallbackAvailable),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(!0),x=(0,X.useRef)(null),S=(0,X.useRef)({fallback:r?.fallback,pollMs:r?.pollMs,fallbackAvailable:r?.fallbackAvailable}),C=(0,X.useRef)(0),w=(0,X.useRef)(0),T=(0,X.useRef)(!1),E=(0,X.useRef)(r),[D,O]=(0,X.useState)(``),[k,A]=(0,X.useState)(!1),j=(0,X.useRef)(!1),M=(0,X.useRef)(null),N=(0,X.useRef)(i),P=(0,X.useCallback)(e=>{N.current=e,a(e)},[]),F=gj(e),[I,L]=(0,X.useState)(void 0),[R,z]=(0,X.useState)(null),B=R?.apiBase===e,V=B?R.mode:yj,[H,U]=(0,X.useState)(!1),[W,ee]=(0,X.useState)(null),[te,ne]=(0,X.useState)(!1),G=(0,X.useRef)(0),K=(0,X.useRef)(e);(0,X.useEffect)(()=>{K.current=e,G.current++},[e]);let re=(0,X.useCallback)(async n=>{if(K.current!==e)return!1;let r=++G.current,i=await zn(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));if(!i||n?.aborted||r!==G.current||K.current!==e)return!1;ne(!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`,multiAgentMode:i.multiAgentMode??`default`}}),!0},[e,t]);(0,X.useEffect)(()=>{let e=new AbortController;return(async()=>{await re(e.signal)})().catch(()=>{e.signal.aborted||(A(!1),ne(!0),O(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[re,t]);let q=async n=>{if(H||!B||K.current!==e)return;let r=e;U(!0),O(``);try{if(await zn(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),K.current!==r||!await re())return;A(!0),O(t(`sub.ultraModeSaved`))}catch(e){if(K.current!==r)return;A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{U(!1)}},ie=(0,X.useCallback)(async()=>{try{if(!await re())return;A(!1),O(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{A(!1),ne(!0),O(t(`sub.ultraModeLoadFail`))}},[re,t]),ae=(0,X.useCallback)(async()=>{x.current?.abort();let r=new AbortController;x.current=r;let{signal:i}=r,a=C.current;try{let r=await zn(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),u(o.pollMs),g(o.fallbackAvailable),m(!0),v(``),E.current&&(E.current={...E.current,...o},Nd(n,E.current))}catch(e){if(i.aborted||a!==C.current||T.current)return;m(!1),v(e instanceof Error&&!(e instanceof SyntaxError)?e.message:t(`sub.loadFail`))}finally{i.aborted||b(!1)}},[e,n,t]);(0,X.useEffect)(()=>((async()=>{await ae()})(),()=>{x.current?.abort()}),[ae]);let oe=(0,X.useCallback)(async r=>{let i=w.current,a=await zn(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),Nd(n,l),l},[e,n,P,t]),se=Fd(n,[e],oe,{isEmpty:()=>!1,initialData:r??void 0}),{state:ce}=se,le=se.refresh,ue=ce.data??r,J=ue?.available??[],de=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 zn(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:J,chosen:a},Nd(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`})))},fe=e=>{w.current+=1,P(e),de(e)},pe=e=>{let t=N.current;!t.includes(e)&&t.length>=5||fe(t.includes(e)?t.filter(t=>t!==e):[...t,e])},me=(e,t)=>{let n=e+t,r=[...N.current];n<0||n>=r.length||([r[e],r[n]]=[r[n],r[e]],fe(r))},he=async()=>{if(!p||T.current||!Number.isInteger(l)||l<5e3||l>6e5)return;T.current=!0,C.current+=1;let r=e;f(!0),O(``);try{let i=await zn(await fetch(`${e}/api/subagent-model-fallback`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:o,pollMs:l})}),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),u(i.pollMs),S.current={...S.current,fallback:i.models,pollMs:i.pollMs};let a={available:J,chosen:E.current?.chosen??[],...S.current};E.current=a,Nd(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,f(!1)}};if(ce.showSkeleton&&!ue)return(0,Z.jsx)(NE,{label:t(`sub.loading`),rows:4});if(ce.kind===`failed-cold`){let e=ce.error instanceof Error?ce.error.message:t(`sub.loadFail`);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Q,{tone:`err`,children:e}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>le(),children:t(`common.retry`)})]})}let ge=F.available.find(e=>e.namespaced===F.model),_e=F.model?ge?He(`${ge.provider}/${ge.model}`,t):F.model:``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`page-head flex-col items-start gap-1.5`,children:[(0,Z.jsx)(`h2`,{children:t(`nav.subagents`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[14px] text-fg-muted`,children:t(`subagentsV2.lede`)})]}),(0,Z.jsx)(`div`,{className:`mt-5 mb-6`,children:(0,Z.jsx)(_j,{chosen:i,max:5,firstModel:_e,firstEffort:F.effort,pin:I,onJump:xj})}),D&&(0,Z.jsx)(Q,{tone:k?`ok`:`err`,children:D}),ce.showError&&(0,Z.jsx)(Q,{tone:`err`,children:t(`sub.loadFail`)}),_&&(0,Z.jsxs)(Q,{tone:`err`,children:[t(`sub.fallbackLabel`),`: `,t(`sub.loadFail`),_!==t(`sub.loadFail`)&&(0,Z.jsxs)(Z.Fragment,{children:[` `,_]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:y,onClick:()=>{b(!0),ae()},children:t(`common.retry`)})]}),(0,Z.jsx)(hj,{available:J,fallbackAvailable:h??[],chosen:i,onToggle:pe,onMove:me,fallback:o,fallbackPollMs:l,fallbackBusy:d||!p,onFallbackChange:e=>{C.current+=1,s(e)},onFallbackPollMsChange:e=>{C.current+=1,u(e)},onFallbackSave:()=>{he()},settingsExtra:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(qA,{apiBase:e,roster:i,id:aj(`subagents`,`pin`),onForceChange:L},e),(0,Z.jsx)(nj,{apiBase:e,id:aj(`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`?ee({mode:t.multiAgentMode,apiBase:e}):q(t)},ultraLoadFailed:te,onUltraModeRetry:()=>{ie()}}}),W&&W.apiBase===e&&(0,Z.jsx)(Pr,{reason:`selection`,mode:W.mode,docsUrl:`https://opencodex.me/guides/subagent-v1-default/`,busy:H,onContinue:()=>{let e=W.mode;ee(null),q({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{ee(null),V.multiAgentMode!==`v1`&&q({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>ee(null)})]})}function Cj(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 wj(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 Tj(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Ej=(e,t)=>Math.abs(e-t)<1.01,Dj=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Oj,kj=()=>{if(Oj!==void 0)return Oj;if(typeof navigator>`u`)return Oj=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Oj=!0;let e=navigator.maxTouchPoints;return Oj=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Aj=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},jj=e=>e,Mj=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},Nj=(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(Aj(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(Aj(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Pj={passive:!0},Fj=typeof window>`u`||`onscrollend`in window,Ij=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Fj,o=0,s=a?null:Dj(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,Pj),a&&r.addEventListener(`scrollend`,u,Pj),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Lj=(e,t)=>Ij(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Rj=(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`]},zj=(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})},Bj=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:jj,rangeExtractor:Mj,onChange:()=>{},measureElement:Rj,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=wj(()=>(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,kj()&&this.targetWindow!=null&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Pj),e.addEventListener(`touchend`,n,Pj),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&&(kj()&&(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=wj(()=>[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=wj(()=>[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=Cj(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=wj(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Uj(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=wj(()=>{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=wj(()=>[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 Tj(t[Vj(0,t.length-1,r?e=>n[e*2]:e=>Tj(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:kj()&&(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&&Ej(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()}},Vj=(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 Hj(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 Uj(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=Hj(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=Vj(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 Wj=typeof document<`u`?X.useLayoutEffect:X.useEffect;function Gj({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=X.useReducer(e=>e+1,0)[1],a=X.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,vn.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=X.useState(()=>{let e=new Bj(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),Wj(()=>l._didMount(),[]),Wj(()=>(o(l),l._willUpdate())),Wj(()=>{s(l)}),l}function Kj(e){return Gj({observeElementRect:Nj,observeElementOffset:Lj,scrollToFn:zj,...e})}var qj=32;function Jj(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Yj(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}var Xj=`codex://threads/`,Zj=512;function Qj(e){let t=e.trim();if(t.length>Zj||t.length<=16||!t.toLowerCase().startsWith(Xj))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 $j(e){let t=e.trim(),n=Qj(t);return n===t?[n]:[n,t]}async function eM(e){let t=$j(e).filter(e=>e!==``&&!Yj(e)&&e.length<=4096);return(await Promise.all(t.map(e=>crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))).map(e=>Jj(e).slice(0,qj))}function tM(e,t,n){if(!e)return!1;let r=$j(t);return r.some(Boolean)?r.includes(e)?!0:n!==void 0&&n.includes(e):!1}var nM={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.`}}},rM={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 iM(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 aM(e,t){if(e<400)return null;let n=iM(t);return(nM[Math.trunc(e)]??(e<500?rM.client:rM.server))[n]}var oM=`flex min-w-0 flex-col rounded-[12px] bg-surface ring-1 ring-inset ring-line`,sM=`mx-1 mb-1 min-w-0 overflow-hidden rounded-[8px] bg-bg ring-1 ring-line`,cM=`flex min-w-0 flex-col gap-4 rounded-[12px] bg-surface p-5 ring-1 ring-inset ring-line`,lM=`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em] text-fg`,uM=`m-0 text-[13px] leading-5 text-fg-muted`,dM=`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-highlight`,fM=Y(`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`,dM,`[&_svg]:size-4 [&_svg]:shrink-0`),pM=Y(`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`,dM,`[&_svg]:size-4`),mM=Y(`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`,dM,`[&_svg]:size-3 [&_svg]:shrink-0 [&_svg]:text-fg-subtle`),hM=`flex min-w-0 flex-col gap-1.5 text-[12px] font-medium text-fg-muted`,gM=`input select-sm h-[var(--ocx-control-h)] w-full min-w-0 max-w-none px-2.5 text-[13px] text-fg`;function _M({options:e,visible:t,onToggle:n,label:r,menuLabel:i}){let[a,o]=(0,X.useState)(!1),s=(0,X.useId)(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)([]);(0,X.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,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.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:fM,children:[(0,Z.jsx)(xc,{icon:jc,size:16,strokeWidth:1.8,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:r}),(0,Z.jsx)(St,{"aria-hidden":!0,className:Y(`size-3.5 text-fg-subtle transition-transform`,a?`-rotate-90`:`rotate-90`)})]}),a&&(0,Z.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,Z.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,Z.jsx)(`span`,{"aria-hidden":!0,className:`grid size-4 shrink-0 place-items-center text-fg`,children:t[e.key]&&(0,Z.jsx)(ut,{className:`size-3.5`})}),e.label]},e.key))})]})}function vM({checked:e,onChange:t,label:n,title:r,className:i}){return(0,Z.jsxs)(`label`,{title:r,className:Y(`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,Z.jsx)(`input`,{type:`checkbox`,checked:e,onChange:e=>t(e.target.checked),className:`peer sr-only`}),(0,Z.jsx)(`span`,{"aria-hidden":!0,className:Y(`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,Z.jsx)(`span`,{className:Y(`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 yM={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 bM({status:e,outcome:t,label:n,announce:r=!0,className:i}){return(0,Z.jsxs)(`span`,{title:n,className:Y(`inline-flex h-[22px] shrink-0 items-center gap-1.5 rounded-full px-2 font-mono text-[12px] font-semibold tabular-nums`,yM[t],i),children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`size-1.5 rounded-full bg-current`}),e,r&&(0,Z.jsx)(`span`,{className:`sr-only`,children:n})]})}var xM=[{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`}],SM=`ocx.logs.columns.v1`,CM={effort:!0,tokens:!0,rate:!0,cost:!0,duration:!0};function wM(){try{let e=window.localStorage.getItem(SM);if(!e)return CM;let t=JSON.parse(e);if(!t||typeof t!=`object`)return CM;let n={...CM};for(let{key:e}of xM){let r=t[e];typeof r==`boolean`&&(n[e]=r)}return n}catch{return CM}}function TM(){let[e,t]=(0,X.useState)(wM);return{columns:e,toggle:(0,X.useCallback)(n=>{let r={...e,[n]:!e[n]};t(r);try{window.localStorage.setItem(SM,JSON.stringify(r))}catch{}},[e])}}var EM=[`provider`,`usage`,`injection`];function DM(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function OM(e){return new Date(e).toLocaleTimeString()}function kM(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function AM(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function jM({entries:e}){let{t}=a();return(0,Z.jsxs)(`section`,{className:cM,"aria-labelledby":`debug-claude-inbound-title`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Z.jsx)(`h3`,{id:`debug-claude-inbound-title`,className:lM,children:t(`debug.claudeInbound.title`)}),(0,Z.jsx)(`p`,{className:uM,children:t(`debug.claudeInbound.sub`)})]}),e.length===0?(0,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-subtle`,children:t(`debug.claudeInbound.empty`)}):(0,Z.jsx)(`div`,{className:`overflow-x-auto rounded-[8px] bg-bg ring-1 ring-inset ring-line`,children:(0,Z.jsxs)(`table`,{className:`debug-inbound-table w-full border-collapse`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,Z.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,Z.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,Z.jsx)(`th`,{children:`thinking`}),(0,Z.jsx)(`th`,{children:`effort`}),(0,Z.jsx)(`th`,{children:`beta`}),(0,Z.jsx)(`th`,{children:`metadata`}),(0,Z.jsx)(`th`,{children:`system`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`muted mono`,children:OM(e.at)}),(0,Z.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,Z.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,Z.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,Z.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,Z.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,Z.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,Z.jsx)(`td`,{className:`mono max-w-40 truncate`,title:e.anthropicBeta,children:e.anthropicBeta??`-`}),(0,Z.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,Z.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}var MM={provider:`debug.streamProvider`,usage:`debug.streamUsage`,injection:`debug.streamInjection`};function NM({debug:e,stream:t,streamEnabled:n,entries:r,refreshing:i,follow:o,scrollContainerRef:s,lineVirtualizer:c,onStreamChange:l,onRefresh:u,onFollowChange:d}){let{t:f}=a();if(!e)return null;let p=[e.enabled?`provider`:null,e.usage?`usage`:null,e.injection?`injection`:null].filter(e=>e!==null);return(0,Z.jsxs)(`section`,{className:oM,"aria-labelledby":`debug-tail-title`,children:[(0,Z.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,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2`,children:[(0,Z.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,Z.jsx)(yc,{size:`sm`,"aria-label":f(`logsV2.debugStream`),value:t,onChange:l,items:p.map(e=>({value:e,label:f(MM[e])}))}),p.length===1&&(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted`,children:f(MM[p[0]])})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(`button`,{type:`button`,className:pM,disabled:i||!n,onClick:u,"aria-label":f(`debug.refresh`),title:f(`debug.refresh`),children:(0,Z.jsx)(`span`,{className:Y(`inline-flex`,i&&`animate-spin`),children:(0,Z.jsx)(Mt,{"aria-hidden":!0})})}),(0,Z.jsx)(vM,{checked:o,onChange:d,label:f(`debug.follow`)})]})]}),(0,Z.jsx)(`div`,{className:sM,children:n?r.length===0?(0,Z.jsxs)(`div`,{className:`empty`,children:[(0,Z.jsx)(`div`,{className:`title`,children:f(`debug.noLinesTitle`)}),(0,Z.jsx)(`div`,{className:`mx-auto mt-1.5 max-w-[560px] text-[13px] text-fg-muted`,children:f(`debug.noLines.${t}`)})]}):(0,Z.jsx)(`div`,{ref:s,className:`debug-tail-lines max-h-[calc(100dvh-320px)] min-h-48 overflow-auto px-4 py-2`,children:(0,Z.jsx)(`div`,{className:`relative w-full`,style:{height:c.getTotalSize()},children:c.getVirtualItems().map(e=>{let t=r[e.index];return(0,Z.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,Z.jsx)(`span`,{className:`text-fg-subtle`,children:DM(t.at)}),(0,Z.jsx)(`span`,{className:`text-fg`,children:t.line})]},e.key)})})}):(0,Z.jsxs)(`div`,{className:`empty`,children:[(0,Z.jsx)(`div`,{className:`title`,children:f(`debug.emptyTitle`)}),(0,Z.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,Z.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 PM=[`debug`,`usage`,`injection`,`claude`];function FM({debug:e,debugBusy:t,onSetFlag:n,onReset:r}){let{t:i}=a();return(0,Z.jsxs)(`section`,{className:cM,"aria-labelledby":`debug-logging-title`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 basis-80 flex-col gap-1`,children:[(0,Z.jsx)(`h3`,{id:`debug-logging-title`,className:lM,children:i(`logsV2.debugLogging`)}),(0,Z.jsx)(`p`,{className:uM,children:i(`debug.subtitle`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:fM,disabled:t,onClick:r,children:i(`debug.reset`)})]}),(0,Z.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:PM.map(r=>{let a=AM(e,r);return(0,Z.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,Z.jsx)(kn,{on:a,disabled:t,label:i(`debug.${r}`),onClick:()=>n(r,!a)}),(0,Z.jsx)(`span`,{className:`min-w-0 text-[13px] font-medium text-fg`,children:i(`debug.${r}`)})]},r)})})]})}function IM({embedded:e}){let{t}=a();return e?null:(0,Z.jsx)(`div`,{className:`page-head`,children:(0,Z.jsx)(`h2`,{children:t(`debug.title`)})})}function LM(e){return`debug-settings:${e}`}function RM({apiBase:t,embedded:n,active:r=!0}){let{t:i}=a(),o=`ocx.debug.settings.v1:${t}`,s=kd(o),c=LM(t),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(`provider`),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)(!0),[_,v]=(0,X.useState)(!1),y=(0,X.useRef)(0),b=(0,X.useRef)(0),x=(0,X.useRef)(0),S=(0,X.useRef)(null),C=(0,X.useRef)(null),w=(0,X.useRef)(null),T=Fd(c,[t],async e=>{let n=await fetch(`${t}/api/debug`,{signal:e});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Nd(o,r),r},{pollMs:2e3,enabled:r,isEmpty:()=>!1,initialData:s??void 0}),E=T.state,D=T.data??s??null,O=dn(`debug-claude-inbound:${t}`,[t,D?.claude],async e=>{let n=await fetch(`${t}/api/claude/inbound-debug`,{signal:e});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:r&&!!D?.claude}).data??[],k=Kj({count:p.length,getScrollElement:()=>C.current,estimateSize:()=>20,overscan:30,getItemKey:e=>p[e].seq}),A=(0,X.useCallback)(e=>kM(D,e),[D]);(0,X.useEffect)(()=>{if(!D||A(d))return;let e=EM.find(A);if(!e)return;let t=window.setTimeout(()=>f(e),0);return()=>window.clearTimeout(t)},[D,d,A]);let j=A(d),M=d===`provider`?`${t}/api/debug/logs`:d===`usage`?`${t}/api/debug/usage-logs`:`${t}/api/debug/injection-logs`,N=(0,X.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,X.useEffect)(()=>{if(!r)return;let e=`${t}:${d}:${j}`,n=w.current!==e;if(w.current=e,!n&&p.length>0)return;y.current=0;let i=new AbortController,a=window.setTimeout(()=>{n&&m([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),x.current+=1,i.abort()}},[r,t,d,j]);let P=(0,X.useRef)(!1),F=(0,X.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let t=e(1e4);N(!1,t.signal).finally(()=>{t.clear(),P.current=!1})});(0,X.useEffect)(()=>{if(r&&h&&j)return Ru(()=>F(),1e3)},[r,h,j]),(0,X.useEffect)(()=>{h&&p.length>0&&k.scrollToIndex(p.length-1,{align:`end`})},[p,h,k]);let I=async e=>{let n=++b.current;u(!0);let r=async()=>{try{let r=await fetch(`${t}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!r.ok)return;let i=await r.json();if(n!==b.current)return;Nd(o,i),pn(c,i)}catch{}},i=(S.current??Promise.resolve()).then(r,r);S.current=i.then(()=>void 0,()=>void 0);try{await i}finally{n===b.current&&u(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,Z.jsxs)(`div`,{className:`debug-v2 flex min-w-0 flex-col gap-4 font-sans text-fg`,children:[(0,Z.jsx)(IM,{embedded:n}),!D&&E.showError?(0,Z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Z.jsx)(`span`,{children:i(`debug.loadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>T.refresh(),children:i(`common.retry`)})]}):E.showSkeleton&&!D?(0,Z.jsx)(NE,{label:i(`debug.loading`),rows:3}):D?(0,Z.jsx)(FM,{debug:D,debugBusy:l,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()}}):null,D&&E.showError&&(0,Z.jsx)(Q,{tone:`err`,children:i(`debug.loadFailed`)}),D?.claude&&(0,Z.jsx)(jM,{entries:O}),(0,Z.jsx)(NM,{debug:D,stream:d,streamEnabled:j,entries:p,refreshing:_,follow:h,scrollContainerRef:C,lineVirtualizer:k,onStreamChange:f,onRefresh:()=>void N(!0),onFollowChange:g})]})}function zM(e,t){return t===`all`?!0:t===`claude`?e.surface===`claude`||e.surface===`claude-desktop`:t===`grok`?e.surface===`grok`:e.surface===void 0}var BM=[`all`,`native`,`translated`,`legacy-bridge`,`blocked`,`none`],VM={surface:`all`,model:``,provider:``,status:`all`,timeWindow:`all`,interceptedOnly:!1,conversationId:``};function HM(e){return e.surface!==`all`||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 UM(e){return Array.isArray(e.attempts)?e.attempts.filter(e=>typeof e==`object`&&!!e):[]}function WM(e){if(typeof e!=`string`)return;let t=e.trim();return t?t.toLowerCase():void 0}function GM(e,t){if(e===`15m`)return t-9e5;if(e===`1h`)return t-36e5;if(e===`24h`)return t-864e5}function KM(e,t,n=Date.now()){let r=t.model.trim().toLowerCase(),i=t.provider.trim().toLowerCase(),a=t.conversationId.trim(),o=GM(t.timeWindow,n),s=t.protocolMode??`all`;return e.filter(e=>{if(!zM(e,t.surface)||t.interceptedOnly&&typeof e.shadowCallRewrittenFrom!=`string`)return!1;if(s!==`all`){let t=Nx(e.protocolTrace)?.mode;if(s===`none`?t!==void 0:t!==s)return!1}if(a&&!tM(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=UM(e);if(r&&![WM(e.model),WM(e.resolvedModel),WM(e.servedModel),...n.map(e=>WM(e.model))].some(e=>e===r)||i&&![WM(e.provider),...n.map(e=>WM(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 qM(e,t){if(typeof t!=`string`)return;let n=t.trim(),r=WM(n);if(!r)return;let i=e.get(r);(i===void 0||n<i)&&e.set(r,n)}function JM(e){let t=new Map,n=new Map;for(let r of e){for(let e of[r.model,r.resolvedModel,r.servedModel,...UM(r).map(e=>e.model)])qM(t,e);for(let e of[r.provider,...UM(r).map(e=>e.provider)])qM(n,e)}return{models:[...t.values()].sort(),providers:[...n.values()].sort()}}var YM=[`all`,`claude`,`codex`,`grok`];function XM(e,t,n){let r=YM.indexOf(t),i=-1;if(e.key===`ArrowRight`||e.key===`ArrowDown`?i=(r+1)%YM.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?i=(r-1+YM.length)%YM.length:e.key===`Home`?i=0:e.key===`End`&&(i=YM.length-1),i<0)return;e.preventDefault();let a=YM[i];n(a),document.getElementById(`logs-surface-${a}`)?.focus()}var ZM={fullWidth:!0,size:`sm`,triggerClassName:`px-2.5 text-fg`},QM=[`all`,`claude`,`codex`,`grok`];function $M(e){return e.maxTokPerSec===15?`slow`:e.minTokPerSec===15&&e.maxTokPerSec===50?`medium`:e.minTokPerSec===50?`fast`:`all`}function eN(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 tN({filters:e,options:t,hasActiveFilters:n,filteredCount:r,totalCount:i,t:a,onFilterChange:o,onResetFilters:s,trailing:c}){let l=(0,X.useId)(),u=(0,X.useId)(),[d,f]=(0,X.useState)(!1),p=(0,X.useRef)(null),m=()=>{s(),p.current?.focus({preventScroll:!0})},h=t=>o({...e,...t}),g=$M(e),_=e.protocolMode??`all`,v=[];return e.interceptedOnly&&v.push({key:`intercepted`,label:a(`logs.filter.interceptedHelpersOnly`),clear:()=>h({interceptedOnly:!1})}),e.provider&&v.push({key:`provider`,label:`${a(`logs.filter.provider.label`)}: ${Ge(e.provider,a)}`,clear:()=>h({provider:``})}),e.model&&v.push({key:`model`,label:`${a(`logs.filter.model.label`)}: ${e.model}`,clear:()=>h({model:``})}),e.timeWindow!==`all`&&v.push({key:`time`,label:`${a(`logs.filter.time.label`)}: ${a(`logs.filter.time.${e.timeWindow}`)}`,clear:()=>h({timeWindow:`all`})}),g!==`all`&&v.push({key:`speed`,label:`${a(`logs.filter.speed.label`)}: ${a(`logs.filter.speed.${g}`)}`,clear:()=>h(eN(`all`))}),e.status!==`all`&&v.push({key:`status`,label:`${a(`logs.filter.status.label`)}: ${a(`logs.filter.status.${e.status}`)}`,clear:()=>h({status:`all`})}),_!==`all`&&v.push({key:`protocol`,label:`${a(`logs.filter.protocol.label`)}: ${a(nN(_))}`,clear:()=>h({protocolMode:`all`})}),(0,Z.jsxs)(`div`,{className:`logs-filter-container flex min-w-0 flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0 flex-1 basis-56 sm:max-w-72`,children:[(0,Z.jsx)(ze,{"aria-hidden":!0,className:`pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-fg-subtle`}),(0,Z.jsx)(`input`,{type:`search`,className:Y(gM,`mono pl-8`),value:e.conversationId,onChange:e=>h({conversationId:e.target.value}),placeholder:a(`logs.filter.conversation.placeholder`),"aria-label":a(`logs.filter.conversation.label`)})]}),(0,Z.jsx)(`div`,{role:`radiogroup`,"aria-label":a(`logs.filter.surface.label`),className:`relative inline-flex max-w-full items-center gap-0.5 rounded-control bg-bg p-0.5 ring-1 ring-inset ring-line`,children:(0,Z.jsx)(_c,{children:QM.map(t=>{let n=e.surface===t;return(0,Z.jsxs)(`button`,{ref:t===`all`?p:void 0,type:`button`,role:`radio`,"aria-checked":n,id:`logs-surface-${t}`,tabIndex:n?0:-1,onClick:()=>h({surface:t}),onKeyDown:e=>XM(e,t,e=>h({surface:e})),className:Y(`ui-v2 relative inline-flex h-7 min-w-8 cursor-pointer items-center justify-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`,n?`text-fg`:`text-fg-subtle hover:text-fg-muted`),children:[n&&(0,Z.jsx)(vc,{layoutId:l}),(0,Z.jsx)(`span`,{className:`relative`,children:a(`logs.filter.surface.${t}`)})]},t)})})}),(0,Z.jsxs)(`button`,{type:`button`,"aria-expanded":d,"aria-controls":u,onClick:()=>f(e=>!e),className:fM,children:[(0,Z.jsx)(nt,{"aria-hidden":!0}),a(`logsV2.filters`),v.length>0&&(0,Z.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:v.length})]}),c&&(0,Z.jsx)(`div`,{className:`ml-auto flex items-center gap-1`,children:c})]}),(0,Z.jsxs)(`div`,{id:u,hidden:!d,className:Y(`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`,d?`grid`:`hidden`),children:[(0,Z.jsxs)(`label`,{className:hM,children:[a(`logs.filter.provider.label`),(0,Z.jsx)($,{...ZM,value:e.provider,label:a(`logs.filter.provider.label`),onChange:e=>h({provider:e}),options:[{value:``,label:a(`logs.filter.provider.all`)},...t.providers.map(e=>({value:e,label:Ge(e,a)}))]})]}),(0,Z.jsxs)(`label`,{className:hM,children:[a(`logs.filter.model.label`),(0,Z.jsx)($,{...ZM,value:e.model,label:a(`logs.filter.model.label`),onChange:e=>h({model:e}),options:[{value:``,label:a(`logs.filter.model.all`)},...t.models.map(e=>({value:e,label:e}))]})]}),(0,Z.jsxs)(`label`,{className:hM,children:[a(`logs.filter.time.label`),(0,Z.jsx)($,{...ZM,value:e.timeWindow,label:a(`logs.filter.time.label`),onChange:e=>h({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,Z.jsxs)(`label`,{className:hM,children:[a(`logs.filter.speed.label`),(0,Z.jsx)($,{...ZM,value:g,label:a(`logs.filter.speed.label`),onChange:e=>h(eN(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,Z.jsxs)(`label`,{className:hM,children:[a(`logs.filter.status.label`),(0,Z.jsx)($,{...ZM,value:e.status,label:a(`logs.filter.status.label`),onChange:e=>h({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,Z.jsxs)(`label`,{className:hM,children:[a(`logs.filter.protocol.label`),(0,Z.jsx)($,{...ZM,value:_,label:a(`logs.filter.protocol.label`),onChange:e=>h({protocolMode:e}),options:BM.map(e=>({value:e,label:a(nN(e))}))})]}),(0,Z.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,Z.jsx)(`input`,{type:`checkbox`,className:`size-4 cursor-pointer accent-[var(--ocx-accent)]`,checked:e.interceptedOnly,onChange:e=>h({interceptedOnly:e.target.checked})}),a(`logs.filter.interceptedHelpersOnly`)]})]}),n&&(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1.5`,children:[v.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:mM,onClick:e.clear,"aria-label":a(`logsV2.removeFilter`,{name:e.label}),children:[(0,Z.jsx)(`span`,{className:`truncate`,children:e.label}),(0,Z.jsx)(We,{"aria-hidden":!0})]},e.key)),(0,Z.jsxs)(`div`,{className:`logs-filter-status ml-auto inline-flex flex-wrap items-center gap-1`,children:[(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:a(`logs.filter.showingCount`,{count:r,total:i})}),(0,Z.jsxs)(`button`,{type:`button`,className:fM,onClick:m,children:[(0,Z.jsx)(We,{"aria-hidden":!0}),` `,a(`logs.filter.reset`)]})]})]})]})}function nN(e){return e===`all`?`logs.filter.protocol.all`:e===`none`?`logs.filter.protocol.none`:Jx[e]}function rN({trace:e,t}){let n=Nx(e);if(!n)return null;let r=eS(n,t),i=t(Jx[n.mode]);return(0,Z.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 iN({trace:e,t}){let n=Nx(e);return(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-protocol`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-protocol`,className:`log-detail-section-title`,children:t(`logs.detail.protocol.section`)}),n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`log-detail-grid`,"data-protocol-mode":n.mode,children:[(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.inbound`)}),(0,Z.jsx)(`span`,{children:Qx(n.inbound,t)}),(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.mode`)}),(0,Z.jsx)(`span`,{children:t(Jx[n.mode])}),n.upstream&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.upstream`)}),(0,Z.jsx)(`span`,{children:Qx(n.upstream,t)})]}),n.requestPath.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.requestPath`)}),(0,Z.jsx)(`span`,{children:$x(n.requestPath,t)}),(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.responsePath`)}),(0,Z.jsx)(`span`,{children:$x(n.responsePath,t)})]}),(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.reasons`)}),(0,Z.jsx)(`span`,{className:`mono log-detail-break`,children:n.reasonCodes.join(`, `)||`–`}),n.featureEffects&&n.featureEffects.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.features`)}),(0,Z.jsx)(`span`,{children:n.featureEffects.map(e=>(0,Z.jsxs)(`span`,{style:{display:`block`},children:[(0,Z.jsx)(`code`,{children:e.feature}),`: `,t(Yx[e.disposition])]},e.feature))})]}),n.attempts&&n.attempts.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.attempts`)}),(0,Z.jsx)(`span`,{children:n.attempts.map(e=>(0,Z.jsxs)(`span`,{style:{display:`block`},children:[t(`logs.detail.protocol.attempt`,{ordinal:e.ordinal}),`:`,` `,$x(e.requestPath,t),` · `,t(Jx[e.mode])]},e.ordinal))})]})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm protocol-deep-link`,onClick:()=>RC({inbound:n.inbound,upstream:AC(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]}):(0,Z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:t(`logs.detail.protocol.none`)})]})}function aN(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?{generatedAt:e,receivedAt:t}:void 0}function oN(e,t,n){return e?e.generatedAt+Math.max(0,t-e.receivedAt):n}function sN(){return hC(window.location.hash)===`logs/debug`?`debug`:`logs`}function cN(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function lN(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),cN(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),cN(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function uN(e){return e.servedModel!==void 0&&e.servedModel!==(e.wireModel??e.model)}function dN(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 fN(e,t){return[uN(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}${dN(e.tierOutcome,t)}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function pN(e){return e.requestedSpeedLabel||void 0}function mN(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 hN=[`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`],gN=[`invalid_request_error`,`authentication_error`,`permission_error`,`not_found_error`,`rate_limit_error`,`api_error`,`overloaded_error`,`request_too_large`],_N=new Set(hN),vN=new Set(gN),yN=0xe8d4a51000,bN=new Set([`header_timeout`,`connect_timeout`,`body_stall`,`body_overflow`,`generation_timeout`,`turn_inactivity`]);function xN(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.code!=`string`||!_N.has(t.code))return;let n=t.code,r=t.value,i=typeof r==`number`&&Number.isSafeInteger(r)&&r>=0&&r<=yN&&bN.has(n),a=n===`provider_error`&&typeof t.type==`string`&&vN.has(t.type)?t.type:void 0;return Object.keys(t).every(e=>e===`code`||e===`value`&&i||e===`type`&&a!==void 0)?t:{code:n,...i?{value:r}:{},...a?{type:a}:{}}}var SN={"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`},CN={"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`},wN={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 TN(e,t){let n=e.failureCause===void 0?void 0:Object.hasOwn(SN,e.failureCause)?SN[e.failureCause]:void 0,r=e.failureStage===void 0?void 0:Object.hasOwn(CN,e.failureStage)?CN[e.failureStage]:void 0,i=e.resendPermission===void 0?void 0:Object.hasOwn(wN,e.resendPermission)?wN[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 EN=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0;function DN(e,t,n){let r=e.failureCause,i=r&&Object.hasOwn(SN,r)?SN[r]:void 0,a=i?{label:n(i)}:{label:t?.label,description:t?.description},o=e.spend;return!o||!EN(o.sends)||!EN(o.settled)||!EN(o.unresolved)||o.settled>o.sends||o.reserved!==void 0&&!EN(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&&EN(e.attempts[0]?.sendCount)&&e.attempts[0].sendCount===o.sends&&(a.retries=Math.max(0,o.sends-1))),a}var ON={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 kN(e,t){return typeof e==`string`&&Object.hasOwn(ON,e)?t(ON[e]):void 0}var AN={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`},jN=new Set([`connect_timeout`,`body_stall`,`body_overflow`,`generation_timeout`,`turn_inactivity`]);function MN(e,t){let n=xN(e);if(n)return n.code===`provider_error`&&n.type?t(`logs.failureDetail.providerErrorTyped`,{type:n.type}):n.code===`header_timeout`&&n.value!==void 0?t(`logs.failureDetail.headerTimeoutAfter`,{value:n.value}):jN.has(n.code)?n.value===void 0?void 0:t(AN[n.code],{value:n.value}):t(AN[n.code])}var NN=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function PN(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=NN.format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function FN(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):PN(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function IN(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 LN(e){return e===`cursor`||e.startsWith(`cursor-`)}function RN(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 zN(e,t){if(!e.usage)return;let n=RN(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(LN(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function BN(e){return e===void 0||typeof e==`string`}function VN(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!BN(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!BN(e.profile.id)||!BN(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!BN(e.selected.provider)||!BN(e.selected.model)||!BN(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`||!BN(t.provider)||!BN(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`||!BN(e.code))return!1}}return!0}function HN(e){if(e.routeDecision===void 0||VN(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function UN(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 WN(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 GN(e){return`ocx.logs.list.v1:${e}`}var KN=[];function qN(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`||!VN(t.routeDecision))return null;return e}function JN(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 YN(e){let t=JN(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function XN(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 ZN(e){if(e.reasoningWireField&&e.reasoningWireValue!==void 0)return`${e.reasoningWireField}=${e.reasoningWireValue}`}function QN(e){return uN(e)?(0,Z.jsxs)(Z.Fragment,{children:[lT(e.wireModel??e.model),` → `,lT(e.servedModel)]}):lT(e.servedModel??e.resolvedModel??e.model)}function $N(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 eP=2e3,tP=3e4,nP=4,rP=3,iP={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`},aP={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`},oP={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"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 sP(e){return iP[e]}function cP(e){return aP[e]}function lP(e){return oP[e]??`logs.detail.attempt.recovery.unknown`}function uP(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}var dP={completed:`logs.detail.outcome.completed`,failed:`logs.detail.outcome.failed`,incomplete:`logs.detail.outcome.incomplete`,aborted:`logs.detail.outcome.aborted`};function fP(e){return dP[dp(e)]}function pP(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 mP(e,t,n){let{date:r,time:i}=pP(e,t,n);return`${r} ${i}`}function hP(e){let t=0;for(let n of e){let e=JN(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...IN(e)}}function gP(e){return Y(`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 _P({apiBase:e}){let{t,locale:n}=a(),r=GN(e),i=qN(kd(r)),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)({error:null,count:0}),[u,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(VM),[h,g]=(0,X.useState)(()=>Date.now()),_=(0,X.useRef)({key:r,active:!1,request:0}),v=(0,X.useRef)({key:r,cursor:null,rows:[]});(0,X.useLayoutEffect)(()=>{let e={key:r,active:!0,request:0};return _.current=e,v.current={key:r,cursor:null,rows:[]},g(Date.now()),()=>{e.active=!1}},[r]);let y=(0,X.useCallback)(()=>{let e=_.current;return oN(e.key===r?e.anchor:void 0,performance.now(),Date.now())},[r]),b=(0,X.useRef)(null),x=(0,X.useRef)({key:r,failures:0,nextAttemptAt:0,error:null}),S=d.find(e=>e.code===n)?.htmlLang,[C,w]=(0,X.useState)();(0,X.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,X.useState)(sN),[D,O]=(0,X.useState)(()=>sN()===`debug`);(0,X.useEffect)(()=>{let e=()=>E(sN());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,X.useEffect)(()=>{T===`debug`&&O(!0)},[T]);let k=cN,A=(0,X.useCallback)(async t=>{let n=_.current;if(t.aborted||!n.active||n.key!==r)throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);let i=++n.request,a=()=>!t.aborted&&n.active&&_.current===n&&n.request===i,o=x.current;if(o.key!==r&&(o={key:r,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===r?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 i=await e.json(),o=performance.now(),u=UN(i),d=u.rows.map(HN),f=c&&u.cursor&&!u.reset?WN(s.rows,d):d;if(!a())throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);v.current={key:r,cursor:u.cursor,rows:f};let p=JM(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=aN(u.generatedAt,o);return h&&(n.anchor=h),g(oN(n.anchor,o,Date.now())),x.current={key:r,failures:0,nextAttemptAt:0,error:null},Nd(r,f),f}catch(e){if(!a())throw e;let t=e??Error(`log request failed`),n=o.failures+1,i=eP*2**Math.min(n,nP);throw x.current={key:r,failures:n,nextAttemptAt:Date.now()+i,error:t},t}},[e,r]),j=Fd(r,[e],A,{isEmpty:e=>e.length===0,enabled:T===`logs`,pollMs:o?eP:void 0,initialData:i??void 0}),M=j.state,N=M.data??i??KN,P=j.refresh,F=(0,X.useCallback)(()=>{x.current={key:r,failures:0,nextAttemptAt:0,error:null},v.current={key:r,cursor:null,rows:[]},P({forceLoading:!0})},[P,r]),I=!j.refreshing&&M.showError;!j.refreshing&&!M.showError&&M.data!==void 0&&c.count!==0?l({error:null,count:0}):I&&c.error!==M.error&&l(e=>({error:M.error,count:e.count+1}));let L=c.count>=rP||!o&&I,R=u?aM(u.status,n):null,z=p.conversationId.trim();(0,X.useEffect)(()=>{if(p.timeWindow===`all`||T!==`logs`)return;g(y());let e=window.setInterval(()=>g(y()),tP);return()=>window.clearInterval(e)},[p.timeWindow,T,y]),(0,X.useEffect)(()=>{let e=!1;if(!z)m(e=>e.conversationQueryHash===void 0?e:{...e,conversationQueryHash:void 0});else return eM(z).then(t=>{e||m(e=>e.conversationQueryHash?.join(` `)===t.join(` `)?e:{...e,conversationQueryHash:t})}),()=>{e=!0}},[z]);let B=(0,X.useMemo)(()=>JM(N),[N]),V=HM(p),H=(0,X.useMemo)(()=>KM(N,p,h),[N,p,h]),U=z?hP(H):null,W=(0,X.useMemo)(()=>H.reduce((e,t)=>e+ +(dp(t)===`failed`),0),[H]),{columns:ee,toggle:te}=TM(),ne=4+xM.filter(e=>ee[e.key]).length,G=Kj({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=G.getVirtualItems(),re=K.length>0?K[0].start:0,q=K.length>0?G.getTotalSize()-K[K.length-1].end:0;return(0,Z.jsxs)(`div`,{className:`logs-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:t(`nav.logs`)}),(0,Z.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":t(`nav.logs`),children:[(0,Z.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:gP(T===`logs`),onClick:()=>k(`logs`),onKeyDown:lN,children:t(`logs.tabLogs`)}),(0,Z.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:gP(T===`debug`),onClick:()=>k(`debug`),onKeyDown:lN,children:t(`logs.tabDebug`)})]})]}),D&&(0,Z.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:T!==`debug`,children:(0,Z.jsx)(RM,{apiBase:e,embedded:!0,active:T===`debug`})}),(0,Z.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:T!==`logs`,children:[(0,Z.jsxs)(`section`,{className:oM,"aria-labelledby":`logs-requests-title`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3 px-4 pt-3.5 pb-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 gap-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-1`,children:[(0,Z.jsx)(`h3`,{id:`logs-requests-title`,className:`m-0 text-[15px] leading-5 font-semibold tracking-[-0.01em]`,children:t(`logsV2.requests`)}),(0,Z.jsxs)(`span`,{className:Y(`inline-flex items-center gap-1.5 text-[13px] font-medium`,o?`text-fg`:`text-fg-subtle`),children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:Y(`size-1.5 rounded-full`,o?`bg-success`:`ring-1 ring-current`)}),t(o?`logsV2.live`:`logsV2.paused`)]}),N.length>0&&(0,Z.jsxs)(`span`,{className:`text-[13px] text-fg-subtle tabular-nums`,children:[t(`logsV2.countLine`,{shown:H.length,total:N.length}),W>0&&(0,Z.jsxs)(`span`,{className:`text-danger`,children:[` · `,t(`logsV2.failedCount`,{count:W})]})]})]}),(0,Z.jsx)(vM,{className:`logs-auto-refresh`,checked:o,onChange:s,label:t(`logs.autoRefresh`),title:t(`logsV2.liveHint`)})]}),(0,Z.jsx)(tN,{filters:p,options:B,hasActiveFilters:V,filteredCount:H.length,totalCount:N.length,t,onFilterChange:m,onResetFilters:()=>m(VM),trailing:(0,Z.jsx)(_M,{options:xM.map(e=>({key:e.key,label:t(e.label)})),visible:ee,onToggle:te,label:t(`logsV2.columns`),menuLabel:t(`logsV2.columnsMenu`)})}),U&&(0,Z.jsx)(`div`,{className:`logs-conversation-totals m-0`,children:(0,Z.jsxs)(Q,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:U.requests,tokens:Ue(U.totalTokens,S??n),cost:PN(U.estimatedCostUsd,t,S,U.priorityLowerBound)}),` `,(0,Z.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),U.unpricedRequests+U.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:U.unpricedRequests,unmetered:U.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,Z.jsxs)(Q,{tone:`err`,children:[M.error instanceof Error?`${t(`logs.loadError`)} ${M.error.message}`:t(`logs.loadError`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:t(`common.retry`)})]}),L&&N.length>0&&(0,Z.jsxs)(Q,{tone:`err`,children:[t(`logs.loadError`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:j.refreshing,children:t(`common.retry`)})]})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,Z.jsx)(`div`,{className:Y(sM,`p-3`),children:(0,Z.jsx)(NE,{label:t(`common.loading`),rows:6})}):H.length===0?(0,Z.jsx)(`div`,{className:sM,children:(0,Z.jsx)(Nn,{title:N.length>0&&V?t(`logs.noMatchingRequests`):t(`logs.noRequests`)})}):(0,Z.jsx)(`div`,{className:sM,children:(0,Z.jsx)(`div`,{ref:b,className:`logs-table-wrap max-h-[calc(100dvh-300px)] overflow-auto [overflow-anchor:none]`,children:(0,Z.jsxs)(`table`,{className:Y(`logs-table ui-v2 w-full min-w-[820px] 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,Z.jsxs)(`colgroup`,{children:[(0,Z.jsx)(`col`,{className:`logs-col-time w-[120px]`}),(0,Z.jsx)(`col`,{className:`logs-col-status w-[80px]`}),(0,Z.jsx)(`col`,{className:`logs-col-model w-auto`}),ee.effort&&(0,Z.jsx)(`col`,{className:`logs-col-effort w-[104px]`}),ee.tokens&&(0,Z.jsx)(`col`,{className:`logs-col-tokens w-[84px]`}),ee.rate&&(0,Z.jsx)(`col`,{className:`logs-col-rate w-[84px]`}),ee.cost&&(0,Z.jsx)(`col`,{className:`logs-col-cost w-[84px]`}),ee.duration&&(0,Z.jsx)(`col`,{className:`logs-col-duration w-[84px]`}),(0,Z.jsx)(`col`,{className:`logs-col-actions w-[40px]`})]}),(0,Z.jsx)(`thead`,{className:`sticky top-0 z-10 bg-bg shadow-[inset_0_-1px_0_var(--ocx-line)]`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{scope:`col`,children:t(`logs.col.time`)}),(0,Z.jsx)(`th`,{scope:`col`,children:t(`logs.col.status`)}),(0,Z.jsxs)(`th`,{scope:`col`,children:[t(`logs.col.provider`),` · `,t(`logs.col.model`)]}),ee.effort&&(0,Z.jsx)(`th`,{scope:`col`,children:t(`logs.col.effort`)}),ee.tokens&&(0,Z.jsx)(`th`,{scope:`col`,className:`text-right!`,children:t(`logs.col.tokens`)}),ee.rate&&(0,Z.jsx)(`th`,{scope:`col`,className:`text-right!`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),ee.cost&&(0,Z.jsx)(`th`,{scope:`col`,className:`text-right!`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),ee.duration&&(0,Z.jsx)(`th`,{scope:`col`,className:`text-right!`,children:t(`logs.col.duration`)}),(0,Z.jsx)(`th`,{scope:`col`,children:(0,Z.jsx)(`span`,{className:`sr-only`,children:t(`logs.details`)})})]})}),(0,Z.jsxs)(`tbody`,{children:[re>0&&(0,Z.jsx)(`tr`,{children:(0,Z.jsx)(`td`,{colSpan:ne,className:`logs-virtual-spacer p-0!`,style:{height:re}})}),K.map(e=>{let r=H[H.length-1-e.index],i=ZN(r),a=r.displayMetrics?.decodeTokPerSecond,o=mN(a?.kind===`value`?a:{}),s=pP(r.timestamp,S,C),c=`${t(`logs.details`)}: ${r.requestId??r.status}`;return(0,Z.jsxs)(`tr`,{"data-index":e.index,ref:G.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(r)},children:[(0,Z.jsx)(`td`,{children:(0,Z.jsxs)(`span`,{className:`flex flex-col leading-tight`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-[12.5px] whitespace-nowrap text-fg tabular-nums`,children:s.time}),(0,Z.jsx)(`span`,{className:`mt-0.5 text-[11.5px] whitespace-nowrap text-fg-subtle tabular-nums`,children:s.date})]})}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(bM,{status:r.status,outcome:dp(r),label:t(fP(r))})}),(0,Z.jsx)(`td`,{title:fN(r,t),children:(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`text-fg-muted`,children:Ge(r.provider,t)}),(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`text-fg-subtle`,children:`·`}),(0,Z.jsx)(`span`,{className:`min-w-0 font-mono text-[12.5px] break-words text-fg`,children:QN(r)}),r.shadowCallRewrittenFrom&&(0,Z.jsx)(`span`,{className:`badge badge-muted whitespace-nowrap`,title:t(`logs.badge.interceptedHelperTitle`),children:t(`logs.badge.interceptedHelper`,{model:r.shadowCallRewrittenFrom})}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,Z.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,Z.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),pN(r)&&(0,Z.jsx)(`span`,{className:`badge badge-amber`,children:pN(r)}),(0,Z.jsx)(rN,{trace:r.protocolTrace,t})]}),(0,Z.jsx)(`span`,{className:`log-reqid block max-w-full truncate font-mono text-[11.5px] text-fg-subtle`,title:r.requestId,children:r.requestId??`-`})]})}),ee.effort&&(0,Z.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:XN(r)}),ee.tokens&&(0,Z.jsx)(`td`,{className:`text-right font-mono tabular-nums`,title:zN(r,t),children:(()=>{let e=YN(r),{read:i,write:a}=RN(r);return e===void 0?(0,Z.jsx)(`span`,{className:`font-sans text-fg-subtle`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,Z.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,Z.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Ue(e,n)]}),i!==void 0&&i>0&&(0,Z.jsxs)(`span`,{className:`text-[11.5px] leading-tight text-fg-subtle`,children:[`c `,Ue(i,n)]}),a!==void 0&&a>0&&(0,Z.jsxs)(`span`,{className:`text-[11.5px] leading-tight text-fg-subtle`,children:[`w `,Ue(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,Z.jsx)(`span`,{className:`text-[11.5px] leading-tight text-fg-subtle`,children:t(LN(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),ee.rate&&(0,Z.jsx)(`td`,{className:`log-col-rate text-right font-mono tabular-nums`,children:(0,Z.jsxs)(`span`,{className:`logs-stack-end max-w-full`,children:[(0,Z.jsx)(`span`,{children:$N(r.displayMetrics?.tokPerSecond,S)}),a?.kind===`value`&&(0,Z.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate max-w-full text-fg-subtle`,title:t(o.detail),children:[(0,Z.jsx)(`span`,{children:$N(a,S)}),(0,Z.jsx)(`span`,{className:`block max-w-full truncate font-sans text-[11px]`,children:t(o.short)})]})]})}),ee.cost&&(0,Z.jsx)(`td`,{className:Y(`text-right tabular-nums`,r.displayMetrics?.cost?.kind===`value`?`font-mono`:`font-sans text-fg-subtle`),children:FN(r.displayMetrics?.cost,t,S)}),ee.duration&&(0,Z.jsxs)(`td`,{className:`text-right font-mono whitespace-nowrap text-fg-muted tabular-nums`,children:[r.durationMs,`ms`]}),(0,Z.jsx)(`td`,{className:`px-1!`,children:(0,Z.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(r),"aria-label":c,title:t(`logs.details`),children:(0,Z.jsx)(St,{"aria-hidden":!0,className:`size-4`})})})]},e.key)}),q>0&&(0,Z.jsx)(`tr`,{children:(0,Z.jsx)(`td`,{colSpan:ne,className:`logs-virtual-spacer p-0!`,style:{height:q}})})]})]})})})]}),u&&(0,Z.jsx)(yP,{detail:u,detailInfo:R,localeCode:n,localeTag:S,serverTimeZone:C,t,onClose:()=>f(null),onFilterConversation:e=>{m(t=>({...t,conversationId:e})),f(null)}})]})]})}function vP(e){let t=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function yP({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=vP(!0),[l,u]=(0,X.useState)(!1),d=RN(e),f=e.displayMetrics?.cost,p=e.displayMetrics?.decodeTokPerSecond,m=mN(p?.kind===`value`?p:{}),h=ZN(e),g=TN(e,a),_=DN(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,Z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,Z.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsxs)(`h3`,{id:`log-detail-title`,className:`flex min-w-0 flex-wrap items-center gap-2.5`,children:[(0,Z.jsx)(bM,{status:e.status,outcome:dp(e),label:a(fP(e)),announce:!1,className:`h-6 text-[13px]`}),_.label&&(0,Z.jsx)(`span`,{className:`logs-detail-info m-0`,children:_.label})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,Z.jsx)(We,{})})]}),_.description&&(0,Z.jsx)(`p`,{className:`modal-desc`,children:_.description}),(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,Z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,Z.jsx)(`span`,{className:`mono`,children:mP(e.timestamp,r,i)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.outcome.label`)}),(0,Z.jsx)(`span`,{children:a(fP(e))}),g.cause&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.cause.label`)}),(0,Z.jsxs)(`span`,{children:[g.cause,g.stage&&` (${a(`logs.detail.stage.label`)}: ${g.stage})`]})]}),g.resend&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.resend.label`)}),(0,Z.jsx)(`span`,{children:g.resend})]}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.sends.label`)}),(0,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.retries.label`)}),(0,Z.jsx)(`span`,{className:`mono`,children:_.retries})]}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,Z.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Z.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,Z.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Z.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,Z.jsx)(`span`,{className:`mono`,children:QN(e)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,Z.jsx)(`span`,{children:Ge(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[XN(e),h?` (${h})`:``]})]}),e.errorCode&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,Z.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),kN(e.upstreamCondition,a)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,Z.jsx)(`span`,{children:kN(e.upstreamCondition,a)})]}),MN(e.failureDetail,a)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.failureDetail`)}),(0,Z.jsx)(`span`,{children:MN(e.failureDetail,a)})]})]})]}),(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,Z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,Z.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,Z.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,Z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,Z.jsx)(iN,{trace:e.protocolTrace,t:a}),(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,Z.jsxs)(`div`,{className:`log-detail-grid log-detail-performance-grid`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.endToEndTokPerSec`)}),(0,Z.jsx)(`span`,{className:`mono`,children:$N(e.displayMetrics?.tokPerSecond,r)}),p?.kind===`value`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,title:a(m.hint),children:a(m.detail)}),(0,Z.jsx)(`span`,{className:`mono`,children:$N(p,r)}),(0,Z.jsx)(`span`,{className:`logs-decode-basis-hint muted text-caption`,children:a(m.hint)})]}),e.firstOutputMs!==void 0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,Z.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,Z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(sP(e.displayMetrics.tokPerSecond.reason))}),e.displayMetrics?.decodeTokPerSecond?.kind===`unavailable`&&(0,Z.jsxs)(`p`,{className:`log-detail-notes-line muted`,children:[a(`logs.detail.decodeTokPerSec`),`: `,a(sP(e.displayMetrics.decodeTokPerSecond.reason))]})]}),(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,Z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Z.jsx)(`span`,{className:`mono`,children:PN(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Z.jsx)(`span`,{className:`mono`,children:PN(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Z.jsx)(`span`,{className:`mono`,children:PN(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Z.jsx)(`span`,{className:`mono`,children:PN(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Z.jsx)(`span`,{className:`mono`,children:PN(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,Z.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,Z.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(uP(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,Z.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,Z.jsx)(`li`,{children:a(cP(e))},e))})]}):(0,Z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Z.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,Z.jsx)(`span`,{children:f?.kind===`unavailable`?a(sP(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,Z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,Z.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,Z.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`num`,children:`#`}),(0,Z.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,Z.jsx)(`th`,{className:`num`,title:a(`logs.detail.endToEndTokPerSec`),children:a(`logs.col.tokPerSec`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,Z.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,Z.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=e.displayMetrics?.decodeTokPerSecond,i=mN(n?.kind===`value`?n:{}),o=ZN(e),s=t?.kind===`value`?t.estimate.price:void 0,c=TN(e,a).cause??e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(lP(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(sP(t.reason)):a(`logs.detail.attempt.completed`));return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,Z.jsxs)(`td`,{children:[(0,Z.jsx)(`span`,{children:Ge(e.provider,a)}),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`br`,{}),(0,Z.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[XN(e),o?` (${o})`:``]})]}),s&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`br`,{}),(0,Z.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[s.jawcodeProvider??s.provider,`/`,s.modelId,` · `,a(`logs.detail.source.${s.source}`),` · `,a(uP(s.status))]})]})]}),(0,Z.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,Z.jsxs)(`td`,{className:`num mono`,children:[$N(e.displayMetrics?.tokPerSecond,r),n?.kind===`value`&&(0,Z.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:a(i.detail),children:[(0,Z.jsx)(`span`,{children:$N(n,r)}),(0,Z.jsx)(`span`,{className:`text-caption`,children:a(i.short)})]})]}),(0,Z.jsx)(`td`,{className:`num mono`,children:FN(t,a,r)}),(0,Z.jsx)(`td`,{className:`log-detail-break`,children:c})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,Z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,Z.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,Z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Z.jsx)(`span`,{className:`mono`,children:e.usage?Ue(e.usage.inputTokens,n):`—`}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Z.jsx)(`span`,{className:`mono`,children:e.usage?Ue(e.usage.outputTokens,n):`—`}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Z.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Ue(d.read,n)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Z.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Ue(d.write,n)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,Z.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Ue(e.usage.reasoningOutputTokens,n)}),(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,Z.jsx)(`span`,{className:`mono`,children:YN(e)===void 0?`—`:Ue(YN(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,Z.jsx)(`span`,{className:`mono`,children:Ue(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,Z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,Z.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,Z.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,Z.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function bP(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 xP(e,t){if(!e||!t)return{ok:!1,error:`required`};let n=bP(e),r=bP(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 SP(e){return`${Math.round(e*100)}%`}function CP(e,t,n){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Ue(e,t):n}function wP(e,t){return typeof e==`number`&&Number.isFinite(e)?SP(e):t}function TP(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:Ue(r,t),total:Ue(e.inputTokens,t)})}function EP(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function DP(e,t){return EP(e.throughputTokensPerSec)?t(`usage.throughput.title`,{samples:e.throughputSamples??0}):t(`usage.throughput.unmeasured`)}function OP(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function kP(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=OP(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 AP(e,t){return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(new Date(`${e}T12:00:00`))}function jP(e,t,n){return n(`usage.chart.dayDetail`,{date:AP(e.date,t),requests:e.requests,tokens:Ue(e.totalTokens,t)})}function MP(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 NP(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 PP(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 FP(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function IP(e,t=!1){let n=PP(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:FP(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=OP(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?FP(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 LP({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,Z.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,Z.jsx)(`polyline`,{points:i,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,vectorEffect:`non-scaling-stroke`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function RP({text:e}){return(0,Z.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,Z.jsx)(q,{"aria-hidden":`true`})})}function zP({label:e,term:t,hint:n,value:r,spark:i,foot:a,meter:o}){return(0,Z.jsxs)(`div`,{className:`@container flex min-w-0 flex-col gap-2 px-4 py-3.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-[13px] font-medium text-fg-muted`,children:e}),t&&(0,Z.jsx)(`span`,{className:`truncate font-mono text-[11px] text-fg-subtle`,children:t}),n&&(0,Z.jsx)(RP,{text:n})]}),(0,Z.jsxs)(`div`,{className:`mt-auto flex min-w-0 items-end justify-between gap-3`,children:[(0,Z.jsx)(`span`,{className:`stat-value truncate text-stat font-semibold tracking-[-0.025em] text-fg tabular-nums`,children:r}),i&&(0,Z.jsx)(LP,{values:i})]}),o!==void 0&&(0,Z.jsx)(`span`,{className:`block h-1 w-full overflow-hidden rounded-full bg-surface-2`,"aria-hidden":`true`,children:(0,Z.jsx)(`span`,{className:`block h-full rounded-full bg-fg`,style:{width:`${Math.max(0,Math.min(1,o))*100}%`}})}),a&&(0,Z.jsx)(`span`,{className:`truncate text-xs text-fg-subtle tabular-nums`,children:a})]})}function BP({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:Ue(l,r),title:i(`usage.card.cachedTokensHint`)},...u>0?[{label:i(`usage.card.cacheWriteTokens`),value:Ue(u,r)}]:[],{label:i(`usage.col.tokPerSec`),value:EP(e.throughputTokensPerSec)?e.throughputTokensPerSec.toFixed(1):i(`usage.unavailable`),title:DP(e,i)},{label:i(`usage.card.activeDays`),value:a.format(n)}];return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2.5`,children:[(0,Z.jsx)(`div`,{className:`@container overflow-hidden rounded-[12px] bg-surface ring-1 ring-line`,role:`group`,"aria-label":i(`usage.section.overview`),children:(0,Z.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,Z.jsx)(zP,{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,Z.jsx)(zP,{label:i(`usage.card.totalTokens`),value:Ue(e.totalTokens,r),spark:t.map(e=>e.totalTokens),foot:i(`usageV2.tokensSplit`,{input:Ue(e.inputTokens,r),output:Ue(e.outputTokens,r)})}),(0,Z.jsx)(zP,{label:i(`usageV2.costLabel`),term:i(`usage.col.apiListPrice`),hint:`${i(`usage.cost.total`)}. ${i(`usage.cost.disclaimer`)}`,value:s?lv(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,Z.jsx)(zP,{label:i(`usage.card.coverage`),hint:i(`usageV2.coverageHint`),value:SP(e.coverageRatio),meter:e.coverageRatio,foot:i(`usageV2.coverageFoot`,{measured:a.format(e.measuredRequests),requests:a.format(e.requests)})})]})}),(0,Z.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,Z.jsxs)(`div`,{className:`usage-fact flex items-baseline gap-1.5`,title:e.title,children:[(0,Z.jsxs)(`dt`,{className:`text-fg-subtle`,children:[e.label,e.title&&(0,Z.jsxs)(`span`,{className:`sr-only`,children:[` (`,e.title,`)`]})]}),(0,Z.jsx)(`dd`,{className:`usage-fact-value m-0 font-medium text-fg-muted tabular-nums`,children:e.value})]},e.label))})]})}function VP({anchor:e,className:t,children:n}){return(0,vn.createPortal)((0,Z.jsx)(`div`,{className:`${t} chart-overlay`,role:`tooltip`,style:MP(e),children:n}),document.body)}function HP({bars:e,locale:t,t:n}){let[r,i]=(0,X.useState)(null),a=NP(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,Z.jsxs)(`div`,{className:`@container flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex gap-3`,children:[(0,Z.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,Z.jsx)(`span`,{children:Ue(e,t)},e))}),(0,Z.jsxs)(`div`,{className:`relative h-[220px] min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0 flex flex-col justify-between`,"aria-hidden":`true`,children:o.map(e=>(0,Z.jsx)(`span`,{className:Y(`block h-px w-full`,e===0?`bg-line-strong`:`bg-line`)},e))}),(0,Z.jsx)(`div`,{className:Y(`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,Z.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":jP(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,Z.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,Z.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:Ue(e.totalTokens,t)}),(0,Z.jsx)(`span`,{className:Y(`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,Z.jsxs)(`div`,{className:`flex gap-3`,"aria-hidden":`true`,children:[(0,Z.jsx)(`div`,{className:`w-12 shrink-0`}),(0,Z.jsx)(`div`,{className:Y(`flex min-w-0 flex-1`,e.length>40?`gap-px`:c?`gap-3`:`gap-1`),children:e.map((e,t)=>(0,Z.jsx)(`span`,{className:`daybar-label relative min-w-0 flex-1 text-center text-[11px] text-fg-subtle tabular-nums`,children:u(t)&&(0,Z.jsx)(`span`,{className:Y(!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,Z.jsxs)(VP,{className:`daybar-tip`,anchor:r.anchor,children:[(0,Z.jsx)(`div`,{className:`daybar-tip-date`,children:AP(s.date,t)}),(0,Z.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Z.jsx)(`span`,{children:n(`usage.heatmap.tooltipRequests`,{requests:s.requests})}),(0,Z.jsx)(`span`,{className:`daybar-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:Ue(s.totalTokens,t)})})]}),s.models.slice(0,8).map(e=>(0,Z.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Z.jsx)(`span`,{className:`daybar-tip-name`,children:lT(e.model)}),(0,Z.jsx)(`span`,{className:`daybar-tip-val`,children:Ue(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]})]})}var UP=e=>new Intl.DateTimeFormat(e,{month:`short`});function WP({heatmap:e,locale:t,t:n}){let r=(0,X.useRef)(null),i=(0,X.useMemo)(()=>e.weeks.flat().filter(e=>e.date),[e]),[a,o]=(0,X.useState)(()=>i.at(-1)?.date??``),[s,c]=(0,X.useState)(null),l=(0,X.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,X.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,Z.jsxs)(`div`,{className:`heatmap usage-v2-heatmap`,ref:r,children:[(0,Z.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${e.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,Z.jsx)(`span`,{className:`heatmap-day-spacer`}),e.months.map(e=>(0,Z.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:UP(t).format(new Date(2e3,e.month,1))},`${e.month}-${e.col}`))]}),(0,Z.jsxs)(`div`,{className:`heatmap-body`,children:[(0,Z.jsxs)(`div`,{className:`heatmap-days`,children:[(0,Z.jsx)(`span`,{}),(0,Z.jsx)(`span`,{children:n(`usage.dayMon`)}),(0,Z.jsx)(`span`,{}),(0,Z.jsx)(`span`,{children:n(`usage.dayWed`)}),(0,Z.jsx)(`span`,{}),(0,Z.jsx)(`span`,{children:n(`usage.dayFri`)}),(0,Z.jsx)(`span`,{})]}),(0,Z.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,Z.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,i)=>e.date?(0,Z.jsx)(`button`,{type:`button`,className:`heatmap-cell heatmap-cell-${e.level}`,"data-date":e.date,tabIndex:u===e.date?0:-1,"aria-label":jP(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,Z.jsx)(`span`,{className:`heatmap-cell heatmap-cell-0`,"aria-hidden":`true`},`pad-${r}-${i}`))},e[0]?.date||`week-${r}`))})]}),(0,Z.jsx)(`span`,{id:l,className:`sr-only`,children:n(`usage.heatmap.keyboardLabel`)}),(0,Z.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:p?jP(p,t,n):``}),s&&(()=>{let e=i.find(e=>e.date===s.date);return e?.date?(0,Z.jsxs)(VP,{className:`heatmap-tip`,anchor:s.anchor,children:[(0,Z.jsx)(`div`,{className:`heatmap-tip-date`,children:AP(e.date,t)}),(0,Z.jsx)(`div`,{className:`heatmap-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:Ue(e.totalTokens,t)})}),(0,Z.jsx)(`div`,{className:`heatmap-tip-req muted`,children:n(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,Z.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,Z.jsx)(`span`,{children:n(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,Z.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,Z.jsx)(`span`,{children:n(`usage.heatmap.more`)})]})]})}function GP({defaultView:e,heatmap:t,bars:n,totalTokens:r,locale:i,t:a}){let[o,s]=(0,X.useState)(e);return(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Z.jsx)(`h3`,{id:`usage-heatmap-title`,className:`m-0 text-[15px] font-semibold text-fg`,children:a(`usage.section.heatmap`)}),(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-muted tabular-nums`,children:a(`usageV2.chartCaption`,{tokens:Ue(r,i)})})]}),(0,Z.jsx)(yc,{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,Z.jsx)(HP,{bars:n,locale:i,t:a}):(0,Z.jsx)(WP,{heatmap:t,locale:i,t:a})]})}function KP({row:e,locale:t,t:n}){if(e.estimatedCostUsd===void 0&&e.pricedRequests===void 0&&e.unpricedRequests===void 0)return(0,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`muted`,children:`—`}),r>0&&(0,Z.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`mono`,children:lv(e.estimatedCostUsd??0,t)}),r>0&&(0,Z.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]})}function qP({ratio:e}){let t=Math.max(0,Math.min(1,e));return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,Z.jsx)(`div`,{className:`usage-bar h-1.5 min-w-16 flex-1 overflow-hidden rounded-full bg-surface-2`,children:(0,Z.jsx)(`div`,{className:`usage-bar-fill h-full rounded-full bg-fg/75`,style:{width:`${Math.round(t*100)}%`}})}),(0,Z.jsx)(`span`,{className:`w-9 shrink-0 text-right font-mono text-xs text-fg-muted tabular-nums`,children:SP(t)})]})}function JP({title:e,titleId:t,meta:n,actions:r,children:i}){return(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,Z.jsx)(`h3`,{id:t,className:`h-section m-0 text-[15px] leading-6 font-semibold tracking-normal text-fg`,children:e}),n&&(0,Z.jsx)(`span`,{className:`text-[13px] text-fg-subtle tabular-nums`,children:n})]}),r]}),i]})}function YP({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,Z.jsxs)(JP,{title:a(`usage.section.models`),titleId:`usage-models-title`,meta:String(t),actions:(0,Z.jsxs)(`label`,{className:`usw-section-toolbar relative m-0 flex w-full max-w-60 items-center`,children:[(0,Z.jsx)(`span`,{className:`pointer-events-none absolute left-2.5 text-fg-subtle [&_svg]:size-3.5`,"aria-hidden":`true`,children:(0,Z.jsx)(ze,{})}),(0,Z.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,Z.jsx)(`div`,{className:`tbl-wrap usage-v2-tbl`,children:(0,Z.jsxs)(`table`,{className:`tbl usage-models-tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:a(`logs.col.model`)}),(0,Z.jsx)(`th`,{children:a(`logs.col.provider`)}),(0,Z.jsx)(`th`,{children:a(`usage.col.share`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.tokens`)}),(0,Z.jsx)(`th`,{className:`num`,"aria-describedby":s,children:a(`usage.col.apiListPrice`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.requests`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.measured`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.inputTokens`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.outputTokens`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.tokPerSec`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.cacheHits`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.cacheWrites`)}),(0,Z.jsx)(`th`,{className:`num`,children:a(`usage.col.cacheHitRate`)})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>{let t=Ge(e.provider,a),n=TP(e,i,a),r=DP(e,a);return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`mono font-medium text-fg`,title:e.model,children:lT(e.model)}),(0,Z.jsx)(`td`,{className:`muted`,title:t,children:t}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(qP,{ratio:e.shareRatio})}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.totalTokens,i)}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(KP,{row:e,locale:i,t:a})}),(0,Z.jsx)(`td`,{className:`num`,children:e.requests}),(0,Z.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.inputTokens,i)}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.outputTokens,i)}),(0,Z.jsxs)(`td`,{className:`num mono`,title:r,children:[(0,Z.jsx)(`span`,{className:`usage-hit-rate`,children:EP(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:c}),EP(e.throughputTokensPerSec)&&(0,Z.jsx)(`span`,{className:`sr-only`,children:r})]}),(0,Z.jsx)(`td`,{className:`num mono`,children:CP(e.cacheReadInputTokens??e.cachedInputTokens,i,c)}),(0,Z.jsx)(`td`,{className:`num mono`,children:CP(e.cacheCreationInputTokens,i,c)}),(0,Z.jsxs)(`td`,{className:`num mono`,title:n,children:[(0,Z.jsx)(`span`,{className:`usage-hit-rate`,children:wP(e.cacheHitRate,c)}),n!==void 0&&(0,Z.jsx)(`span`,{className:`sr-only`,children:n})]})]},`${e.provider}/${e.model}`)})})]})}),(0,Z.jsx)(`p`,{id:s,className:`m-0 text-xs text-fg-subtle`,children:a(`usage.cost.disclaimer`)})]})}function XP({providers:e,locale:t,t:n}){let r=n(`usage.unavailable`),i=`usage-providers-list-price-disclaimer`;return(0,Z.jsxs)(JP,{title:n(`usage.section.providers`),titleId:`usage-providers-title`,meta:String(e.length),children:[(0,Z.jsx)(`div`,{className:`tbl-wrap usage-v2-tbl`,children:(0,Z.jsxs)(`table`,{className:`tbl usage-providers-tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Z.jsx)(`th`,{children:n(`usage.col.share`)}),(0,Z.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Z.jsx)(`th`,{className:`num`,"aria-describedby":i,children:n(`usage.col.apiListPrice`)}),(0,Z.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Z.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,Z.jsx)(`th`,{className:`num`,children:n(`usage.col.tokPerSec`)})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`font-medium text-fg`,children:Ge(e.provider,n)}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(qP,{ratio:e.shareRatio})}),(0,Z.jsx)(`td`,{className:`num mono`,children:Ue(e.totalTokens,t)}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(KP,{row:e,locale:t,t:n})}),(0,Z.jsx)(`td`,{className:`num`,children:e.requests}),(0,Z.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Z.jsxs)(`td`,{className:`num mono`,title:DP(e,n),children:[(0,Z.jsx)(`span`,{className:`usage-hit-rate`,children:EP(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:r}),EP(e.throughputTokensPerSec)&&(0,Z.jsx)(`span`,{className:`sr-only`,children:DP(e,n)})]})]},e.provider))})]})}),(0,Z.jsx)(`p`,{id:i,className:`m-0 text-xs text-fg-subtle`,children:n(`usage.cost.disclaimer`)})]})}function ZP({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,Z.jsxs)(JP,{title:n(`usage.section.coverage`),titleId:`usage-coverage-title`,meta:SP(e.coverageRatio),children:[(0,Z.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,Z.jsx)(`span`,{className:Y(`block h-full first:rounded-l-full last:rounded-r-full`,e.tone),style:{width:`${e.count/i*100}%`}},e.key))}),(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,Z.jsx)(`dt`,{className:`text-xs text-fg-subtle`,children:n(`usage.coverage.measured`)}),(0,Z.jsx)(`dd`,{className:`m-0 text-[17px] font-semibold text-fg tabular-nums`,children:r.format(e.measuredRequests)})]}),o.map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,Z.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-xs text-fg-subtle`,children:[(0,Z.jsx)(`span`,{className:Y(`size-2 shrink-0 rounded-[2px]`,t.tone),"aria-hidden":`true`}),t.label]}),(0,Z.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,Z.jsx)(`p`,{className:`m-0 text-xs leading-5 text-fg-subtle`,children:n(`usage.coverage.note`)})]})}var QP=`h-[calc(var(--ocx-control-h)-4px)] gap-1.5 px-2.5 text-[13px]`;function $P({range:e,onRange:t,t:n}){return(0,Z.jsx)(Z.Fragment,{children:(0,Z.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,Z.jsx)(`button`,{type:`button`,className:Y(`usage-segmented-btn${e===r?` active`:``}`,QP),"aria-label":i,"aria-pressed":e===r,onClick:()=>t(r),children:i},r)})})})}function eF({scope:e,onScope:t,t:n}){return(0,Z.jsxs)(`div`,{className:`usage-source-row m-0 flex items-center gap-2 text-[13px] text-fg-muted`,children:[(0,Z.jsx)(`span`,{children:n(`usage.source.connected`)}),(0,Z.jsx)(`div`,{className:`usage-segmented usage-scope-control`,role:`group`,"aria-label":n(`usage.scope.label`),children:[`machine`,`hub`].map(r=>(0,Z.jsx)(`button`,{type:`button`,className:Y(`usage-segmented-btn${e===r?` active`:``}`,QP),"aria-pressed":e===r,onClick:()=>t(r),children:n(r===`machine`?`usage.scope.machine`:`usage.scope.hub`)},r))})]})}function tF({open:e,active:t,onToggle:n,t:r}){return(0,Z.jsxs)(`button`,{type:`button`,className:Y(`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,Z.jsx)(xc,{icon:Sc,size:15,strokeWidth:1.8,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{children:r(`usage.range.custom`)}),(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`,className:`usage-range-chevron`})]})}function nF({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,Z.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 rF({label:e,value:t,invalid:n,describedBy:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`usage-range-field grid min-w-0 gap-1`,children:[(0,Z.jsx)(`span`,{className:`field-label m-0 text-xs font-medium text-fg-muted`,children:e}),(0,Z.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 iF({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,Z.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,Z.jsxs)(`div`,{className:`usage-range-fields`,children:[(0,Z.jsx)(rF,{label:a(`usage.range.start`),value:e.since,invalid:t!==null,describedBy:o,onChange:e=>n({since:e})}),(0,Z.jsx)(rF,{label:a(`usage.range.end`),value:e.until,invalid:t!==null,describedBy:o,onChange:e=>n({until:e})}),(0,Z.jsx)(lp,{type:`submit`,variant:`primary`,size:`sm`,className:`usage-range-action h-9`,children:a(`usage.range.apply`)}),(0,Z.jsx)(lp,{type:`button`,variant:`ghost`,size:`sm`,className:`usage-range-action h-9`,onClick:i,children:a(`usage.range.clear`)})]}),(0,Z.jsx)(`p`,{id:`usage-range-help`,className:`m-0 text-xs text-fg-subtle`,children:a(`usage.range.help`)}),t&&(0,Z.jsx)(`p`,{id:`usage-range-error`,role:`alert`,className:`notice notice-err m-0`,children:a(`usage.range.${t}`)})]})}function aF({children:e}){return(0,Z.jsx)(`div`,{className:`usage-range-bar flex flex-wrap items-center gap-2`,children:e})}var oF=[`requests`,`tokens`,`cost`,`quota`,`none`],sF=[6,24,72,168],cF=[`line`,`stackedBar`],lF=[`total`,`input`,`output`,`cached`],uF=[`sum`,`average`,`max`],dF=[`model`,`modelAccount`],fF={requests:`usage.companion.menuRequests`,tokens:`usage.companion.menuTokens`,cost:`usage.companion.menuCost`,quota:`usage.companion.menuQuota`,none:`usage.companion.menuNone`},pF={6:`usage.companion.window6`,24:`usage.companion.window24`,72:`usage.companion.window72`,168:`usage.companion.window168`},mF={total:`usage.companion.metricTotal`,input:`usage.companion.metricInput`,output:`usage.companion.metricOutput`,cached:`usage.companion.metricCached`},hF=[[`showToday`,`usage.companion.sectionToday`],[`showChart`,`usage.companion.sectionChart`],[`showModels`,`usage.companion.sectionModels`],[`showCost`,`usage.companion.sectionCost`],[`showAccounts`,`usage.companion.sectionAccounts`]],gF={sum:`usage.companion.aggregationSum`,average:`usage.companion.aggregationAverage`,max:`usage.companion.aggregationMax`},_F={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`]},vF={macos:`usage.companion.osMac`,windows:`usage.companion.osWindows`,linux:`usage.companion.osLinux`},yF=`h-7 px-2.5 text-[13px]`,bF=`field-label text-xs font-medium text-fg-muted`;function xF({title:e,aside:t,className:n,children:r}){return(0,Z.jsxs)(`section`,{className:Y(`flex min-w-0 flex-col gap-4 rounded-[12px] bg-surface p-5 ring-1 ring-line`,n),children:[(e||t)&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e&&(0,Z.jsx)(`h3`,{className:`m-0 text-[15px] font-semibold text-fg`,children:e}),t]}),r]})}function SF({value:e,onChange:t,t:n}){return(0,Z.jsx)(`div`,{className:`usage-segmented w-fit`,role:`group`,"aria-label":n(`usage.companion.installOs`),children:Object.keys(vF).map(r=>(0,Z.jsx)(`button`,{type:`button`,className:Y(`usage-segmented-btn${e===r?` active`:``}`,yF),"aria-pressed":e===r,onClick:()=>t(r),children:n(vF[r])},r))})}function CF({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Z.jsxs)(`div`,{className:`usage-companion-control grid min-w-0 gap-1.5`,children:[(0,Z.jsx)(`span`,{className:bF,children:e}),(0,Z.jsx)(`div`,{className:`usage-segmented flex w-fit max-w-full flex-wrap`,role:`group`,"aria-label":e,children:n.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:Y(`usage-segmented-btn${e===t?` active`:``}`,yF),"aria-pressed":e===t,onClick:()=>i(e),children:r(e)},String(e)))})]})}function wF({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`usage-companion-control grid min-w-0 gap-1.5`,children:[(0,Z.jsx)(`span`,{className:bF,children:e}),(0,Z.jsx)($,{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 TF({tone:e}){return(0,Z.jsx)(`span`,{className:Y(`usage-companion-install-dot size-2 shrink-0 rounded-full`,e===`on`?`bg-success`:`bg-fg-subtle`),"aria-hidden":`true`})}function EF({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?``:Mp(o,Np(a),t),l=Rd(),u=Ld()??`2.98.0-preview.20261107`,d=_F[n],f=(0,Z.jsxs)(`ol`,{className:`usage-companion-install-steps m-0 grid gap-2 pl-5 text-[13px] text-fg-muted`,children:[(0,Z.jsxs)(`li`,{children:[a(d[0]),` `,(0,Z.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,Z.jsx)(`li`,{children:a(d[1])}),(0,Z.jsx)(`li`,{children:a(d[2])})]}),p=(0,Z.jsxs)(`div`,{className:`grid gap-3`,children:[(0,Z.jsx)(SF,{value:n,onChange:r,t:a}),f,n===`macos`?(0,Z.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,Z.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,Z.jsxs)(`details`,{className:`usage-companion-install-guide grid gap-3 border-t border-line pt-3`,open:t,children:[(0,Z.jsx)(`summary`,{className:`w-fit cursor-pointer text-[13px] font-medium text-fg-muted hover:text-fg`,children:e}),(0,Z.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,Z.jsxs)(xF,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Z.jsx)(`h3`,{className:`m-0 text-[15px] font-semibold text-fg`,children:a(`usage.companion.title`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:a(`usage.companion.description`)})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l&&(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:i,children:a(`usage.companion.openInBrowser`)}),(0,Z.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,Z.jsx)(dt,{"aria-hidden":`true`})]})]})]}),(0,Z.jsxs)(`div`,{className:Y(`usage-companion-install-status flex items-center gap-2 text-[13px]`,h.tone===`on`?`text-fg`:`text-fg-muted`),children:[(0,Z.jsx)(TF,{tone:h.tone}),(0,Z.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 DF({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,Z.jsxs)(`div`,{className:`usage-companion-models grid gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,Z.jsx)(`span`,{className:bF,children:o(`usage.companion.modelsOnChart`)}),(0,Z.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,Z.jsx)(lp,{variant:`ghost`,size:`sm`,onClick:()=>a({models:null}),disabled:i,children:o(`usage.companion.modelsShowAll`)})]}),(0,Z.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,Z.jsxs)(`div`,{className:`usage-companion-model-group`,children:[(0,Z.jsxs)(`div`,{className:`usage-companion-model-group-header`,children:[(0,Z.jsx)(`span`,{className:`usage-companion-model-provider`,children:e.provider}),(0,Z.jsx)(`span`,{className:`usage-companion-model-chip mono text-caption`,children:e.models.length}),(0,Z.jsx)(kn,{on:s,mixed:o>0&&!s,onClick:()=>a({models:Me(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,Z.jsxs)(`div`,{className:`usage-companion-model-row${o?``:` is-off`}`,children:[(0,Z.jsx)(kn,{on:o,onClick:()=>a({models:Me(t.models,n,[e.id],!o)}),disabled:i,label:e.id,title:e.id}),(0,Z.jsx)(`code`,{className:`mono text-control`,children:e.id}),(0,Z.jsx)(`span`,{className:`usage-companion-model-total muted text-caption`,children:r.has(e.id)?Ye(e.total):`—`})]},e.id)})]},e.provider)})})]})}function OF({children:e}){return(0,Z.jsx)(`h4`,{className:`m-0 text-[13px] font-semibold text-fg`,children:e})}function kF({current:e,disabled:t,providerNames:n,onUpdate:r,t:i}){let a=new Set(e.hiddenProviders);return(0,Z.jsxs)(`fieldset`,{className:`usage-companion-controls m-0 flex min-w-0 flex-col gap-5 border-0 p-0`,disabled:t,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3`,children:[(0,Z.jsx)(OF,{children:i(`usageV2.companionMenuBar`)}),(0,Z.jsx)(CF,{label:i(`usage.companion.menuBarShows`),value:e.menuBarMetric,options:oF,optionLabel:e=>i(fF[e]),onChange:e=>r({menuBarMetric:e})})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 border-t border-line pt-4`,children:[(0,Z.jsx)(OF,{children:i(`usageV2.companionChart`)}),(0,Z.jsx)(CF,{label:i(`usage.companion.window`),value:e.chartHours,options:sF,optionLabel:e=>i(pF[e]),onChange:e=>r({chartHours:e,bucketMinutes:tt(e)})}),(0,Z.jsx)(CF,{label:i(`usage.companion.style`),value:e.chartStyle,options:cF,optionLabel:e=>i(e===`line`?`usage.companion.styleLine`:`usage.companion.styleStacked`),onChange:e=>r({chartStyle:e})}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)(wF,{label:i(`usage.companion.metric`),value:e.tokenMetric,options:lF,optionLabel:e=>i(mF[e]),onChange:e=>r({tokenMetric:e})}),(0,Z.jsx)(wF,{label:i(`usage.companion.groupBy`),value:e.chartGrouping,options:dF,optionLabel:e=>i(e===`model`?`usage.companion.groupModel`:`usage.companion.groupAccount`),onChange:e=>r({chartGrouping:e})})]})]}),(0,Z.jsxs)(`fieldset`,{className:`usage-companion-switches m-0 grid gap-1 border-0 border-t border-line p-0 pt-4`,children:[(0,Z.jsx)(`legend`,{className:`float-left mb-2 w-full p-0`,children:(0,Z.jsx)(OF,{children:i(`usage.companion.popoverSections`)})}),hF.map(([t,n])=>(0,Z.jsxs)(`div`,{className:`usage-companion-switch flex items-center justify-between gap-3 py-1 text-[13px] text-fg`,children:[(0,Z.jsx)(`span`,{children:i(n)}),(0,Z.jsx)(kn,{on:e[t],label:i(n),onClick:()=>r({[t]:!e[t]})})]},t))]}),(0,Z.jsxs)(`details`,{className:`usage-companion-advanced border-t border-line pt-4`,children:[(0,Z.jsx)(`summary`,{className:`w-fit cursor-pointer text-[13px] font-semibold text-fg`,children:i(`usage.companion.advanced`)}),(0,Z.jsxs)(`div`,{className:`usage-companion-advanced-body grid gap-4 pt-3`,children:[(0,Z.jsx)(wF,{label:i(`usage.companion.aggregation`),value:e.aggregation,options:uF,optionLabel:e=>i(gF[e]),onChange:e=>r({aggregation:e})}),(0,Z.jsxs)(`label`,{className:`usage-companion-control grid min-w-0 gap-1.5`,children:[(0,Z.jsx)(`span`,{className:bF,children:i(`usage.companion.menuText`)}),(0,Z.jsx)(`input`,{className:`h-9 rounded-control text-[13px]`,value:e.menuBarTemplate??``,onChange:e=>r({menuBarTemplate:e.target.value}),maxLength:200}),(0,Z.jsxs)(`span`,{className:`text-xs text-fg-subtle`,children:[i(`usage.companion.placeholders`),` `,(0,Z.jsx)(`code`,{children:`{requests} {totalTokens} {inputTokens} {outputTokens} {costUsd} {quotaPercent}`})]})]}),n.length>0&&(0,Z.jsxs)(`fieldset`,{className:`usage-companion-check-list m-0 grid gap-2 border-0 p-0`,children:[(0,Z.jsx)(`legend`,{className:Y(bF,`mb-1 p-0`),children:i(`usage.companion.hideProviders`)}),n.map(t=>(0,Z.jsxs)(`label`,{children:[(0,Z.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,Z.jsx)(`span`,{children:t})]},t))]})]})]})]})}function AF(e,t){return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`}).format(e)}function jF(e){return e instanceof Error&&e.message?e.message:String(e)}function MF(e){let[t,n]=(0,X.useState)(!1);return(0,X.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 NF({apiBase:e,providers:t,onSettingsLoaded:n}){let{t:r,locale:i}=a(),o=(0,X.useRef)(null),s=MF(o),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(`idle`),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),O=(0,X.useRef)(null),k=(0,X.useRef)(null),A=(0,X.useRef)(null),j=(0,X.useRef)(S),M=(0,X.useRef)(u),N=(0,X.useRef)(new Map),[P,F]=(0,X.useState)(new Map),[I,L]=(0,X.useState)(()=>{let e=Hd();return e===`unknown`?`macos`:e});(0,X.useEffect)(()=>{j.current=S},[S]),(0,X.useEffect)(()=>{M.current=u},[u]);let R=(0,X.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){_(jF(e))}},[e,n]);(0,X.useEffect)(()=>{if(!s||c)return;let e=setTimeout(()=>void R(),0);return()=>clearTimeout(e)},[R,c,s]),(0,X.useEffect)(()=>{if(!s)return;let e=setInterval(()=>{j.current!==`saving`&&(M.current&&k.current!==M.current||R())},6e4);return()=>clearInterval(e)},[R,s]);let z=(0,X.useMemo)(()=>u?kt(u):null,[u]),B=(0,X.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?Ct(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(jF(e))}finally{t.signal.aborted||x(!1)}},[u,e,z]);(0,X.useEffect)(()=>{if(!s||!z)return;let e=setTimeout(()=>void B(),250),t=setInterval(()=>void B(),6e4);return()=>{clearTimeout(e),clearInterval(t),A.current?.abort()}},[z,B,s]);let V=(0,X.useCallback)(e=>{c?.corrupt||(d(t=>t&&{...t,...e}),C(`saving`),D(null))},[c?.corrupt]);(0,X.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=Ke(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(jF(e)),C(`error`)}},300),()=>{O.current&&clearTimeout(O.current)}},[e,m,c?.corrupt,S,u]);let H=(0,X.useRef)(m);(0,X.useEffect)(()=>{H.current=m},[m]),(0,X.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:Ke(t,H.current)}),keepalive:!0}).catch(()=>{})},[e]);let U=(0,X.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(jF(e)),C(`error`)}},[e,R]),W=(0,X.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(jF(e))}},[e]);if(g)return(0,Z.jsx)(`section`,{ref:o,className:`usage-companion-panel`,children:(0,Z.jsx)(xF,{children:(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,role:`alert`,children:[(0,Z.jsx)(`p`,{className:`m-0 text-[14px] text-fg`,children:r(`usage.companion.settingsUnavailable`)}),(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:()=>void R(),children:r(`common.retry`)})]})})});let ee=u;if(!ee)return(0,Z.jsx)(`section`,{ref:o,className:`usage-companion-panel`,"aria-busy":`true`,children:(0,Z.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 te=t.map(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t).toSorted(),ne=Dt(m,P),G=S===`saved`&&c?.updatedAt?r(`usage.companion.saved`,{time:AF(c.updatedAt,i)}):S===`error`?r(`usage.companion.saveFailed`,{error:E??``}):``,K=c?.corrupt===!0;return(0,Z.jsxs)(`section`,{ref:o,className:`usage-companion-panel flex flex-col gap-4`,children:[K&&(0,Z.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,Z.jsx)(`span`,{children:r(`usage.companion.corrupt`)}),(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:()=>void U(),disabled:S===`saving`,children:r(`usage.companion.corruptReset`)})]}),(0,Z.jsx)(EF,{response:c,fetchedAt:w,installOs:I,onInstallOs:L,onOpenInBrowser:()=>void W(),t:r}),(0,Z.jsxs)(`div`,{className:`grid items-start gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,25rem)]`,children:[(0,Z.jsxs)(xF,{title:r(`usageV2.companionPreview`),children:[(0,Z.jsx)(rt,{timeline:f,chartStyle:ee.chartStyle,hours:ee.chartHours,loading:b,error:v,onRetry:()=>void B(),locale:i,t:r}),ne.length>0&&(0,Z.jsx)(DF,{groups:ne,current:ee,availableModels:m,knownTotals:P,disabled:K,onUpdate:V,t:r})]}),(0,Z.jsx)(xF,{title:r(`usageV2.companionSettings`),children:(0,Z.jsx)(kF,{current:ee,disabled:K,providerNames:te,onUpdate:V,t:r})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 px-1`,children:[(0,Z.jsxs)(`div`,{className:Y(`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:[G||`\xA0`,S===`error`&&(0,Z.jsx)(lp,{variant:`ghost`,size:`sm`,onClick:()=>{C(`saving`)},children:r(`common.retry`)})]}),(0,Z.jsx)(lp,{variant:`ghost`,size:`sm`,onClick:()=>void U(),children:r(`usage.companion.reset`)})]}),(0,Z.jsx)(`p`,{className:`m-0 px-1 text-xs text-fg-subtle`,children:r(`usage.companion.footer`)})]})}function PF({apiBase:e,providers:t}){let[n,r]=(0,X.useState)([]);return(0,X.useEffect)(()=>{if(t.length>0)return;let n=new AbortController;return fetch(`${e}/api/config`,{signal:n.signal}).then(e=>zn(e)).then(e=>{n.signal.aborted||r(Object.keys(e?.providers??{}).map(e=>({provider:e})))}).catch(()=>{}),()=>n.abort()},[e,t.length]),(0,Z.jsx)(NF,{apiBase:e,providers:t.length>0?t:n})}function FF(){return window.location.hash.replace(/^#\/?/,``)===`usage/companion`?`companion`:`report`}function IF(e){window.location.hash=e===`report`?`usage`:`usage/companion`}function LF(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`;IF(t),document.getElementById(`usage-tab-${t}`)?.focus()}}function RF(e){return window.addEventListener(L,e),()=>window.removeEventListener(L,e)}function zF(){return(0,X.useEffect)(()=>{U()},[]),(0,X.useSyncExternalStore)(RF,H,H)}var BF=[`all`,`codex`,`claude_code`,`claude_desktop`,`grok`,`opencode`,`aside`,`other`,`unknown`];function VF(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 HF(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 UF(e){return/(?:^|,)\s*no-store\s*(?:,|$)/i.test(e.headers.get(`cache-control`)??``)}function WF(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 GF=e=>!!e&&typeof e==`object`&&!Array.isArray(e),KF=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,qF=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0,JF=(e,t,n)=>t.every(t=>e[t]===void 0||n(e[t])),YF=(e,t)=>t.every(t=>KF(e[t]));function XF(e,t=0){return typeof e==`number`?Number.isFinite(e):!e||typeof e!=`object`?!0:t>=16?!1:Object.values(e).every(e=>XF(e,t+1))}function ZF(e){if(!GF(e)||!XF(e)||!GF(e.summary)||!Array.isArray(e.days)||!Array.isArray(e.models)||!Array.isArray(e.providers)||!KF(e.generatedAt)||e.since!==null&&!KF(e.since)||typeof e.historyTruncated!=`boolean`||typeof e.entriesTruncated!=`boolean`||!KF(e.truncatedPrefixBytes)||!KF(e.entriesDropped)||!KF(e.legacyUnclassifiedRequests)||!JF(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(!YF(t,[`requests`,`measuredRequests`,`reportedRequests`,`unreportedRequests`,`unsupportedRequests`,`estimatedRequests`])||![`inputTokens`,`outputTokens`,`cachedInputTokens`,`reasoningOutputTokens`,`totalTokens`].every(e=>qF(t[e]))||!qF(t.coverageRatio)||t.coverageRatio>1||!JF(t,[`cacheReadInputTokens`,`cacheCreationInputTokens`,`cacheObservedInputTokens`,`throughputOutputTokens`,`throughputDurationMs`],qF)||!JF(t,[`pricedRequests`,`unpricedRequests`,`unmeteredRequests`,`throughputSamples`,`attemptCount`,`sends`,`settledSends`,`unresolvedSends`,`spendRequests`,`cacheObservedRequests`,`cacheSynthesizedRequests`,`cacheUnknownRequests`],KF)||!JF(t,[`estimatedCostUsd`,`throughputTokensPerSec`],qF)||!JF(e,[`legacyUnclassifiedRequests`],KF)||!e.days.every(e=>GF(e)&&typeof e.date==`string`&&/^\d{4}-\d{2}-\d{2}$/.test(e.date)&&YF(e,[`requests`,`measuredRequests`,`reportedRequests`])&&qF(e.totalTokens)&&JF(e,[`estimatedCostUsd`],qF)&&Array.isArray(e.models)&&e.models.every(e=>GF(e)&&typeof e.model==`string`&&typeof e.provider==`string`&&YF(e,[`requests`])&&qF(e.totalTokens)&&JF(e,[`attemptCount`],KF)&&JF(e,[`inputTokens`,`outputTokens`,`cacheReadInputTokens`,`cacheCreationInputTokens`,`cacheObservedInputTokens`],qF))))return!1;let n=(e,t)=>GF(e)&&typeof e.provider==`string`&&(!t||typeof e.model==`string`)&&YF(e,[`requests`,`measuredRequests`,`reportedRequests`,`estimatedRequests`])&&qF(e.totalTokens)&&(!t||qF(e.inputTokens)&&qF(e.outputTokens))&&qF(e.shareRatio)&&JF(e,[`inputTokens`,`outputTokens`,`cachedInputTokens`,`cacheReadInputTokens`,`cacheCreationInputTokens`,`cacheObservedInputTokens`],qF)&&JF(e,[`pricedRequests`,`unpricedRequests`,`unmeteredRequests`,`throughputSamples`,`attemptCount`],KF)&&JF(e,[`estimatedCostUsd`,`throughputTokensPerSec`],qF)&&(e.cacheHitRate===void 0||e.cacheHitRate===null||qF(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 QF=class extends Error{},$F=class extends Error{};function eI(e,t,n,r,i,a){let o=JSON.stringify(n),s=`ocx.usage.resource:${JSON.stringify([e,t,n,i,a,r.generation])}`,c=n?.device.kind===`unconfigured`,l=(0,X.useCallback)(async n=>{let s=JSON.parse(o);if(!s)throw new QF;let l=VF(s);l.set(`range`,t),l.set(`surface`,`all`),i!==void 0&&a!==void 0&&(l.set(`since`,String(i)),l.set(`until`,String(a)));let u=await fetch(`${e}/api/usage?${l}`,{signal:n,...c?{cache:`no-store`}:{}});if(n.aborted||H().generation!==r.generation)throw new QF;if(u.status===401)throw T(r.generation),new QF;if(u.status===403)throw new $F;let d=await Vr(u);if(n.aborted||H().generation!==r.generation||!ZF(d)||!HF(d.sourceFilter,s)||d.range!==t||d.surface!==`all`||c&&!UF(u)||i!==void 0&&(d.customWindow!==!0||d.since!==i||d.until!==a))throw new QF;return d},[e,o,t,r.generation,i,a,c]),u=Fd(s,[s],l,{isEmpty:()=>!1,enabled:!r.blocked}),d=u.refresh,f=u.state.refreshing;(0,X.useEffect)(()=>{if(!c||r.blocked||f)return;let e=setTimeout(()=>d({forceLoading:!0}),15e3);return()=>clearTimeout(e)},[c,r.blocked,f,u.state.kind,d]),(0,X.useEffect)(()=>{if(!c||r.blocked)return;let t=()=>d({forceLoading:!0}),n=n=>{S(n,e)&&t()};return window.addEventListener(`focus`,t),window.addEventListener(C,n),()=>{window.removeEventListener(`focus`,t),window.removeEventListener(C,n)}},[c,r.blocked,e,d]);let p=u.state.error instanceof QF||u.state.error instanceof $F,m=r.blocked||p&&!u.state.refreshing,h=m||p||c&&(u.state.refreshing||u.state.showError),g=h?void 0:u.state.data,_=m?{...u.state,data:void 0,kind:`failed-cold`,showSkeleton:!1,showError:!0}:(c||p)&&h?{...u.state,data:void 0,kind:u.state.showError&&!u.state.refreshing?`failed-cold`:`cold`,showSkeleton:u.state.refreshing}:u.state;return{...u,data:g,state:_}}var tI={all:``,codex:`Codex`,claude_code:`Claude Code`,claude_desktop:`Claude Desktop`,grok:`Grok`,opencode:`OpenCode`,aside:`Aside`,other:``,unknown:``},nI=(e,t)=>e.kind===t.kind&&(e.kind!==`key`||t.kind===`key`&&e.id===t.id),rI=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,iI=[{kind:`all`},{kind:`no-key`},{kind:`unconfigured`}],aI={codex:`openai.svg`,claude_code:`claude-color.svg`,claude_desktop:`claude-color.svg`,grok:`grok.svg`,opencode:`opencode.svg`,aside:`aside.svg`};function oI(e){let t=aI[e];return t?(0,Z.jsx)(`img`,{className:`usage-source-mark${e===`grok`?` usage-source-mark--mono`:``}`,src:`/provider-icons/${t}`,alt:``}):(0,Z.jsx)(wt,{width:16,height:16,"aria-hidden":`true`})}function sI(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 cI(e,t){if(!e||!HF(e.sourceFilter,t)||!e.window||!Number.isFinite(e.window.since)||!WF(e.window)||typeof e.usageIncomplete!=`boolean`||!e.apps||!BF.every(t=>rI(e.apps[t]))||!rI(e.legacyUnclassifiedRequests)||e.unavailableConfiguredKeys!==void 0&&(!rI(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||!rI(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 lI({apiBase:e,requested:t,generation:n,identity:r,resultKey:i,setResult:a,setKnownInventory:o,setRoster:s}){let c=!1,l=0,d,f,p=async()=>{let m=++l;f?.abort(),f=new AbortController;let h=f;a({key:i});try{let{facets:d,selectableInventory:f}=await u(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===l&&T(n),!t.ok||!UF(t))throw Error(`usage source unavailable`);return t},[a,o]=await Promise.all([i(`${e}/api/usage/source-facets?${VF(t)}`),i(`${e}/api/usage/devices`)]),s=await a.json();if(!cI(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 u=c.devices;if(u.length>1024)throw Error(`inventory too large`);let d=new Set,f=0;for(let e of u){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:u.filter(e=>e.apiKeyId===e.apiKeyId.trim())}}catch(e){throw h.abort(),e}});!c&&m===l&&H().generation===n&&(o({identity:r,items:f}),s({identity:r,devices:d.devices.map(e=>e.device)}),a({key:i,facets:d,inventory:f}))}catch{h.abort(),!c&&m===l&&a({key:i,failed:!0})}finally{!c&&m===l&&(d=setTimeout(p,15e3))}};p();let m=()=>{d&&clearTimeout(d),p()},h=t=>{S(t,e)&&m()};return window.addEventListener(`focus`,m),window.addEventListener(C,h),()=>{c=!0,l++,f?.abort(),d&&clearTimeout(d),window.removeEventListener(`focus`,m),window.removeEventListener(C,h)}}function uI({apiBase:e,filter:t,onClient:n,onDevice:r,deviceLocked:i,facetsAllowed:a,homeScope:o,session:s,t:c,locale:l}){let[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)({key:``}),[g,_]=(0,X.useState)({identity:``,items:[]}),[v,y]=(0,X.useState)({identity:``,devices:[]}),b=JSON.stringify([e,s.generation]),x=(0,X.useRef)(null),w=JSON.stringify(t),T=e=>tI[e]||c(e===`all`?`usageV2.allApps`:e===`other`?`usageV2.otherApps`:`usageV2.unknown`),E=JSON.stringify([w,b]),D=!s.blocked&&m.key===E?m:{key:E},O=e=>{if(e.kind===`all`)return c(`usageV2.allDevices`);if(e.kind===`no-key`)return c(o?`usageV2.homeDevice`:Hd()===`macos`?`usageV2.thisMac`:`usageV2.thisDevice`);if(e.kind===`unconfigured`)return c(`usageV2.unconfigured`);if(e.kind===`key`){let t=D.inventory??(!s.blocked&&g.identity===b?g.items:[]),n=t.findIndex(t=>t.apiKeyId===e.id),r=t[n],i=D.facets?.devices.filter(e=>e.device.kind===`key`).findIndex(t=>nI(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,X.useEffect)(()=>{let t=JSON.parse(w);if(u&&t&&a&&!s.blocked)return lI({apiBase:e,requested:t,generation:s.generation,identity:b,resultKey:E,setResult:h,setKnownInventory:_,setRoster:y})},[u,e,a,w,b,E,s.blocked,s.generation]),(0,X.useEffect)(()=>{let t=()=>_({identity:``,items:[]}),n=n=>{S(n,e)&&t()},r=()=>{t(),y({identity:``,devices:[]}),h({key:``})};return window.addEventListener(`focus`,t),window.addEventListener(C,n),window.addEventListener(L,r),()=>{window.removeEventListener(`focus`,t),window.removeEventListener(C,n),window.removeEventListener(L,r)}},[e]);let k=e=>e===`codex`?[c(`usageV2.codexDetail`),D.facets&&!D.facets.usageIncomplete?c(`usageV2.codexUnclassified`,{count:D.facets.legacyUnclassifiedRequests.toLocaleString(l)}):null].filter(Boolean).join(` · `):e===`other`?c(`usageV2.otherDetail`):``,A=f.trim().toLocaleLowerCase(l),j=e=>!A||e.toLocaleLowerCase(l).includes(A),M=e=>D.facets&&!D.facets.usageIncomplete&&e!==void 0?e.toLocaleString(l):`—`,N=!s.blocked&&v.identity===b?v.devices:iI,P=t?.device,F=i?t?[t.device]:[]:P&&!N.some(e=>nI(e,P))?[...N,P]:N,I=BF.filter(e=>j(`${T(e)} ${k(e)}`)),R=F.filter(e=>j(O(e))),z=I.includes(t?.client??`codex`),B=!!t&&R.some(e=>nI(t.device,e));return(0,Z.jsxs)($.Popup,{open:u,onOpenChange:e=>{d(e),e?p(``):h({key:``})},label:c(`usageV2.source`),initialFocusRef:x,maxHeight:700,className:`ui-v2 overflow-auto rounded-panel bg-raised p-3 text-[13px] text-fg shadow-lg ring-1 ring-line`,onKeyDown:sI,trigger:(0,Z.jsxs)(Z.Fragment,{children:[oI(t?.client??`codex`),(0,Z.jsx)(`span`,{children:T(t?.client??`codex`)}),(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Z.jsx)(`span`,{children:t?O(t.device):c(`usageV2.unknown`)})]}),children:[(0,Z.jsx)(`input`,{ref:x,className:`input w-full`,type:`search`,"aria-label":c(`usageV2.searchSources`),placeholder:c(`usageV2.searchSources`),value:f,onChange:e=>p(e.currentTarget.value)}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":c(`usageV2.apps`),className:`mt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between px-2 text-fg-muted`,children:[(0,Z.jsx)(`span`,{children:c(`usageV2.apps`)}),(0,Z.jsx)(`span`,{children:c(`usageV2.last30`)})]}),I.map(e=>{let r=t?.client===e;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,tabIndex:r||!z&&I[0]===e?0:-1,onClick:()=>n(e),className:Y(`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,Z.jsx)(`span`,{className:`shrink-0 text-fg-muted`,children:oI(e)}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:T(e)}),k(e)&&(0,Z.jsx)(`span`,{className:`block text-xs text-fg-muted`,children:k(e)})]}),(0,Z.jsx)(`span`,{className:`text-fg-muted tabular-nums`,children:M(D.facets?.apps[e])}),r&&(0,Z.jsx)(ut,{width:16,height:16,"aria-hidden":`true`})]},e)})]}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":c(`usageV2.devices`),className:`mt-3 border-t border-line pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between px-2 text-fg-muted`,children:[(0,Z.jsx)(`span`,{children:c(`usageV2.devices`)}),(0,Z.jsx)(`span`,{children:c(`usageV2.last30`)})]}),R.map(e=>{let n=!!t&&nI(t.device,e),a=e.kind===`key`&&D.inventory?.some(t=>t.apiKeyId===e.id);return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,tabIndex:t&&(n||!B&&R[0]===e)?0:-1,onClick:()=>r(e),disabled:i,className:Y(`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,Z.jsx)(`span`,{className:`shrink-0 text-fg-muted`,children:e.kind===`key`?(0,Z.jsx)(xc,{icon:Ac,size:16,"aria-hidden":`true`}):e.kind===`unconfigured`?(0,Z.jsx)(Et,{width:16,height:16,"aria-hidden":`true`}):(0,Z.jsx)(ne,{width:16,height:16,"aria-hidden":`true`})}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:O(e)}),a&&(0,Z.jsx)(`span`,{className:`block text-xs text-fg-muted`,children:c(`usageV2.remoteLink`)})]}),(0,Z.jsx)(`span`,{className:`text-fg-muted tabular-nums`,children:M(D.facets?.devices.find(t=>nI(t.device,e))?.requests)}),n&&(0,Z.jsx)(ut,{width:16,height:16,"aria-hidden":`true`})]},e.kind===`key`?`key:${e.id}`:e.kind)})]}),(0,Z.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,Z.jsx)(`p`,{className:`mb-0 text-fg-muted`,children:c(`usageV2.unconfiguredHelp`)}),(0,Z.jsx)(`p`,{className:`mb-0 text-fg-muted`,children:c(`usageV2.classificationHelp`)}),!!D.facets?.unavailableConfiguredKeys&&(0,Z.jsx)(`p`,{role:`status`,className:`mb-0 text-fg-muted`,children:c(`usageV2.unavailableKeys`,{count:D.facets.unavailableConfiguredKeys.toLocaleString(l)})}),(D.failed||D.facets?.usageIncomplete||!a)&&(0,Z.jsx)(`p`,{role:`status`,className:`mb-0 text-fg-muted`,children:c(`usageV2.countsUnavailable`)})]})}function dI({filtered:e,t}){return(0,Z.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,Z.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,Z.jsx)(xc,{icon:Cc,size:20,strokeWidth:1.8})}),(0,Z.jsx)(`p`,{className:`m-0 max-w-[48ch] text-[15px] font-medium text-fg text-balance`,children:t(`usage.empty`)}),e&&(0,Z.jsx)(`p`,{className:`m-0 max-w-[48ch] text-[13px] text-fg-muted`,children:t(`usageV2.emptyFiltered`)})]})}function fI({data:e,range:t,customWindow:n,bars:r,activeDays:i,filteredModels:a,modelQuery:o,onModelQuery:s,sortedProviders:c,filtered:l,locale:u,t:d}){let f=(0,X.useMemo)(()=>IP(e?.days??[],n),[e?.days,n]);if(!e)return null;if(e.summary.requests===0)return(0,Z.jsx)(dI,{filtered:l,t:d});let p=n||t===`all`?`calendar`:`bars`,m=[{id:`overview`,body:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(BP,{summary:e.summary,days:r,activeDays:i,locale:u,t:d}),(0,Z.jsx)(GP,{defaultView:p,heatmap:f,bars:r,totalTokens:e.summary.totalTokens,locale:u,t:d},`${t}:${n}`)]})},{id:`models`,body:(0,Z.jsx)(YP,{models:a,totalModels:e.models.length,modelQuery:o,onModelQuery:s,locale:u,t:d})},{id:`providers`,body:(0,Z.jsx)(XP,{providers:c,locale:u,t:d})},{id:`coverage`,body:(0,Z.jsx)(ZP,{summary:e.summary,locale:u,t:d})}];return(0,Z.jsx)(`div`,{className:`usage-workspace-root`,children:(0,Z.jsx)(`section`,{className:`usage-workspace-main flex flex-col gap-4`,"aria-label":d(`usage.workspace.report`),children:m.map(e=>(0,Z.jsx)(`div`,{id:aj(`usage`,e.id),className:`usw-body usw-section-block flex flex-col gap-4`,children:e.body},e.id))})})}function pI({apiBase:e,connected:t=!1,apiKeyId:n,topology:r=t?`unknown`:`home`}){let{t:i,locale:o}=a(),[s,c]=(0,X.useState)(FF);(0,X.useEffect)(()=>{let e=()=>c(FF());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let[l,u]=(0,X.useState)(`30d`),[d,f]=(0,X.useState)(`codex`),[p,m]=(0,X.useState)({kind:`all`}),[h,g]=(0,X.useState)(`machine`),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)({since:``,until:``}),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(null),[T,E]=(0,X.useState)(!1),D=x?.since,O=x?.until,k=()=>{S(null),b({since:``,until:``}),w(null)},A=e=>{u(e),k()},j=()=>{let e=xP(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=zF(),I=eI(e,l,P,F,D,O),{state:L}=I,R=I.data??null,z=(0,X.useMemo)(()=>{let e=R?.days??[];return x||l===`all`?e.toSorted((e,t)=>e.date.localeCompare(t.date)):kP(e,l===`7d`?7:30)},[R?.days,x,l]),B=(0,X.useMemo)(()=>(R?.days??[]).filter(e=>e.requests>0).length,[R?.days]),V=(0,X.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,X.useMemo)(()=>(R?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[R?.providers]);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`page-head usage-head`,children:(0,Z.jsx)(`h2`,{id:`usage-page-title`,children:i(`usage.title`)})}),(0,Z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`nav.usage`),children:[`report`,`companion`].map(e=>(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:`usage-tab-${e}`,"aria-selected":s===e,"aria-controls":`usage-panel-${e}`,tabIndex:s===e?0:-1,className:`page-tab${s===e?` page-tab--active`:``}`,onClick:()=>IF(e),onKeyDown:LF,children:i(e===`report`?`usage.workspace.report`:`usage.section.companion`)},e))}),s===`companion`?(0,Z.jsx)(`div`,{role:`tabpanel`,id:`usage-panel-companion`,"aria-labelledby":`usage-tab-companion`,children:(0,Z.jsx)(PF,{apiBase:e,providers:R?.providers??[]})}):(0,Z.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,Z.jsx)(`p`,{className:`page-sub m-0 text-[13px]`,children:i(`usage.subtitle`)}),(0,Z.jsxs)(`section`,{className:`usage-range flex flex-col gap-3`,children:[(0,Z.jsxs)(aF,{children:[(0,Z.jsx)(uI,{apiBase:e,filter:P,onClient:f,onDevice:m,session:F,deviceLocked:M,facetsAllowed:r===`home`||r===`hub`,homeScope:t,t:i,locale:o}),(0,Z.jsx)($P,{range:x?null:l,onRange:A,t:i}),(0,Z.jsx)(tF,{open:T,active:x!==null,onToggle:()=>{T&&w(null),E(!T)},t:i}),t&&r===`hub`&&(0,Z.jsx)(`div`,{className:`ml-auto`,children:(0,Z.jsx)(eF,{scope:h,onScope:e=>{g(e),m({kind:`all`})},t:i})}),x&&(0,Z.jsx)(nF,{window:x,locale:o,t:i})]}),T&&(0,Z.jsx)(iF,{draft:y,error:C,onDraft:e=>{b(t=>({...t,...e})),w(null)},onApply:j,onClear:k,t:i})]}),L.showSkeleton&&!R?(0,Z.jsx)(NE,{label:i(`usage.loading`),rows:6,className:`usage-v2-skeleton`}):L.kind===`failed-cold`?(0,Z.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,Z.jsx)(`span`,{className:`grid size-10 place-items-center rounded-control bg-danger-soft text-danger [&_svg]:size-5`,"aria-hidden":`true`,children:(0,Z.jsx)(at,{})}),(0,Z.jsx)(`p`,{className:`m-0 max-w-[56ch] text-[14px] text-fg`,children:L.error instanceof QF?`${i(`usage.loadError`)} ${i(`dash.codexRestartMalformed`)}`:L.error instanceof Br||L.error instanceof $F?i(`usage.loadError`):t?i(`usage.hubOffline`):L.error instanceof Error?`${i(`usage.loadError`)} ${L.error.message}`:i(`usage.loadError`)}),(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:()=>I.refresh(),children:i(`common.retry`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[L.showError&&(0,Z.jsx)(Q,{tone:`err`,children:i(t&&!(L.error instanceof Br)?`usage.hubOffline`:`usage.loadError`)}),(0,Z.jsx)(Ur,{data:R}),(d===`grok`||d===`aside`||d===`other`)&&(0,Z.jsx)(`p`,{className:`text-fg-muted text-[13px]`,role:`status`,children:i(`usageV2.clientUnverified`)}),d===`codex`&&typeof R?.legacyUnclassifiedRequests==`number`&&(0,Z.jsx)(`p`,{className:`text-fg-muted text-[13px]`,role:`status`,children:i(`usageV2.legacy`,{count:R.legacyUnclassifiedRequests})}),R?.historyTruncated&&(0,Z.jsx)(Q,{tone:`warn`,children:(()=>{let e=mI(R.snapshotWindowStart),t=mI(R.snapshotWindowEnd);return e!==null&&t!==null?i(`usage.historyTruncatedWindow`,{start:e,end:t}):i(`usage.historyTruncated`)})()}),(0,Z.jsx)(fI,{data:R,range:l,customWindow:x!==null,bars:z,activeDays:B,filteredModels:V,modelQuery:_,onModelQuery:v,sortedProviders:H,filtered:d!==`all`||N?.kind!==`all`||l!==`all`||x!==null,locale:o,t:i})]})]})]})}function mI(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function hI(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 gI={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 _I(e,t){return gI[e][t]}var vI={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 yI(e,t){return vI[e][t]}var bI={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 xI(e,t){return bI[e].schema[t]}function SI(e,t){return bI[e].protection[t]}function CI(e,t){return bI[e].mode[t]}var wI={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 TI(e,t){let n=wI[e.key];return n?t(n):e.label}function EI(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function DI(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function OI(e,t){switch(t){case`codex_running`:return yI(e,`error.codex_running`);case`process_enumeration_failed`:return yI(e,`error.process_enumeration_failed`);case`busy`:return yI(e,`error.busy`);case`unsupported_schema`:return yI(e,`error.unsupported_schema`);case`trigger_collision`:return _I(e,`error.trigger_collision`);case`unsafe_path`:return yI(e,`error.unsafe_path`);case`database_error`:return yI(e,`error.database_error`);case`auto_vacuum_not_incremental`:return yI(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return yI(e,`error.integrity_check_failed`);case`config_write_failed`:return _I(e,`error.config_write_failed`);default:return yI(e,`error.generic`)}}function kI({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,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,Z.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,Z.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:n(`dash.status`)}),(0,Z.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,Z.jsx)(`code`,{children:xI(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Z.jsx)(`code`,{children:_I(t,`inspectionOnly`)})]}):null]})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:hI(e.files.databaseBytes,t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:(0,Z.jsx)(`code`,{children:`WAL`})}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:hI(e.files.walBytes,t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:(0,Z.jsx)(`code`,{children:`SHM`})}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:hI(e.files.shmBytes,t)})]}),s&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:(0,Z.jsx)(`code`,{children:`TRACE`})}),(0,Z.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:(0,Z.jsx)(`code`,{children:`freelist`})}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:hI(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,Z.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,Z.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Z.jsx)(`dd`,{className:`muted`,children:_I(t,`metricsSkippedLarge`).replace(`{threshold}`,hI(e.metricsSkipped.thresholdBytes,t))})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:(0,Z.jsx)(`code`,{children:`sqlite_home`})}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,Z.jsx)(`code`,{children:e.externalSqliteHome?_I(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,Z.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,Z.jsx)(`h4`,{className:`stw-section-title`,children:_I(t,`protection`)}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:(0,Z.jsx)(`code`,{children:SI(t,l.state)})}),(0,Z.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,Z.jsx)(`code`,{children:CI(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Z.jsx)(`code`,{children:CI(t,l.observedMode)})]})]})]}),(0,Z.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Z.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:_I(t,`compat`)}),(0,Z.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:_I(t,`quiet`)}),(0,Z.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:_I(t,`disable`)}),l.state===`drifted`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:_I(t,`repair`)}),r&&(0,Z.jsx)(`span`,{className:`muted`,role:`status`,children:yI(t,`applying`)})]}),i&&(0,Z.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,Z.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,Z.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:_I(t,`confirmCompact`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:_I(t,`cancel`)})]}):(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:_I(t,`compact`)})})}),a&&(0,Z.jsx)(`div`,{className:`stw-section`,children:(0,Z.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,Z.jsxs)(`div`,{className:`stw-section`,children:[(0,Z.jsx)(`h4`,{className:`stw-section-title`,children:(0,Z.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,Z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Z.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,Z.jsx)(`code`,{children:e.target})}),(0,Z.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,Z.jsx)(`p`,{className:`stw-hint`,children:(0,Z.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function AI({locale:e,t}){return(0,Z.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,Z.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,Z.jsx)(`p`,{className:`stw-hint`,children:_I(e,`inspectionUnavailable`)})]})}function jI({report:e,locale:t,apiBase:n=``,logGuardBusy:r=!1,onLogGuardAction:i}){let a=c(),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),_=(0,X.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),v=_.find(e=>e.key===o)??null,y=l?.generation===e.generatedAt?l.report:e.codexLogs??null,b=p?.generation===e.generatedAt?p.message:null,x=h?.generation===e.generatedAt?h.summary:null,S=r||d,C=(0,X.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,X.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,Z.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,Z.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":a(`storage.section.buckets`),children:[(0,Z.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,Z.jsx)(`span`,{className:`storage-workspace-rail-title`,children:a(`storage.section.buckets`)}),(0,Z.jsx)(`span`,{className:`storage-workspace-rail-count`,children:_.length})]}),(0,Z.jsx)(`div`,{className:`storage-workspace-rail-list`,children:_.length===0?(0,Z.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:a(`storage.empty`)}):_.map(e=>(0,Z.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,Z.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,Z.jsx)(`span`,{className:`storage-workspace-rail-name`,children:TI(e,a)}),(0,Z.jsx)(`span`,{className:`storage-workspace-rail-size`,children:hI(e.bytes,t)})]}),(0,Z.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,a(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,Z.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":v?TI(v,a):a(`storage.section.largest`),children:v?(0,Z.jsxs)(`div`,{className:`stw-detail`,children:[(0,Z.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>s(null),children:[(0,Z.jsx)(St,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),a(`modal.back`)]})}),(0,Z.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,Z.jsx)(`h2`,{className:`stw-detail-title`,children:TI(v,a)}),(0,Z.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a(`storage.col.size`)}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:hI(v.bytes,t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a(`storage.col.files`)}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:v.fileCount.toLocaleString(t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a(`storage.col.oldest`)}),(0,Z.jsx)(`dd`,{children:EI(v.oldest,t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a(`storage.col.newest`)}),(0,Z.jsx)(`dd`,{children:EI(v.newest,t)})]}),(0,Z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a(`storage.col.rows`)}),(0,Z.jsx)(`dd`,{className:`stw-kv-mono`,children:DI(v,t,a)})]})]}),(v.largest?.length??0)>0&&(0,Z.jsxs)(`div`,{className:`stw-section`,children:[(0,Z.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),v.largest.map(e=>(0,Z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Z.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,Z.jsx)(`span`,{className:`stw-file-size`,children:hI(e.bytes,t)})]},e.path))]})]})]}):(0,Z.jsxs)(`div`,{className:`stw-overview`,children:[(0,Z.jsxs)(`div`,{className:`stw-summary`,children:[(0,Z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Z.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.total`)}),(0,Z.jsx)(`div`,{className:`stw-summary-value`,children:hI(e.total.bytes,t)})]}),(0,Z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Z.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.files`)}),(0,Z.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,Z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Z.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.home`)}),(0,Z.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),y?(0,Z.jsx)(kI,{report:y,locale:t,t:a,busy:S,error:b,compaction:x,onAction:r=>{if(i){i(r);return}if(d)return;let a=e.generatedAt;(async()=>{f(!0),m(null),r.action===`compact`&&g(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(()=>({}));m({generation:a,message:OI(t,e.error)});return}if(r.action===`compact`){let e=(await o.json().catch(()=>null))?.report;if(e){let n=hI(e.logicalBytesReclaimed??0,t),r=hI(e.physicalDatabaseBytesReclaimed??0,t),i=e.complete?_I(t,`compactComplete`):_I(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;g({generation:a,summary:[`${i}${s}`,`${o.toLocaleString(t)} ${_I(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${n}/api/storage/codex-logs`);if(e.ok){let t=await e.json();u({generation:a,report:t})}}catch{}return}let s=await o.json();u({generation:a,report:s})}catch{m({generation:a,message:yI(t,`error.generic`)})}finally{f(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,Z.jsx)(AI,{locale:t,t:a}):null,C.length>0?(0,Z.jsxs)(`div`,{className:`stw-section`,children:[(0,Z.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),C.map(e=>{let n=w.get(e.bucketKey);return(0,Z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Z.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,Z.jsx)(`span`,{className:`stw-file-bucket`,children:TI(n,a)}),(0,Z.jsx)(`span`,{className:`stw-file-size`,children:hI(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,Z.jsxs)(`p`,{className:`stw-hint`,children:[(0,Z.jsx)(Ot,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),a(`storage.workspace.selectBucket`)]})]})})]})}var MI=1024**3,NI=[10,25,50],PI=(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 FI({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,X.useState)(25),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(null),y=(0,X.useRef)(null),b=(0,X.useRef)(!1),x=(0,X.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,X.useEffect)(()=>{b.current=f},[f]),(0,X.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){_(PI(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:hI(a.bytes,t)});h(a.skippedReferencedPaths?.length?`${s} ${n(`storage.cleanup.skippedReferenced`,{count:String(a.skippedReferencedPaths.length)})}`:s),r()}catch(e){_(PI(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,Z.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,Z.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,Z.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,Z.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,Z.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,Z.jsx)(`div`,{className:`storage-manual-panel__presets`,children:NI.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:C(e)},e))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void w(),children:n(`storage.cleanup.preview`)})]}),m&&(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,Z.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,Z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&x(),children:(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,Z.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:hI(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,Z.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,Z.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,Z.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,Z.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,Z.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,Z.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,Z.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,Z.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Z.jsx)(`button`,{ref:v,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>x(),children:n(`storage.cleanup.cancel`)}),(0,Z.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 II({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(!1);(0,X.useEffect)(()=>{g.current=o},[o]);let _=(0,X.useCallback)(()=>l(null),[]);(0,X.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,X.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=Fd(`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:hI(a.bytes,t)})),r()}catch(e){p(PI(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,Z.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,Z.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),y.showError&&!c&&(0,Z.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,Z.jsx)(PE,{live:!y.showError,children:n(`storage.trash.loading`)}),y.showSkeleton?(0,Z.jsx)(NE,{label:n(`storage.trash.loading`),rows:2}):b.length===0?(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,Z.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,Z.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,Z.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,Z.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,Z.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,Z.jsx)(`th`,{})]})}),(0,Z.jsx)(`tbody`,{children:b.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{className:`muted`,children:C(e)}),(0,Z.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,Z.jsx)(`td`,{className:`num mono`,children:hI(e.bytes,t)}),(0,Z.jsx)(`td`,{className:`muted`,children:w(e.mode)}),(0,Z.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,Z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&_(),children:(0,Z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,Z.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:hI(c.bytes,t),id:c.id})}),f&&(0,Z.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,Z.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Z.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>_(),children:n(`storage.trash.cancel`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void S(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function LI(e){let{job:t,...n}=e;return n}function RI(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/MI*100)/100));return e.target.reduceToBytes===void 0?{policy:LI(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:LI(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/MI*100)/100))}}async function zI(e){await new Promise(t=>window.setTimeout(t,e))}function BI({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=kd(i),o=(0,X.useRef)(!!a),[s,c]=(0,X.useState)(()=>a?.policy??null),[l,u]=(0,X.useState)(()=>!a),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(()=>a?.targetMode??`percent`),[x,S]=(0,X.useState)(()=>a?.percent??`25`),[C,w]=(0,X.useState)(()=>a?.reduceGb??`4`),[T,E]=(0,X.useState)(()=>a?.thresholdGb??`5`),D=(0,X.useRef)(null),O=(0,X.useRef)(!1),k=(0,X.useRef)(!1),A=(0,X.useRef)(0),j=(0,X.useCallback)(e=>{let t=RI(e);c(t.policy),E(t.thresholdGb),b(t.targetMode),S(t.percent),w(t.reduceGb),o.current=!0,Nd(i,t),O.current=!1},[i]),M=(0,X.useCallback)(()=>{O.current=!0},[]),N=(0,X.useCallback)(e=>{k.current=e},[]),P=(0,X.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,X.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{P(e.signal)},0);return()=>{window.clearTimeout(t),A.current+=1,e.abort()}},[P]),(0,X.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*MI)}}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*MI)},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 zI(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=LI(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:hI(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:hI(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,Z.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,Z.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,Z.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Z.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,Z.jsx)(`div`,{className:`storage-policy-enable`,children:(0,Z.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,Z.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,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,Z.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,Z.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,Z.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,Z.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,Z.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,Z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Z.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,Z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Z.jsx)(wh,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{M(),E(Ch(T,.1,0,1e4,.1))},onDecrement:()=>{M(),E(Ch(T,-.1,0,1e4,.1))}})]})]})]}),(0,Z.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,Z.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,Z.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`percent`,disabled:d||p,onChange:()=>{M(),b(`percent`)}}),(0,Z.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),y===`percent`&&(0,Z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Z.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,Z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Z.jsx)(wh,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{M(),S(Ch(x,1,1,100))},onDecrement:()=>{M(),S(Ch(x,-1,1,100))}})]})]}),(0,Z.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`reduce`,disabled:d||p,onChange:()=>{M(),b(`reduce`)}}),(0,Z.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),y===`reduce`&&(0,Z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Z.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,Z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Z.jsx)(wh,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{M(),w(Ch(C,.1,0,1e4,.1))},onDecrement:()=>{M(),w(Ch(C,-.1,0,1e4,.1))}})]})]})]}),(0,Z.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,Z.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,Z.jsx)($,{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,Z.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,Z.jsx)($,{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,Z.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,Z.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,Z.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,Z.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[R(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:hI(s.lastRun.freedBytes,t)})}`:``]})]}),(0,Z.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Z.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,Z.jsx)(`span`,{className:`storage-policy-meta-value`,children:R(s.nextRun)})]})]}),(0,Z.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void I(),children:n(`storage.policy.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,Z.jsx)(`span`,{className:`storage-policy-actions__status${_?` is-error`:``}`,role:_?`alert`:`status`,"aria-live":`polite`,children:_??h??``})]})]}):(0,Z.jsx)(`section`,{className:`storage-cleanup-pane`,children:_&&(0,Z.jsx)(`p`,{className:`err`,role:`alert`,children:_})})}function VI({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,X.useState)(`policy`),u=(0,X.useRef)(null),d=(0,X.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,Z.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,Z.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,Z.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,Z.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,Z.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,Z.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,Z.jsx)(BI,{apiBase:e,locale:t,t:n,onDone:o}),(0,Z.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,Z.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,Z.jsx)(FI,{apiBase:e,locale:t,t:n,onDone:o}):(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,Z.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,Z.jsx)(II,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,Z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function HI({apiBase:e}){let{t,locale:n}=a(),r=`ocx.storage.report.v1:${e}`,i=kd(r),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(0),u=(0,X.useRef)(!1),[d,f]=(0,X.useState)({apiBase:e,settled:!1,hasEntries:!1}),p=(0,X.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 Nd(r,a),u.current&&(u.current=!1,s(t(`storage.rescanned`))),a}catch(e){throw u.current&&(u.current=!1,s(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,r,t]),m=Fd(`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,X.useCallback)(()=>{s(null),u.current=!0,v(),l(e=>e+1)},[v]),b=(0,X.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,Z.jsxs)(`div`,{className:`storage-v2 flex min-w-0 flex-col gap-4 font-sans text-fg`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 basis-80 flex-col gap-1`,children:[(0,Z.jsx)(`h2`,{id:`storage-page-title`,className:`m-0 text-title font-semibold tracking-[-0.025em]`,children:t(`storage.title`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:t(`storage.subtitle`)})]}),(0,Z.jsxs)(`div`,{className:`storage-page-head-actions flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`storage-page-head-feedback text-[13px] text-fg-muted`,role:`status`,"aria-live":`polite`,children:o??``}),(0,Z.jsxs)(`button`,{type:`button`,className:Y(fM,`disabled:cursor-default disabled:opacity-50`),disabled:_,onClick:()=>void y(),children:[(0,Z.jsx)(`span`,{className:Y(`inline-flex`,_&&`animate-spin`),children:(0,Z.jsx)(Mt,{"aria-hidden":!0})}),t(`storage.refresh`)]})]})]}),g&&g.error===void 0&&(0,Z.jsxs)(`p`,{className:`storage-page-meta m-0 -mt-2`,children:[(0,Z.jsx)(`code`,{className:`mono storage-page-meta__home`,title:g.codexHome,children:g.codexHome}),(0,Z.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,Z.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(g.generatedAt).toLocaleString(n)]})]}),h.showSkeleton&&!g?(0,Z.jsx)(NE,{label:t(`storage.loading`),rows:5}):h.kind===`failed-cold`&&!g?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:h.error instanceof Error?h.error.message:t(`storage.error`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,Z.jsxs)(Z.Fragment,{children:[h.showError&&(0,Z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,Z.jsx)(Nn,{title:t(`storage.empty`)}):g&&g.total.fileCount>0&&(0,Z.jsx)(jI,{report:g,locale:n,apiBase:e})]}),g&&g.error===void 0&&h.refreshing&&!h.showSkeleton&&(0,Z.jsx)(PE,{live:!h.showError,children:t(`storage.loading`)}),E&&(0,Z.jsx)(VI,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:c,onDone:()=>void y(),onTrashEntriesChange:b})]})}var UI=`/api/codex-auth/features/default-mode-request-user-input`;function WI({apiBase:t}){let n=c(),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(!1),h=(0,X.useRef)(!1),g=(0,X.useRef)(0),_=(0,X.useCallback)(async()=>{if(m.current)return;let n=++g.current,r=e(15e3);try{let e=await fetch(`${t}${UI}`,{signal:r.signal});if(!e.ok)throw Error(`load`);let a=await e.json();if(m.current||n!==g.current)return;h.current=a.enabled===!0,i(h.current),o(!0),d(!1)}catch{!m.current&&n===g.current&&d(!0)}finally{r.clear()}},[t]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{_()},0),t=Ru(()=>{_()},3e4);return()=>{window.clearTimeout(e),t()}},[_]);let v=(0,X.useCallback)(async()=>{if(m.current||!a||u)return;let e=!h.current,r=h.current;h.current=e,i(e),m.current=!0,l(!0),p(null),g.current++;try{let r=await fetch(`${t}${UI}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e})}),a=await zn(r)??{};if(a.ok!==!0)throw Error(String(r.status));h.current=a.enabled===!0,i(h.current),o(!0),p({tone:`ok`,message:n(a.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){h.current=r,i(r);let t=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:n(`codexAuth.requestUserInputUpdateFailed`);p({tone:`err`,message:t})}finally{m.current=!1,l(!1)}},[t,a,u,n]),y=s||!a||u;return(0,Z.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":s||!a&&!u||void 0,children:[(0,Z.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,Z.jsx)(`strong`,{children:n(`codexAuth.requestUserInput`)}),(0,Z.jsx)(`div`,{className:`card-sub`,role:u?`alert`:void 0,children:n(u?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,Z.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
|
|
9
|
+
default_mode_request_user_input = true`})]}),(0,Z.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[u&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{_()},children:n(`common.retry`)}),(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{v()},disabled:y,"aria-pressed":r,"aria-label":n(`codexAuth.requestUserInput`),title:n(`codexAuth.requestUserInput`),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]}),f&&(0,Z.jsx)(`div`,{className:`codex-request-user-input-feedback${f.tone===`err`?` is-error`:``}`,role:f.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:f.message})]})}function GI({apiBase:t}){let n=c(),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(!1),h=(0,X.useRef)(0),g=(0,X.useCallback)(async()=>{if(m.current)return;let n=++h.current,r=e(15e3);try{let e=await fetch(`${t}/api/settings`,{signal:r.signal});if(!e.ok)throw Error(`load`);let a=await e.json();if(m.current||n!==h.current)return;i(a.ultraFastTier===!0),o(!0),d(!1)}catch{!m.current&&n===h.current&&d(!0)}finally{r.clear()}},[t]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=Ru(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,X.useCallback)(async()=>{if(m.current||!a||u)return;let o=!r;m.current=!0,l(!0),p(null),i(o);let s=e(15e3);try{let e=await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({ultraFastTier:o}),signal:s.signal});if(!e.ok)throw Error(`save`);let r=await e.json(),a=typeof r.ultraFastTier==`boolean`?r.ultraFastTier:o;i(a),p({tone:`ok`,message:n(a?`codexAuth.ultraFastEnabled`:`codexAuth.ultraFastDisabled`)})}catch{i(!o),p({tone:`err`,message:n(`codexAuth.ultraFastFailed`)})}finally{s.clear(),m.current=!1,l(!1)}},[t,r,a,u,n]),v=s||!a||u;return(0,Z.jsxs)(`div`,{className:`card card-row codex-ultrafast-card`,style:{marginTop:16},"aria-busy":s||!a&&!u||void 0,children:[(0,Z.jsxs)(`div`,{className:`codex-ultrafast-copy`,children:[(0,Z.jsx)(`strong`,{children:n(`codexAuth.ultraFastTitle`)}),(0,Z.jsx)(`div`,{className:`card-sub`,role:u?`alert`:void 0,children:n(u?`codexAuth.ultraFastLoadFailed`:`codexAuth.ultraFastDesc`)})]}),(0,Z.jsxs)(`div`,{className:`codex-ultrafast-controls`,children:[u&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},children:n(`common.retry`)}),(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{_()},disabled:v,"aria-pressed":r,"aria-label":n(`codexAuth.ultraFastTitle`),title:n(`codexAuth.ultraFastTitle`),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]}),f&&(0,Z.jsx)(`div`,{className:`codex-ultrafast-feedback${f.tone===`err`?` is-error`:``}`,role:f.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:f.message})]})}var KI=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function qI(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`||!KI.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 JI(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=qI(t.codexMainAccountHardLockFallback);return{...t,codexMainAccountHardLock:t.codexMainAccountHardLock,mainAccountHardLock:n,codexMainAccountHardLockFallback:r}}function YI({pending:e,thresholds:t,onCancel:n,onConfirm:r}){let i=c(),a=(0,X.useId)(),o=(0,X.useRef)(null),s=(0,X.useRef)(null),l=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let e=o.current;return e&&!e.open&&e.showModal(),s.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Z.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:l.current,r=t.shiftKey?l.current:s.current;document.activeElement===n&&(t.preventDefault(),r?.focus())},children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`common.close`),disabled:e,onClick:n}),(0,Z.jsxs)(`div`,{className:`modal-card codex-main-hard-lock-dialog`,role:`document`,children:[(0,Z.jsx)(`h3`,{id:`${a}-title`,children:i(`codexAuth.mainHardLockConfirmTitle`,t)}),(0,Z.jsx)(`p`,{id:`${a}-body`,className:`modal-desc`,children:i(`codexAuth.mainHardLockConfirmBody`)}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{ref:s,type:`button`,className:`btn btn-ghost`,disabled:e,onClick:n,children:i(`codexAuth.cancel`)}),(0,Z.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,disabled:e,onClick:r,children:i(e?`common.saving`:`codexAuth.mainHardLockConfirm`)})]})]})]})}function XI(e){return(0,Z.jsx)(ZI,{...e},e.apiBase)}function ZI({apiBase:t,onSaved:n}){let r=c(),i=(0,X.useId)(),[a,o]=(0,X.useState)(null),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)([]),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(!1),O=(0,X.useRef)(!1),k=(0,X.useRef)(!1),A=(0,X.useRef)(0),j=(0,X.useRef)(null),M=(0,X.useRef)(null),N=(0,X.useRef)(!1),P=(0,X.useCallback)(()=>{if(N.current||M.current)return;let e=new AbortController;M.current=e,(async()=>{try{let n=await fetch(`${t}/api/models`,{signal:e.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===e&&(M.current=null)}})()},[t]),F=(0,X.useRef)(null),I=(0,X.useRef)(null),L=(0,X.useRef)(!1),R=(0,X.useCallback)(async()=>{if(O.current)return;let n=++A.current;j.current?.abort();let r=e(15e3);j.current=r.controller;try{let e=await fetch(`${t}/api/settings`,{signal:r.signal});if(!e.ok)throw Error(`load`);let i=JI(await e.json());if(!k.current||n!==A.current)return;o(i),x(i.codexMainAccountHardLockFallback),l(!1),h(null)}catch{k.current&&n===A.current&&l(!0)}finally{r.clear()}},[t]);(0,X.useEffect)(()=>{k.current=!0;let e=window.setTimeout(()=>{R()},0),t=Ru(()=>{R()},3e4);return()=>{k.current=!1,A.current+=1,j.current?.abort(),M.current?.abort(),M.current=null,window.clearTimeout(e),t()}},[R]),(0,X.useEffect)(()=>{v||g||!L.current||(F.current&&!F.current.disabled?(F.current.focus(),L.current=!1):I.current?.focus())},[v,g,s,a]);let z=async()=>{let e=!1;try{e=await n()}catch{}k.current&&p(!e)},B=async n=>{if(O.current||!a)return;O.current=!0,A.current+=1,j.current?.abort(),_(!0),d(!1),p(!1),h(null);let r=e(15e3),i=!1;try{let e=await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLock:n}),signal:r.signal});if(!e.ok)throw Error(`save`);let a=await e.json();if(!a||typeof a!=`object`||!(`ok`in a)||a.ok!==!0)throw Error(`unconfirmed`);let s=JI(a);i=!0,k.current&&(o(s),l(!1),h(s.codexMainAccountHardLock))}catch{k.current&&(d(!0),l(!0))}finally{r.clear()}i&&await z(),O.current=!1,k.current&&(_(!1),y(!1),i||R())},V=()=>{O.current||y(!1)},H=async n=>{if(O.current||w||!a)return;O.current=!0,A.current+=1,j.current?.abort(),T(!0),D(!1);let r=e(15e3),i=!1;try{let e=await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLockFallback:n}),signal:r.signal});if(!e.ok)throw Error(`save`);let a=await e.json();if(!a||typeof a!=`object`||!(`ok`in a)||a.ok!==!0)throw Error(`unconfirmed`);let s=JI(a);i=!0,k.current&&(o(s),x(s.codexMainAccountHardLockFallback),l(!1))}catch{k.current&&D(!0)}finally{r.clear()}i&&await z(),O.current=!1,k.current&&(T(!1),i||R())},U=b?.enabled!==!1&&!!b?.model,W=()=>{b?.model&&H({...b,enabled:!U})},ee=e=>{if(!e)return;let{enabled:t,...n}=b??{};H({...n,model:e,...b?.enabled===!1?{enabled:!0}:{}})},te=e=>{H({...b??{},...e?{reasoningEffort:e}:{reasoningEffort:void 0}})},ne=async()=>{O.current||(O.current=!0,A.current+=1,_(!0),await z(),O.current=!1,k.current&&_(!1))},G=a?.codexMainAccountHardLock,K=Wg(a?.mainAccountHardLock.thresholds);return(0,Z.jsxs)(`section`,{ref:I,id:`codex-main-hard-lock-setting`,tabIndex:-1,className:`card card-row codex-main-hard-lock-setting`,"aria-labelledby":`${i}-title`,"aria-busy":g||!a&&!s||void 0,onBlurCapture:e=>{e.relatedTarget!==null&&!e.currentTarget.contains(e.relatedTarget)&&(L.current=!1)},children:[(0,Z.jsxs)(`div`,{className:`codex-main-hard-lock-copy`,children:[(0,Z.jsx)(`strong`,{id:`${i}-title`,children:r(`codexAuth.mainHardLockTitle`,K)}),(0,Z.jsx)(`div`,{id:`${i}-desc`,className:`card-sub`,children:r(`codexAuth.mainHardLockDesc`,K)})]}),(0,Z.jsx)(`button`,{ref:F,type:`button`,className:`toggle ${G===!0?`on`:``}`,disabled:g||G===void 0||s,"aria-pressed":G,"aria-label":r(`codexAuth.mainHardLockTitle`,K),"aria-describedby":`${i}-desc`,onClick:()=>{O.current||G===void 0||s||(L.current=!0,G?B(!1):y(!0))},children:(0,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsxs)(`div`,{className:`codex-main-hard-lock-feedback`,children:[a?.mainAccountHardLock.externalUsage&&(0,Z.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Z.jsx)(`p`,{role:`status`,children:r(`codexAuth.mainExternalUsageWarning`)})}),(u||s)&&(0,Z.jsxs)(`p`,{role:`alert`,children:[r(u?`codexAuth.mainHardLockSaveFailed`:`codexAuth.mainHardLockLoadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:g,onClick:()=>{R()},children:r(`common.retry`)})]}),m!==null&&!f&&(0,Z.jsx)(`p`,{role:`status`,children:r(m?`codexAuth.mainHardLockEnabled`:`codexAuth.mainHardLockDisabled`,K)}),f&&(0,Z.jsxs)(`p`,{role:`status`,children:[r(`codexAuth.mainHardLockRefreshFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:g,onClick:()=>{ne()},children:r(`common.retry`)})]})]}),(0,Z.jsxs)(`div`,{className:`codex-main-hard-lock-fallback`,role:`group`,"aria-label":r(`codexAuth.mainHardLockFallbackTitle`),onFocusCapture:P,onPointerDownCapture:P,onClickCapture:P,style:{flexBasis:`100%`},children:[(0,Z.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,Z.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8,minWidth:0},children:(0,Z.jsx)(`span`,{className:`font-semibold`,children:r(`codexAuth.mainHardLockFallbackTitle`)})}),(0,Z.jsxs)(`div`,{className:`setting-controls`,style:{flex:`0 1 auto`},children:[(0,Z.jsx)(`button`,{type:`button`,className:`switch ${U?`on`:``}`,onClick:W,disabled:w||s||!b?.model,"aria-label":r(`codexAuth.mainHardLockFallbackTitle`),"aria-pressed":U,children:(0,Z.jsx)(`span`,{className:`knob`})}),(0,Z.jsx)($,{value:b?.model??``,options:[...new Set([b?.model,...S.map(e=>e.namespaced)].filter(e=>!!e))].map(e=>({value:e,label:He(e,r)})),onChange:ee,disabled:w||s,label:r(`codexAuth.mainHardLockFallbackModel`),align:`right`}),(0,Z.jsx)($,{value:b?.reasoningEffort??``,options:[{value:``,label:r(`codexAuth.mainHardLockFallbackDefaultEffort`)},...KI.map(e=>({value:e,label:r(`models.reasoningEffort.${e}`)}))],onChange:te,disabled:w||s||!U,label:r(`codexAuth.mainHardLockFallbackEffort`),align:`right`})]})]}),(0,Z.jsx)(`div`,{className:`muted setting-hint`,children:r(`codexAuth.mainHardLockFallbackDesc`)}),a?.mainAccountHardLock.state===`blocked`&&U&&b?.model&&(0,Z.jsx)(`p`,{role:`status`,className:`codex-main-hard-lock-status is-blocked`,children:r(`codexAuth.mainHardLockFallbackActive`,{model:b.model})}),E&&(0,Z.jsxs)(`p`,{role:`alert`,children:[r(`codexAuth.mainHardLockFallbackSaveFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:w,onClick:()=>{R()},children:r(`common.retry`)})]})]}),v&&(0,Z.jsx)(YI,{pending:g,thresholds:K,onCancel:V,onConfirm:()=>{B(!0)}})]})}function QI({apiBase:t}){let n=c(),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(!1),h=(0,X.useRef)(!1),g=(0,X.useRef)(0),_=(0,X.useCallback)(async()=>{if(h.current)return;let n=++g.current,r=e(15e3);try{let e=await fetch(`${t}/api/settings`,{signal:r.signal});if(!e.ok)throw Error(`load`);let a=await e.json();if(h.current||n!==g.current)return;if(typeof a.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);m.current=a.codexAccountPickerEnabled,i(a.codexAccountPickerEnabled),o(!0),d(!1)}catch{!h.current&&n===g.current&&d(!0)}finally{r.clear()}},[t]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{_()},0),t=Ru(()=>{_()},3e4);return()=>{window.clearTimeout(e),t()}},[_]);let v=(0,X.useCallback)(async()=>{if(h.current||!a)return;let e=m.current,r=!e;m.current=r,i(r),h.current=!0,l(!0),p(null),g.current+=1;try{let e=await zn(await fetch(`${t}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexAccountPickerEnabled:r})}))??{};if(e.ok!==!0||typeof e.codexAccountPickerEnabled!=`boolean`)throw Error(`unconfirmed`);m.current=e.codexAccountPickerEnabled,i(e.codexAccountPickerEnabled),o(!0),d(!1),p(e.catalogRefreshPending===!0?{tone:`warn`,message:n(`codexAuth.catalogRefreshPending`)}:{tone:`ok`,message:n(`codexAuth.accountPickerUpdated`)})}catch{m.current=e,i(e),p({tone:`err`,message:n(`codexAuth.accountPickerUpdateFailed`)})}finally{h.current=!1,l(!1)}},[t,a,n]),y=u&&!a;return(0,Z.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":s||!a&&!y||void 0,children:[(0,Z.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,Z.jsx)(`strong`,{children:n(`codexAuth.accountPickerTitle`)}),(0,Z.jsx)(`div`,{className:`card-sub`,role:y?`status`:void 0,children:n(y?`codexAuth.accountPickerLoadFailed`:a?r?`codexAuth.accountPickerOnDesc`:`codexAuth.accountPickerOffDesc`:`common.loading`)}),a&&r&&(0,Z.jsx)(`div`,{className:`card-sub faint`,children:n(`codexAuth.accountPickerCompatibility`)}),a&&u&&(0,Z.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:n(`codexAuth.accountPickerRefreshFailed`)})]}),(0,Z.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[u&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{_()},disabled:s,children:n(`common.retry`)}),a&&(0,Z.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{v()},disabled:s,"aria-pressed":r,"aria-label":n(`codexAuth.accountPickerTitle`),title:n(`codexAuth.accountPickerTitle`),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]}),f&&(0,Z.jsx)(`div`,{className:`codex-account-picker-feedback is-${f.tone}`,role:f.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:f.message})]})}function $I(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 eL({state:e,busy:t,onEnable:n}){let r=c(),i=L_();if(e===null)return null;let a=e===`pool`||e===`direct`;return(0,Z.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,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-[13px] font-medium text-fg-muted`,children:r(`codexAuth.accountModeTitle`)}),e===`pool`?(0,Z.jsx)(`span`,{className:`badge openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,Z.jsx)(`span`,{className:`badge openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null,a&&(0,Z.jsx)(Hh,{open:i.open,controls:i.id,name:r(`codexAuth.accountModeTitle`),onToggle:i.toggle}),(e===`absent`||e===`disabled`)&&(0,Z.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,Z.jsxs)(Uh,{id:i.id,open:i.open,children:[e===`pool`&&r(`codexAuth.accountModePoolDesc`),e===`direct`&&(0,Z.jsxs)(Z.Fragment,{children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>_n(`providers`),children:r(`codexAuth.openProviders`)})]})]}),(e===`absent`||e===`disabled`)&&(0,Z.jsx)(`p`,{className:`card-sub m-0 text-[13px] text-fg-muted`,children:r(`codexAuth.openaiUnavailableDesc`)}),e===`invalid`&&(0,Z.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc m-0 text-[13px] text-fg-muted`,children:[r(`codexAuth.openaiMissing`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>_n(`providers`),children:r(`codexAuth.openProviders`)})]})]})}function tL(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 nL({apiBase:e}){return(0,Z.jsx)(rL,{apiBase:e},e)}function rL({apiBase:t}){let n=c(),r=Jg(t),{load:i}=r,a=(0,X.useRef)(!1);(0,X.useLayoutEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let o=(0,X.useCallback)(()=>a.current?i(!1):Promise.resolve(!1),[i]),s=`ocx.codex-auth.config.v1:${t}`,l=kd(s),[u,d]=(0,X.useState)(()=>l?.bannerState??null),[f,p]=(0,X.useState)(()=>l?.accountModeState??null),m=(0,X.useRef)(null),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(``),y=(0,X.useCallback)(async()=>{let n=e(15e3);try{let e=await fetch(`${t}/api/config`,{signal:n.signal});if(!e.ok)throw Error(String(e.status));let r=await e.json(),i=Bb(tL(r));if(i===`absent`||i===`disabled`||i===`invalid`){d(i);let e=i===`disabled`?`disabled`:`absent`;p(e),Nd(s,{bannerState:i,accountModeState:e});return}let a=$I(r);d(a),p(a),Nd(s,{bannerState:a,accountModeState:a})}catch{}finally{n.clear()}},[t,s]);(0,X.useEffect)(()=>{m.current!==t&&(m.current=t,Promise.resolve().then(()=>{y()}));let e=Ru(()=>{y()},3e4);return()=>{e()}},[t,y]);let b=async()=>{g(!0),v(``);try{if(u!==`absent`&&u!==`disabled`)return;await qb(t,u),await y()}catch(e){e instanceof Kb?v(n(e.i18nKey)):v(e instanceof Error?e.message:n(`prov.saveFailed`))}finally{g(!1)}};return(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsx)(zv,{apiBase:t,controller:r,hasMainHardLockSetting:!0,accountModeState:f,banner:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(eL,{state:u,busy:h,onEnable:()=>{b()}}),_&&(0,Z.jsx)(Bh,{tone:`err`,role:`alert`,children:_})]}),advancedExtras:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(QI,{apiBase:t}),(0,Z.jsx)(WI,{apiBase:t}),(0,Z.jsx)(GI,{apiBase:t}),(0,Z.jsx)(XI,{apiBase:t,onSaved:o})]})})})}var iL={"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`},aL={"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`},oL={"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`},sL={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 cL({descriptor:e,toggle:t,bytes:n,transitionOnly:r=!1,busy:i,writesRefused:a,onToggle:o,onReset:s,onSelectBase:l,baseSelection:u,onOpen:d}){let f=c(),p=iL[e.id],m=p?f(p):e.id,h=oL[e.id],g=t?.defaultedUserValue??e.default??!0,_=u?.kind==="default";return(0,Z.jsxs)(`li`,{className:`codex-set-prompt__row`,"data-layer-id":e.id,"data-layer-class":e.class,children:[(0,Z.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:e.order===null?`·`:e.order+1}),(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>d(e.id),children:m}),e.key&&(0,Z.jsx)(`code`,{className:`codex-set-prompt__key`,children:e.key}),n!==null&&n>0&&(0,Z.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:f(`codexSet.dialog.sourceBytes`,{bytes:n}),children:n>=1024?Math.round(n/1024)+` KB`:n+` B`}),e.class===`base`&&l?(0,Z.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${_?`on`:``}`,"aria-checked":_,"aria-label":m,disabled:i||a||u?.kind===`external`,onClick:()=>{l(!_)},children:(0,Z.jsx)(`span`,{className:`toggle-knob`})}):e.class===`config-toggle`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${g?`on`:``}`,"aria-checked":g,"aria-label":m,disabled:i||a,onClick:()=>{o(e.id,!g)},children:(0,Z.jsx)(`span`,{className:`toggle-knob`})}),t!==void 0&&t.userFileValue!==null&&s&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:i||a,onClick:()=>{s(e.id)},children:f(`codexSet.row.resetDefault`,{value:String(t.default)})})]}):e.class===`feature-gated`?(0,Z.jsxs)(`span`,{className:`codex-set-prompt__note`,children:[f(`codexSet.row.featureGated`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>_n(`integrations/codex`),children:f(`codexSet.row.openFeatures`)})]}):(0,Z.jsx)(`span`,{className:`codex-set-prompt__note codex-set-prompt__note--locked`,children:f(r?`codexSet.row.onChange`:h||`codexSet.row.alwaysOn`)})]})}function lL({descriptor:e,toggle:t,text:n,probe:r,busy:i,onToggle:a,onReset:o,onClose:s,onRemeasure:l}){let u=c(),d=(0,X.useRef)(null),f=`codex-set-layer-dialog-`+e.id;(0,X.useEffect)(()=>{let e=d.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let p=(0,X.useCallback)(e=>{e.preventDefault(),s()},[s]),m=sL[e.class],h=iL[e.id],g=aL[e.id],_=oL[e.id];return(0,Z.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":f,onCancel:p,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:s}),(0,Z.jsxs)(`div`,{className:`modal-card codex-set-layer-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:f,children:h?u(h):e.id}),e.class===`config-toggle`&&t&&(0,Z.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${t.defaultedUserValue?`on`:``}`,"aria-checked":t.defaultedUserValue,"aria-label":h?u(h):e.id,disabled:i,onClick:()=>{a(e.id,!t.defaultedUserValue)},children:(0,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:u(`common.close`)})]}),(0,Z.jsx)(`p`,{className:`muted small`,children:u(g||`codexSet.dialog.unknownLayer`)}),(0,Z.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.class`)}),(0,Z.jsx)(`span`,{children:u(m)})]}),e.key&&(0,Z.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.key`)}),(0,Z.jsx)(`code`,{className:`api-code`,children:e.key}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{navigator.clipboard?.writeText(e.key??``)},children:u(`codexSet.dialog.copyKey`)})]}),e.class===`config-toggle`&&t&&(0,Z.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.fileValue`)}),(0,Z.jsx)(`span`,{children:t.userFileValue===null?u(`codexSet.dialog.absentDefault`,{value:String(t.default)}):u(`codexSet.dialog.setValue`,{value:String(t.userFileValue),fallback:String(t.default)})}),t.userFileValue!==null&&o&&(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:i,onClick:()=>{o(e.id)},children:u(`codexSet.row.resetDefault`,{value:String(t.default)})})]}),e.class===`runtime-conditional`&&_&&(0,Z.jsx)(`p`,{className:`muted small`,children:u(_)}),e.class===`feature-gated`&&(0,Z.jsx)(`div`,{className:`codex-set-layer-dialog__line`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>_n(`integrations/codex`),children:u(`codexSet.row.openFeatures`)})}),n?.reason===`ok`&&n.text?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.sourceText`)}),(0,Z.jsx)(`span`,{className:`muted small`,children:u(`codexSet.dialog.sourceBytes`,{bytes:n.bytes})})]}),(0,Z.jsx)(`pre`,{className:`api-code codex-set-layer-dialog__text`,children:n.text})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted small codex-set-layer-dialog__no-text`,children:n?.reason===`empty-source`?u(`codexSet.dialog.emptySource`,{path:n.sourcePath??``}):n?.reason===`not-rendered`?u(`codexSet.dialog.notRendered`):n?.reason===`unmapped`?u(`codexSet.dialog.unmapped`):n?.reason===`not-exposed`?u(`codexSet.dialog.notExposed`):r&&r.ok===!1?r.failure?.kind===`program-not-found`?u(`codexSet.dialog.probeNotFound`):r.failure?.kind===`command-unsupported`?u(`codexSet.dialog.probeUnsupported`):r.failure?.kind===`output-invalid`?u(`codexSet.dialog.probeInvalid`):r.failure?.kind===`execution-failed`||r.failure?.kind===`request-failed`?u(`codexSet.dialog.probeFailed`):u(`codexSet.dialog.probeBusy`):u(`codexSet.dialog.textUnavailable`)}),r&&r.ok===!1&&r.failure===void 0&&l&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`common.retry`)})]})]})]})}var uL=65536;function dL(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 fL(e){return e.replace(/\r\n/g,`
|
|
10
|
+
`).replace(/\r/g,`
|
|
11
|
+
`).replace(/\t/g,` `)}function pL(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(n!==`
|
|
12
|
+
`&&(e<32||e===127)||e>=55296&&e<=57343)return{position:t};t+=1}return null}function mL(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=fL(e.body),i=dL(r);if(i>65536)return{kind:`body-too-large`,bytes:i};let a=pL(r);if(a)return{kind:`invalid-character`,position:a.position};let o=dL([...t.filter(t=>t.enabled&&t.id!==e.id).map(e=>e.body),...e.enabled?[r]:[]].join(`
|
|
13
|
+
|
|
14
|
+
`));return o>131072?{kind:`composed-too-large`,bytes:o}:null}function hL(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 gL(e){return e.filter(e=>e.enabled).map(e=>e.body).join(`
|
|
15
|
+
|
|
16
|
+
`)}var _L=null;function vL(){return _L??1e4}function yL(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 bL({layer:e,index:t,total:n,busy:r,onToggle:i,onEdit:a,onDelete:o,onMove:s}){let l=c();return(0,Z.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,Z.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:t+1}),(0,Z.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>a(e.id),children:e.title}),(0,Z.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:l(`codexSet.dialog.sourceBytes`,{bytes:dL(e.body)}),children:dL(e.body)>=1024?Math.round(dL(e.body)/1024)+` KB`:dL(e.body)+` B`}),(0,Z.jsxs)(`span`,{className:`codex-set-custom__reorder`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":l(`codexSet.custom.moveUp`,{title:e.title}),disabled:t===0||r,onClick:()=>s(e.id,-1),children:`↑`}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":l(`codexSet.custom.moveDown`,{title:e.title}),disabled:t===n-1||r,onClick:()=>s(e.id,1),children:`↓`})]}),(0,Z.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,Z.jsx)(`span`,{className:`toggle-knob`})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-set-custom__delete`,"aria-label":l(`codexSet.custom.delete`,{title:e.title}),disabled:r,onClick:()=>o(e.id),children:`×`})]})}var xL=8192,SL=[{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 CL(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 wL(e){let t=[],n=[];for(let r of SL){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 CL(e)>xL&&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 TL({layer:e,seed:t,others:n,busy:r,navigation:i,onSave:a,onClose:o}){let s=c(),l=(0,X.useRef)(null),[u,d]=(0,X.useState)(e?.title??t?.title??``),[f,p]=(0,X.useState)(e?.body??t?.body??``),m=(0,X.useRef)(new Map),[h,g]=(0,X.useState)(!1),_=e?.id??null,v=(0,X.useRef)(_),y=(0,X.useRef)({title:u,body:f});(0,X.useEffect)(()=>{y.current={title:u,body:f}},[u,f]),(0,X.useEffect)(()=>{if(v.current===_)return;v.current!==null&&m.current.set(v.current,y.current),v.current=_;let t=_===null?void 0:m.current.get(_);d(t?.title??e?.title??``),p(t?.body??e?.body??``)},[_,e]),(0,X.useEffect)(()=>{g([...m.current].some(([e,t])=>{if(e===_)return!1;let r=n.find(t=>t.id===e);return r===void 0||t.title!==r.title||t.body!==r.body}))},[_,n]);let[b,x]=(0,X.useState)(null),S=`codex-set-custom-dialog`,C=e?.title??t?.title??``,w=e?.body??t?.body??``,T=u!==C||f!==w;(0,X.useEffect)(()=>{let e=l.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let E=(0,X.useCallback)(()=>{T||h?x({kind:`close`}):o()},[T,h,o]),D=(0,X.useCallback)(e=>{e.preventDefault(),E()},[E]),O={id:e?.id??null,title:u,body:f,enabled:e?.enabled??!0},k=mL(O,n),A=fL(f),j=A!==f,M=(0,X.useMemo)(()=>wL(A),[A]),N=dL(A),P=e=>{r||k!==null||e!==_||a({...O,body:A})},F=()=>{r||k!==null||(h?x({kind:`save`,targetId:_}):P(_))},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:uL}):k.kind===`composed-too-large`?s(`codexSet.custom.composedTooLarge`,{bytes:k.bytes}):s(`codexSet.custom.invalidCharacter`,{position:k.position}):null;return(0,Z.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":S,onCancel:D,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:E}),(0,Z.jsxs)(`div`,{className:`modal-card codex-set-custom-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:S,children:s(e?`codexSet.custom.editTitle`:`codexSet.custom.newTitle`)}),i&&(0,Z.jsxs)(`span`,{className:`codex-set-custom-dialog__nav`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":s(`codexSet.custom.prevLayer`),disabled:i.position<=1||r||b!==null,onClick:i.onPrev,children:`←`}),(0,Z.jsx)(`span`,{className:`codex-set-custom-dialog__nav-pos`,children:s(`codexSet.custom.navPosition`,{position:i.position,total:i.total})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":s(`codexSet.custom.nextLayer`),disabled:i.position>=i.total||r||b!==null,onClick:i.onNext,children:`→`})]})]}),(0,Z.jsxs)(`label`,{className:`field`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:s(`codexSet.custom.titleLabel`)}),(0,Z.jsx)(`input`,{className:`input`,type:`text`,value:u,maxLength:100,onChange:e=>d(e.target.value)})]}),(0,Z.jsxs)(`label`,{className:`field`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:s(`codexSet.custom.bodyLabel`)}),(0,Z.jsx)(`textarea`,{className:`input`,rows:10,value:f,onChange:e=>p(e.target.value)})]}),(0,Z.jsx)(`p`,{className:`muted small`,children:s(`codexSet.custom.bodySize`,{bytes:N,max:uL})}),j&&(0,Z.jsx)(`p`,{className:`muted small codex-set-custom-dialog__normalized`,children:s(`codexSet.custom.normalized`)}),I&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:I}),M.length>0&&(0,Z.jsx)(`ul`,{className:`codex-set-custom-dialog__lint`,children:M.map((e,t)=>(0,Z.jsxs)(`li`,{"data-lint-rule":e.rule,"data-lint-level":e.level,children:[s(e.messageKey),e.span&&(0,Z.jsx)(`code`,{className:`codex-set-custom-dialog__span`,children:A.slice(e.span[0],e.span[1])})]},e.rule+`:`+t))}),b?(0,Z.jsxs)(`div`,{className:`modal-actions codex-set-custom-dialog__discard`,role:`alertdialog`,"aria-labelledby":S+`-discard`,children:[(0,Z.jsx)(`span`,{id:S+`-discard`,className:`muted small`,children:s(b.kind===`save`?`codexSet.custom.discardOthersAndSave`:`codexSet.custom.discardPrompt`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>x(null),children:s(`codexSet.custom.keepEditing`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:b.kind===`save`&&(k!==null||r||b.targetId!==_),onClick:()=>b.kind===`save`?P(b.targetId):o(),children:s(b.kind===`save`?`common.save`:`common.discard`)})]}):(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k!==null||r,onClick:F,children:s(`common.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:E,children:s(`common.cancel`)})]})]})]})}var EL=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(`
|
|
17
|
+
`)},{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(`
|
|
18
|
+
`)},{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(`
|
|
19
|
+
`)},{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(`
|
|
20
|
+
`)},{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(`
|
|
21
|
+
`)}]);function DL({onBlank:e,onPreset:t,disabled:n,presets:r=EL}){let i=c(),[a,o]=(0,X.useState)(!1),s=(0,X.useRef)(null),l=a&&!n;(0,X.useEffect)(()=>{if(!l)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)}},[l]);let u=e=>{o(!1),e()};return r.length===0?(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm codex-set-custom__add`,disabled:n,onClick:e,children:i(`codexSet.custom.add`)}):(0,Z.jsxs)(`div`,{className:`codex-set-preset`,ref:s,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm codex-set-custom__add`,"aria-expanded":l,disabled:n,onClick:()=>o(e=>!e),children:i(`codexSet.custom.add`)}),l&&(0,Z.jsxs)(`div`,{className:`codex-set-preset__menu`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`codex-set-preset__item`,onClick:()=>u(e),children:(0,Z.jsx)(`span`,{className:`codex-set-preset__name`,children:i(`codexSet.preset.blank`)})}),r.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`codex-set-preset__item`,"data-preset-id":e.id,onClick:()=>u(()=>t(e.body,i(e.nameKey))),children:[(0,Z.jsx)(`span`,{className:`codex-set-preset__name`,children:i(e.nameKey)}),(0,Z.jsx)(`span`,{className:`codex-set-preset__desc`,children:i(e.descriptionKey)}),(0,Z.jsx)(`span`,{className:`codex-set-preset__provenance`,children:i(e.provenanceKey)}),(0,Z.jsx)(`span`,{className:`codex-set-preset__preview`,children:e.body})]},e.id))]})]})}var OL=48,kL=`new`,AL=`field mt-3 grid gap-1`;function jL({variants:e,selection:t,maxVariants:n,busy:r,importPreview:i,importRefusal:a,onSelect:o,onSave:s,onDelete:l,onImport:u,onImportTitle:d,onClose:f}){let p=c(),m=(0,X.useRef)(null),h=[{kind:`default`},...e.map(e=>({kind:`variant`,variant:e})),...e.length<n?[{kind:`new`}]:[]],g=t.kind===`variant`?Math.max(0,h.findIndex(e=>e.variant?.id===t.id)):0,[_,v]=(0,X.useState)(g),y=h[Math.min(_,h.length-1)],[b,x]=(0,X.useState)(y.variant?.title??``),[S,C]=(0,X.useState)(y.variant?.body??``),w=y.kind==="default"?null:y.variant?.id??kL,T=(0,X.useRef)(new Map),E=(0,X.useRef)(w),D=(0,X.useRef)(y),O=(0,X.useRef)(null),k=(0,X.useRef)(new Set),A=(0,X.useRef)({title:b,body:S});(0,X.useEffect)(()=>{A.current={title:b,body:S}},[b,S]),(0,X.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!==kL&&!n.has(E.current),c=i&&r!==null&&E.current===(r.id??kL)&&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!==kL&&!n.has(e)&&T.current.delete(e);if(r&&i&&T.current.delete(r.id??kL),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??y.variant?.title??``),C(e?.body??y.variant?.body??``)}E.current=w,D.current=y},[w,y,e]);let[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)(!1);(0,X.useEffect)(()=>{P([...T.current].some(([t,n])=>{if(t===w)return!1;if(t===kL)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,b,S]);let F=N||w!==null&&(b!==(y.variant?.title??``)||S!==(y.variant?.body??``)),[I,L]=(0,X.useState)(i?.effectiveTitle??``),R=i?.effectiveTitle??null,[z,B]=(0,X.useState)(R);R!==z&&(B(R),L(R??``));let V=(0,X.useCallback)(e=>{v(t=>{let n=t+e;return n<0?h.length-1:n>=h.length?0:n})},[h.length]);(0,X.useEffect)(()=>{let e=m.current;e&&!e.open&&e.showModal()},[]);let H=(0,X.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)<OL||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)))},te=(0,X.useCallback)(()=>{F?M({kind:`close`}):f()},[F,f]),ne=(0,X.useCallback)(e=>{e.preventDefault(),te()},[te]),G=y.kind==="default"?t.kind==="default":y.kind===`variant`&&t.kind===`variant`&&t.id===y.variant.id,K=t.kind===`external`,re=fL(S),q=dL(re),ie=pL(re),ae=q>65536?{kind:`body-too-large`,bytes:q}:ie===null?null:{kind:`invalid-character`,position:ie.position},oe=re!==S,se=wL(re),ce=ae?ae.kind===`body-too-large`?p(`codexSet.custom.bodyTooLarge`,{bytes:ae.bytes,max:uL}):p(`codexSet.custom.invalidCharacter`,{position:ae.position}):null,le=async e=>{if(r||ae!==null||S.trim().length===0||e!==w)return;let t={title:b,body:S},n=b.replace(/[\r\n]+/g,` `).trim()||y.variant?.id||``;if(O.current={id:y.variant?.id??null,title:n,body:re},!await s({id:y.variant?.id??null,title:b,body:re})){O.current=null;return}let i=e??kL;if(T.current.delete(i),i!==kL&&E.current===e&&A.current.title===t.title&&A.current.body===t.body&&(A.current={title:n,body:re},x(n),C(re)),j?.kind===`save`){for(let e of[...T.current.keys()])e!==i&&T.current.delete(e);M(null)}};return(0,Z.jsx)(`dialog`,{ref:m,className:`modal-overlay codex-set-base-dialog`,"aria-label":p(`codexSet.base.title`),onCancel:ne,onClose:f,onKeyDown:ee,onPointerDown:U,onPointerUp:W,children:(0,Z.jsxs)(`div`,{className:`modal-card`,children:[(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`strong`,{children:p(`codexSet.base.title`)}),(0,Z.jsxs)(`span`,{className:`codex-set-base-dialog__nav`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":p(`codexSet.base.prev`),disabled:r||h.length<2||j!==null,onClick:()=>V(-1),children:`←`}),(0,Z.jsx)(`span`,{className:`codex-set-base-dialog__pos`,"data-slot-kind":y.kind,children:p(`codexSet.base.position`,{position:_+1,total:h.length})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":p(`codexSet.base.next`),disabled:r||h.length<2||j!==null,onClick:()=>V(1),children:`→`})]})]}),(0,Z.jsx)(`p`,{className:`card-sub`,children:p(`codexSet.base.swipeHint`)}),h.length>1&&(0,Z.jsx)(`div`,{className:`codex-set-base-dialog__dots`,"aria-hidden":`true`,children:h.map((e,t)=>(0,Z.jsx)(`span`,{className:`codex-set-base-dialog__dot${t===_?` active`:``}`},t))}),K&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:p(`codexSet.base.externalBlocked`,{path:t.path})}),K&&(i?(0,Z.jsxs)(Z.Fragment,{children:[a!==null&&(0,Z.jsx)(`p`,{className:`muted small`,children:a}),(0,Z.jsx)(`p`,{className:`muted small`,children:p(`codexSet.base.importPreview`,{path:i.resolvedPath??i.rawPath??``})}),(0,Z.jsx)(`pre`,{className:`api-code codex-set-custom__adopt-preview`,children:i.serialized}),(0,Z.jsx)(`p`,{className:`muted small`,children:p(`codexSet.base.importFormat`,{bodyBytes:i.bodyBytes,serializedBytes:i.serializedBytes})}),(0,Z.jsxs)(`label`,{className:AL,children:[(0,Z.jsx)(`span`,{children:p(`codexSet.base.importTitle`)}),(0,Z.jsx)(`input`,{className:`input`,type:`text`,value:I,disabled:r,maxLength:80,onChange:e=>{L(e.target.value),d(e.target.value)}})]}),I.trim()!==i.effectiveTitle&&(0,Z.jsx)(`p`,{className:`muted small`,children:p(`codexSet.base.importTitlePending`)}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:r||I.trim()!==i.effectiveTitle,onClick:()=>u(!0,I.trim()||void 0),children:p(`codexSet.base.importConfirm`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:te,children:p(`common.cancel`)})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[a!==null&&(0,Z.jsx)(`p`,{className:`muted small`,children:a}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:r,onClick:()=>u(!1),children:p(`codexSet.base.import`)})]})),y.kind==="default"?(0,Z.jsxs)(`div`,{className:`codex-set-base-dialog__default`,children:[(0,Z.jsx)(`strong`,{children:p(`codexSet.base.defaultTitle`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:p(`codexSet.base.defaultBody`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:AL,children:[(0,Z.jsx)(`span`,{children:p(`codexSet.base.variantTitle`)}),(0,Z.jsx)(`input`,{className:`input`,type:`text`,value:b,disabled:r||K,onChange:e=>x(e.target.value)})]}),(0,Z.jsxs)(`label`,{className:AL,children:[(0,Z.jsx)(`span`,{children:p(`codexSet.base.variantBody`)}),(0,Z.jsx)(`textarea`,{className:`input`,rows:12,value:S,disabled:r||K,onChange:e=>C(e.target.value)})]}),(0,Z.jsx)(`p`,{className:`muted small`,children:p(`codexSet.custom.bodySize`,{bytes:q,max:uL})}),oe&&(0,Z.jsx)(`p`,{className:`muted small codex-set-custom-dialog__normalized`,children:p(`codexSet.custom.normalized`)}),ce&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:ce}),se.length>0&&(0,Z.jsx)(`ul`,{className:`codex-set-custom-dialog__lint`,children:se.map((e,t)=>(0,Z.jsxs)(`li`,{"data-lint-rule":e.rule,"data-lint-level":e.level,children:[p(e.messageKey),e.span&&(0,Z.jsx)(`code`,{className:`codex-set-custom-dialog__span`,children:re.slice(e.span[0],e.span[1])})]},e.rule+`:`+t))}),(0,Z.jsx)(`p`,{className:`muted small`,children:p(`codexSet.base.replacesWarning`)})]}),j?(0,Z.jsxs)(`div`,{className:`modal-actions codex-set-custom-dialog__discard`,role:`alertdialog`,"aria-labelledby":`codex-set-base-dialog-discard`,children:[(0,Z.jsx)(`span`,{id:`codex-set-base-dialog-discard`,className:`muted small`,children:p(j.kind===`save`?`codexSet.custom.discardOthersAndSave`:`codexSet.custom.discardPrompt`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>M(null),children:p(`codexSet.custom.keepEditing`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:j.kind===`save`&&(ae!==null||r||S.trim().length===0||j.targetKey!==w),onClick:()=>j.kind===`save`?void le(j.targetKey):f(),children:p(j.kind===`save`?`common.save`:`common.discard`)})]}):(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[y.kind!=="default"&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:r||K||ae!==null||S.trim().length===0,onClick:()=>{r||ae!==null||(N?M({kind:`save`,targetKey:w}):le(w))},children:p(`common.save`)}),!G&&y.kind!==`new`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:r||K,onClick:()=>o(y.kind==="default"?{kind:`default`}:{kind:`variant`,id:y.variant.id}),children:p(`codexSet.base.use`)}),G&&(0,Z.jsx)(`span`,{className:`pill`,children:p(`codexSet.base.inUse`)}),y.kind===`variant`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:r||K,onClick:()=>l(y.variant.id),children:p(`common.delete`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:te,children:p(`common.close`)})]})]})})}function ML(e){return`codex-prompt:`+e}var NL={"journal-present":`codexSet.drift.journalPresent`,"projection-stale":`codexSet.drift.projectionStale`,"store-missing":`codexSet.drift.storeMissing`,"owned-malformed":`codexSet.drift.ownedMalformed`};function PL({apiBase:e}){let t=c(),n=ML(e),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(null),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),E=(0,X.useRef)(0),D=(0,X.useRef)(!1),O=(0,X.useRef)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(null),N=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let P=(0,X.useCallback)(()=>{A(null)},[]),F=(0,X.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=Fd(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}pn(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):(pn(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){pn(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),l(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`)),pn(n,{...L,custom:c}),I.refresh(),!1):(pn(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:hL(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`)&&d(null)},te=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`)),h(null),_(o.code===`adopt_unsupported_form`?{path:o.path,line:o.line,rawLine:o.rawLine}:null);return}if(o.snapshot){pn(n,o.snapshot),P(),h(null);return}h(o.preview??null)}catch{i(t(`codexSet.prompt.writeFailed`))}finally{o(null)}}},ne=async r=>{if(L&&L.drift!==null){y(!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?pn(n,o.snapshot):I.refresh(),P()}catch{i(t(`codexSet.prompt.repairFailed`))}finally{y(!1)}}},G=[...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`]),re=G.filter(e=>!K.has(e.id)),q=G.filter(e=>K.has(e.id)),ie=G.find(e=>e.id===s)??null,ae=u===null||u===`new`?-1:L?.custom.findIndex(e=>e.id===u)??-1,oe=ae>=0?L.custom[ae]:null,se=u!==null&&u!==`new`&&L!==void 0&&ae<0;return(0,X.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,Z.jsxs)(`div`,{className:`panel codex-set-prompt`,children:[(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`strong`,{children:t(`codexSet.prompt.title`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k===null||a!==null,onClick:P,children:t(`codexSet.prompt.remeasure`)})]}),(0,Z.jsx)(`p`,{className:`card-sub`,children:t(`codexSet.prompt.timing`)}),R.refreshing&&(0,Z.jsx)(PE,{live:!R.showError,children:t(`common.loading`)}),R.showSkeleton&&(0,Z.jsx)(NE,{label:t(`common.loading`),rows:5}),L&&!L.readable&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`codexSet.prompt.unreadable`)}),R.showError&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`codexSet.prompt.loadFailed`)}),(r||se)&&(0,Z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:se?t(`codexSet.custom.layerGone`):r}),L?.drift&&(0,Z.jsxs)(`div`,{className:`notice codex-set-prompt__drift`,role:`alert`,"data-drift":L.drift,children:[(0,Z.jsx)(`span`,{children:t(NL[L.drift])}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:v,onClick:()=>{ne(!0)},children:t(`codexSet.prompt.repair`)})]}),(0,Z.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:re.map(e=>(0,Z.jsx)(cL,{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}):l(e.id)}):void 0,baseSelection:L?.baseSelection,onOpen:l},e.id))}),q.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`row codex-set-prompt__group`,children:(0,Z.jsx)(`strong`,{children:t(`codexSet.group.transition`)})}),(0,Z.jsx)(`p`,{className:`muted small`,children:t(`codexSet.group.transitionDesc`)}),(0,Z.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:q.map(e=>(0,Z.jsx)(cL,{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:l},e.id))})]}),L&&!L.extensionLayersEnumerable&&(0,Z.jsx)(`p`,{className:`muted small codex-set-prompt__extensions`,children:t(`codexSet.prompt.extensionsUnknown`)}),ie&&(ie.class===`base`&&L?(0,Z.jsx)(jL,{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,Z.jsx)(lL,{descriptor:ie,toggle:L?.toggles.find(e=>e.id===ie.id),text:k?.layers?.[ie.id],probe:k,busy:a!==null,onToggle:(e,t)=>{z(e,t)},onReset:e=>{z(e,null)},onClose:()=>l(null),onRemeasure:P})),L&&(0,Z.jsxs)(`section`,{className:`codex-set-custom`,children:[(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`strong`,{children:t(`codexSet.custom.heading`)}),L.developerInstructionsState===`external`?null:(0,Z.jsx)(DL,{disabled:L.custom.length>=32||a!==null||!L.readable,onBlank:()=>{x(null),d(`new`)},onPreset:(e,t)=>{x({body:e,title:t}),d(`new`)}})]}),L.custom.length>=32&&(0,Z.jsx)(`p`,{className:`muted small`,children:t(`codexSet.custom.limitReached`,{max:32})}),L.developerInstructionsState===`external`&&L.modelInstructionsFile===null&&(0,Z.jsxs)(`div`,{className:`codex-set-custom__adopt`,children:[(0,Z.jsx)(`p`,{className:`muted small`,children:t(`codexSet.custom.notOwned`)}),g&&(0,Z.jsx)(`p`,{className:`muted small codex-set-custom__adopt-refusal`,children:t(`codexSet.custom.adoptUnsupported`,{path:g.path??``,line:g.line??0})}),m?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`pre`,{className:`api-code codex-set-custom__adopt-preview`,children:m.decodedBody}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:a!==null,onClick:()=>{te(!0)},children:t(`codexSet.custom.adoptConfirm`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>h(null),children:t(`common.cancel`)})]})]}):(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:a!==null,onClick:()=>{te(!1)},children:t(`codexSet.custom.adopt`)})]}),L.baseSelection.kind===`external`&&(0,Z.jsxs)(`p`,{className:`muted small codex-set-custom__replaced`,children:[t(`codexSet.custom.baseReplaced`,{path:L.baseSelection.path}),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>l(`base-instructions`),children:t(`codexSet.custom.baseReplacedOpen`)})]}),(0,Z.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:L.custom.map((e,t)=>(0,Z.jsx)(bL,{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:d,onDelete:p,onMove:(e,t)=>{W(yL(L.custom,e,t),e)}},e.id))}),L.custom.length>0&&(()=>{let e=gL(L.custom),n=dL(e);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:n>131072?`notice notice-err`:`muted small`,children:t(`codexSet.custom.composedSize`,{bytes:n,max:131072})}),e.length>0&&(0,Z.jsxs)(`details`,{className:`codex-set-custom__preview`,children:[(0,Z.jsx)(`summary`,{className:`muted small`,children:t(`codexSet.custom.composedPreview`)}),(0,Z.jsx)(`pre`,{className:`api-code codex-set-custom__preview-body`,children:e})]})]})})(),j&&(0,Z.jsxs)(`div`,{className:`notice codex-set-custom__deleted`,role:`status`,children:[(0,Z.jsx)(`span`,{children:t(`codexSet.custom.deletedNamed`,{title:j.layer.title})}),(0,Z.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),vL())})()},children:t(`common.undo`)})]}),f&&(0,Z.jsxs)(`div`,{className:`notice codex-set-custom__confirm`,role:`alertdialog`,"aria-labelledby":`codex-set-delete-confirm`,children:[(0,Z.jsx)(`span`,{id:`codex-set-delete-confirm`,children:t(`codexSet.custom.deleteConfirmNamed`,{title:L.custom.find(e=>e.id===f)?.title??``})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:()=>{let e=f,t=L.custom.findIndex(t=>t.id===e),n=t>=0?L.custom[t]:null;p(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),vL()))})()},children:t(`common.delete`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>p(null),children:t(`common.cancel`)})]})]}),u&&L&&!se&&(0,Z.jsx)(TL,{layer:u===`new`?null:oe,seed:u===`new`?b:null,others:L.custom,busy:a!==null,navigation:ae>=0&&L.custom.length>1?{position:ae+1,total:L.custom.length,onPrev:()=>{ae>0&&d(L.custom[ae-1].id)},onNext:()=>{ae<L.custom.length-1&&d(L.custom[ae+1].id)}}:void 0,onSave:ee,onClose:()=>{d(null),x(null)}})]})}var FL=[`pairing_required`,`standalone_required`,`join_port_mismatch`],IL=[`connecting`,`connected`,`reconnecting`,`failed`,`idle`],LL=[`standalone`,`home`,`child`],RL=class extends Error{code;status;hint;constructor(e,t,n=null){super(e),this.name=`LinkApiError`,this.code=e,this.status=t,this.hint=n}},zL=160;function BL(e){return typeof e==`object`&&!!e}function VL(e){return e<32||e>=127&&e<=159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e===65279}function HL(e){if(typeof e!=`string`)return null;let t=Array.from(e,e=>VL(e.codePointAt(0)??0)?` `:e).join(``).replace(/\s+/g,` `).trim();if(!t)return null;let n=Array.from(t);return n.length>zL?`${n.slice(0,159).join(``)}\u2026`:t}function UL(e){return typeof e==`string`&&e.length>0}function WL(e){return typeof e==`string`&&IL.includes(e)}function GL(e){if(!BL(e)||!LL.includes(e.role))throw Error(`invalid status`);let t=e.listener;if(!BL(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(!BL(e)||!UL(e.id)||!UL(e.alias)||![`hub-initiated`,`client-initiated`].includes(String(e.direction))||!WL(e.state)||!UL(e.since)||e.reason!==null&&typeof e.reason!=`string`||typeof e.tunnelPort!=`number`)throw Error(`invalid link`);return{id:e.id,alias:e.alias,direction:e.direction,state:e.state,since:e.since,reason:e.reason,tunnelPort:e.tunnelPort}}),r=null;if(e.child!==null){if(!BL(e.child)||!UL(e.child.alias)||!WL(e.child.state)||!UL(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=FL.includes(e.joinDenied)?e.joinDenied:null;return{role:e.role,listener:{state:t.state,port:t.port},links:n,child:r,joinAvailable:e.joinAvailable===!0,joinDenied:i}}async function KL(e){let t;try{t=await e.json()}catch{}if(!e.ok){let n=BL(t)&&BL(t.error)?t.error:null;throw new RL(n&&typeof n.code==`string`?n.code:`unknown`,e.status,HL(n?.hint))}if(t==null)throw new RL(`invalid_body`,e.status);return t}async function qL(e,t,n){return KL(await fetch(`${e}${t}`,{...n,cache:`no-store`}))}async function JL(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!BL(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 YL=1e3,XL=5e3,ZL=145e3,QL=2e3;function $L(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 eR(e,t,n,r={}){let i=r.now??Date.now,a=r.sleep??$L,o=i()+ZL,s=!1;for(;;){if(n.aborted)return`aborted`;let c=await JL(e,AbortSignal.any([n,AbortSignal.timeout(QL)]),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?XL:YL,n)}}var tR=/^ocx_pair_[A-Za-z0-9_-]{43}$/,nR=1e4,rR=class extends Error{kind;constructor(e){super(`pairing_${e}`),this.kind=e,this.name=`PairingError`}},iR=16384;function aR(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 oR(e,t=iR){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 sR(e){return aR(e)?!0:e.headers.get(`content-type`)?.toLowerCase().includes(`text/html`)?aR(e,await oR(e)):!1}async function cR(e,t,n,r){r?.throwIfAborted();let i=t.trim();if(!tR.test(i))throw new rR(`invalid-code`);let a=n??((e,t)=>window.fetch(e,t)),o=j(e.id);return u(nR,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 rR(`unreachable`)}if(!n.ok)throw await sR(n)?new rR(`cloudflare-challenge`):(k(n),n.status===401?new rR(`refused`):n.status===403?new rR(`origin-denied`):new rR(`request-failed`));let s;try{s=await n.text()}catch(e){throw r?.aborted?e:new rR(`invalid-response`)}if(t.throwIfAborted(),aR(n,s))throw new rR(`cloudflare-challenge`);if(!o.install(s))throw o.rollback(),new rR(`invalid-response`);return o}).catch(e=>{throw o.rollback(),r?.throwIfAborted(),e instanceof rR?e:new rR(`unreachable`)})}async function lR(e,t,n){n?.throwIfAborted();let r=t??((e,t)=>F(`shared`,e,t??{}));return u(nR,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 rR(`unreachable`)}if(t.throwIfAborted(),!n.ok)throw await sR(n)?new rR(`cloudflare-challenge`):await g(n)?new rR(`client-state-changed`):(k(n),n.status===401?new rR(`remote-link-unauthorized`):n.status===403?new rR(`remote-link-forbidden`):new rR(`request-failed`));if(await sR(n))throw new rR(`cloudflare-challenge`);if(!D(`shared`))throw new rR(`invalid-response`);try{let e=await n.json();t.throwIfAborted(),GL(e)}catch{throw t.throwIfAborted(),new rR(`invalid-response`)}}).catch(e=>{throw n?.throwIfAborted(),e instanceof rR?e:new rR(`unreachable`)})}var uR=`/api/codex/desktop-compatibility/`,dR=e=>!!e&&typeof e==`object`&&!Array.isArray(e),fR=class extends Error{code;constructor(e){super(e),this.code=e}};async function pR(e){let t;try{t=await e.json()}catch{throw new fR(`invalid_response`)}if(!dR(t))throw new fR(`invalid_response`);if(!e.ok||t.ok!==!0){let e=t.error??(dR(t.activation)?t.activation.reason:void 0)??(dR(t.launch)?t.launch.reason:void 0);throw new fR(typeof e==`string`&&/^[a-z][a-z_-]{0,79}$/.test(e)?e:`operation_unconfirmed`)}return t}function mR(e){if(!dR(e)||typeof e.startOnProxyStart!=`boolean`||typeof e.revision!=`string`||!/^[a-f0-9]{64}$/.test(e.revision))throw new fR(`invalid_startup_settings`);return{startOnProxyStart:e.startOnProxyStart,revision:e.revision}}async function hR(e,t){return mR((await pR(await fetch(e+`/api/codex/desktop-compatibility/settings`,{signal:t}))).settings)}async function gR(e,t,n,r){return mR((await pR(await fetch(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 _R(e){if(!dR(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 fR(`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 vR(e){if(!dR(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 fR(`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 fR(`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(!dR(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 fR(`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(!dR(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 fR(`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(!dR(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 fR(`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 yR(e,t){return vR((await pR(await fetch(e+`/api/codex/desktop-compatibility/runtime`,{signal:t}))).runtime)}async function bR(e,t){return _R((await pR(await fetch(e+`/api/codex/desktop-compatibility/certificate`,{signal:t}))).certificate)}async function xR(e,t){try{await u(1e4,t,async t=>{let n=await F(`machine`,e+`/api/codex/desktop-compatibility/certificate`,{signal:t});if(n.status===401||n.status===403)throw k(n),new rR(`refused`);let r=_R((await pR(n)).certificate);if(t.throwIfAborted(),r.mutationAuthorized!==!0)throw new rR(`refused`)})}catch(e){throw t.throwIfAborted(),e instanceof rR?e:new rR(e instanceof fR?`invalid-response`:`unreachable`)}}async function SR(e,t){let[n,r]=await Promise.all([bR(e,t),yR(e,t)]);return{certificate:n,runtime:r}}async function CR(e,t,n){if(t.target===`certificate`&&t.action!==`prepare`&&(!t.fingerprint||!/^[A-F0-9]{64}$/.test(t.fingerprint)))throw new fR(`certificate_fingerprint_required`);await pR(await fetch(e+uR+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}:{}})}))}function wR({apiBase:t,active:n,authorized:r}){let i=c(),a=`desktop-compatibility-startup:${t}`,o=ln(a,e=>hR(t,e),{enabled:n,deadlineMs:15e3,staleAfterMs:0}),[s,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)({alive:!0,pending:!1,generation:0,refreshRequired:!1,operation:null});(0,X.useEffect)(()=>{let e=m.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(),l(!1),r&&(d(!0),p(`connection_unconfirmed`))};return window.addEventListener(x,n),()=>{window.removeEventListener(x,n),e.alive=!1,t()}},[]);async function h(n){let i=m.current;if(!i.alive||i.pending||n&&(i.refreshRequired||!o.data||!r))return;i.pending=!0;let s=++i.generation;l(!0),p(null);let c=e(15e3);i.operation=c;let u=()=>i.alive&&i.generation===s&&i.operation===c;try{if(n&&await gR(t,o.data,!o.data.startOnProxyStart,c.signal),!u())return;c.signal.throwIfAborted();let e=await hR(t,c.signal);if(!u())return;c.signal.throwIfAborted(),i.refreshRequired=!1,pn(a,e),d(!1)}catch(e){u()&&(i.refreshRequired=!0,d(!0),p(e instanceof fR?e.code:`connection_unconfirmed`))}finally{c.clear(),i.operation===c&&(i.operation=null),i.generation===s&&(i.pending=!1,i.alive&&l(!1))}}let g=o.error instanceof fR?o.error.code:o.error?`connection_unconfirmed`:null;return(0,Z.jsxs)(`div`,{className:`panel acc-desktop__setting`,children:[(0,Z.jsx)(kn,{on:o.data?.startOnProxyStart===!0,label:i(`desktopCompat.autoStart`),showLabel:!0,disabled:!r||s||u||!o.lastAttemptOk||o.refreshing,onClick:()=>void h(!0)}),(0,Z.jsx)(`p`,{className:`muted text-control`,children:i(`desktopCompat.autoStartHint`)}),(f||g)&&(0,Z.jsxs)(Bh,{tone:`err`,role:`alert`,children:[i(`desktopCompat.error`),` `,(0,Z.jsx)(`code`,{children:f??g})]}),(u||g)&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>void h(!1),children:i(`desktopCompat.refresh`)})]})}function TR({target:e,onConnected:t,onCommitted:n,onPairingStart:r,local:i=!1,focusOnMount:a=!1}){let o=c(),[s,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),g=(0,X.useRef)(null),_=(0,X.useRef)(null);(0,X.useEffect)(()=>{a&&_.current?.focus()},[a]);let v=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{v.current?.abort(),g.current?.rollback()},[]);let y=Xh(),b=`ocx gui pair --origin "${window.location.origin}"`,x=y.outcomeFor(b);return(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-col gap-1 px-4 pt-3 pb-3`,children:[(0,Z.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,Z.jsxs)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:[!i&&(0,Z.jsxs)(Z.Fragment,{children:[o(`connection.pairing.hub`),`: `]}),(0,Z.jsx)(`code`,{className:`font-mono text-fg`,children:e.serverOrigin})]})]}),(0,Z.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,Z.jsx)(`p`,{className:`m-0`,children:o(`connection.pairing.getCode`)}),(0,Z.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,Z.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,Z.jsx)(`code`,{children:b})}),(0,Z.jsx)(lp,{variant:`ghost`,size:`sm`,onClick:()=>y.copy(b,b),children:o(x===`copied`?`startup.copied`:`startup.copy`)})]}),x===`unavailable`&&(0,Z.jsx)(`p`,{className:`m-0`,role:`status`,children:o(`prov.linkCopyUnavailable`)}),!i&&(0,Z.jsx)(`p`,{className:`m-0`,children:o(`connection.pairing.askOperator`)}),(0,Z.jsx)(`p`,{className:`m-0`,children:o(`connection.pairing.notApiKey`)}),(0,Z.jsxs)(`form`,{onSubmit:async i=>{if(i.preventDefault(),v.current)return;g.current||r?.(),d(!0),p(null);let a=new AbortController;v.current=a;try{g.current||(g.current=await cR(e,s,void 0,a.signal),a.signal.aborted&&(g.current.rollback(),g.current=null,a.signal.throwIfAborted()),l(``),h(!0)),a.signal.aborted||(await t(a.signal),a.signal.throwIfAborted(),g.current?.commit(),g.current=null,h(!1),n?.())}catch(e){if(!a.signal.aborted){let t=e instanceof rR?e.kind:`unreachable`;(t===`refused`||t===`remote-link-unauthorized`||t===`remote-link-forbidden`)&&(g.current?.rollback(),g.current=null,h(!1)),p(t)}}finally{a.signal.aborted||d(!1),v.current===a&&(v.current=null)}},className:`flex min-w-0 flex-col gap-1.5`,children:[(0,Z.jsx)(`label`,{htmlFor:`connect-pairing-code`,className:`text-[13px] font-semibold text-fg`,children:o(`connection.pairing.code`)}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`input`,{ref:_,id:`connect-pairing-code`,name:`pairingCode`,value:s,onChange:e=>l(e.currentTarget.value),autoComplete:`off`,spellCheck:!1,disabled:u||m,className:`input mono min-w-0 flex-1 font-mono`,"aria-invalid":!!f||void 0,"aria-describedby":f?`connect-pairing-error`:void 0}),(0,Z.jsx)(lp,{type:`submit`,variant:`primary`,disabled:u||!m&&!s.trim(),children:o(u?`connection.pairing.submitting`:m?`connection.pairing.retryValidation`:`connection.pairing.submit`)})]}),f&&(0,Z.jsx)(`p`,{id:`connect-pairing-error`,className:`m-0 text-[13px] text-danger`,role:`alert`,children:o(m?`connection.pairing.validationPending`:f===`invalid-code`?`connection.pairing.notApiKey`:f===`unreachable`?`connection.pairing.networkError`:f===`request-failed`?`connection.pairing.requestError`:f===`origin-denied`?`connection.pairing.originDenied`:f===`cloudflare-challenge`?`connection.pairing.cloudflareChallenge`:f===`remote-link-unauthorized`||f===`remote-link-forbidden`?`connection.pairing.sessionNotAuthorized`:f===`client-state-changed`?`connection.clientStateChanged`:f===`invalid-response`?`connection.pairing.responseError`:`connection.pairing.error`)})]}),e.transport===`relay`&&(0,Z.jsx)(`p`,{className:`m-0 text-fg-subtle`,children:o(`connection.pairing.relayWarning`)})]})]})}var ER={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`},DR={build_unverified:`desktopCompat.blockedByBuild`,egress_proxy_invalid:`desktopCompat.blockedByProxy`,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 OR({apiBase:t,active:n}){let{t:r,locale:i}=a(),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!0),[b,S]=(0,X.useState)(!1),C=(0,X.useRef)({alive:!0,pending:!1,generation:0,operations:new Set}),w=`desktop-compatibility-certificate:${t}`,T=`desktop-compatibility-runtime:${t}`,E=ln(w,e=>bR(t,e),{enabled:n,deadlineMs:15e3,staleAfterMs:0}),D=ln(T,e=>yR(t,e),{enabled:n,deadlineMs:1e4,staleAfterMs:0,pollMs:5e3}),O=E.data&&D.data?{certificate:E.data,runtime:D.data}:null,k=!o&&E.lastAttemptOk&&D.lastAttemptOk&&!E.refreshing&&!D.refreshing,j=c||E.loading||D.loading,M=E.error??D.error,N=u??(M?M instanceof fR?M.code:`connection_unconfirmed`:null),P=E.data?.mutationAuthorized===!0&&v&&N!==`local_dashboard_confirmation_required`;(0,X.useEffect)(()=>{let e=C.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(),l(!1),y(!1),s(!0),h(null),_(!1),p(!1)}};return window.addEventListener(x,t),()=>{window.removeEventListener(x,t),e.alive=!1,e.generation++,e.pending=!1;for(let t of e.operations)t.controller.abort(),t.clear();e.operations.clear()}},[]);let F=(0,X.useCallback)(async n=>{let r=C.current;if(r.pending||n&&(!P||b))return;r.pending=!0;let i=++r.generation;l(!0),d(null),p(!1),s(!0);let a=e(n?14e4:15e3);r.operations.add(a);try{n&&await CR(t,n,a.signal);let e=await SR(t,a.signal);r.alive&&r.generation===i&&(pn(w,e.certificate),pn(T,e.runtime),s(!1),y(!0),p(!!n),h(null),_(!1))}catch(e){r.alive&&r.generation===i&&(d(e instanceof fR?e.code:`connection_unconfirmed`),h(null),_(!1))}finally{r.operations.delete(a),a.clear(),r.generation===i&&(r.pending=!1,r.alive&&l(!1))}},[t,w,T,P,b]),I=!!O?.certificate.supported&&!!O.runtime.supported,L=O?.runtime.phase===`off`&&!O.certificate.busy,R=O?.runtime.phase===`running`,z=[];if(O&&I){let e=O.certificate;L&&e.state===`missing`&&z.push({target:`certificate`,action:`prepare`}),L&&e.fingerprint&&(e.state===`prepared`&&z.push({target:`certificate`,action:`trust`,fingerprint:e.fingerprint}),[`trusted`,`expired`,`renewal-required`,`unknown`].includes(e.state)&&z.push({target:`certificate`,action:`remove-trust`,fingerprint:e.fingerprint}),[`prepared`,`trusted`,`expired`,`renewal-required`].includes(e.state)&&z.push({target:`certificate`,action:`renew`,fingerprint:e.fingerprint})),L&&e.state===`trusted`&&z.push({target:`runtime`,action:`start`}),R&&z.push({target:`runtime`,action:`launch`},{target:`runtime`,action:`observe`},{target:`runtime`,action:`apply`}),(R||O.runtime.phase===`cleanup-required`)&&z.push({target:`runtime`,action:`stop`})}let B=O?.certificate.state===`trusted`?`ok`:O?.certificate.state===`missing`?`idle`:`warn`,V=R?`ok`:`idle`;return(0,Z.jsxs)(`section`,{className:`panel acc-desktop relative flex flex-col gap-4`,children:[(0,Z.jsxs)(`div`,{className:`acc-desktop__intro flex flex-col gap-1 pr-36`,children:[(0,Z.jsx)(`h2`,{children:r(`desktopCompat.title`)}),(0,Z.jsx)(`p`,{className:`muted text-body`,children:r(`desktopCompat.description`)}),(0,Z.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.localOnly`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm acc-desktop__refresh`,disabled:j,onClick:()=>void F(),children:r(j?`common.loading`:`desktopCompat.refresh`)}),(0,Z.jsx)(wR,{apiBase:t,active:n,authorized:P&&!b&&!o}),N&&(0,Z.jsxs)(Bh,{tone:`err`,role:`alert`,children:[(0,Z.jsx)(`p`,{className:`m-0`,children:r(N in DR?DR[N]:`desktopCompat.error`)}),(0,Z.jsx)(`code`,{className:`text-[12px] text-fg-muted`,children:N})]}),f&&(0,Z.jsx)(Bh,{tone:`ok`,role:`status`,children:r(`desktopCompat.done`)}),E.data?.supported&&(!P||b)&&(0,Z.jsx)(`div`,{className:`acc-desktop__card`,children:(0,Z.jsx)(TR,{local:!0,target:A(t).machine,onPairingStart:()=>{S(!0),h(null),_(!1),p(!1)},onConnected:e=>xR(t,e),onCommitted:()=>{S(!1),F()}})}),O&&(0,Z.jsxs)(Z.Fragment,{children:[!I&&(0,Z.jsx)(Bh,{tone:`warn`,children:r(`desktopCompat.unsupported`)}),(0,Z.jsxs)(`dl`,{className:`acc-desktop__status`,children:[(0,Z.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Z.jsx)(`dt`,{children:r(`desktopCompat.certificate`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsxs)(`span`,{className:`acc-desktop__state`,children:[(0,Z.jsx)(Vh,{tone:B}),(0,Z.jsx)(`code`,{children:O.certificate.state})]})}),O.certificate.fingerprint&&(0,Z.jsx)(`dd`,{className:`mono text-label acc-desktop__detail`,style:{overflowWrap:`anywhere`},children:O.certificate.fingerprint})]}),O.certificate.expiresAt!==void 0&&(0,Z.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Z.jsx)(`dt`,{children:r(`desktopCompat.expiry`)}),(0,Z.jsx)(`dd`,{children:new Date(O.certificate.expiresAt).toLocaleString(i)})]}),(0,Z.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Z.jsx)(`dt`,{children:r(`desktopCompat.runtime`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsxs)(`span`,{className:`acc-desktop__state`,children:[(0,Z.jsx)(Vh,{tone:V}),(0,Z.jsx)(`code`,{children:O.runtime.phase}),O.runtime.usage&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(`code`,{children:O.runtime.usage.mode})]})]})})]}),O.runtime.buildAssessment&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Z.jsx)(`dt`,{children:r(`desktopCompat.assessedPackage`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`code`,{children:O.runtime.buildAssessment.assessedVersion})})]}),(0,Z.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Z.jsx)(`dt`,{children:r(`desktopCompat.observedPackage`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`code`,{children:O.runtime.buildAssessment.observedVersion??r(`desktopCompat.noObservedPackage`)})})]}),(0,Z.jsxs)(`div`,{className:`acc-desktop__stat`,children:[(0,Z.jsx)(`dt`,{children:r(`desktopCompat.lastObservedAt`)}),(0,Z.jsx)(`dd`,{children:new Date(O.runtime.buildAssessment.completedAt).toLocaleString(i)})]})]})]}),O.certificate.renewalDue&&(0,Z.jsx)(Bh,{tone:`warn`,children:r(`desktopCompat.renewalDue`)}),O.runtime.usage?.mode===`apply`&&(0,Z.jsx)(Bh,{tone:`warn`,children:r(`desktopCompat.trialRisk`)}),O.runtime.usage?.mode===`observe`&&O.runtime.usage.phase.endsWith(`awaiting-original-response`)&&(0,Z.jsx)(Bh,{tone:`warn`,role:`status`,children:r(`desktopCompat.cacheRefreshHint`)}),O.runtime.contextFailure&&(0,Z.jsx)(Bh,{tone:`warn`,role:`status`,children:r(DR[O.runtime.contextFailure])}),R&&(0,Z.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.reconnectHint`)}),O.runtime.usage?.observation&&(0,Z.jsx)(`p`,{className:`muted text-control`,role:`status`,children:r(`desktopCompat.observation`,{json:O.runtime.usage.observation.jsonSnapshots,sse:O.runtime.usage.observation.streamSnapshots,streams:O.runtime.usage.observation.validatedActiveStreams})})]}),z.length>0&&(0,Z.jsx)(`div`,{className:`acc-desktop__actions flex flex-wrap gap-2`,children:z.map(e=>(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:j||!k||!P||b,onClick:()=>{[`trust`,`remove-trust`,`renew`,`apply`].includes(e.action)?(h(e),_(!1),p(!1)):F(e)},children:r(ER[e.action])},e.action))}),m&&(0,Z.jsxs)(`fieldset`,{className:`acc-desktop__confirm`,disabled:j||!P||b,children:[(0,Z.jsx)(`legend`,{children:r(ER[m.action])}),(0,Z.jsx)(Bh,{tone:`warn`,children:r(m.action===`apply`?`desktopCompat.trialRisk`:`desktopCompat.risk`)}),m.action===`apply`&&(0,Z.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.cacheRefreshHint`)}),m.target===`certificate`&&m.fingerprint&&(0,Z.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:m.fingerprint}),(0,Z.jsxs)(`label`,{className:`row`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked)}),r(`desktopCompat.acknowledge`)]}),(0,Z.jsxs)(`div`,{className:`row`,style:{gap:`var(--space-2)`},children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!g||!k,onClick:()=>void F(m),children:r(`desktopCompat.confirm`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h(null),_(!1)},children:r(`common.cancel`)})]})]})]})}function kR(e){let{t}=a();return e.connected?(0,Z.jsxs)(`section`,{className:`panel acc-desktop flex flex-col gap-4`,children:[(0,Z.jsx)(`h2`,{children:t(`desktopCompat.title`)}),(0,Z.jsx)(Bh,{tone:`warn`,children:t(`desktopCompat.connectedUnavailable`)})]}):(0,Z.jsx)(OR,{...e},e.apiBase)}var AR=[`multiauth`,`prompt`,`desktop`];function jR(){let e=window.location.hash.replace(/^#\/?/,``);return e===`codex-set/desktop`?`desktop`:e===`codex-set/prompt`?`prompt`:`multiauth`}function MR(e){window.location.hash=e===`multiauth`?`codex-set`:`codex-set/${e}`}function NR(e){if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(e.key))return;e.preventDefault();let t=AR.indexOf(jR()),n=AR[e.key===`Home`?0:e.key===`End`?AR.length-1:(t+(e.key===`ArrowRight`?1:-1)+AR.length)%AR.length];MR(n),document.getElementById(`codex-set-tab-${n}`)?.focus()}function PR({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=c(),[i,a]=(0,X.useState)(jR),[o,s]=(0,X.useState)(()=>jR()===`prompt`),[l,u]=(0,X.useState)(()=>jR()===`multiauth`),[d,f]=(0,X.useState)(()=>jR()===`desktop`);(0,X.useEffect)(()=>{let e=()=>a(jR());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let p=o||i===`prompt`,m=l||i===`multiauth`;p!==o&&s(!0),m!==l&&u(!0);let h=d||i===`desktop`;return h!==d&&f(!0),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`nav.codexSet`),children:[(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-multiauth`,"aria-selected":i===`multiauth`,"aria-controls":`codex-set-panel-multiauth`,tabIndex:i===`multiauth`?0:-1,className:`page-tab${i===`multiauth`?` page-tab--active`:``}`,onClick:()=>MR(`multiauth`),onKeyDown:NR,children:r(`codexSet.tab.multiauth`)}),(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-prompt`,"aria-selected":i===`prompt`,"aria-controls":`codex-set-panel-prompt`,tabIndex:i===`prompt`?0:-1,className:`page-tab${i===`prompt`?` page-tab--active`:``}`,onClick:()=>MR(`prompt`),onKeyDown:NR,children:r(`codexSet.tab.prompt`)}),(0,Z.jsx)(`button`,{type:`button`,role:`tab`,id:`codex-set-tab-desktop`,"aria-selected":i===`desktop`,"aria-controls":`codex-set-panel-desktop`,tabIndex:i===`desktop`?0:-1,className:`page-tab${i===`desktop`?` page-tab--active`:``}`,onClick:()=>MR(`desktop`),onKeyDown:NR,children:r(`desktopCompat.title`)})]}),p&&(0,Z.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-prompt`,"aria-labelledby":`codex-set-tab-prompt`,hidden:i!==`prompt`,children:(0,Z.jsx)(PL,{apiBase:e})}),m&&(0,Z.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-multiauth`,"aria-labelledby":`codex-set-tab-multiauth`,hidden:i!==`multiauth`,children:(0,Z.jsx)(nL,{apiBase:e})}),h&&(0,Z.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-desktop`,"aria-labelledby":`codex-set-tab-desktop`,hidden:i!==`desktop`,children:(0,Z.jsx)(kR,{apiBase:t,active:i===`desktop`,connected:n})})]})}var FR=[`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`],IR={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`},LR={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`},RR=new Set([`opencode`,`kimi`,`prime`,`aside`,`hermes`]),zR={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`},BR={...zR,opencode:LR.opencode??null,pi:LR.pi??null,"gentle-shell":null,omp:LR.omp??null,hermes:LR.hermes??null,openclaw:LR.openclaw??null,kimi:LR.kimi??null,gajae:LR.gajae??null,dsh:LR.dsh??null,mcode:LR.mcode??null,zcode:LR.zcode??null,prime:LR.prime??null,aside:LR.aside??null,raycast:LR.raycast??null,omo:LR.omo??null,cline:LR.cline??null,commandcode:LR.commandcode??null,kilo:LR.kilo??null,droid:LR.droid??null,qoder:LR.qoder??null,"qoder-cn":LR[`qoder-cn`]??null,workbuddy:null,"workbuddy-ai":null,t3code:LR.t3code??null},VR=[zR.grok],HR=new Set([...[...RR].map(e=>LR[e]).filter(e=>e!==void 0),...VR]);function UR(e){return BR[e]}function WR({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?HR.has(e)?(0,Z.jsx)(`span`,{className:`${i} client-mark--mask`,style:{...a,maskImage:`url(${e})`,WebkitMaskImage:`url(${e})`},"aria-hidden":`true`}):(0,Z.jsx)(`span`,{className:`${i} client-mark--img`,style:a,"aria-hidden":`true`,children:(0,Z.jsx)(`img`,{src:e,alt:``,width:n,height:n})}):(0,Z.jsx)(`span`,{className:`${i} client-mark--monogram`,style:a,"aria-hidden":`true`,children:t.slice(0,1)})}function GR(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function KR(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 qR(e){return e.id}function JR(e,t,n){let r=(0,X.useRef)(0),i=(0,X.useRef)(!1),a=(0,X.useCallback)((e=`pairing`)=>{r.current++,n(e)},[n]),o=(0,X.useCallback)(()=>{i.current=!1,r.current++},[]);return(0,X.useLayoutEffect)(()=>(i.current=!0,a(`lifecycle`),o),[e,t,a,o]),(0,X.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&a(`session`)},t=()=>{Nt()&&a(`lifecycle`)};window.addEventListener(P,e),window.addEventListener(x,e);let n=Pt(t);return()=>{window.removeEventListener(P,e),window.removeEventListener(x,e),n()}},[a]),{generation:r,invalidate:a,current:(0,X.useCallback)(e=>i.current&&t&&!Nt()&&r.current===e,[t])}}function YR(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 XR=new Set([`required`,`accepted`,`rejected`]);function ZR(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`&&XR.has(t.bearer)&&XR.has(t.dedicated)&&XR.has(t.xApiKey)})}var QR=new Set([`fixed`,`api-surfaces`,`claude-code-legacy`,`invalid`]),$R=[`responses`,`chat`,`messages`];function ez(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n={};for(let e of $R){let r=t[e];if(!r||typeof r!=`object`||Array.isArray(r))return;let{enabled:i,source:a}=r;if(typeof i!=`boolean`||!QR.has(a))return;n[e]={enabled:i,source:a}}return n}function tz(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 nz={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 rz(e){let t=e||nz.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 iz(e,t){let n=new Date(e);return!e||Number.isNaN(n.getTime())?`—`:n.toLocaleDateString(t)}function az({url:e}){return(0,Z.jsx)(oz,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,Z.jsx)(`code`,{className:`api-code api-code-inline api-endpoint-url`,children:e})})}function oz({text:e,hintKey:t,copiedKey:n,className:r,children:i}){let{t:o}=a(),s=(0,X.useId)(),c=(0,X.useRef)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),h=(0,X.useRef)(null),g=l||d;(0,X.useEffect)(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]),(0,X.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,vn.createPortal)((0,Z.jsx)(`span`,{id:s,className:`ocx-tooltip-bubble api-copy-tip-fixed`,role:`tooltip`,style:{top:p.top,left:p.left},children:o(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":o(t),"aria-describedby":g?s:void 0};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,...x,children:i}),b]})}function sz({text:e}){return(0,Z.jsx)(oz,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,Z.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}var cz=`claude/code`,lz={fixed:`api.surface.source.fixed`,"api-surfaces":`api.surface.source.explicit`,"claude-code-legacy":`api.surface.source.inherited`,invalid:`api.surface.source.invalid`},uz=[{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 dz({apiBase:e,endpoints:t,surfaces:n,onChanged:r}){let{t:i}=a(),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),u=async t=>{if(!o){s(!0),l(null);try{let n=await Kx(e,{messagesEnabled:!t.enabled});n.kind===`ok`?r():l(n.kind===`unavailable`?`unavailable`:`failed`)}finally{s(!1)}}};return(0,Z.jsx)(`div`,{className:`api-endpoints api-surface-cards`,children:uz.map(e=>{let r=n[e.id],a=r.enabled?i(`api.surface.on`):i(`api.surface.off`);return(0,Z.jsxs)(`div`,{className:`api-surface-card${r.enabled?``:` api-surface-card-off`}`,"data-surface":e.id,children:[(0,Z.jsxs)(`div`,{className:`api-surface-card-head`,children:[(0,Z.jsx)(`span`,{className:`api-surface-card-title`,children:i(e.titleKey)}),e.id===`messages`?(0,Z.jsx)(kn,{on:r.enabled,disabled:o,onClick:()=>{u(r)},label:`${i(`api.surface.messagesToggle`)}: ${a}`}):null,(0,Z.jsx)(`span`,{className:`badge ${r.enabled?`badge-green`:`badge-muted`}`,children:a})]}),(0,Z.jsx)(az,{url:e.url(t)}),(0,Z.jsx)(`span`,{className:`small ${r.source===`invalid`?`api-surface-invalid`:`muted`}`,children:i(lz[r.source])}),e.id===`messages`?(0,Z.jsxs)(Z.Fragment,{children:[r.enabled?null:(0,Z.jsx)(`span`,{className:`muted small`,children:i(`api.surface.closedNote`)}),r.enabled?(0,Z.jsx)(`span`,{className:`muted small`,children:i(`api.surface.messagesCloseNote`)}):null,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm api-surface-card-link`,onClick:()=>_n(cz),children:i(`api.surface.openClaude`)}),c?(0,Z.jsx)(Q,{tone:`err`,children:i(c===`unavailable`?`api.surface.toggleUnavailable`:`api.surface.toggleFailed`)}):null]}):null]},e.id)})})}function fz(e,t){return t(e===`required`?`api.auth.required`:e===`accepted`?`api.auth.accepted`:`api.auth.rejected`)}function pz({endpoints:e,claudeCodeEnabled:t,authMatrix:n,surfaces:r,apiBase:i,onSurfacesChanged:o}){let{t:s}=a(),c=r&&i!==void 0&&o?{surfaces:r,apiBase:i,onChanged:o}:null;return(0,Z.jsxs)(`div`,{className:`panel api-panel`,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:s(`api.endpointsTitle`)}),(0,Z.jsxs)(`div`,{className:`api-endpoints`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted small`,children:s(`api.baseUrl`)}),(0,Z.jsx)(az,{url:e.baseUrl})]}),c?null:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted small`,children:s(`api.responsesEndpoint`)}),(0,Z.jsx)(az,{url:e.responses})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted small`,children:s(`api.chatCompletionsEndpoint`)}),(0,Z.jsx)(az,{url:e.chatCompletions})]}),t&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted small`,children:s(`api.messagesEndpoint`)}),(0,Z.jsx)(az,{url:e.messages})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`muted small`,children:s(`api.modelsEndpoint`)}),(0,Z.jsx)(az,{url:e.models})]})]}),c?(0,Z.jsx)(dz,{endpoints:e,...c}):null,(0,Z.jsx)(`p`,{className:`muted small`,children:s(`api.endpointNote`)}),(0,Z.jsxs)(`div`,{className:`api-auth-matrix-block`,children:[(0,Z.jsx)(`h4`,{className:`api-auth-matrix-title`,children:s(`api.authTitle`)}),(0,Z.jsx)(`div`,{className:`api-auth-matrix-scroll`,children:(0,Z.jsxs)(`table`,{className:`api-auth-matrix`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:s(`api.auth.endpoint`)}),(0,Z.jsx)(`th`,{children:(0,Z.jsx)(`code`,{children:`Authorization: Bearer`})}),(0,Z.jsx)(`th`,{children:(0,Z.jsx)(`code`,{children:`x-opencodex-api-key`})}),(0,Z.jsx)(`th`,{children:(0,Z.jsx)(`code`,{children:`x-api-key`})})]})}),(0,Z.jsx)(`tbody`,{children:n.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.endpoint})}),(0,Z.jsx)(`td`,{children:fz(e.bearer,s)}),(0,Z.jsx)(`td`,{children:fz(e.dedicated,s)}),(0,Z.jsx)(`td`,{children:fz(e.xApiKey,s)})]},e.endpoint))})]})}),(0,Z.jsx)(`p`,{className:`muted small`,children:s(`api.authLoopback`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:s(`api.authBaseUrlNote`)})]})]})}function mz({keys:e,keysLoading:t=!1,keysLoadFailed:n,newName:r,creating:i,newKey:o,copied:s,confirmDelete:c,localeTag:l,showKeyList:u=!0,onNewNameChange:d,onCreate:f,onDismissNewKey:p,onCopyKey:m,onConfirmDelete:h,onCancelDelete:g,onDelete:_}){let{t:v}=a();return(0,Z.jsxs)(Z.Fragment,{children:[o&&(0,Z.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:v(`api.newKeyTitle`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:v(`api.newKeyNote`)}),(0,Z.jsxs)(`div`,{className:`api-form-row`,children:[(0,Z.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:o}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:m,children:s?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ut,{}),` `,v(`api.copied`)]}):v(`api.copy`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:p,children:v(`api.dismiss`)})]}),(0,Z.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:v(`api.generateTitle`)}),(0,Z.jsxs)(`div`,{className:`api-form-row`,children:[(0,Z.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,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:[(0,Z.jsx)(be,{}),` `,v(i?`api.generating`:`api.generate`)]})]})]}),u&&(0,Z.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:t?v(`api.activeKeysLoading`):v(`api.activeKeys`,{count:e.length})}),t?(0,Z.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":v(`common.loading`)}):e.length>0?(0,Z.jsx)(`div`,{className:`tbl-wrap`,children:(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:v(`api.colName`)}),(0,Z.jsx)(`th`,{children:v(`api.colKey`)}),(0,Z.jsx)(`th`,{children:v(`api.colCreated`)}),(0,Z.jsx)(`th`,{})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:e.name}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.prefix})}),(0,Z.jsx)(`td`,{children:iz(e.createdAt,l)}),(0,Z.jsx)(`td`,{children:c===e.id?(0,Z.jsxs)(`span`,{className:`api-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>_(e.id),children:v(`api.confirm`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,children:v(`common.cancel`)})]}):(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":v(`api.deleteAria`),onClick:()=>h(e.id),children:(0,Z.jsx)(We,{})})})]},e.id))})]})}):n?(0,Z.jsx)(`p`,{className:`muted`,children:v(`api.keysLoadFailed`)}):(0,Z.jsx)(`p`,{className:`muted`,children:v(`api.noKeys`)})]})]})}function hz({filteredModels:e,modelsLoading:t,modelsRefreshing:n=!1,modelsLoadFailed:r,modelCount:i,hasModelData:o,modelQuery:s,copiedModelId:c,modelTests:l,claudeCodeEnabled:u,onModelQueryChange:d,onCopyModelId:f,onTestModel:p,onRetryModels:m,canTestModels:h,sourceLabel:g,protocolLabel:_}){let{t:v}=a();return(0,Z.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,Z.jsxs)(`div`,{className:`api-panel-head`,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:v(`api.modelsTitle`)}),(0,Z.jsx)(`span`,{className:`muted mono text-label`,children:v(`api.modelsCount`,{count:e.length})})]}),(0,Z.jsx)(`p`,{className:`muted small`,children:v(`api.modelsSubtitle`)}),(0,Z.jsx)(`input`,{type:`search`,className:`input`,value:s,onChange:e=>d(e.target.value),placeholder:v(`api.modelsSearch`),"aria-label":v(`api.modelsSearch`)}),r&&(0,Z.jsxs)(`div`,{className:`api-models-error`,children:[(0,Z.jsx)(`p`,{className:`muted small`,role:`alert`,children:v(`api.modelsLoadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:v(`common.retry`)})]}),n&&!t&&(0,Z.jsx)(`p`,{className:`muted small`,"aria-live":`polite`,children:v(`api.modelsLoading`)}),t?(0,Z.jsx)(NE,{label:v(`api.modelsLoading`),rows:3}):o?e.length===0?(0,Z.jsx)(`p`,{className:`muted small api-models-empty`,children:i===0?v(`api.modelsEmpty`):v(`api.modelsNoMatch`,{query:s.trim()})}):(0,Z.jsx)(`div`,{className:`api-models-scroll`,children:(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:v(`api.colModel`)}),(0,Z.jsx)(`th`,{children:v(`api.colSource`)}),(0,Z.jsx)(`th`,{children:v(`api.colProtocols`)})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>{let t=qR(e),n=GR(u);return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsxs)(`div`,{className:`api-model-cell`,children:[(0,Z.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,Z.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,Z.jsx)(`td`,{children:g(e)}),(0,Z.jsx)(`td`,{children:(0,Z.jsxs)(`div`,{className:`api-model-actions`,children:[(0,Z.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,Z.jsxs)(`span`,{className:`api-model-test-chip`,children:[(0,Z.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,Z.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 gz({endpoints:e,claudeCodeEnabled:t}){let{t:n}=a(),r=JSON.stringify(n(`api.usageSampleInput`)),i=`curl ${e.chatCompletions} \\
|
|
22
|
+
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
23
|
+
-H "Content-Type: application/json" \\
|
|
24
|
+
-d '{
|
|
25
|
+
"model": "gpt-5.6-luna",
|
|
26
|
+
"messages": [{"role": "user", "content": ${r}}]
|
|
27
|
+
}'`,o=`curl ${e.responses} \\
|
|
28
|
+
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
29
|
+
-H "Content-Type: application/json" \\
|
|
30
|
+
-d '{
|
|
31
|
+
"model": "gpt-5.6-luna",
|
|
32
|
+
"input": ${r}
|
|
33
|
+
}'`,s=`curl ${e.messages} \\
|
|
34
|
+
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
35
|
+
-H "Content-Type: application/json" \\
|
|
36
|
+
-d '{
|
|
37
|
+
"model": "claude-sonnet-4-6",
|
|
38
|
+
"max_tokens": 64,
|
|
39
|
+
"messages": [{"role": "user", "content": ${r}}]
|
|
40
|
+
}'`;return(0,Z.jsxs)(`section`,{className:`panel api-panel awi-usage-panel`,children:[(0,Z.jsx)(`h3`,{className:`panel-title`,children:n(`api.workspace.usageExamples`)}),(0,Z.jsxs)(`div`,{className:`awi-usage-panel-body`,children:[(0,Z.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Z.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageChatTitle`)}),(0,Z.jsx)(sz,{text:i})]}),(0,Z.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Z.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageResponsesTitle`)}),(0,Z.jsx)(sz,{text:o})]}),t&&(0,Z.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Z.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageMessagesTitle`)}),(0,Z.jsx)(sz,{text:s})]})]})]})}function _z({client:e,apiBase:t,onOpenDetails:n,onCopy:r,onDownload:i}){let a=c(),[o,s]=(0,X.useState)(0),l=[t,e,String(o)].join(`|`),[u,d]=(0,X.useState)(null);(0,X.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;d({key:l,data:a,failed:!1})}catch{if(r)return;d({key:l,data:null,failed:!0})}})(),()=>{r=!0,n.abort()}},[t,e,l]);let f=u!==null&&u.key===l?u:null,p=f?.data??null,m=f?.failed??!1,h=f===null,g=a(IR[e]),_=LR[e],v=p?.text??``,y=(0,X.useCallback)(t=>{p&&n(e,p,v,t.currentTarget)},[e,p,v,n]);return(0,Z.jsxs)(`li`,{className:`awi-clientconfig-row`,children:[(0,Z.jsx)(`span`,{className:`awi-clientconfig-mark`,children:(0,Z.jsx)(WR,{src:_??null,label:g,size:20})}),(0,Z.jsxs)(`span`,{className:`awi-clientconfig-identity`,children:[(0,Z.jsx)(`span`,{className:`awi-clientconfig-name`,children:g}),(0,Z.jsx)(`span`,{className:`muted text-label awi-clientconfig-meta`,children:h?a(`api.clientConfig.loading`):m||!p?(0,Z.jsx)(`span`,{role:`alert`,children:a(`api.clientConfig.rowError`,{client:g})}):a(`api.clientConfig.rowMeta`,{destination:p.destination,count:p.modelCount})})]}),(0,Z.jsx)(`span`,{className:`awi-clientconfig-row-actions`,children:m&&!h?(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e=>e+1),children:a(`common.retry`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":a(`api.clientConfig.copyAria`,{client:g}),disabled:!p,onClick:()=>{p&&r(e,v)},children:a(`api.clientConfig.copy`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"aria-label":a(`api.clientConfig.downloadAria`,{client:g}),disabled:!p,onClick:()=>{p&&i(e,p,v)},children:a(`api.clientConfig.download`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":a(`api.clientConfig.detailsAria`,{client:g}),disabled:!p,onClick:y,children:a(`api.clientConfig.details`)})]})})]})}function vz({client:e,envelope:t,json:n,hasKeys:r,onClose:i,onCopy:a,onDownload:o}){let s=c(),l=(0,X.useRef)(null),u=`awi-clientconfig-dialog-${e}`;(0,X.useEffect)(()=>{let e=l.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]);let d=(0,X.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Z.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":u,onCancel:d,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,Z.jsxs)(`div`,{className:`modal-card awi-clientconfig-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:u,children:s(IR[e])}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:s(`common.close`)})]}),(0,Z.jsx)(`pre`,{className:`api-code api-example-pre awi-clientconfig-json`,tabIndex:0,role:`group`,"aria-label":s(`api.clientConfig.jsonLabel`,{client:s(IR[e])}),children:n}),(0,Z.jsx)(`p`,{className:`muted small awi-clientconfig-count`,children:s(`api.clientConfig.modelCount`,{count:t.modelCount})}),t.modelsWithoutLimits>0&&(0,Z.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,Z.jsx)(`p`,{className:`muted small awi-clientconfig-nokey`,children:s(`api.clientConfig.noKeyYet`,{env:t.apiKeyEnv})}),(0,Z.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.destination`)}),(0,Z.jsx)(sz,{text:t.destination})]}),(0,Z.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[e!==`cline`&&t.apiKeyEnv!==``&&(0,Z.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.envHint`)}),(0,Z.jsx)(sz,{text:t.exportHint})]}),(0,Z.jsx)(`p`,{className:`muted small awi-clientconfig-merge`,children:s(e===`cline`?`api.clientConfig.clineBundle`:`api.clientConfig.mergeWarning`)}),(e===`cline`||t.apiKeyEnv!==``)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted text-label awi-clientconfig-where-title`,children:s(`api.clientConfig.whereDisclosure`)}),(0,Z.jsx)(`p`,{className:`muted small`,children:s(e===`cline`?`integrations.semantics.cline`:`api.clientConfig.whereBody`)})]}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:s(`api.clientConfig.copy`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:o,children:s(`api.clientConfig.download`)})]})]})]})}function yz({apiBase:e,baseUrl:t,hasKeys:n}){let r=c(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),l=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(i!==null)return;let e=l.current;e&&(l.current=null,e.isConnected&&e.focus())},[i]);let u=(0,X.useCallback)(async(e,t,n)=>{try{await navigator.clipboard.writeText(t),s(n?r(`api.clientConfig.copiedAnnounceClient`,{client:r(IR[e])}):r(`api.clientConfig.copiedAnnounce`))}catch{s(r(`api.clientConfig.copyFailed`))}},[r]),d=(0,X.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]),f=(0,X.useCallback)(()=>a(null),[]),p=(0,X.useCallback)((e,t,n,r)=>{l.current=r,a({client:e,envelope:t,json:n})},[]);return(0,Z.jsxs)(`section`,{className:`panel api-panel awi-clientconfig-panel`,children:[(0,Z.jsx)(`div`,{className:`api-panel-head awi-clientconfig-head`,children:(0,Z.jsx)(`h3`,{className:`panel-title`,children:r(`api.clientConfig.title`)})}),(0,Z.jsx)(`ul`,{className:`awi-clientconfig-rows`,"aria-label":r(`api.clientConfig.rowsLabel`),children:FR.map(t=>(0,Z.jsx)(_z,{client:t,apiBase:e,onOpenDetails:p,onCopy:(e,t)=>{u(e,t,!0)},onDownload:d},t))}),(0,Z.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,Z.jsx)(`span`,{className:`muted text-label`,children:r(`api.baseUrl`)}),(0,Z.jsx)(sz,{text:t})]}),(0,Z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:o}),i&&(0,Z.jsx)(vz,{client:i.client,envelope:i.envelope,json:i.json,hasKeys:n,onClose:f,onCopy:()=>{u(i.client,i.json,!1)},onDownload:()=>d(i.client,i.envelope,i.json)})]})}function bz({keys:e,keysLoading:t,keysLoadFailed:n,attributionSince:i,usageMetadata:a,localeTag:o,apiBase:s,active:l=!0,onPairingStart:u,busy:d,onSelect:f,onDelete:p,onReveal:m}){let h=c(),[g,_]=(0,X.useState)({}),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),O=(0,X.useRef)(null),[k,j]=(0,X.useState)(null),[M,N]=(0,X.useState)(!1),[P,F]=(0,X.useState)(null),[I,L]=(0,X.useState)(null),R=(0,X.useRef)(null),z=JR(s,l,(0,X.useCallback)(e=>{let t=R.current;R.current=null,_({}),y(null),x(null),C(n=>e===`session`?t??n:e===`pairing`?n:null),T(null),D(null),O.current!==null&&window.clearTimeout(O.current),O.current=null},[]));(0,X.useEffect)(()=>{if(!k)return;let e=window.setTimeout(()=>N(!0),300);return()=>window.clearTimeout(e)},[k]);let B=(0,X.useRef)(new Set),V=e=>{let t=g[e.id];return t!==void 0&&t.startsWith(e.prefix.replace(/\.\.\.$/,``))?t:void 0},H=d||P!==null,U=A(s).shared,W=r()&&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(x(null),C(null),V(e)!==void 0)_(({[n]:e,...t})=>t);else if(m&&!v){R.current=n,y(n);try{let e=await m(n);if(!z.current(t)||B.current.has(n))return;e.ok?_(t=>({...t,[n]:e.key})):e.kind===`denied`?(z.invalidate(),u?.(),C(n)):x(n)}catch{z.current(t)&&x(n)}finally{z.current(t)&&(R.current=null,y(null))}}},te=e=>{T(t=>t===e?null:t),D(e)},ne=(e,t)=>{let n=z.generation.current;if(!z.current(n))return;D(null);let r;try{r=navigator.clipboard?.writeText?.(t)}catch{r=void 0}r?r.then(()=>{z.current(n)&&!B.current.has(e)&&(T(e),O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{T(t=>t===e?null:t),O.current=null},2e3))},()=>{z.current(n)&&te(e)}):te(e)};(0,X.useEffect)(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);let G=async e=>{if(p&&M&&!P){F(e),L(null);try{await p(e)?(B.current.add(e),j(null),N(!1),_(({[e]:t,...n})=>n)):L(e)}finally{F(null)}}};return(0,Z.jsxs)(`div`,{className:`panel api-panel awi-keylist-panel`,"aria-busy":t,children:[(0,Z.jsx)(`div`,{className:`api-panel-head`,children:(0,Z.jsx)(`h3`,{className:`panel-title`,children:t?h(`api.activeKeysLoading`):h(`api.activeKeys`,{count:e.length})})}),(0,Z.jsx)(Ur,{data:a}),S!==null&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Q,{tone:`warn`,children:h(`api.key.revealDenied`)}),W&&(0,Z.jsx)(TR,{local:!0,target:U,onPairingStart:()=>{z.invalidate(),u?.()},onConnected:()=>{z.invalidate(),u?.(),C(null)}})]}),t?(0,Z.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":h(`common.loading`)}):e.length===0?(0,Z.jsx)(`p`,{className:`muted small`,children:h(n?`api.keysLoadFailed`:`api.noKeys`)}):(0,Z.jsx)(`div`,{className:`tbl-wrap`,children:(0,Z.jsxs)(`table`,{className:`tbl awi-keylist-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:h(`api.colName`)}),(0,Z.jsx)(`th`,{children:h(`api.colKey`)}),(0,Z.jsx)(`th`,{children:h(`api.attribution.requests7d`)}),(0,Z.jsx)(`th`,{children:h(`api.attribution.lastUsed`)}),p&&(0,Z.jsx)(`th`,{className:`awi-keylist-actions-col`,children:(0,Z.jsx)(`span`,{className:`sr-only`,children:h(`api.colActions`)})})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>{let t=V(e),n=k===e.id;return(0,Z.jsxs)(`tr`,{className:n?`awi-keylist-row is-confirming`:`awi-keylist-row`,children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`button`,{type:`button`,className:`awi-keylist-name`,disabled:H,onClick:()=>f(e.id),children:e.name})}),(0,Z.jsx)(`td`,{className:`awi-keylist-keycell`,children:m?(0,Z.jsxs)(`span`,{className:`awi-keylist-keywrap`,children:[(0,Z.jsx)(`button`,{type:`button`,className:t?`awi-keylist-key is-revealed`:`awi-keylist-key`,"aria-expanded":t!==void 0,"aria-label":h(t?`api.key.hideAria`:`api.key.revealAria`,{name:e.name}),title:h(t?`api.key.hideHint`:`api.key.revealHint`),disabled:v===e.id,onClick:()=>{ee(e)},children:(0,Z.jsx)(`code`,{children:t??e.prefix})}),t&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm awi-keylist-copy`,onClick:()=>ne(e.id,t),children:w===e.id?h(`api.copied`):h(`api.copy`)}),E===e.id&&(0,Z.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:h(`api.key.copyFailedShort`)}),b===e.id&&(0,Z.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:h(`api.key.revealFailed`)})]}):(0,Z.jsx)(`code`,{children:e.prefix})}),(0,Z.jsx)(`td`,{children:i?e.usage.ambiguous?h(`api.attribution.railAmbiguous`):e.usage.requests7d.toLocaleString(o):h(`api.attribution.unavailable`)}),(0,Z.jsx)(`td`,{children:!i||e.usage.ambiguous?`—`:e.usage.lastUsedAt?iz(e.usage.lastUsedAt,o):h(a?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)}),p&&(0,Z.jsxs)(`td`,{className:`awi-keylist-actions`,children:[n?(0,Z.jsxs)(`span`,{className:`awi-keylist-confirm`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,"aria-label":h(`api.key.deleteRowAria`,{name:e.name}),disabled:!M||P!==null,onClick:()=>{G(e.id)},children:P===e.id?h(`api.key.deleting`):h(`api.key.deleteShort`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P!==null,onClick:()=>{j(null),N(!1),L(null)},children:h(`common.cancel`)})]}):(0,Z.jsx)(`button`,{type:`button`,className:`awi-keylist-delete`,"aria-label":h(`api.key.deleteRowAria`,{name:e.name}),title:h(`api.workspace.deleteKey`),disabled:H,onClick:()=>{L(null),N(!1),j(e.id)},children:(0,Z.jsx)(ge,{width:16,height:16,"aria-hidden":`true`})}),I===e.id&&(0,Z.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:h(`api.deleteFailed`)})]})]},e.id)})})]})})]})}var xz=class extends Error{code;constructor(e){super(e),this.code=e}},Sz=2097152;async function Cz(t,n,r,i,a){if(!i.size||i.size>25e6)throw new xz(`size`);if(!r.trim())throw new xz(`auth`);a.throwIfAborted();let o=e(13e4),s=()=>o.controller.abort(a.reason);a.addEventListener(`abort`,s,{once:!0});try{let e=new FormData;e.set(`file`,i),e.set(`model`,n),e.set(`response_format`,`json`);let a=await M(t,{method:`POST`,headers:{"X-OpenCodex-API-Key":r.trim()},body:e,signal:o.signal});if(!a.ok)throw a.body?.cancel().catch(()=>{}),new xz(a.status===401||a.status===403?`auth`:a.status===429?`rateLimit`:a.status===413?`size`:a.status>=500?`unavailable`:`invalid`);let s=a.body?.getReader();if(!s)throw new xz(`protocol`);let c=()=>{s.cancel().catch(()=>{})};o.signal.addEventListener(`abort`,c,{once:!0});let l=``,u=0,d=new TextDecoder;try{for(o.signal.throwIfAborted();;){let e=await s.read();if(o.signal.throwIfAborted(),e.done)break;if(u+=e.value.byteLength,u>Sz)throw new xz(`protocol`);l+=d.decode(e.value,{stream:!0})}l+=d.decode()}finally{o.signal.removeEventListener(`abort`,c),s.cancel().catch(()=>{}),s.releaseLock()}let f;try{f=JSON.parse(l)}catch{throw new xz(`protocol`)}if(!f||typeof f!=`object`||typeof f.text!=`string`)throw new xz(`protocol`);return f.text}catch(e){throw a.aborted?a.reason:o.signal.aborted?new xz(`timeout`):e instanceof xz?e:new xz(`network`)}finally{a.removeEventListener(`abort`,s),o.clear()}}function wz(e){let t=new TextEncoder().encode(e.trim());if(!t.length||t.length>4096)throw new xz(`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 Tz={type:`session.update`,session:{instructions:``,audio:{output:{voice:`cove`}},delegation:{type:`client`}}},Ez=new Set([`session.started`,`session.updated`,`delegation.created`,`output_audio.delta`]);function Dz(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 xz(`invalid`);t.searchParams.set(`model`,e.model);let n=new WebSocket(t.href,wz(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(Tz))}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`))}Ez.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 Oz(e,t,n,r){let i=new URL(e);t&&i.searchParams.set(`model`,n);let a=t?Tz:{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();
|
|
41
|
+
if (!key) throw new Error("missing_data_key");
|
|
42
|
+
const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(key)))
|
|
43
|
+
.replace(/\\+/g, "-").replace(/\\//g, "_").replace(/=+$/, "");
|
|
44
|
+
const ws = new WebSocket(${JSON.stringify(i.href)},
|
|
45
|
+
["opencodex-audio", "opencodex-key." + encoded]);
|
|
46
|
+
ws.onopen = () => ws.send(JSON.stringify(${JSON.stringify(a)}));
|
|
47
|
+
ws.onmessage = ({ data }) => console.log(JSON.parse(data).type);
|
|
48
|
+
// After session.started, send your protocol's audio frames.
|
|
49
|
+
// Dictation: mono PCM16 at the declared sample_rate_hz (48000 here).
|
|
50
|
+
// Live Voice: input_audio.append / output_audio.delta, 24 kHz mono.
|
|
51
|
+
const closeSession = () => ws.send(JSON.stringify({ type: "session.close" }));`}function kz(e,t){return[`curl ${JSON.stringify(e)}`,` -H "X-OpenCodex-API-Key: $OPENCODEX_API_KEY"`,` -F "file=@recording.wav" -F "model=${t}"`].join(` \\
|
|
52
|
+
`)}function Az({value:e,onChange:t}){let n=c(),r=(0,X.useId)();return(0,Z.jsxs)(`label`,{className:`audio-api-field`,htmlFor:r,children:[(0,Z.jsx)(`span`,{children:n(`audio.key`)}),(0,Z.jsx)(`input`,{id:r,className:`input`,type:`password`,autoComplete:`off`,spellCheck:!1,maxLength:4096,value:e,onChange:e=>t(e.target.value)})]})}function jz({code:e}){let t=c();return e?(0,Z.jsx)(`p`,{className:`audio-api-error`,role:`alert`,children:t(`audio.error.${e}`)}):null}function Mz({audio:e}){let t=c(),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),p=(0,X.useRef)(null),m=(0,X.useId)(),h=(0,X.useId)();(0,X.useEffect)(()=>()=>{p.current?.abort(),p.current=null},[]);let g=()=>{p.current?.abort(),p.current=null,s(!1)},_=async()=>{if(!e?.transcriptionConfigured||!i||!n.trim()||p.current)return;let t=new AbortController;p.current=t,s(!0),f(null),u(null);try{let r=await Cz(e.transcriptionEndpoint,e.transcriptionModel,n,i,t.signal);p.current===t&&u(r)}catch(e){p.current===t&&!t.signal.aborted&&f(e instanceof xz?e.code:`network`)}finally{p.current===t&&(p.current=null,s(!1))}};return(0,Z.jsxs)(`section`,{className:`audio-api-section`,"aria-labelledby":h,children:[(0,Z.jsxs)(`header`,{className:`audio-api-head`,children:[(0,Z.jsx)(`h3`,{id:h,children:t(`audio.dictation`)}),(0,Z.jsx)(`span`,{className:`muted small`,children:t(e?.transcriptionConfigured?`audio.configured`:e?`audio.notConfigured`:`audio.unknown`)})]}),e&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`audio-api-endpoints`,children:[(0,Z.jsx)(`code`,{children:e.transcriptionModel}),(0,Z.jsx)(az,{url:e.transcriptionEndpoint})]}),(0,Z.jsxs)(`form`,{className:`audio-api-form`,onSubmit:e=>{e.preventDefault(),_()},children:[(0,Z.jsx)(Az,{value:n,onChange:e=>{g(),f(null),r(e)}}),(0,Z.jsxs)(`label`,{className:`audio-api-field`,htmlFor:m,children:[(0,Z.jsx)(`span`,{children:t(`audio.file`)}),(0,Z.jsx)(`input`,{id:m,className:`input`,type:`file`,accept:`audio/*,.mp4,.webm`,onChange:e=>{g(),f(null),u(null),a(e.target.files?.[0]??null)}})]}),(0,Z.jsxs)(`div`,{className:`audio-api-actions`,children:[(0,Z.jsxs)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:o||!e.transcriptionConfigured||!i||!n.trim(),children:[(0,Z.jsx)(le,{width:16,height:16,"aria-hidden":`true`}),t(o?`audio.transcribing`:`audio.transcribe`)]}),o&&(0,Z.jsxs)(`button`,{className:`btn`,type:`button`,onClick:g,children:[(0,Z.jsx)(We,{width:16,height:16,"aria-hidden":`true`}),t(`common.cancel`)]})]})]}),(0,Z.jsx)(jz,{code:d}),l!==null&&(0,Z.jsxs)(`div`,{className:`audio-api-result`,"aria-live":`polite`,children:[(0,Z.jsx)(`h4`,{children:t(`audio.transcript`)}),l?(0,Z.jsx)(sz,{text:l}):(0,Z.jsx)(`p`,{className:`muted small`,children:t(`audio.emptyTranscript`)})]}),(0,Z.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Z.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Z.jsx)(sz,{text:kz(e.transcriptionEndpoint,e.transcriptionModel)}),(0,Z.jsxs)(`div`,{className:`audio-api-head`,children:[(0,Z.jsx)(`h4`,{children:t(`audio.streaming`)}),(0,Z.jsx)(`span`,{className:`muted small`,children:t(e.dictationConfigured?`audio.configured`:`audio.notConfigured`)})]}),(0,Z.jsx)(az,{url:e.dictationStreamEndpoint}),(0,Z.jsx)(sz,{text:Oz(e.dictationStreamEndpoint,!1,e.transcriptionModel,t(`audio.key`))})]})]})]})}function Nz({audio:e}){let t=c(),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(`idle`),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)([]),d=(0,X.useRef)(null),f=(0,X.useId)();(0,X.useEffect)(()=>()=>{d.current?.dispose?.(),d.current=null},[]);let p=()=>{d.current&&(d.current?.dispose?.(),d.current=null,a(`disconnected`))},m=()=>{if(!e?.liveConfigured||!n.trim()||d.current)return;s(null),u([]);let t={};d.current=t;try{t.dispose=Dz({endpoint:e.liveEndpoint,model:e.liveModel,key:n,onState:(e,n)=>{d.current===t&&(a(e),s(n??null),(e===`failed`||e===`disconnected`)&&(d.current=null))},onEvent:e=>{d.current===t&&u(t=>[...t.slice(-7),e])}})}catch(e){d.current=null,a(`failed`),s(e instanceof xz?e.code:`network`)}},h=i===`connecting`||i===`connected`;return(0,Z.jsxs)(`section`,{className:`audio-api-section`,"aria-labelledby":f,children:[(0,Z.jsxs)(`header`,{className:`audio-api-head`,children:[(0,Z.jsx)(`h3`,{id:f,children:t(`audio.liveVoice`)}),(0,Z.jsx)(`span`,{className:`muted small`,children:t(e?.liveConfigured?`audio.configured`:e?`audio.notConfigured`:`audio.unknown`)})]}),e&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`audio-api-endpoints`,children:[(0,Z.jsx)(`code`,{children:e.liveModel}),(0,Z.jsx)(az,{url:e.liveEndpoint}),(0,Z.jsx)(az,{url:e.realtimeCallsEndpoint})]}),(0,Z.jsxs)(`form`,{className:`audio-api-form`,onSubmit:e=>{e.preventDefault(),m()},children:[(0,Z.jsx)(Az,{value:n,onChange:e=>{p(),s(null),u([]),r(e)}}),(0,Z.jsxs)(`div`,{className:`audio-api-actions`,children:[(0,Z.jsxs)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:h||!e.liveConfigured||!n.trim(),children:[(0,Z.jsx)(Fe,{width:16,height:16,"aria-hidden":`true`}),t(`audio.connect`)]}),h&&(0,Z.jsxs)(`button`,{className:`btn`,type:`button`,onClick:p,children:[(0,Z.jsx)(We,{width:16,height:16,"aria-hidden":`true`}),t(`audio.disconnect`)]}),(0,Z.jsx)(`span`,{className:`audio-api-status`,role:`status`,children:t(`audio.state.${i}`)})]})]}),(0,Z.jsx)(jz,{code:o}),l.length>0&&(0,Z.jsx)(`pre`,{className:`audio-api-events`,"aria-label":t(`audio.events`),children:l.join(`
|
|
53
|
+
`)}),(0,Z.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Z.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Z.jsx)(sz,{text:Oz(e.liveEndpoint,!0,e.liveModel,t(`audio.key`))})]})]})]})}function Pz({keys:e,apiBase:t,active:n=!0,onPairingStart:r,attributionSince:i,historyTruncated:a,usageMetadata:o,authMatrix:s,keysLoading:l,keysLoadFailed:u,endpoints:d,claudeCodeEnabled:f,surfaces:p,onSurfacesChanged:m,localeTag:h,newName:g,creating:_,newKey:v,copied:y,rotationSecret:b=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:te,onTestModel:ne,onRetryModels:G,sourceLabel:K,protocolLabel:re}){let q=c(),[ie,ae]=(0,X.useState)(null),[oe,se]=(0,X.useState)(!1),[ce,le]=(0,X.useState)(!1),[ue,J]=(0,X.useState)(!1),[de,fe]=(0,X.useState)(!1),[pe,me]=(0,X.useState)(``),[he,_e]=(0,X.useState)(!1),[ve,ye]=(0,X.useState)(!1),[be,xe]=(0,X.useState)(!1),[Se,Ce]=(0,X.useState)(!1),[we,Te]=(0,X.useState)(!1),[Ee,De]=(0,X.useState)(!1),[Oe,ke]=(0,X.useState)(null),Ae=ie?e.find(e=>e.id===ie)??null:null,je=Ae?b?.id===Ae.id?b.rotationId:Ae.pendingRotation?.id:void 0,Me=je!==void 0||!!B,Ne=ue||he||Se,Pe=()=>{let e=b;if(!e)return;let t=navigator.clipboard?.writeText?.(e.key);t?t.then(()=>{De(!1),ke(e.rotationId),window.setTimeout(()=>ke(null),2e3)}).catch(()=>{De(!0)}):De(!0)},Fe=async e=>{if(Ae&&!Se){Ce(!0),Te(!1);try{let t=je;(e===`start`?await B?.(Ae.id)??!1:t&&(await(e===`commit`?V:H)?.(Ae.id,t)??!1))||Te(!0)}finally{Ce(!1)}}},Ie=(0,X.useMemo)(()=>[{id:`keys`,label:q(`api.section.keys`),meta:l?void 0:String(e.length)},{id:`connect`,label:q(`api.section.connect`)},{id:`endpoints`,label:q(`api.section.endpoints`)},{id:`plan`,label:q(`api.section.plan`)},{id:`dictation`,label:q(`audio.dictation`)},{id:`live-voice`,label:q(`audio.liveVoice`)},{id:`models`,label:q(`api.section.models`),meta:String(D)},{id:`examples`,label:q(`api.section.examples`)}],[q,e.length,l,D]),Le=()=>{se(!1),le(!1)},Re=()=>{ae(null),Le(),fe(!1),ye(!1),xe(!1)};(0,X.useEffect)(()=>{if(!oe)return;let e=window.setTimeout(()=>le(!0),300);return()=>window.clearTimeout(e)},[oe]);let ze=()=>{Ae&&se(!0)},Be=async()=>{if(Ae&&ce&&!ue){J(!0),xe(!1);try{await L(Ae.id)?(Le(),ae(null)):xe(!0)}finally{J(!1)}}},Ve=()=>{Ae&&(me(Ae.name),ye(!1),fe(!0))},He=async()=>{if(!Ae||he)return;let e=pe.trim();if(!e||e===Ae.name)fe(!1);else{_e(!0),ye(!1);try{await z(Ae.id,e)?fe(!1):ye(!0)}finally{_e(!1)}}};return(0,Z.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!Ae&&(0,Z.jsx)(cj,{scope:`api`,items:Ie,ariaLabel:q(`api.workspace.sections`),mobileReadingLine:108}),(0,Z.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,Z.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":q(`api.workspace.details`),children:Ae?(0,Z.jsxs)(`div`,{className:`awi-detail`,children:[(0,Z.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:Re,disabled:Ne,children:[(0,Z.jsx)(St,{className:`awi-back-chevron`,"aria-hidden":`true`}),q(`modal.back`)]})}),(0,Z.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,Z.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,Z.jsx)(`h2`,{className:`awi-detail-title`,children:Ae.name}),(0,Z.jsx)(`span`,{className:`awi-detail-actions`,children:oe?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{Be()},disabled:!ce||ue,children:[(0,Z.jsx)(ge,{}),` `,q(ue?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Le,disabled:ue,children:q(`common.cancel`)})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ve,disabled:de,children:q(`api.key.rename`)},`rename`),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:ze,"aria-label":q(`api.deleteAria`),children:[(0,Z.jsx)(ge,{}),` `,q(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),oe&&(0,Z.jsx)(`p`,{className:`muted awi-delete-hint`,children:q(`api.workspace.deleteConfirm`)}),be&&(0,Z.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:q(`api.deleteFailed`)}),de&&(0,Z.jsxs)(`div`,{className:`awi-rename`,children:[(0,Z.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:q(`api.key.name`)}),(0,Z.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:pe,maxLength:64,disabled:he,onChange:e=>me(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),He())}}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{He()},disabled:he,children:q(he?`api.key.renaming`:`api.key.saveName`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>fe(!1),disabled:he,children:q(`common.cancel`)}),ve&&(0,Z.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:q(`api.key.renameFailed`)})]}),(0,Z.jsxs)(`div`,{className:`awi-section`,children:[(0,Z.jsx)(`h3`,{className:`awi-section-title`,children:q(`api.workspace.keyDetails`)}),(0,Z.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:q(`api.workspace.keyPrefix`)}),(0,Z.jsx)(`dd`,{children:(0,Z.jsx)(`code`,{children:Ae.prefix})})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:q(`api.colCreated`)}),(0,Z.jsx)(`dd`,{children:iz(Ae.createdAt,h)})]})]})]}),Me&&(0,Z.jsxs)(`div`,{className:`awi-section`,"aria-live":`polite`,children:[(0,Z.jsx)(`h3`,{className:`awi-section-title`,children:q(`api.rotation.title`)}),je?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted`,children:q(`api.rotation.pending`)}),Ae.pendingRotation&&(0,Z.jsxs)(`p`,{className:`muted`,children:[q(`api.rotation.expires`),` `,iz(Ae.pendingRotation.expiresAt,h)]}),b?.id===Ae.id&&(0,Z.jsxs)(`div`,{className:`api-key-reveal`,role:`status`,children:[(0,Z.jsx)(`p`,{children:q(`api.rotation.secretOnce`)}),(0,Z.jsx)(`code`,{children:b.key}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:U??Pe,children:x||Oe===b.rotationId?q(`api.copied`):q(`api.copy`)}),W&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:W,children:q(`common.close`)})]}),Ee&&(0,Z.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:q(`api.key.copyFailed`)})]}),(V||H)&&(0,Z.jsxs)(`div`,{className:`awi-detail-actions`,children:[V&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:Se,onClick:()=>{Fe(`commit`)},children:q(`api.rotation.commit`)}),H&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:Se,onClick:()=>{Fe(`abort`)},children:q(`api.rotation.abort`)})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted`,children:q(`api.rotation.description`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:Se,onClick:()=>{Fe(`start`)},children:q(Se?`api.rotation.starting`:`api.rotation.start`)})]}),we&&(0,Z.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:q(`api.rotation.failed`)})]}),(0,Z.jsxs)(`div`,{className:`awi-section`,children:[(0,Z.jsx)(`h3`,{className:`awi-section-title`,children:q(`api.attribution.title`)}),(0,Z.jsx)(Ur,{data:o}),i?Ae.usage.ambiguous?(0,Z.jsx)(`p`,{className:`muted`,children:q(`api.attribution.ambiguous`)}):(0,Z.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:q(`api.attribution.requests7d`)}),(0,Z.jsx)(`dd`,{children:Ae.usage.requests7d.toLocaleString(h)})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a||o?.usageIncomplete?q(`api.attribution.totalRequestsAvailable`):q(`api.attribution.totalRequests`)}),(0,Z.jsx)(`dd`,{children:Ae.usage.totalRequests.toLocaleString(h)})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:q(`api.attribution.lastUsed`)}),(0,Z.jsx)(`dd`,{children:Ae.usage.lastUsedAt?iz(Ae.usage.lastUsedAt,h):q(o?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)})]}),(0,Z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Z.jsx)(`dt`,{children:a||o?.usageIncomplete?q(`api.attribution.sinceAvailable`):q(`api.attribution.since`)}),(0,Z.jsx)(`dd`,{children:iz(i,h)})]})]}):(0,Z.jsx)(`p`,{className:`muted`,children:q(`api.attribution.unavailableDetail`)})]})]})]}):(0,Z.jsx)(`div`,{className:`awi-overview`,children:(0,Z.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,Z.jsxs)(`div`,{id:aj(`api`,`keys`),className:`awi-section-anchor`,children:[(0,Z.jsx)(mz,{keys:e,keysLoading:l,keysLoadFailed:u,newName:g,creating:_,newKey:v,copied:y,confirmDelete:null,localeTag:h,showKeyList:!1,onNewNameChange:N,onCreate:P,onDismissNewKey:F,onCopyKey:I,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,Z.jsx)(bz,{keys:e,keysLoading:l,keysLoadFailed:u,attributionSince:i,usageMetadata:o,localeTag:h,apiBase:t,active:n,onPairingStart:r,busy:Ne,onDelete:L,onReveal:R,onSelect:e=>{ae(e),Le(),fe(!1),ye(!1),xe(!1)}})]}),(0,Z.jsx)(`div`,{id:aj(`api`,`connect`),className:`awi-section-anchor`,children:(0,Z.jsx)(yz,{apiBase:t,baseUrl:d.baseUrl,hasKeys:e.length>0})}),(0,Z.jsx)(`div`,{id:aj(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,Z.jsx)(pz,{endpoints:d,claudeCodeEnabled:f,authMatrix:s,surfaces:p,apiBase:t,onSurfacesChanged:m})}),(0,Z.jsx)(`div`,{id:aj(`api`,`plan`),className:`awi-section-anchor`,children:(0,Z.jsx)(gD,{apiBase:t,models:C??S,protocolLabel:re},t)}),(0,Z.jsx)(`div`,{id:aj(`api`,`dictation`),className:`awi-section-anchor`,children:n&&(0,Z.jsx)(Mz,{audio:d.audio},`${t}:${JSON.stringify(d.audio)}`)}),(0,Z.jsx)(`div`,{id:aj(`api`,`live-voice`),className:`awi-section-anchor`,children:n&&(0,Z.jsx)(Nz,{audio:d.audio},`${t}:${JSON.stringify(d.audio)}`)}),(0,Z.jsx)(`div`,{id:aj(`api`,`models`),className:`awi-section-anchor`,children:(0,Z.jsx)(hz,{filteredModels:S,modelsLoading:w,modelsRefreshing:T,modelsLoadFailed:E,modelCount:D,hasModelData:O,modelQuery:k,copiedModelId:A,modelTests:j,claudeCodeEnabled:f,onModelQueryChange:ee,onCopyModelId:te,onTestModel:ne,onRetryModels:G,canTestModels:M,sourceLabel:K,protocolLabel:re})}),(0,Z.jsx)(`div`,{id:aj(`api`,`examples`),className:`awi-section-anchor`,children:(0,Z.jsx)(gz,{endpoints:d,claudeCodeEnabled:f})})]})})})})]})}var Fz=[],Iz=15e3;function Lz(e){let t=e.replace(/\/$/,``);if(!t)return nz;try{return new URL(t).host?rz(`${t}/v1/responses`):nz}catch{return nz}}function Rz(e){if(!e||!ZR(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!YR(e.usage)||!zz(e.pendingRotation)))return null;if(e.surfaces!==void 0&&!ez(e.surfaces)){let{surfaces:t,...n}=e;e=n}if(e.endpoints?.audio!==void 0&&!tz(e.endpoints.audio,e.endpoints.baseUrl)){let{audio:t,...n}=e.endpoints;return{...e,endpoints:n}}return e}function zz(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 Bz({apiBase:t,active:n=!0}){let{t:r,locale:o}=a(),s=d.find(e=>e.code===o)?.htmlLang,c=`ocx.apikeys.list.v2:${t}`,l=`ocx.apikeys.models.v1:${t}`,u=`api-keys:${t}`,f=`api-models:${t}`,p=jd(c),m=jd(l),h=Rz(p?.data??null),g=m?.data??null,_=(0,X.useRef)(t);(0,X.useLayoutEffect)(()=>{_.current=t},[t]);let[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)({}),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(null),[P,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(null),[R,z]=(0,X.useState)(!1),B=(0,X.useRef)(!1),V=JR(t,n,(0,X.useCallback)(()=>{N(null),F(!1),L(null),z(!1)},[])),H=(0,X.useCallback)(async e=>{let n=await Bn(await fetch(`${t}/api/keys`,{signal:e}));if(!n||!ZR(n.authMatrix))throw Error(r(`api.keysLoadFailed`));let i=n.keys??[];if(i.some(e=>!YR(e.usage)||!zz(e.pendingRotation)))throw Error(r(`api.keysLoadFailed`));let a=i,o=rz(n.endpoint??``),s=ez(n.surfaces),l={keys:a,endpoints:{baseUrl:n.baseUrl??o.baseUrl,responses:n.responsesEndpoint??n.endpoint??nz.responses,chatCompletions:n.chatCompletionsEndpoint??o.chatCompletions,messages:n.messagesEndpoint??o.messages,models:n.modelsEndpoint??o.models,...tz(n.audio,n.baseUrl??o.baseUrl)?{audio:n.audio}:{}},claudeCodeEnabled:n.claudeCodeEnabled!==!1,...s?{surfaces:s}:{},...n.attributionSince?{attributionSince:n.attributionSince}:{},...n.historyTruncated===!0?{historyTruncated:!0}:{},...Rr(n),authMatrix:n.authMatrix};return e.aborted||Md(c,l),l},[t,c,r]),U=(0,X.useCallback)(async e=>{let n=await fetch(`${t}/v1/models`,{signal:e});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=>KR(e)).sort((e,t)=>qR(e).localeCompare(qR(t)));return Md(l,o),o},[t,l,r]),W=Fd(u,[t],H,{isEmpty:e=>e.keys.length===0,initialData:h??void 0,initialDataCachedAt:p?.cachedAt??null,staleAfterMs:6e4,enabled:n}),ee=Fd(f,[t],U,{isEmpty:e=>e.length===0,initialData:g??void 0,initialDataCachedAt:m?.cachedAt??null,staleAfterMs:6e4,enabled:n}),te=W.state,ne=ee.state,G=te.data??h,K=ne.data??g??Fz,re=G?.keys??[],q=G?.endpoints??Lz(t),ie=G?.claudeCodeEnabled??!0,ae=G?.surfaces,oe=G?.attributionSince,se=G?.historyTruncated===!0,ce=G?.authMatrix??[],le=W.refresh,ue=ee.refresh,J=(0,X.useMemo)(()=>{let e=S.trim().toLowerCase();return e?K.filter(t=>qR(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):K},[S,K]),de=async e=>{let n=V.generation.current;if(B.current)return!1;B.current=!0,j(!0),x(null),y(null);try{let i=e??O,a=await fetch(`${t}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:i||`default`})});a.ok&&(_.current===t?le():fn(u));let o=await zn(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(t),!0)}catch{return x(r(`api.createFailed`)),!1}finally{B.current=!1,j(!1)}},fe=async n=>{x(null);let r=e(Iz);try{return(await fetch(`${t}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n}),signal:r.signal})).ok?(le(),!0):!1}catch{return!1}finally{r.clear()}},pe=async n=>{let r=e(Iz);try{let e=await fetch(`${t}/api/keys/reveal`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n}),signal:r.signal,cache:`no-store`});if(e.status===401||e.status===403)return{ok:!1,kind:`denied`};if(!e.ok)return{ok:!1,kind:`failed`};let i=await e.json();return typeof i.key==`string`&&i.key?{ok:!0,key:i.key}:{ok:!1,kind:`failed`}}catch{return{ok:!1,kind:`failed`}}finally{r.clear()}},me=async(n,r)=>{x(null);let i=e(Iz);try{return(await fetch(`${t}/api/keys`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n,name:r}),signal:i.signal})).ok?(le(),!0):!1}catch{return!1}finally{i.clear()}},he=async n=>{let i=V.generation.current;x(null),y(null);let a=e(Iz);try{let e=await fetch(`${t}/api/keys/rotate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n}),signal:a.signal});e.ok&&(_.current===t?le():fn(u));let o=await zn(e,r(`api.rotation.startFailed`));return V.current(i)?!o||typeof o.key!=`string`||!o.key||typeof o.rotationId!=`string`||!o.rotationId?!1:(L({id:n,key:o.key,rotationId:o.rotationId}),!0):(y(t),!0)}catch{return!1}finally{a.clear()}},ge=async(n,r,i)=>{x(null);let a=e(Iz);try{return(await fetch(`${t}${i===`commit`?`/api/keys/rotate/commit`:`/api/keys/rotate`}`,{method:i===`commit`?`POST`:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n,rotationId:r}),signal:a.signal})).ok?(L(e=>e?.id===n?null:e),le(),!0):!1}catch{return!1}finally{a.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`):Ge(e.provider,r),xe=e=>r(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),Se=(e,t)=>e===`responses`?{url:q.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:q.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:q.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=qR(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,Z.jsxs)(`section`,{className:`api-page`,"aria-busy":te.refreshing||ne.refreshing||void 0,children:[(0,Z.jsx)(`div`,{className:`page-head`,children:(0,Z.jsx)(`h2`,{children:r(`api.title`)})}),(0,Z.jsxs)(`p`,{className:`page-sub`,children:[Te[0],(0,Z.jsx)(`code`,{children:`x-opencodex-api-key`}),Te[1]]}),v===t&&(0,Z.jsx)(Q,{tone:`warn`,children:r(`api.key.mutationHidden`)}),b&&(0,Z.jsx)(Q,{tone:`err`,children:b}),te.showError&&G&&(0,Z.jsx)(Q,{tone:`err`,children:r(`api.keysLoadFailed`)}),te.showSkeleton&&!G?(0,Z.jsx)(NE,{label:r(`api.activeKeysLoading`),rows:4}):te.kind===`failed-cold`&&!G?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Q,{tone:`err`,children:te.error instanceof Error?te.error.message:r(`api.keysLoadFailed`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>le(),children:r(`common.retry`)})]}):(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsx)(Pz,{active:n,onPairingStart:()=>V.invalidate(),keys:re,apiBase:t,attributionSince:oe,historyTruncated:se,usageMetadata:Rr(G),authMatrix:ce,keysLoading:!1,keysLoadFailed:te.showError,endpoints:q,claudeCodeEnabled:ie,surfaces:ae,onSurfacesChanged:()=>{le()},localeTag:s,newName:O,creating:A,newKey:M,copied:P,rotationSecret:I,rotationCopied:R,filteredModels:J,planModels:K,modelsLoading:ne.showSkeleton&&!ne.data&&!g,modelsRefreshing:ne.refreshing&&ne.showError&&(ne.data!==void 0||g!==null),modelsLoadFailed:ne.showError,modelCount:K.length,hasModelData:ne.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,...i()?{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:()=>{ue({forceLoading:!0})},canTestModels:M!==null,sourceLabel:be,protocolLabel:xe},t)})]})}var Vz=[`none`,`live`,`stopped`,`disabled`,`broken`,`foreign`,`local`,`unknown`];function Hz(e){return e===void 0?`none`:Vz.find(t=>t===e)??`unknown`}function Uz(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 Wz(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 Gz=`failed`;function Kz({apiBase:e,reason:t,port:n,onStarted:r}){let i=c(),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(null),u=async()=>{if(!a){o(!0),l(null);try{let t=await fetch(`${e}/api/claude-intercept/start`,{method:`POST`}),n=await t.json();!t.ok||!n.ok?l({reason:n.reason??Gz,port:n.port}):r()}catch{l({reason:Gz})}finally{o(!1)}}};return(0,Z.jsxs)(`span`,{role:`status`,children:[i(Wz(s?.reason??t),{port:s?.port??n??``}),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:a,onClick:()=>void u(),children:i(a?`claude.intercept.starting`:`claude.intercept.start`)})]})}function qz(e){let[t,n]=(0,X.useState)(!1),r=(0,X.useRef)(!1);return{pending:t,change:async(t,i,a)=>{if(!r.current){r.current=!0,n(!0);try{i((await yE(e,`claude`,t)).desiredEnabled)}catch(e){a(e)}finally{r.current=!1,n(!1)}}}}}function Jz(e,t){let n=(e??[]).map(e=>({value:e,label:lT(e)}));return[{value:``,label:t},...n]}function Yz(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}function Xz(){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 Zz=829800;function Qz(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 $z(e){return e===`200k`?`200k`:`1m`}var eB=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`],tB=/\[1m\]$/i,nB={ANTHROPIC_DEFAULT_OPUS_MODEL:`claude-opus-5-5`,ANTHROPIC_DEFAULT_SONNET_MODEL:`claude-sonnet-5`,ANTHROPIC_DEFAULT_FABLE_MODEL:`claude-fable-5-1`};function rB(e){return e.replace(tB,``)}function iB(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 aB(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 eB){let n=e.effectiveModelEnv[t];if(!n)continue;if(!r){if(nB[t]===rB(n))continue;i[t]=rB(n);continue}let a=iB(e,t);a&&(i[t]=tB.test(a)?n:rB(n))}return i}function oB(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=aB(e),s=eB.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(`
|
|
54
|
+
`)}function sB({code:e,className:t,size:n=`md`}){let r=c(),[i,a]=(0,X.useState)(`idle`),o=(0,X.useRef)(null);(0,X.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)},l=r(i===`copied`?`api.copied`:`api.copy`);return(0,Z.jsxs)(`div`,{className:Y(`ui-v2 relative min-w-0 rounded-[8px] bg-surface ring-1 ring-inset ring-line`,t),children:[(0,Z.jsx)(`pre`,{className:Y(`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,Z.jsx)(`code`,{children:e})}),(0,Z.jsx)(`button`,{type:`button`,className:Y(yp,`absolute top-1 right-1`,i===`copied`&&`text-success hover:text-success`),"aria-label":l,title:l,onClick:()=>{s()},children:(0,Z.jsx)(xc,{icon:i===`copied`?Pc:Ec,strokeWidth:1.8,"aria-hidden":`true`})}),(0,Z.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:i===`copied`?r(`api.copied`):i===`failed`?r(`api.key.copyFailedShort`):``})]})}var cB=Symbol(`modelEditStartedDisabled`);function lB(e){if(!e||!e[cB])return e;let t={...e};return delete t[cB],t}function uB(e){return e?e.backend??`auto`:`inherit`}function dB(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 fB(e,t){let n={...e};return t===`anthropic`||t===`anthropic2`?n.anthropicInstance=t:n.anthropicInstance!==void 0&&(n.anthropicInstance=null),n}function pB(e,t){let n=e?.enabled===!1||e?.[cB];return{...e,model:t,...n?{enabled:t.trim().length>0,[cB]:!0}:{}}}function mB(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 hB({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,Z.jsxs)(`label`,{className:`toggle`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,Z.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function gB({supported:e,checked:t,onChange:n}){let r=c(),i=e?void 0:`claude-system-env-unsupported`;return(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,Z.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,Z.jsx)(`span`,{className:`desc`,id:i,children:(0,Z.jsx)(N,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,Z.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,Z.jsx)(hB,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function _B({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=c(),a=t??e;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,Z.jsx)($,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,Z.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function vB(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 yB({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=c();return(0,Z.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsx)($,{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,Z.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,Z.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,Z.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:vB(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,Z.jsx)(gB,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsx)($,{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,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(`claude.contextAccounting`)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(`claude.contextAccountingDesc`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsx)($,{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,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,Z.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,Z.jsx)(hB,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.contextAccounting===`1m`&&e.autoContext&&(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,Z.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsx)($,{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,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,Z.jsx)(hB,{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,Z.jsxs)(`div`,{className:`setting-row claudecode-sidecar-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label setting-copy`,children:[(0,Z.jsx)(`span`,{className:`title`,children:i(o)}),(0,Z.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,Z.jsxs)(`div`,{className:`setting-controls`,children:[(0,Z.jsx)($,{value:uB(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]:dB(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,Z.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:pB(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),autoComplete:`off`}),a&&(0,Z.jsx)(`datalist`,{id:c,children:n.map(e=>(0,Z.jsx)(`option`,{value:e},e))}),l===`anthropic`&&(0,Z.jsx)($,{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]:fB(a,n)}),portal:!0}),l===`anthropic`&&a?.anthropicInstance&&e.sidecarPools?.[t]?.parent&&a.anthropicInstance!==e.sidecarPools[t].parent&&(0,Z.jsx)(`span`,{className:`muted setting-hint`,children:i(`sidecar.poolMixed`)})]})]},t)})]})}function bB({manualEnv:e}){let t=c();return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted text-label claude-quickstart-hint`,children:(0,Z.jsx)(N,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,Z.jsx)(sB,{code:`ocx claude`}),(0,Z.jsxs)(`details`,{className:`claude-quickstart-manual`,children:[(0,Z.jsx)(`summary`,{className:`muted text-label`,children:t(`claude.manualEnv`)}),(0,Z.jsx)(sB,{code:e,size:`sm`})]})]})}function xB({rows:e,onRowsChange:t}){let n=c();return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),e.length>0&&(0,Z.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,Z.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,Z.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,Z.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,Z.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,Z.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,Z.jsx)(We,{})})]},r.id))}),(0,Z.jsx)(`div`,{style:{marginTop:e.length>0?8:0},children:(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:Xz(),from:``,to:``}]),children:[(0,Z.jsx)(be,{}),` `,n(`claude.addMapping`)]})})]})}var SB=`etc`;function CB(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:SB,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function wB({aliases:e}){let t=c();return(0,Z.jsxs)(`div`,{className:`claude-aliases`,children:[(0,Z.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,Z.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,Z.jsx)(`div`,{className:`claude-aliases-scroll`,children:CB(e).map(([e,n])=>(0,Z.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,Z.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===SB?t(`claude.aliasProviderOther`):e,(0,Z.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,Z.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,Z.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,Z.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,Z.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}var TB=[`opus`,`sonnet`,`haiku`,`fable`];function EB({state:e,options:t,onChange:n,apiBase:r,dirty:i}){let a=c(),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(``),_=t.map(e=>e.value===``?{...e,label:a(`claude.tierDefaults.unset`)}:e);async function v(e){u(!0),f(``),m(!1),g(``);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),m(!0),f(a(`claude.tierDefaults.recovery`)),typeof e.backupPath==`string`&&g(e.backupPath);return}throw Error(`apply_refused`)}let n=await zn(t);e?(s(null),f(a(`claude.tierDefaults.applied`))):s(n)}catch{s(null),m(!0),f(a(`claude.tierDefaults.failed`))}finally{u(!1)}}return(0,Z.jsxs)(Z.Fragment,{children:[TB.map(t=>{let r=e.tierModels?.[t]??``,i=r&&!_.some(e=>e.value===r)?[..._,{value:r,label:r}]:_;return(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsx)(`span`,{className:`setting-label`,children:a(`claudeDesktop.family.${t}`)}),(0,Z.jsx)($,{value:r,options:i,label:a(`claudeDesktop.family.${t}`),onChange:r=>{s(null),n({...e,tierModels:{...e.tierModels,[t]:r}})}})]},t)}),(0,Z.jsxs)(`div`,{className:`btn-row`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:l||i,onClick:()=>void v(!1),children:[(0,Z.jsx)(se,{}),` `,a(`claude.tierDefaults.preview`)]}),o&&(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:l||i||!o.changes.length,onClick:()=>void v(!0),children:[(0,Z.jsx)(ut,{}),` `,a(`claude.tierDefaults.apply`)]})]}),o&&(0,Z.jsx)(`pre`,{children:o.changes.length?o.changes.map(e=>`${e.key}\n${e.before??`-`} -> ${e.after}`).join(`
|
|
55
|
+
|
|
56
|
+
`):a(`claude.tierDefaults.applied`)}),d&&(0,Z.jsx)(`p`,{role:p?`alert`:`status`,children:d}),h&&(0,Z.jsx)(`pre`,{children:h})]})}var DB=[`authMode`,`systemEnv`,`fastMode`,`autoContext`,`autoCompactWindow`,`contextAccounting`,`injectAgents`,`smallFastModel`,`tierModels`,`webSearchSidecar`,`visionSidecar`];function OB(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 kB(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:OB(t),webSearchSidecar:mB(e.webSearchSidecar),visionSidecar:mB(e.visionSidecar)}}function AB(e){return JSON.stringify([kB(e.state,e.rows),e.rows.map(e=>[e.from,e.to])])}function jB(e,t){return AB(e)!==AB(t)}function MB(e){return Object.fromEntries(DB.map(t=>[t,e[t]]))}function NB(e,t){return{...t,...MB(e)}}function PB(e,t){return{...e,...MB(t)}}function FB(e,t){return!e||e.adoptNextRead||!e.savePending&&!jB(e.draft,e.baseline)?{draft:t,baseline:t,adoptNextRead:!1,savePending:e?.savePending}:{draft:{state:NB(e.draft.state,t.state),rows:e.draft.rows},baseline:t,adoptNextRead:!1,savePending:e.savePending}}function IB(e,t){return{state:{...e,...MB(t.state),visionSidecar:lB(t.state.visionSidecar),webSearchSidecar:lB(t.state.webSearchSidecar)},rows:Object.entries(OB(t.rows)).map(([e,t])=>({id:Xz(),from:e,to:t}))}}function LB(e,t){if(!e)return e;let n=IB(e.baseline.state,t),r=n.rows;if(AB(e.draft)===AB(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(mB(t.state[e]));if(JSON.stringify(mB(i.state[e]))!==n)continue;let r=lB(i.state[e]);r!==i.state[e]&&(i={...i,state:{...i.state,[e]:r}})}return{draft:i,baseline:n,adoptNextRead:!1}}function RB(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:Hz(e.sharedProxy),contextAccounting:$z(e.contextAccounting),servedContextAccounting:$z(e.servedContextAccounting??e.contextAccounting)}}var zB=new Map,BB=e=>zB.get(e)??0,VB=e=>{zB.set(e,BB(e)+1)},HB=Symbol(`claude-code-live`),UB=new Map;function WB(e,t,n){for(let r of UB.get(e)??[])r(t,n)}var GB={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 KB({title:e,count:t,children:n}){let r=(0,X.useId)();return(0,Z.jsxs)(`section`,{className:`ccw-section`,"aria-labelledby":r,children:[(0,Z.jsxs)(`h3`,{className:`ccw-section-title`,id:r,children:[e,t==null?null:(0,Z.jsx)(`span`,{className:`count`,children:t})]}),n]})}function qB({apiBase:e,active:t=!0}){let n=c(),{locale:r}=a(),i=d.find(e=>e.code===r)?.htmlLang??`en`,o=`ocx.claude-code.v1:${e}`,s=`claude-code:${e}`,l=(0,X.useMemo)(()=>jd(o),[o]),u=(0,X.useMemo)(()=>l?.data?{...l.data,state:RB(l.data.state)}:null,[l]),[f,p]=(0,X.useState)(()=>u?{draft:u,baseline:u,adoptNextRead:!1}:null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(!1),{pending:S,change:C}=qz(e),[w,T]=(0,X.useState)(!1),E=(0,X.useRef)(!1),D=(0,X.useCallback)(async t=>{let r=BB(o),i=await zn(await fetch(`${e}/api/claude-code`,{signal:t}),n(`claude.loadFail`));if(!i)throw Error(n(`claude.loadFail`));let a={state:RB({...i,authMode:i.authMode===`proxy`||i.authMode===`subscription`?i.authMode:`auto`,...Yz(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:Xz(),from:e,to:String(t)}))};if(t.aborted)throw Error(`Claude Code request aborted`);return r===BB(o)?(Md(o,a),a):{...a,superseded:!0}},[e,o,n]),O=Fd(s,[e],D,{isEmpty:()=>!1,enabled:t,initialData:u??void 0,initialDataCachedAt:l?.cachedAt??null,staleAfterMs:6e4}),k=O.state,[A,j]=(0,X.useState)(k.data);if(k.data!==A){j(k.data);let e=k.data;e&&!e.superseded&&p(t=>FB(t,{state:e.state,rows:e.rows}))}let M=k.data??u,N=f?.draft.state??M?.state??null,P=f?.draft.rows??M?.rows??[],F=f!==null&&jB(f.draft,f.baseline),I=e=>{p(t=>t&&{...t,draft:{...t.draft,state:e},adoptNextRead:!1})},L=e=>{p(t=>t&&{...t,draft:{...t.draft,rows:e},adoptNextRead:!1})},R=e=>{let t=jd(o)?.data;t&&Md(o,{...t,state:{...t.state,...e}}),WB(o,{kind:`live`,fields:e},HB)},[z]=(0,X.useState)(()=>Symbol(`claude-code-page`));(0,X.useEffect)(()=>{let e=(e,t)=>{if(e.kind===`live`){let{fields:t}=e;p(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;p(e=>FB(e,t))}},t=UB.get(o)??new Set;return t.add(e),UB.set(o,t),()=>{t.delete(e)}},[o,z]);let B=(0,X.useMemo)(()=>Jz(N?.available,n(`claude.smallFastModelUnsetOption`)),[N?.available,n]),V=(0,X.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,Zz,9e5,1e6].sort((e,t)=>e-t),t=N?.autoCompactWindow??null,r=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:n(`claude.autoCompactDefault`,{value:Qz(Zz,i)})},...r.map(e=>({value:String(e),label:Qz(e,i)}))]},[N?.autoCompactWindow,n,i]),H=async()=>{N&&(y(``),await C(!N.enabled,e=>{VB(o),R({enabled:e}),O.refresh()},e=>{x(!1),y(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}))},U=async()=>{if(!N||E.current)return;E.current=!0,T(!0),y(``);let t=!N.cliFirstParty;try{let r=await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cliFirstParty:t})});if(!r.ok){let e=await r.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)?n(Wz(e.code),{port:e.port??``,bound:e.bound??``,configured:e.configured??``}):n(i))}await zn(r,n(`claude.saveFailed`)),VB(o),R({cliFirstParty:t}),O.refresh()}catch(e){x(!1),y(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}finally{E.current=!1,T(!1)}},W=async()=>{if(!N||!f||m)return;let t=f.draft;y(``),_(``),h(!0),p(e=>e&&{...e,savePending:!0}),VB(o);try{await zn(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(kB(t.state,t.rows))}),n(`claude.saveFailed`)),VB(o);let r=jd(o)?.data,i=IB(r?.state??t.state,t);Md(o,i),WB(o,{kind:`saved`,copy:i},z),p(e=>LB(e,t)),x(!0),_(``),y(n(`claude.saved`)),O.refresh()}catch(e){p(e=>e&&{...e,savePending:!1}),x(!1),_(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}finally{h(!1)}},ee=()=>{y(``),_(``),p(e=>e&&{draft:{state:PB(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,Z.jsx)(NE,{label:n(`claude.loading`),rows:3});if(k.kind===`failed-cold`){let e=k.error instanceof Error?k.error.message:n(`claude.loadFail`);return(0,Z.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,Z.jsx)(Q,{tone:`err`,children:e}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>O.refresh(),children:n(`common.retry`)})]})}if(!N)return null;let te=(0,Z.jsxs)(`div`,{className:`setting-row claudecode-connection-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,id:`claudecode-connection-label`,children:n(`claude.enabledLabel`)}),(0,Z.jsx)(`span`,{className:`desc`,children:n(`claude.subtitle`)})]}),(0,Z.jsx)(kn,{on:N.enabled,onClick:()=>void H(),disabled:S,label:n(`claude.toggleAria`)})]});return(0,Z.jsxs)(`div`,{className:`claudecode-workspace-shell claudecode-doc`,children:[v&&(0,Z.jsx)(Q,{tone:b?`ok`:`err`,children:v}),k.showError&&(0,Z.jsx)(Q,{tone:`err`,children:n(`claude.loadFail`)}),(0,Z.jsx)(`div`,{className:`card claudecode-connection-card`,children:(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,id:`claudecode-first-party-label`,children:n(`claude.firstParty.label`)}),(0,Z.jsx)(`span`,{className:`desc`,children:n(`claude.firstParty.desc`)})]}),(0,Z.jsx)(kn,{on:N.cliFirstParty,onClick:()=>void U(),disabled:w,label:n(`claude.firstParty.aria`)})]})}),!N.interceptRunning&&(0,Z.jsx)(Kz,{apiBase:e,reason:N.interceptReason,port:N.interceptFailurePort,onStarted:()=>O.refresh()}),N.cliFirstParty&&(0,Z.jsx)(Q,{tone:`warn`,children:n(`claude.firstParty.risk`)}),(()=>{let e=Uz(N),t=e&&GB[e];return t?(0,Z.jsx)(Q,{tone:`warn`,children:n(t)}):null})(),(0,Z.jsx)(KB,{title:n(`claude.quickstart`),children:(0,Z.jsx)(bB,{manualEnv:oB(N)})}),(0,Z.jsx)(KB,{title:n(`claude.workspace.settings`),children:(0,Z.jsx)(yB,{state:N,autoCompactOptions:V,availableModels:N.available??[],onStateChange:I})}),(0,Z.jsx)(KB,{title:n(`claude.tierDefaults.title`),children:(0,Z.jsx)(EB,{state:N,options:B,onChange:I,apiBase:e,dirty:!!f&&jB(f.draft,f.baseline)})}),(0,Z.jsx)(KB,{title:n(`claude.smallFastModel`),children:(0,Z.jsx)(_B,{value:N.smallFastModel,tierHaikuModel:N.tierModels?.haiku,options:B,onChange:e=>I({...N,smallFastModel:e})})}),(0,Z.jsx)(KB,{title:n(`claude.modelMap`),count:P.length,children:(0,Z.jsx)(xB,{rows:P,onRowsChange:L})}),(0,Z.jsx)(KB,{title:n(`claude.aliases`),count:N.aliases.length,children:(0,Z.jsx)(wB,{aliases:N.aliases})}),(0,Z.jsx)(`div`,{className:`card claudecode-master-card`,children:te}),(0,Z.jsxs)(`div`,{className:`ccw-savebar`,role:`region`,"aria-label":n(`claude.saveBar.label`),children:[g&&(0,Z.jsx)(`span`,{className:`ccw-savebar-error`,role:`alert`,children:g}),(0,Z.jsx)(`span`,{className:`ccw-savebar-state${F?` dirty`:``}`,"aria-live":`polite`,"aria-atomic":`true`,children:n(F?`claude.saveBar.dirty`:`claude.saveBar.clean`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!F||m,onClick:ee,children:n(`claude.saveBar.revert`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:m,onClick:()=>{W()},children:n(`common.save`)})]})]})}function JB({apiBase:e,active:t=!0,embedded:n=!1}){let r=c();return(0,Z.jsxs)(`section`,{className:`claude-page${n?` claude-page--embedded`:``}`,children:[!n&&(0,Z.jsx)(`div`,{className:`page-head`,children:(0,Z.jsx)(`h2`,{children:r(`nav.claude`)})}),(0,Z.jsx)(`p`,{className:`page-sub`,children:r(`claude.pageSub`)}),(0,Z.jsx)(qB,{apiBase:e,active:t},e)]})}function YB(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 XB(e){return new Set(Object.keys(e))}function ZB(e,t){return t!==null&&e===t}function QB(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function $B(e){return{read(t){let n=QB(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=QB(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function eV(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function tV(e){return e.label||e.route}function nV({apiBase:e,bindings:t,suggestions:n,models:r,onSaved:i}){let{t:o}=a(),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),h=(0,X.useMemo)(()=>r.filter(e=>e.available),[r]),g=(0,X.useMemo)(()=>new Set(Object.keys(t)),[t]),_=(0,X.useMemo)(()=>n.filter(e=>!g.has(e)),[n,g]),v=(0,X.useMemo)(()=>Object.entries(t).sort(([e],[t])=>e.localeCompare(t)),[t]),y=s.trim(),b=y.startsWith(`claude-`)&&l!==``&&d===null,x=async(t,n)=>{if(d===null){f(n),m(null);try{let n=await zn(await fetch(`${e}/api/claude-desktop/first-party-bindings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),o(`claudeDesktop.firstParty.bindings.saveFailed`));if(!n||n.ok!==!0||typeof n.modelBindings!=`object`||n.modelBindings===null)throw Error(o(`claudeDesktop.firstParty.bindings.saveFailed`));c(``),u(``),i(n.modelBindings)}catch(e){m(e instanceof Error?e.message:o(`claudeDesktop.firstParty.bindings.saveFailed`))}finally{f(null)}}};return(0,Z.jsxs)(`section`,{className:`claude-bindings`,"aria-labelledby":`claude-bindings-title`,children:[(0,Z.jsx)(`h3`,{id:`claude-bindings-title`,className:`claude-bindings-title`,children:o(`claudeDesktop.firstParty.bindings.title`)}),(0,Z.jsx)(`p`,{className:`claude-bindings-hint`,children:o(`claudeDesktop.firstParty.bindings.hint`)}),p&&(0,Z.jsx)(Q,{tone:`err`,children:p}),v.length===0?(0,Z.jsx)(`p`,{className:`claude-bindings-empty`,children:o(`claudeDesktop.firstParty.bindings.empty`)}):(0,Z.jsx)(`ul`,{className:`claude-bindings-list`,children:v.map(([e,t])=>{let n=h.some(e=>e.route===t);return(0,Z.jsxs)(`li`,{className:`claude-bindings-row`,children:[(0,Z.jsx)(`code`,{className:`claude-bindings-id`,title:e,children:e}),(0,Z.jsx)(St,{className:`claude-bindings-arrow`,width:12,height:12,"aria-hidden":`true`}),(0,Z.jsx)($,{fullWidth:!0,className:`claude-bindings-select`,label:o(`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:tV(e)}))]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-bindings-remove`,"aria-label":o(`claudeDesktop.firstParty.bindings.remove`,{id:e}),disabled:d!==null,onClick:()=>void x({remove:[e]},e),children:(0,Z.jsx)(We,{width:12,height:12,"aria-hidden":`true`})})]},e)})}),(0,Z.jsxs)(`div`,{className:`claude-bindings-add`,children:[(0,Z.jsx)(`input`,{className:`input claude-bindings-input`,type:`text`,list:`claude-bindings-suggestions`,"aria-label":o(`claudeDesktop.firstParty.bindings.pickerLabel`),placeholder:o(`claudeDesktop.firstParty.bindings.pickerPlaceholder`),value:s,disabled:d!==null,onChange:e=>c(e.target.value)}),(0,Z.jsx)(`datalist`,{id:`claude-bindings-suggestions`,children:_.map(e=>(0,Z.jsx)(`option`,{value:e},e))}),(0,Z.jsx)($,{fullWidth:!0,className:`claude-bindings-select`,label:o(`claudeDesktop.firstParty.bindings.routeLabel`),value:l,disabled:d!==null,onChange:u,options:[{value:``,label:o(`claudeDesktop.firstParty.bindings.routePlaceholder`)},...h.map(e=>({value:e.route,label:tV(e)}))]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!b,onClick:()=>void x({set:{[y]:l}},y),children:o(d!==null&&d===y?`common.saving`:`claudeDesktop.firstParty.bindings.add`)})]})]})}function rV(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 iV(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 aV({apiBase:e,picker:t,onUpdated:n,pickerReason:r,pickerFailurePort:i}){let{t:o}=a(),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),p=s??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 zn(t,o(`claudeDesktop.updateFailed`));else{try{r=await t.json()}catch{throw Error(o(`claudeDesktop.updateFailed`))}if(!r.picker)throw Error(o(Wz(r.reason),{port:r.port??``}))}if(!r||r.ok!==!0&&!r.picker||!r.picker||!rV(r.picker))throw Error(o(`claudeDesktop.updateFailed`));c(r.picker),n?.(r.picker)}catch(e){f(e instanceof Error?e.message:o(`claudeDesktop.updateFailed`))}finally{u(!1)}}};return(0,Z.jsxs)(`section`,{className:`claude-picker`,"aria-labelledby":`claude-picker-title`,children:[!p.listenerReady&&r&&(0,Z.jsx)(`span`,{role:`status`,children:o(Wz(r===`port_in_use`&&!i?`failed`:r),{port:i??``})}),!p.listenerReady&&!r&&(0,Z.jsx)(Kz,{apiBase:e,onStarted:()=>{c(null),n?.(p)}}),(0,Z.jsxs)(`div`,{className:`claude-picker-header`,children:[(0,Z.jsxs)(`div`,{className:`claude-picker-copy`,children:[(0,Z.jsx)(`h3`,{id:`claude-picker-title`,className:`claude-picker-title`,children:o(`claudeDesktop.picker.title`)}),(0,Z.jsx)(`p`,{className:`claude-picker-hint`,children:o(`claudeDesktop.picker.hint`)})]}),(0,Z.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${p.desired?`on`:``}`,"aria-checked":p.desired,"aria-label":o(`claudeDesktop.picker.toggle`),disabled:l,onClick:()=>void m(),children:(0,Z.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Z.jsx)(Q,{tone:`err`,children:d}),(0,Z.jsxs)(`p`,{className:`claude-picker-state claude-picker-state-${p.reason}`,"aria-live":`polite`,children:[(0,Z.jsx)(`span`,{className:`claude-picker-state-dot`,"aria-hidden":`true`}),(0,Z.jsx)(`span`,{children:o(iV(p.reason))}),p.reason===`trust_pending`&&p.hint&&(0,Z.jsx)(`code`,{children:p.hint})]}),(0,Z.jsx)(`p`,{className:`claude-picker-models`,children:o(`claudeDesktop.picker.models`,{count:p.models})}),(0,Z.jsx)(`p`,{className:`claude-picker-offline-note`,role:`note`,children:o(`claudeDesktop.picker.offlineNote`)})]})}function oV(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 sV(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 cV(e,t){return JSON.stringify(sV(e))===JSON.stringify(sV(t))}function lV(e,t){if(!e)return!0;let n=e.routes.includes(t);return e.mode===`include`?n:!n}function uV(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 sV({mode:r.mode,routes:[...i]})}function dV(e,t,n){if((e?.mode??`exclude`)===n)return e;let r=t.filter(t=>lV(e,t)===(n===`include`));return n===`include`?{mode:n,routes:[...new Set(r)].sort()}:sV({mode:n,routes:r})}function fV(e){let t=e.indexOf(`/`);return t>0?e.slice(0,t):e}function pV(e){return[...new Set(e.map(e=>fV(e.route)))].sort()}function mV(e,t,n){let r=t.trim().toLowerCase();return e.filter(e=>(!n||fV(e.route)===n)&&(!r||e.route.toLowerCase().includes(r)||e.label.toLowerCase().includes(r)))}function hV(e,t){let n=0,r=0,i=0;for(let a of e){let e=lV(t,a.route);a.available?(r+=1,e&&(n+=1)):e&&t?.mode===`include`&&(i+=1)}return{selected:n,available:r,selectedUnavailable:i}}function gV(e,t){let n=e.filter(e=>lV(t,e.route));return n.length>0?n:[...e]}function _V(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 vV=6;function yV(e){let t=e.slice(0,vV).join(`, `);return e.length>vV?`${t} +${e.length-vV}`:t}function bV({models:e,visibility:t,onChange:n,rendered:r,appliedModels:i,disabled:o,badges:s}){let{t:c}=a(),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(6),h=(0,X.useMemo)(()=>pV(e),[e]),g=(0,X.useMemo)(()=>mV(e,l,d),[e,l,d]),_=hV(e,t),v=_V(gV(r,t),i),y=g.map(e=>e.route),b=t?.mode??`exclude`;return(0,Z.jsxs)(`div`,{className:`claude-visibility`,children:[(0,Z.jsxs)(`div`,{className:`claude-visibility-counts`,role:`status`,children:[(0,Z.jsx)(`span`,{className:`claude-visibility-count`,children:c(`claudeDesktop.visibility.selected`,{n:_.selected})}),(0,Z.jsx)(`span`,{className:`claude-visibility-count`,children:c(`claudeDesktop.visibility.available`,{n:_.available})}),(0,Z.jsx)(`span`,{className:`claude-visibility-count`,children:i?c(`claudeDesktop.visibility.applied`,{n:i.length}):c(`claudeDesktop.visibility.appliedUnknown`)}),_.selectedUnavailable>0&&(0,Z.jsx)(`span`,{className:`claude-visibility-count muted`,children:c(`claudeDesktop.visibility.selectedUnavailable`,{n:_.selectedUnavailable})})]}),(0,Z.jsxs)(`fieldset`,{className:`claude-visibility-policy`,disabled:o,children:[(0,Z.jsx)(`legend`,{children:c(`claudeDesktop.visibility.newModels`)}),[`exclude`,`include`].map(r=>(0,Z.jsxs)(`label`,{children:[(0,Z.jsx)(`input`,{type:`radio`,name:`claude-desktop-new-models`,value:r,checked:b===r,onChange:()=>n(dV(t,e.map(e=>e.route),r))}),c(r===`exclude`?`claudeDesktop.visibility.newShow`:`claudeDesktop.visibility.newHide`)]},r))]}),(0,Z.jsxs)(`div`,{className:`claude-visibility-filters`,children:[(0,Z.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,Z.jsx)($,{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,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:o||g.length===0,onClick:()=>n(uV(t,y,!0)),children:c(`claudeDesktop.visibility.selectShown`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:o||g.length===0,onClick:()=>n(uV(t,y,!1)),children:c(`claudeDesktop.visibility.clearShown`)})]}),_.selected===0&&_.available>0&&(0,Z.jsx)(Q,{tone:`warn`,children:c(`claudeDesktop.visibility.noneSelected`)}),g.length===0?(0,Z.jsx)(`p`,{className:`claude-desktop-list-hint`,children:c(`claudeDesktop.visibility.noMatch`)}):(0,Z.jsx)(`ul`,{className:`card claude-desktop-list-rows`,children:g.slice(0,p).map(e=>{let r=lV(t,e.route);return(0,Z.jsxs)(`li`,{className:`claude-desktop-list-row${r?``:` hidden-row`}`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:r,disabled:o,"aria-label":c(`claudeDesktop.visibility.toggle`,{model:e.label}),onChange:r=>n(uV(t,[e.route],r.target.checked))}),(0,Z.jsxs)(`span`,{className:`claude-desktop-list-names`,children:[(0,Z.jsx)(`strong`,{title:e.label,children:e.label}),e.label!==e.route&&(0,Z.jsx)(`code`,{title:e.route,children:e.route})]}),(0,Z.jsx)(`span`,{className:`badge badge-muted claude-visibility-provider`,children:fV(e.route)}),s(e)]},e.route)})}),g.length>p&&(0,Z.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,Z.jsxs)(`div`,{className:`claude-visibility-preview`,children:[(0,Z.jsx)(`span`,{className:`claude-visibility-preview-title`,children:c(`claudeDesktop.visibility.previewTitle`)}),v.added.length===0&&v.removed.length===0?(0,Z.jsx)(`span`,{children:c(`claudeDesktop.visibility.previewSame`)}):(0,Z.jsxs)(Z.Fragment,{children:[v.added.length>0&&(0,Z.jsx)(`span`,{className:`claude-visibility-added`,children:c(`claudeDesktop.visibility.previewAdds`,{models:yV(v.added)})}),v.removed.length>0&&(0,Z.jsx)(`span`,{className:`claude-visibility-removed`,children:c(`claudeDesktop.visibility.previewRemoves`,{models:yV(v.removed)})})]})]}),(0,Z.jsx)(`p`,{className:`claude-desktop-list-hint`,children:c(`claudeDesktop.visibility.replaceNote`)})]})}var xV=[`opus`,`fable`,`sonnet`,`haiku`];function SV(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 CV(e,t){let n=Object.fromEntries(xV.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 xV){let i=n[e].toSorted(),a=t.defaults[e];r[e]=a&&i.includes(a)?a:i[0]??null}return r}function wV(e,t,n){return e.filter(e=>(t.assignments[e.route]?.family??`opus`)===n).length}function TV(e,t,n){return e.defaults[n]??t[n]??``}function EV(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 DV(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))}var OV=$B(`ocx.claudeDesktop.collapsedFamilies.v2`),kV=[`first-party`,`gateway`];function AV(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 jV(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.health;if(t.mode!==void 0&&!kV.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&&!AV(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 MV={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function NV(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 PV(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:xV.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 FV(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}var IV=`route`;function LV({route:e,t}){let[n=``,r=``]=t(`claudeDesktop.roles.unavailableOption`,{route:IV}).split(IV);return(0,Z.jsxs)(`span`,{className:`claude-role-option`,children:[n&&(0,Z.jsx)(`span`,{className:`claude-role-option__status`,children:n}),(0,Z.jsx)(`span`,{className:`claude-role-option__route`,children:e}),r&&(0,Z.jsx)(`span`,{className:`claude-role-option__status`,children:r})]})}function RV(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 zV(e){return oV(e?.visibility)?sV(e.visibility):null}function BV(e){return jd(e)?.data??null}function VV(e){return jd(e)?.cachedAt??null}function HV(e){let t=BV(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?NV(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function UV({apiBase:e,active:t=!0}){let{t:n,locale:r}=a(),i=d.find(e=>e.code===r)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,X.useMemo)(()=>HV(o),[o]),[l,u]=(0,X.useState)(()=>c.profile),[f,p]=(0,X.useState)(()=>c.savedProfile),[m,h]=(0,X.useState)(()=>c.destinations),[g,_]=(0,X.useState)(void 0),[v,y]=(0,X.useState)(void 0),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)({}),[O,k]=(0,X.useState)({}),[A,j]=(0,X.useState)(()=>OV.read()??new Set(xV)),[M,N]=(0,X.useState)({}),[P,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(null),R=(0,X.useRef)(null),z=(0,X.useCallback)(async t=>{let r=await zn(await fetch(`${e}/api/claude-desktop`,{signal:t}),n(`claudeDesktop.loadFail`));if(!r||!(`profile`in r)||!(`models`in r))throw Error(FV(r,n(`claudeDesktop.loadFail`)));let i=PV(r),a={data:r,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),p(NV(i)),_(zV(r)),y(zV(r)),h(Object.fromEntries(r.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),OV.read()===null){let e=Object.fromEntries(xV.map(e=>[e,0]));for(let t of r.models)e[i.assignments[t.route]?.family??`opus`]+=1;j(XB(e))}return Md(o,a),a},[e,o,n,h,u,p,_,y]),B=Fd(s,[e],z,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0,initialDataCachedAt:VV(o),staleAfterMs:6e4}),V=B.state,H=V.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),U=H?.data??null,W=l??H?.profile??null,ee=f??H?.profile??null,te=H?Object.fromEntries(H.data.models.map(e=>[e.route,H.profile.assignments[e.route]?.family??`opus`])):{},ne=Object.keys(m).length>0?m:te,G=g===void 0?zV(U):g,K=v===void 0?zV(U):v,re=(0,X.useMemo)(()=>W!==null&&ee!==null&&JSON.stringify(W)!==JSON.stringify(ee)||!cV(G,K),[W,ee,G,K]),q=(0,X.useMemo)(()=>{let e=Object.fromEntries(xV.map(e=>[e,[]]));if(!U||!W)return e;for(let t of U.models)e[W.assignments[t.route]?.family??`opus`].push(t);return e},[U,W]),ie=(0,X.useMemo)(()=>U&&W?CV(U.models,W):{opus:null,fable:null,sonnet:null,haiku:null},[U,W]),ae=`ocx.claude-desktop.status.v1:${e}`,oe=`claude-desktop-status:${e}`,se=jd(ae),ce=se&&jV(se.data)?se.data:null,le=Fd(oe,[e],async t=>{let n=await Bn(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!jV(n))throw Error(`Claude Desktop status unavailable`);return Md(ae,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:ce??void 0}),ue=le.state,J=ue.data??ce,de=ue.showError,fe=J!==null,pe=fe||de,me=J?.mode??`gateway`,he=I??me,ge=fe&&he!==me,_e=J?.firstParty?.modelBindings,ve=_e?JSON.stringify(_e):null,[ye,be]=(0,X.useState)(null),[xe,Se]=(0,X.useState)(ve);xe!==ve&&(Se(ve),be(null));let Ce=ye??_e??{},we=(0,X.useMemo)(()=>J?.firstParty?.pickerSuggestions??[],[J]),Te=(e,t,r=!1)=>{W&&(r||W.assignments[e]?.family!==t)&&(u(n=>n&&SV(n,e,t,r)),h(n=>({...n,[e]:t})),C(n(`claudeDesktop.moved`,{route:e,family:n(MV[t])})))},Ee=e=>{let t=eV(A,e);OV.write(t),j(t)},De=async t=>{if(W&&!w){T(`save`),x(null);try{await zn(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:W,visibility:sV(G)})}),n(`claudeDesktop.saveFailed`)),p(NV(W)),y(sV(G)),t?(T(`apply`),(await zn(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:he})}),n(`claudeDesktop.applyFailed`)))?.saved===!1?(x({tone:`warn`,text:n(`claudeDesktop.appliedMarkerUnsaved`)}),C(n(`claudeDesktop.appliedMarkerUnsaved`))):(x({tone:`ok`,text:n(`claudeDesktop.savedApplied`)}),C(n(`claudeDesktop.savedAppliedAnnounce`))),L(null)):(x({tone:`ok`,text:n(`claudeDesktop.saved`)}),C(n(`claudeDesktop.savedAnnounce`))),le.refresh()}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.updateFailed`);x({tone:`err`,text:t}),C(t)}finally{T(null)}}},Oe=()=>{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(n(`claudeDesktop.exported`))},ke=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(n(`claudeDesktop.importExpected`));let r=PV({...U,profile:e});u(r),x({tone:`ok`,text:n(`claudeDesktop.importReady`)}),C(n(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.importInvalid`);x({tone:`err`,text:t}),C(n(`claudeDesktop.importFailed`,{error:t}))}},Ae=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&Te(n,t)};if(V.kind===`disabled`&&!H)return null;if(V.showSkeleton&&!H)return(0,Z.jsx)(NE,{label:n(`claudeDesktop.loading`),rows:4});if(V.kind===`failed-cold`){let e=V.error instanceof Error?V.error.message:n(`claudeDesktop.loadFail`);return(0,Z.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,Z.jsx)(Q,{tone:`err`,children:e}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>B.refresh(),children:n(`claudeDesktop.retry`)})]})}if(!U||!W)return null;let je=TV(W,ie,`opus`),Me=TV(W,ie,`haiku`),Ne=new Map(U.models.map(e=>[e.route,e])),Pe=(e,t,r)=>{let i=EV(U.models,t||null).map(e=>({value:e.route,label:e.label}));if(e&&!i.some(t=>t.value===e)){let t=Ne.get(e);i.unshift({value:e,label:t?.available===!1||!t?(0,Z.jsx)(LV,{route:e,t:n}):e})}return r?i.unshift({value:``,label:n(`claudeDesktop.roles.unset`)}):e||i.unshift({value:``,label:n(`claudeDesktop.roles.pick`)}),i},Fe=e=>{if(!e)return;let t=Ne.get(e);return t?.available?t.label:n(`claudeDesktop.roles.unavailableOption`,{route:e})},Ie=DV(U.models,je||null,Me||null),Le=wV(U.models,W,`haiku`)===0,Re=hV(U.models,G).selected===0&&U.models.some(e=>e.available),ze=Array.isArray(U.rendered)?_V(gV(U.rendered,K),J?.appliedModels??null):null,Be=me===`gateway`&&!!ze&&(ze.added.length>0||ze.removed.length>0);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,Z.jsx)(`p`,{className:`claude-panel-lead`,children:n(`claudeDesktop.subtitle`,{port:U.port})})}),(0,Z.jsxs)(`fieldset`,{className:`claude-mode-picker`,disabled:w!==null||!pe,children:[(0,Z.jsx)(`legend`,{children:n(`claudeDesktop.mode.legend`)}),kV.map(e=>(0,Z.jsxs)(`label`,{className:`claude-mode-option${pe&&he===e?` active`:``}`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`claude-desktop-mode`,value:e,checked:pe&&he===e,onChange:()=>L(e)}),(0,Z.jsxs)(`span`,{className:`claude-mode-title`,children:[n(e===`first-party`?`claudeDesktop.mode.firstParty`:`claudeDesktop.mode.gateway`),e===`gateway`&&(0,Z.jsx)(`span`,{className:`claude-mode-default`,children:n(`claudeDesktop.mode.defaultBadge`)}),fe&&me===e&&(0,Z.jsx)(`span`,{className:`claude-mode-current`,children:n(`claudeDesktop.mode.current`)})]}),(0,Z.jsx)(`span`,{className:`claude-mode-hint`,children:n(e===`first-party`?`claudeDesktop.mode.firstPartyHint`:`claudeDesktop.mode.gatewayHint`)})]},e)),he===`first-party`&&(0,Z.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:n(`claudeDesktop.mode.firstPartyRisk`)}),ge&&(0,Z.jsx)(`span`,{className:`claude-mode-switch-note`,children:n(`claudeDesktop.mode.switchNote`)})]}),(0,Z.jsxs)(`div`,{className:`claude-status-bar ${de&&!J?`not-applied`:J?J.desiredEnabled?me===`gateway`&&J.activeProfile===!1?`not-applied`:J.stale||J.applied&&Be?`stale`:J.applied?`applied`:`not-applied`:`not-applied`:`pending`}`,"aria-busy":!J&&!de||void 0,children:[(0,Z.jsx)(`span`,{className:`claude-status-dot`}),(0,Z.jsx)(`span`,{children:de&&!J?n(`claudeDesktop.loadFail`):J?J.desiredEnabled?me===`gateway`&&J.activeProfile===!1?n(`claudeDesktop.status.notActiveProfile`):J.stale?n(`claudeDesktop.status.stale`):J.applied&&Be?n(`claudeDesktop.status.pendingApply`):J.applied?n(me===`first-party`?`claudeDesktop.status.appliedFirstParty`:`claudeDesktop.status.applied`):n(`claudeDesktop.status.notApplied`):n(`claudeDesktop.status.disabled`):n(`claudeDesktop.loading`)}),J?.firstParty&&me===`first-party`&&J.desiredEnabled&&(0,Z.jsx)(`span`,{className:`claude-status-health`,children:J.firstParty.interceptRunning?n(`claudeDesktop.firstParty.proxyRunning`,{port:J.firstParty.proxyPort}):(0,Z.jsx)(Kz,{apiBase:e,reason:J.firstParty.interceptReason,port:J.firstParty.proxyPort,onStarted:()=>le.refresh()})}),J?.health.lastRequestAt&&(0,Z.jsxs)(`span`,{className:`claude-status-health`,children:[n(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(J.health.lastRequestAt).toLocaleTimeString(i)]}),J&&J.health.requestCount>0&&(0,Z.jsx)(`span`,{className:`claude-status-health`,children:n(`claudeDesktop.health.stats`,{count:J.health.requestCount,errors:J.health.errorCount})}),(0,Z.jsxs)(`span`,{className:`claude-status-actions`,children:[(0,Z.jsx)(`span`,{className:`claude-dirty${re?` active`:``}`,children:n(re?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,Z.jsxs)(`span`,{className:`claude-save-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!re||Re||w!==null,onClick:()=>void De(!1),children:n(w===`save`?`claudeDesktop.saving`:`common.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:Re||w!==null,onClick:()=>void De(!0),children:w===`apply`?n(`claudeDesktop.applying`):w===`save`?n(`claudeDesktop.saving`):J?.desiredEnabled===!1?n(`claudeDesktop.enableApply`):n(ge?`claudeDesktop.switchModeApply`:`claudeDesktop.saveApply`)})]})]})]}),J?.riskWarning&&he!==`first-party`&&(0,Z.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:n(`claudeDesktop.mode.firstPartyRisk`)}),(0,Z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:S}),b&&(0,Z.jsx)(Q,{tone:b.tone,children:b.text}),V.showError&&(0,Z.jsx)(Q,{tone:`err`,children:n(`claudeDesktop.loadFail`)}),de&&J&&(0,Z.jsx)(Q,{tone:`err`,children:n(`claudeDesktop.loadFail`)}),me===`first-party`&&J?.firstParty?.picker&&(0,Z.jsx)(aV,{apiBase:e,picker:J.firstParty.picker,pickerReason:J.firstParty.pickerReason,pickerFailurePort:J.firstParty.pickerFailurePort,onUpdated:()=>void le.refresh()},`${J.firstParty.picker.reason}:${J.firstParty.picker.desired}:${J.firstParty.picker.effective}:${J.firstParty.picker.models}:${J.firstParty.picker.hint??``}`),me===`first-party`&&(0,Z.jsx)(nV,{apiBase:e,bindings:Ce,suggestions:we,models:U.models,onSaved:e=>{be(e),le.refresh()}}),U.models.length===0&&(0,Z.jsx)(Nn,{title:n(`claudeDesktop.emptyTitle`),children:n(`claudeDesktop.emptyHint`)}),U.models.length>0&&(0,Z.jsxs)(`section`,{className:`card claude-desktop-roles`,"aria-labelledby":`claude-desktop-roles-title`,children:[(0,Z.jsx)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-roles-title`,children:n(`claudeDesktop.roles.title`)}),me===`first-party`&&(0,Z.jsx)(`p`,{className:`claude-desktop-roles-scope`,children:n(`claudeDesktop.roles.gatewayScope`)}),(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:n(`claudeDesktop.roles.default`)}),(0,Z.jsx)(`span`,{className:`desc`,children:n(`claudeDesktop.roles.defaultDesc`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsx)($,{value:je,options:Pe(je,Me,!1),onChange:e=>{e&&Te(e,`opus`,!0)},label:n(`claudeDesktop.roles.default`),title:Fe(je),disabled:w!==null,style:{minWidth:240},align:`right`,portal:!0})})]}),(0,Z.jsxs)(`div`,{className:`setting-row`,children:[(0,Z.jsxs)(`div`,{className:`setting-label`,children:[(0,Z.jsx)(`span`,{className:`title`,children:n(`claudeDesktop.roles.quick`)}),(0,Z.jsx)(`span`,{className:`desc`,children:n(`claudeDesktop.roles.quickDesc`)})]}),(0,Z.jsx)(`div`,{className:`setting-controls`,children:(0,Z.jsx)($,{value:Me,options:Pe(Me,je,Le),onChange:e=>{e&&Te(e,`haiku`,!0)},label:n(`claudeDesktop.roles.quick`),title:Fe(Me),disabled:w!==null,style:{minWidth:240},align:`right`,portal:!0})})]})]}),(0,Z.jsxs)(`section`,{className:`claude-desktop-list`,"aria-labelledby":`claude-desktop-list-title`,children:[(0,Z.jsxs)(`div`,{className:`claude-desktop-list-head`,children:[(0,Z.jsxs)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-list-title`,children:[n(`claudeDesktop.roles.listTitle`),(0,Z.jsx)(`span`,{className:`count`,children:U.models.length})]}),(0,Z.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,Z.jsx)(`input`,{ref:R,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ke(e)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R.current?.click(),children:n(`claudeDesktop.importJson`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Oe,children:n(`claudeDesktop.exportJson`)})]})]}),U.models.length>0&&(0,Z.jsx)(`p`,{className:`claude-desktop-list-hint`,children:n(`claudeDesktop.roles.listHint`)}),U.models.length>0&&(0,Z.jsx)(bV,{models:Ie,visibility:G,onChange:_,rendered:Array.isArray(U.rendered)?U.rendered:[],appliedModels:me===`gateway`?J?.appliedModels??null:null,disabled:w!==null,badges:e=>{let t=RV(e.contextWindow,n);return(0,Z.jsxs)(Z.Fragment,{children:[e.route===je&&(0,Z.jsx)(`span`,{className:`claude-row-default`,children:n(`claudeDesktop.defaultBadge`)}),e.route===Me&&(0,Z.jsx)(`span`,{className:`claude-row-default claude-row-quick`,children:n(`claudeDesktop.roles.quickBadge`)}),t&&(0,Z.jsx)(`span`,{className:`claude-model-context`,children:t}),e.supports1m===!0&&(0,Z.jsx)(`span`,{className:`claude-1m-chip`,children:n(`claudeDesktop.supports1m`)}),!e.available&&(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:n(`claudeDesktop.unavailable`)})]})}})]}),(0,Z.jsxs)(`details`,{className:`claude-desktop-advanced`,open:P,onToggle:e=>F(e.currentTarget.open),children:[(0,Z.jsxs)(`summary`,{children:[(0,Z.jsxs)(`span`,{className:`claude-desktop-advanced-title`,children:[(0,Z.jsx)(St,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:P?`rotate(90deg)`:`none`}}),n(`claudeDesktop.advanced.title`)]}),(0,Z.jsx)(`span`,{className:`claude-desktop-advanced-chips`,children:xV.map(e=>{let t=q[e].length,r=W.defaults[e],i=ie[e];return(0,Z.jsxs)(`span`,{className:`claude-desktop-advanced-chip`,children:[(0,Z.jsx)(`b`,{children:n(MV[e])}),i?(0,Z.jsx)(`code`,{title:i,children:i}):(0,Z.jsx)(`span`,{children:n(`claudeDesktop.advanced.empty`)}),t>0&&(0,Z.jsx)(`span`,{className:`claude-desktop-advanced-count`,children:t}),t>0&&r===null&&(0,Z.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.chooseDefault`)}),i&&r!==null&&i!==r&&(0,Z.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.temporaryDefault`)})]},e)})})]}),(0,Z.jsx)(`p`,{className:`claude-desktop-advanced-desc`,children:n(`claudeDesktop.advanced.desc`)}),(0,Z.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":n(`claudeDesktop.assignmentsLabel`),children:xV.map(e=>{let t=q[e],r=YB(t,E[e]??``,O[e]??6),i=A.has(e),a=ie[e];return(0,Z.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>Ae(t,e),children:[(0,Z.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,Z.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>Ee(e),children:[(0,Z.jsx)(St,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,Z.jsx)(`span`,{className:`ocx-group-name`,children:n(MV[e])}),(0,Z.jsx)(`span`,{className:`ocx-group-count`,children:n(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,Z.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&W.defaults[e]===null&&(0,Z.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.chooseDefault`)}),a&&a!==W.defaults[e]&&(0,Z.jsx)(`span`,{className:`claude-default-needed`,title:a,children:n(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,Z.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[r.showSearch&&(0,Z.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:n(`models.search`),"aria-label":n(`models.search`),value:E[e]??``,onChange:t=>{let n=t.target.value;D(t=>({...t,[e]:n})),k(t=>({...t,[e]:6}))}}),(0,Z.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,Z.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneEmpty`)}):r.noMatch?(0,Z.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneNoMatch`)}):r.shown.map(t=>{let r=W.assignments[t.route],i=RV(t.contextWindow,n),a=ne[t.route]??`opus`,o=M[t.route]??ZB(t.route,ie[e]);return(0,Z.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,Z.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,Z.jsx)(St,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,Z.jsxs)(`span`,{className:`claude-model-names`,children:[(0,Z.jsx)(`strong`,{title:t.label,children:t.label}),(0,Z.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,Z.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,Z.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:n(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,Z.jsx)(`span`,{className:`claude-1m-chip`,children:n(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,Z.jsx)(`span`,{className:`claude-effort-badge off`,children:n(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,Z.jsx)(`span`,{className:`claude-effort-badge on`,children:n(`claudeDesktop.effort.supported`)}),W.defaults[e]===t.route&&(0,Z.jsx)(`span`,{className:`claude-row-default`,children:n(`claudeDesktop.defaultBadge`)}),(0,Z.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?n(`claudeDesktop.available`):n(`claudeDesktop.unavailable`)})]}),o&&(0,Z.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[ie[e]===t.route&&W.defaults[e]!==t.route&&(0,Z.jsx)(`span`,{className:`claude-effective-default`,children:n(`claudeDesktop.temporaryDefault`)}),(0,Z.jsxs)(`div`,{className:`claude-field`,children:[(0,Z.jsx)(`span`,{children:n(`claudeDesktop.alias`)}),(0,Z.jsx)(`code`,{className:`claude-alias`,title:r.alias,children:r.alias})]}),(0,Z.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:W.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),n(`claudeDesktop.useAsDefault`,{family:n(MV[e])})]}),(0,Z.jsxs)(`div`,{className:`claude-move-row`,children:[(0,Z.jsx)(`label`,{htmlFor:`move-${t.route}`,children:n(`claudeDesktop.moveTo`)}),(0,Z.jsx)($,{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:xV.map(e=>({value:e,label:n(MV[e])}))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>Te(t.route,a),children:n(`claudeDesktop.move`)})]})]})]},t.route)}),r.hidden>0&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>k(t=>({...t,[e]:(t[e]??6)+6})),children:n(`models.showMore`,{n:r.hidden})})]})]})]},e)})})]})]})}function WV(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 GV=$B(`ocx.grok.collapsedGroups.v2`),KV=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],qV=new Set(KV.map(e=>e.id));function JV(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 YV({apiBase:e,active:t=!0}){let n=c(),r=`ocx.grok.status.v1:${e}`,i=jd(r),a=i?.data??null,[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(()=>GV.read()??new Set(qV)),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(``),_=(0,X.useCallback)(async t=>{let i=await zn(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 Md(r,a),a},[e,r,n]),v=`grok-status:${e}`,y=Fd(v,[e],_,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:i?.cachedAt??null,staleAfterMs:6e4,enabled:t}),{state:b}=y,x=y.refresh,S=b.data??a,C=(0,X.useMemo)(()=>new Set(S?.excluded??[]),[S]),w=o??C,T=(0,X.useMemo)(()=>o!==null&&(o.size!==C.size||[...o].some(e=>!C.has(e))),[o,C]),E=(0,X.useMemo)(()=>new Map((S?.models??[]).map(e=>[e.id,e.alias])),[S]),D=e=>{let t=eV(l,e);GV.write(t),u(t)},O=e=>{let t=e?new Set(KV.map(e=>e.id)):new Set;GV.write(t),u(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(!d){f(`save`),m(null);try{await zn(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&&pn(v,{...S,excluded:i}),s(null),t){f(`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?(m({tone:`err`,text:r.message??n(`grok.applySkipped`)}),g(r.message??n(`grok.applySkipped`))):(m({tone:`ok`,text:n(`grok.savedApplied`)}),g(n(`grok.savedApplied`))),await x()}else m({tone:`ok`,text:n(`grok.saved`)}),g(n(`grok.saved`)),S&&Md(r,{...S,excluded:i})}catch(e){let t=e instanceof Error?e.message:n(`grok.saveFailed`);m({tone:`err`,text:t}),g(t)}finally{f(null)}}};if(b.showSkeleton&&!S)return(0,Z.jsx)(`section`,{className:`grok-page`,children:(0,Z.jsx)(NE,{label:n(`grok.loading`),rows:4})});if(b.kind===`failed-cold`){let e=b.error instanceof Error?b.error.message:n(`grok.loadFail`);return(0,Z.jsxs)(`section`,{className:`grok-page`,children:[(0,Z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x(),children:n(`common.retry`)})]})}return(0,Z.jsxs)(`section`,{className:`grok-page`,"aria-busy":b.refreshing||void 0,children:[(0,Z.jsx)(`h2`,{className:`page-title`,children:n(`grok.title`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`grok.subtitle`)}),(0,Z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:h}),p&&(0,Z.jsx)(Q,{tone:p.tone,children:p.text}),b.showError&&(0,Z.jsx)(Q,{tone:`err`,children:n(`grok.loadFail`)}),S&&S.candidates.length>0&&(0,Z.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,Z.jsx)(`span`,{className:`claude-dirty${T?` active`:``}`,children:n(T?`grok.unsaved`:`grok.upToDate`)}),(0,Z.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!T||d!==null,onClick:()=>void A(!1),children:n(d===`save`?`grok.saving`:`common.save`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!T||d!==null,onClick:()=>void A(!0),children:n(d===`apply`?`grok.applying`:d===`save`?`grok.saving`:`grok.saveApply`)})]})]}),S?.present?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,Z.jsx)(`span`,{children:n(`grok.endpoint`)}),(0,Z.jsx)(`code`,{children:S.baseUrl??`—`})]}),(0,Z.jsx)(`p`,{className:`page-sub`,children:(0,Z.jsx)(`code`,{children:S.configPath})})]}):(0,Z.jsxs)(Nn,{title:n(`grok.notConfiguredTitle`),children:[n(`grok.notConfiguredHint`),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`code`,{children:S?.configPath})]}),S&&S.candidates.length>0&&(0,Z.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,Z.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!0),disabled:d!==null,children:[(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`}),` `,n(`models.collapseAll`)]}),(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!1),disabled:d!==null,children:[(0,Z.jsx)(St,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,n(`models.expandAll`)]})]}),KV.map(e=>{let t=WV(S.candidates,E,w,e.id);if(t.total===0)return null;let r=l.has(e.id);return(0,Z.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,Z.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,Z.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>D(e.id),children:[(0,Z.jsx)(St,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,Z.jsx)(`span`,{className:`ocx-group-name`,children:n(e.tkey)}),(0,Z.jsx)(`span`,{className:`ocx-group-count`,children:n(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!r&&(0,Z.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,Z.jsxs)(`div`,{className:`grok-model-row`,children:[(0,Z.jsx)(kn,{on:e.enabled,onClick:()=>k(e.id,!e.enabled),disabled:d!==null,label:n(`grok.toggleModel`,{id:e.id})}),(0,Z.jsxs)(`span`,{className:`grok-model-names`,children:[(0,Z.jsx)(`strong`,{title:e.id,children:e.id}),(0,Z.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,Z.jsx)(`span`,{className:`claude-model-context`,children:JV(e.contextWindow,n)})]},e.id))})]},e.id)})]})]})}async function XV(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor`,{signal:t});if(!n.ok)return null;let r=await Bn(n);return!r||typeof r!=`object`||!r.gateway||!r.privateInference?null:r}catch{return null}}async function ZV(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor/local-installer`,{signal:t});if(!n.ok)return null;let r=await Bn(n);return!r||typeof r!=`object`||typeof r.available!=`boolean`?null:r}catch{return null}}function QV({value:e,label:t}){let n=c(),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(null);(0,X.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,Z.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Z.jsx)(`span`,{className:`cursor-gateway-label`,children:t}),(0,Z.jsx)(`code`,{className:`cursor-gateway-value`,children:e}),(0,Z.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 $V({labelKey:e,installed:t,path:n,version:r}){let i=c();return(0,Z.jsxs)(`div`,{className:`cursor-detect-row`,"data-installed":t?`true`:`false`,children:[(0,Z.jsx)(`span`,{className:`cursor-detect-name`,children:i(e)}),(0,Z.jsx)(`span`,{className:`badge ${t?`badge-green`:`badge-muted`}`,children:i(t?`integrations.cursor.detected`:`integrations.cursor.notFound`)}),t&&n&&(0,Z.jsxs)(`span`,{className:`cursor-detect-path muted`,children:[r?`${r} · `:``,n]})]})}function eH({apiBase:e}){let t=c(),[n,r]=(0,X.useState)(`idle`),[i,a]=(0,X.useState)(null),o=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>o.current?.abort(),[]);let s=async()=>{o.current?.abort();let t=new AbortController;o.current=t,r(`checking`);let n=await ZV(e,t.signal);t.signal.aborted||(a(n),r(`done`))};return n===`done`&&i?.available&&i.url!==null?(0,Z.jsxs)(`span`,{"data-cursor-installer-hint":!0,children:[t(`integrations.cursor.installerIntro`,{version:i.version??t(`integrations.cursor.unknownVersion`)}),` `,(0,Z.jsx)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,"data-cursor-installer-url":!0,children:t(`integrations.cursor.installerOpen`)}),`.`]}):(0,Z.jsxs)(Z.Fragment,{children:[n===`done`&&(0,Z.jsxs)(`span`,{"data-cursor-installer-unavailable":!0,children:[t(`integrations.cursor.installerUnavailable`),` `]}),(0,Z.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 tH({apiBase:e,active:t}){let{t:n,locale:r}=a(),[i,o]=(0,X.useState)(()=>Date.now()),s=(0,X.useCallback)(async t=>{let n=await XV(e,t);if(!n)throw Error(`cursor status unavailable`);return o(Date.now()),n},[e]),c=Fd(`integration-cursor-page:${e}`,[e],s,{isEmpty:()=>!1,enabled:t,pollMs:15e3,pauseWhenHidden:!0}),l=c.state.data??null,u=Np(n);return(0,Z.jsxs)(`section`,{className:`integration-native-page cursor-page`,"aria-labelledby":`cursor-integration-title`,children:[(0,Z.jsx)(`h3`,{id:`cursor-integration-title`,children:n(`integrations.cursor.title`)}),(0,Z.jsx)(`p`,{children:n(`integrations.cursor.intro`)}),c.state.showError&&(0,Z.jsx)(Q,{tone:`err`,children:n(`integrations.cursor.unavailable`)}),!l&&!c.state.showError&&(0,Z.jsx)(NE,{label:n(`integrations.cursor.loading`),rows:4}),l&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`cursor-card`,children:[(0,Z.jsx)(`h4`,{children:n(`integrations.cursor.detection`)}),(0,Z.jsx)($V,{labelKey:`integrations.cursor.privateInference`,installed:l.privateInference.installed,path:l.privateInference.path,version:l.privateInference.version}),(0,Z.jsx)($V,{labelKey:`integrations.cursor.regular`,installed:l.regularCursor.installed,path:l.regularCursor.path,version:null}),!l.privateInference.installed&&(0,Z.jsxs)(Q,{tone:`warn`,children:[n(l.regularCursor.installed?`integrations.cursor.regularOnly`:`integrations.cursor.nothingFound`),` `,(0,Z.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,"data-cursor-guide":`notice`,children:n(`integrations.cursor.guide`)}),l.regularCursor.installed&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`span`,{"data-cursor-installer":!0,children:(0,Z.jsx)(eH,{apiBase:e})})]})]})]}),(0,Z.jsxs)(`div`,{className:`cursor-card`,children:[(0,Z.jsx)(`h4`,{children:n(`integrations.cursor.gateway`)}),(0,Z.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.gatewayHint`)}),(0,Z.jsx)(QV,{label:n(`integrations.cursor.baseUrl`),value:l.gateway.baseUrl}),l.gateway.apiKeyMode===`placeholder`?(0,Z.jsx)(QV,{label:n(`integrations.cursor.apiKey`),value:l.gateway.placeholder}):(0,Z.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Z.jsx)(`span`,{className:`cursor-gateway-label`,children:n(`integrations.cursor.apiKey`)}),(0,Z.jsx)(`span`,{className:`cursor-gateway-value`,children:n(`integrations.cursor.apiKeyCredential`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>_n(`integrations/keys`),children:n(`integrations.tab.keys`)})]})]}),(0,Z.jsxs)(`div`,{className:`cursor-card`,"data-seen":l.lastSeen?`true`:`false`,children:[(0,Z.jsx)(`h4`,{children:n(`integrations.cursor.connection`)}),l.lastSeen?(0,Z.jsx)(`p`,{children:(0,Z.jsx)(`span`,{className:`badge ${i-l.lastSeen.at<864e5?`badge-green`:`badge-muted`}`,children:n(`integrations.cursor.seen`,{time:Mp(l.lastSeen.at,u,i),ua:l.lastSeen.userAgent})})}):(0,Z.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.neverSeen`)})]}),(0,Z.jsxs)(`div`,{className:`cursor-card`,children:[(0,Z.jsx)(`h4`,{children:n(`integrations.cursor.models`)}),(0,Z.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,Z.jsxs)(`table`,{className:`cursor-model-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:n(`integrations.cursor.colModel`)}),(0,Z.jsx)(`th`,{children:n(`integrations.cursor.colReasoning`)}),(0,Z.jsx)(`th`,{children:n(`integrations.cursor.colContext`)})]})}),(0,Z.jsx)(`tbody`,{children:l.models.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.id})}),(0,Z.jsx)(`td`,{children:e.reasoning?e.reasoning.join(` · `):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(`span`,{className:`cursor-effort-rows`,children:n(e.effortRows.length===1?`integrations.cursor.effortRowsOne`:`integrations.cursor.effortRowsMany`,{n:e.effortRows.length})}):(0,Z.jsx)(`span`,{className:`cursor-effort-rows muted`,children:n(`integrations.cursor.effortRowsOff`)})]})}),(0,Z.jsx)(`td`,{children:e.context?`${Ue(e.context.defaultWindow,r)} · ${Ue(e.context.longWindow,r)}`:n(`integrations.cursor.singleWindow`)})]},e.id))})]}),l.models.some(e=>e.tableLess)&&(0,Z.jsx)(`p`,{className:`muted`,"data-cursor-tableless-hint":!0,children:n(`integrations.cursor.tableLessHint`)})]}),(0,Z.jsx)(`p`,{children:(0,Z.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,children:n(`integrations.cursor.guide`)})})]})]})}function nH(e){let t=c(),[n,r]=(0,X.useState)(!1),i=(0,X.useId)();return{open:n,button:(0,Z.jsx)(`button`,{type:`button`,className:Y(yp,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,Z.jsx)(xc,{icon:Dc,strokeWidth:1.8,"aria-hidden":`true`})}),panel:(e,t)=>(0,Z.jsx)(`div`,{id:i,hidden:!n,className:Y(`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 rH={"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`},iH={"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 aH({state:e,installed:t,id:n}){let r=c(),i=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,Z.jsx)(`span`,{id:n,className:iH[i],"data-integration-state":i,children:r(rH[i])})}var oH={apply:`integrations.plan.operation.apply`,overwrite:`integrations.plan.operation.overwrite`,disable:`integrations.plan.operation.disable`,restore:`integrations.plan.operation.restore`},sH={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`},cH={none:`integrations.plan.foreign.none`,unowned:`integrations.plan.foreign.unowned`,"foreign-edit":`integrations.plan.foreign.foreignEdit`,drift:`integrations.plan.foreign.drift`},lH={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 uH({plan:e,missingStorePath:t}){let n=c(),r=e.refusalReason?lH[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,Z.jsxs)(`div`,{className:`integration-plan-details`,children:[(0,Z.jsx)(`p`,{className:`integration-plan-operation`,children:n(`integrations.plan.operation`,{operation:n(oH[e.operation])})}),e.foreignEdit!==`none`&&(0,Z.jsx)(`p`,{children:n(cH[e.foreignEdit])}),!e.willChange&&e.canApply&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:n(e.operation===`disable`?`integrations.plan.noop.disabled`:`integrations.plan.noop.applied`)}),e.profileId!==void 0&&(0,Z.jsx)(`p`,{children:n(`integrations.plan.noop.profilePreference`)})]}),!e.canApply&&(0,Z.jsx)(`p`,{children:a}),e.changes.length>0&&(0,Z.jsx)(`ul`,{className:`integration-plan-changes`,children:e.changes.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{children:n(sH[e.kind])}),` `,(0,Z.jsx)(`code`,{children:e.path})]},`${e.kind}:${e.path}`))})]})}function dH({plan:e,plans:t,missingStorePath:n}){let r=c();return!e&&(!t||t.length===0)?null:(0,Z.jsxs)(`section`,{className:`integration-plan`,"aria-labelledby":`integration-plan-heading`,children:[(0,Z.jsx)(`h4`,{id:`integration-plan-heading`,children:r(`integrations.plan.heading`)}),e&&(0,Z.jsx)(uH,{plan:e,missingStorePath:n}),t?.map(e=>(0,Z.jsxs)(`section`,{className:`integration-plan-group`,children:[(0,Z.jsx)(`h5`,{children:e.label}),(0,Z.jsx)(uH,{plan:e.plan})]},`${e.clientId}:${e.plan.fingerprint}`))]})}function fH({copyKey:e,vars:t}){let n=c()(e,t),r=t?.path;if(!r||!n.includes(r))return(0,Z.jsx)(`p`,{children:n});let[i,...a]=n.split(r);return(0,Z.jsxs)(`p`,{children:[i,(0,Z.jsx)(`code`,{children:r}),a.join(r)]})}function pH(e){return e.changes.some(e=>e.kind===`snapshot`||e.kind===`journal`)}function mH({copy:e,plan:t=null,plans:n,hasUnboundAction:r=!1,planStale:i=!1,planLoading:a=!1,planFailure:o=null,missingStorePath:s,onConfirm:l,onClose:u}){let d=c(),f=(0,X.useRef)(null),p=(0,X.useRef)(null),m=(0,X.useRef)(null),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),x=`integration-consequence-dialog-title`,S=t!==null||a||o!==null||n!==void 0,C=y?.sourceFingerprint===(t?.fingerprint??null)?y.plan:t,w=y?.sourceFingerprint===(t?.fingerprint??null),T=n!==void 0&&!r&&!n.some(e=>e.plan.canApply),E=!S||(C?pH(C):n?.some(e=>pH(e.plan))===!0),D=(0,X.useCallback)(()=>{h||u()},[u,h]);(0,X.useEffect)(()=>{let e=f.current,t=document.activeElement;return p.current=t?.tagName===`BUTTON`?t:null,e&&!e.open&&e.showModal(),m.current?.focus(),()=>{e?.open&&e.close(),p.current?.isConnected&&p.current.focus?.()}},[]);let O=(0,X.useCallback)(e=>{e.preventDefault(),D()},[D]),k=(0,X.useCallback)(async()=>{if(!h){g(!0),v(null);try{await l(C??void 0)}catch(e){if(e instanceof RT&&e.stalePlan){b({sourceFingerprint:t?.fingerprint??null,plan:e.stalePlan});return}v(e instanceof Error?e.message:d(`integrations.error.generic`))}finally{g(!1)}}},[C,l,h,t?.fingerprint,d]),A=[(0,Z.jsx)(fH,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,Z.jsx)(fH,{copyKey:e.breakageKey,vars:e.vars},`breakage`)];return E&&A.push((0,Z.jsx)(fH,{copyKey:e.undoKey,vars:e.vars},`undo`)),e.sideEffectKey&&A.push((0,Z.jsx)(fH,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,Z.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":x,"aria-busy":h,onCancel:O,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,onClick:D}),(0,Z.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,Z.jsxs)(`div`,{className:`modal-head`,children:[(0,Z.jsx)(`h3`,{id:x,children:d(e.titleKey,e.vars)}),(0,Z.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost btn-sm`,onClick:D,disabled:h,children:d(`common.close`)})]}),(0,Z.jsx)(`div`,{className:`integration-consequence-body`,children:A}),(0,Z.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[a&&(0,Z.jsx)(`p`,{children:d(`integrations.preview.loading`)}),h&&(0,Z.jsx)(`p`,{children:d(`integrations.mutation.pending`)}),(w||i)&&(0,Z.jsx)(Q,{tone:`err`,children:d(`integrations.preview.stale`)}),o&&(0,Z.jsx)(Q,{tone:`err`,children:o})]}),(0,Z.jsx)(dH,{plan:C,plans:n,missingStorePath:s}),_&&(0,Z.jsx)(Q,{tone:`err`,children:_}),(0,Z.jsx)(`div`,{className:`modal-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void k(),disabled:h||a||!!o||S&&!C&&n===void 0||T||C?.canApply===!1,children:d(e.confirmKey)})})]})]})}function hH({apiBase:e,row:t,onClose:n,onRestored:r,profileId:i,onReconcile:a,hermesProfile:o}){let s=c(),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(!1),p=(0,X.useRef)(n),m=(0,X.useRef)(r),h=(0,X.useRef)(a),g=(0,X.useRef)(s),_=(0,X.useRef)(null),v=(0,X.useRef)(0),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(!0),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),j=t.clientId===`aside`?i??t.profileId:void 0,M=t.clientId===`hermes`?o:void 0,N=y?.plan??null,P=N?.foreignEdit===`drift`;(0,X.useEffect)(()=>{p.current=n,m.current=r,h.current=a,g.current=s},[n,a,r,s]);let F=(0,X.useCallback)(()=>{T||(v.current+=1,_.current?.abort(),_.current=null,p.current())},[T]);(0,X.useEffect)(()=>{let e=l.current,t=document.activeElement;return u.current=t?.tagName===`BUTTON`?t:null,d.current=t?.closest?.(`section, [role='region'], main`)??null,e&&!e.open&&e.showModal(),()=>{e?.open&&e.close();let t=d.current;if(f.current&&t?.isConnected){t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.();return}let n=u.current;n?.isConnected?n.focus?.():t?.isConnected&&(t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.())}},[]);let I=(0,X.useCallback)(async()=>{let n=new AbortController,r=v.current+1;v.current=r,_.current?.abort(),_.current=n,S(!0),O(null),A(null),b(null),w(!1);try{let i=!1,a=await $T(e,t.opId,i,n.signal,j,M);if(a.refusalReason===`drift_requires_confirm`&&(i=!0,a=await $T(e,t.opId,i,n.signal,j,M)),n.signal.aborted||r!==v.current)return;b({plan:a,confirmDrift:i})}catch(e){if(n.signal.aborted||r!==v.current)return;if(HT(e)){h.current?.(),p.current();return}O(g.current(`integrations.preview.failed`))}finally{!n.signal.aborted&&r===v.current&&(_.current=null,S(!1))}},[e,t.opId,j,M]);(0,X.useEffect)(()=>{let e=window.setTimeout(()=>{I()},0);return()=>{window.clearTimeout(e),v.current+=1,_.current?.abort(),_.current=null}},[I]);let L=(0,X.useCallback)(e=>{e.preventDefault(),F()},[F]),R=async()=>{if(T||x||!y||!y.plan.canApply)return;let n=y.confirmDrift;E(!0),A(null);try{await tE(e,{opId:t.opId,confirmDrift:n,profileId:j,hermesProfile:M,binding:UT(y.plan)}),f.current=!0,m.current(),p.current()}catch(r){if(t.clientId===`aside`&&h.current?.(),r instanceof RT&&r.stalePlan){let i=r.stalePlan,a=n;E(!1);try{if(i.refusalReason===`drift_requires_confirm`){let n=new AbortController,r=v.current+1;v.current=r,_.current?.abort(),_.current=n,S(!0),a=!0;try{i=await $T(e,t.opId,a,n.signal,j,M)}finally{!n.signal.aborted&&r===v.current&&(_.current=null,S(!1))}if(n.signal.aborted||r!==v.current)return}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;if(HT(e)){h.current?.(),p.current();return}O(g.current(`integrations.preview.failed`));return}b({plan:i,confirmDrift:a}),w(!0);return}A(EE(s,r)),E(!1)}};return(0,Z.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":`integration-restore-title`,"aria-busy":T,onCancel:L,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:F}),(0,Z.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,role:`document`,children:[(0,Z.jsx)(`div`,{className:`modal-head`,children:(0,Z.jsx)(`h3`,{id:`integration-restore-title`,children:s(P?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,Z.jsx)(`div`,{className:`modal-desc`,children:s(P?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,Z.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[x&&(0,Z.jsx)(`p`,{children:s(`integrations.preview.loading`)}),T&&(0,Z.jsx)(`p`,{children:s(`integrations.mutation.pending`)}),C&&(0,Z.jsx)(Q,{tone:`err`,children:s(`integrations.preview.stale`)})]}),(0,Z.jsx)(dH,{plan:N}),D&&(0,Z.jsx)(Q,{tone:`err`,children:D}),k&&(0,Z.jsx)(Q,{tone:`err`,children:k}),(0,Z.jsxs)(`div`,{className:`modal-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:F,disabled:T,children:s(`common.cancel`)}),(0,Z.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 gH={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`},_H={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`,overwrite:`integrations.kind.overwrite`};function vH(e){return e===`current`||e===`stale`}function yH(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 bH(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 xH(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 SH(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=xH(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 CH(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 wH(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 TH(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=wH(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 EH(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 DH(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:gH[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&(vH(e.state)||vT(e)),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function OH(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=[yH(e.codex,t,e.nativeSettled),SH(e.claude,n,e.nativeSettled),CH(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),TH(e.grok,r,e.nativeSettled),EH(e.cursor)];for(let t of _T){let n=i.get(t);n?a.push(DH(n)):e.clientsSettled||a.push({id:t,hash:`integrations/${t}`,labelKey:gH[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:bH(e.keyPhase,e.keyCount),rows:a}}function kH(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 AH=6;function jH({row:e,showClient:t,onRestore:n,onDelete:r}){let i=c();return(0,Z.jsxs)(`li`,{className:`integration-history-row`,children:[(0,Z.jsx)(`span`,{className:`integration-history-kind`,children:i(_H[e.kind])}),t&&(0,Z.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,Z.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,Z.jsx)(`span`,{className:`badge badge-muted`,children:i(`integrations.action.snapshotExpired`)}):(0,Z.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,Z.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 MH({rows:e,showClient:t,onRestore:n,onDelete:r}){let i=c(),[a,o]=(0,X.useState)(AH),[s,...l]=e;if(!s)return null;let u=l.slice(0,a),d=l.length-u.length;return(0,Z.jsxs)(`div`,{className:`integration-history`,children:[(0,Z.jsx)(`ul`,{className:`integration-history-list`,children:(0,Z.jsx)(jH,{row:s,showClient:t,onRestore:n,onDelete:r})}),l.length>0&&(0,Z.jsxs)(`details`,{className:`integration-history-older`,children:[(0,Z.jsx)(`summary`,{children:i(`integrations.rollback.older`)}),(0,Z.jsx)(`ul`,{className:`integration-history-list`,children:u.map(e=>(0,Z.jsx)(jH,{row:e,showClient:t,onRestore:n,onDelete:r},e.opId))}),d>0&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm integration-history-more`,onClick:()=>o(e=>e+AH),children:i(`integrations.rollback.showMore`,{n:String(Math.min(d,AH))})})]})]})}var NH={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`},PH={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`},FH={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`},IH={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`},LH={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`},RH={titleKey:`integrations.bulk.title`,changesKey:`integrations.bulk.body`,breakageKey:`integrations.bulk.breakage`,undoKey:`integrations.bulk.undo`,confirmKey:`integrations.bulk.confirm`};function zH(e){return e.flatMap(e=>e.plan?[{clientId:e.clientId,label:e.label,plan:e.plan}]:[])}function BH(e){return e.state===`current`||e.state===`stale`||vT(e)}function VH({row:e,pending:t,result:n,onOpen:r,onToggle:i,onOverwrite:a}){let o=c(),s=e.detail??(e.detailKey?o(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`)?EE(o,new mE(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&&vT(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,Z.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,"data-tone":p,children:[(0,Z.jsxs)(`div`,{className:`integration-card-head`,children:[(0,Z.jsx)(WR,{src:UR(e.id),label:o(e.labelKey),size:20}),(0,Z.jsx)(`h4`,{children:(0,Z.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:r,children:o(e.labelKey)})}),(0,Z.jsx)(aH,{state:e.state,installed:e.installed})]}),s&&(0,Z.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:s}),e.status?.reason===`candidate-conflict`&&e.status.conflictPaths?.map(e=>(0,Z.jsx)(Q,{tone:`err`,children:o(`integrations.status.candidateConflict`,{path:e})},e)),n?.tone===`err`&&(0,Z.jsx)(Q,{tone:`err`,children:n.text}),n?.tone===`ok`&&(0,Z.jsx)(Q,{tone:`ok`,children:n.text}),(0,Z.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&i&&(0,Z.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,Z.jsx)(kn,{on:d,onClick:i,disabled:e.state===`unknown`||!e.installed||(e.state===`conflict`||e.state===`unsafe`)&&!f||l||t,label:o(d?`integrations.action.disable`:`integrations.action.apply`)}),u&&(0,Z.jsx)(`p`,{className:`integration-toggle-blocked`,children:u})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,tabIndex:-1,children:o(`integrations.action.settings`)}),a&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:a,disabled:t,children:o(`integrations.action.overwrite`)})]})]})}function HH(e){return e.state!==`unknown`&&(e.state===`not-installed`||!e.installed)&&!(e.toggleOn??e.applied)}function UH({apiBase:e,active:t=!0}){let n=c(),r=nH(n(`integrations.catalog.title`)),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)({}),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),x=(0,X.useRef)(null),S=(0,X.useRef)(0),C=(0,X.useRef)(null),w=(0,X.useRef)(0),T=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(h!==null)return;let e=T.current;e&&(T.current=null,e.isConnected&&e.focus())},[h]),(0,X.useEffect)(()=>()=>{S.current+=1,w.current+=1,x.current?.abort(),C.current?.abort()},[]);let E=(0,X.useCallback)(async t=>(await YT(e,t)).clients,[e]),D=(0,X.useCallback)(async t=>(await ZT(e,void 0,t)).operations,[e]),O=(0,X.useCallback)(t=>iE(e,t),[e]),k=(0,X.useCallback)(t=>aE(e,t),[e]),A=(0,X.useCallback)(t=>oE(e,t),[e]),j=(0,X.useCallback)(t=>sE(e,t),[e]),M=(0,X.useCallback)(t=>cE(e,t),[e]),N=(0,X.useCallback)(t=>XV(e,t),[e]),P=(0,X.useCallback)(async t=>(await vE(e,t))?.clients??null,[e]),F=Fd(`integration-states:${e}`,[e],E,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.states.v1:${e}`}),I=Fd(`integration-journal-all:${e}`,[e],D,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.journal.v1:${e}`}),L=Fd(`integration-codex:${e}`,[e],O,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.codex.v1:${e}`}),R=Fd(`integration-keys:${e}`,[e],k,{isEmpty:()=>!1,enabled:t,sessionCacheKey:`ocx.integrations.keys.v1:${e}`}),z=Fd(`integration-claude:${e}`,[e],A,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude.v1:${e}`}),B=Fd(`integration-claude-desktop:${e}`,[e],j,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude-desktop.v1:${e}`}),V=Fd(`integration-grok:${e}`,[e],M,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.grok.v1:${e}`}),H=Fd(`integration-cursor:${e}`,[e],N,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.cursor.v1:${e}`}),U=Fd(`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??[],te=W.filter(BH),ne=W.filter(e=>e.installed),G=F.state.data!==void 0,K=U.state.data??null,re=K!==null,q=R.state.kind===`cold`||R.state.kind===`retrying-cold`?`checking`:R.state.kind===`failed-cold`||R.state.kind===`failed-with-stale`?`unavailable`:`settled`,{keysRow:ie,rows:ae}=OH({clients:W,clientsSettled:G,codex:L.state.data??null,keyCount:R.state.data??null,keyPhase:q,claude:z.state.data??null,claudeDesktop:B.state.data??null,grok:V.state.data??null,cursor:H.state.data??null,native:K,nativeSettled:re}),oe=kH(ae),se=()=>{F.refresh(),I.refresh(),L.refresh(),R.refresh(),z.refresh(),B.refresh(),V.refresh(),U.refresh()},ce=async()=>{if(i||y||te.length===0)return;let t=new AbortController,r=w.current+1;w.current=r,C.current?.abort(),C.current=t,b({actions:[],loading:!0,failure:null,stale:!1,failures:[]});try{let i=await Promise.all(te.map(async r=>{let i=ae.find(e=>e.status?.clientId===r.clientId);if(r.clientId===`aside`)return{clientId:r.clientId,label:i?n(i.labelKey):r.clientId,plan:null};let a=await QT(e,r.clientId,`disable`,t.signal);return{clientId:r.clientId,label:i?n(i.labelKey):r.clientId,plan:a}}));if(t.signal.aborted||r!==w.current)return;C.current=null,b({actions:i,loading:!1,failure:null,stale:!1,failures:[]})}catch(e){if(t.signal.aborted||r!==w.current)return;if(C.current=null,HT(e)){b(null),se();return}b({actions:[],loading:!1,failure:n(`integrations.preview.failed`),stale:!1,failures:[]})}},le=()=>{w.current+=1,C.current?.abort(),C.current=null,b(null)},ue=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 eE(e,i.clientId,{enabled:!1,...i.plan?{binding:UT(i.plan)}:{}})}catch(e){if(i.plan&&e instanceof RT&&e.stalePlan){o.push({...i,plan:e.stalePlan});continue}r.push(`${i.clientId}: ${EE(n,e)}`)}if(o.length>0){se(),a(!1),b({actions:o,loading:!1,failure: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 YT(e)).clients.some(BH)}catch{r.push(n(`integrations.error.stale`))}c&&r.length===0&&r.push(n(`integrations.error.stale`)),se(),a(!1),b(null),s(r.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:r.join(`; `)})})},J=ee[0]?.at,[de,fe]=(0,X.useState)(null),pe=()=>{U.refresh(),L.refresh(),z.refresh(),V.refresh()},me=(e,t)=>{m(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 eE(e,t.status.clientId,{enabled:r,...i?{overwriteConflict:i.operation===`overwrite`,binding:UT(i)}:{}}),se()}else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await yE(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 RT&&e.stalePlan)throw e;if(me(t.id,{tone:`err`,text:EE(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(EE(n,e,void 0,t.togglePath??void 0),{cause:e})}finally{fe(null)}}},ge=async(t,r)=>{if(!t.status||_)return;let i=new AbortController,a=S.current+1;S.current=a,x.current?.abort(),x.current=i,v({row:t,operation:r,plan:null,loading:!0,failure:null});try{let n=await QT(e,t.status.clientId,r,i.signal);if(i.signal.aborted||a!==S.current)return;x.current=null,v({row:t,operation:r,plan:n,loading:!1,failure:null})}catch(e){if(i.signal.aborted||a!==S.current)return;if(x.current=null,HT(e)){v(null),se();return}v({row:t,operation:r,plan:null,loading:!1,failure:n(`integrations.preview.failed`)})}},_e=()=>{S.current+=1,x.current?.abort(),x.current=null,v(null)},ve=(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,g(e)},ye=ae.filter(e=>!HH(e)),be=ae.filter(HH),xe=e=>(0,Z.jsx)(VH,{row:e,pending:de!==null,result:p[e.id]??null,onOpen:()=>_n(e.hash),onToggle:e.toggle?()=>ve(e,!(e.toggleOn??e.applied)):null,onOverwrite:e.status!==null&&e.status.state===`conflict`&&e.status.reason!==`candidate-conflict`&&e.installed?()=>void ge(e,`overwrite`):null},e.id);return(0,Z.jsxs)(`section`,{className:`integrations-overview`,children:[(0,Z.jsxs)(`div`,{className:`integration-summary`,children:[(0,Z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,Z.jsx)(`strong`,{children:oe.detected})]}),(0,Z.jsxs)(`div`,{className:`integration-summary-cell`,"data-tone":oe.applied>0?`ok`:void 0,children:[(0,Z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,Z.jsx)(`strong`,{children:oe.applied})]}),(0,Z.jsxs)(`div`,{className:`integration-summary-cell`,"data-tone":oe.stale>0?`warn`:void 0,children:[(0,Z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,Z.jsx)(`strong`,{children:oe.stale})]}),oe.unknown>0&&(0,Z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,Z.jsx)(`strong`,{children:oe.unknown})]}),(0,Z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,Z.jsx)(`strong`,{className:`integration-summary-when`,children:J?new Date(J).toLocaleString():n(`integrations.status.unknown`)})]})]}),(0,Z.jsxs)(`div`,{className:`connect-catalog-head`,children:[(0,Z.jsx)(`h3`,{children:n(`integrations.catalog.title`)}),r.button,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm connect-disable-all`,onClick:()=>void ce(),disabled:i||!!y||te.length===0,children:n(`integrations.summary.disableAll`)})]}),r.panel((0,Z.jsx)(`p`,{children:n(`integrations.onboarding`)}),`connect-help-panel`),(0,Z.jsx)(WH,{row:ie}),F.state.kind===`failed-cold`&&(0,Z.jsx)(Q,{tone:`err`,children:n(`integrations.error.load`)}),F.state.kind===`failed-with-stale`&&(0,Z.jsx)(Q,{tone:`err`,children:n(`integrations.error.stale`)}),o&&(0,Z.jsx)(Q,{tone:o.tone,children:o.text}),ae.length===0?F.state.kind===`failed-cold`?null:(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,Z.jsxs)(Z.Fragment,{children:[ye.length>0&&(0,Z.jsx)(`ul`,{className:`integration-cards`,children:ye.map(xe)}),be.length>0&&(0,Z.jsxs)(`details`,{className:`connect-elsewhere`,children:[(0,Z.jsxs)(`summary`,{children:[(0,Z.jsx)(`span`,{className:`connect-elsewhere-title`,children:n(`connectV2.elsewhereTitle`,{count:String(be.length)})}),(0,Z.jsx)(`span`,{className:`connect-elsewhere-hint`,children:n(`connectV2.elsewhereHint`)})]}),(0,Z.jsx)(`ul`,{className:`integration-cards integration-cards--elsewhere`,children:be.map(xe)})]})]}),G&&ne.length===0&&(0,Z.jsxs)(`div`,{className:`integration-empty`,children:[(0,Z.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,Z.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,Z.jsx)(`h3`,{children:n(`integrations.rollback.title`)}),I.state.showSkeleton?(0,Z.jsx)(NE,{label:n(`integrations.rollback.title`),rows:2}):I.state.kind===`failed-cold`?(0,Z.jsxs)(Q,{tone:`err`,children:[n(`integrations.rollback.failed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void I.refresh(),children:n(`common.retry`)})]}):ee.length===0?(0,Z.jsxs)(`div`,{className:`integration-empty`,children:[(0,Z.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,Z.jsx)(MH,{rows:ee,showClient:!0,onRestore:u,onDelete:f}),l&&(0,Z.jsx)(hH,{apiBase:e,row:l,onClose:()=>u(null),onRestored:se,onReconcile:se}),d&&(0,Z.jsx)(mH,{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:d.configPath}},onClose:()=>f(null),onConfirm:async()=>{try{await nE(e,d.opId,void 0,d.clientId===`aside`?d.profileId:void 0)}catch(e){if(zT(e)){f(null),await I.refresh();return}throw Error(EE(n,e),{cause:e})}f(null),await I.refresh()}}),h&&(0,Z.jsx)(mH,{copy:{...h.toggle===`claude-desktop`?FH:h.id===`codex`?PH:NH,vars:{path:h.togglePath??``}},onClose:()=>g(null),onConfirm:async()=>{await he(h,!1),g(null)}}),_&&_.row.status&&(0,Z.jsx)(mH,{copy:_.operation===`overwrite`?{titleKey:`integrations.dialog.overwrite.title`,changesKey:_.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:_.row.status.configPath}}:_.operation===`disable`?LH:IH,plan:_.plan,planLoading:_.loading,planFailure:_.failure,onClose:_e,onConfirm:async e=>{e&&(await he(_.row,e.operation!==`disable`,e),v(null))}}),y&&(0,Z.jsx)(mH,{copy:RH,plans:zH(y.actions),hasUnboundAction:y.actions.some(e=>e.plan===null),planStale:y.stale,planLoading:y.loading,planFailure:y.failure,onClose:le,onConfirm:async()=>{await ue(y)}})]})}function WH({row:e}){let t=c(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,Z.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,Z.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,Z.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,Z.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>_n(e.hash),children:t(`integrations.action.manageKeys`)})]})}function GH({install:e}){let t=c();return(0,Z.jsxs)(Z.Fragment,{children:[e.plan===`free`&&(0,Z.jsx)(Q,{tone:`warn`,children:t(`integrations.raycast.proRequired`)}),e.plan===`unknown`&&(0,Z.jsx)(`p`,{className:`page-sub`,"data-raycast-plan":`unknown`,children:t(`integrations.raycast.planUnknown`)}),!e.aiDirPresent&&(0,Z.jsx)(`p`,{className:`page-sub`,"data-raycast-ai-dir":`absent`,children:t(`integrations.raycast.revealConfig`)})]})}function KH({reasoning:e,defaults:t,disabled:n,onChange:r,onReview:i}){let a=c(),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)),l=(e,n)=>{let i={...t};n?i[e]=n:delete i[e],r(i)};return(0,Z.jsxs)(`section`,{className:`droid-reasoning-panel`,"aria-labelledby":`droid-reasoning-title`,children:[(0,Z.jsxs)(`div`,{className:`droid-reasoning-heading`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h4`,{id:`droid-reasoning-title`,children:a(`integrations.droidReasoning.title`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:a(`integrations.droidReasoning.description`)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:i,disabled:n,children:a(`integrations.droidReasoning.saveReview`)})]}),e.models.length>0?(0,Z.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,Z.jsxs)(`li`,{className:`droid-reasoning-row`,children:[(0,Z.jsxs)(`div`,{className:`droid-reasoning-model`,children:[(0,Z.jsx)(`span`,{children:e.label}),(0,Z.jsx)(`code`,{children:e.model})]}),e.efforts.length>0?(0,Z.jsx)($,{value:r,options:o,onChange:t=>l(e.model,t),disabled:n,label:a(`integrations.droidReasoning.modelDefault`,{model:e.label})}):(0,Z.jsx)(`span`,{className:`muted text-caption`,children:a(`integrations.droidReasoning.noEfforts`)})]},e.model)})}):(0,Z.jsx)(`p`,{className:`page-sub`,children:a(`integrations.droidReasoning.noModels`)}),s.length>0&&(0,Z.jsxs)(`div`,{className:`droid-reasoning-unsupported`,role:`status`,children:[(0,Z.jsx)(`p`,{children:a(`integrations.droidReasoning.unsupportedTitle`)}),(0,Z.jsx)(`ul`,{children:s.map(([e,t])=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`code`,{children:e}),` `,a(`integrations.droidReasoning.unsupportedEffort`,{effort:t}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:()=>l(e,``),children:a(`integrations.droidReasoning.clear`)})]},e))})]})]})}function qH(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 JH={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`},YH={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`},XH={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`},ZH={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 QH(e){return(0,Z.jsx)($H,{...e},JSON.stringify([e.apiBase,e.client,e.profileId,e.hermesProfile]))}function $H({apiBase:e,client:t,active:n=!0,profileId:r,profileLabel:i,hermesProfile:a,onRefresh:o}){let s=c(),l=r===void 0?a===void 0?t:`${t}/${a}`:`${t}:${r}`,[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),S=(0,X.useRef)(null),C=(0,X.useRef)(0);(0,X.useEffect)(()=>()=>{C.current+=1,S.current?.abort()},[]);let w=(0,X.useCallback)(n=>XT(e,t,n,r,a),[e,t,r,a]),T=(0,X.useCallback)(async n=>(await ZT(e,t,n,r,a)).operations,[e,t,r,a]),E=Fd(`integration-state:${e}:${l}`,[e,t,r,a],w,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${l}`}),D=Fd(`integration-journal:${e}:${l}`,[e,t,r,a],T,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${l}`}),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=()=>{p(null),j()},N=async(n,i=t===`droid`&&n!==`disable`&&f?.scopeKey===l?f.values:void 0)=>{if(!k||u||b)return;let o=i===void 0?void 0:{...i},c=new AbortController,d=C.current+1;C.current=d,S.current?.abort(),S.current=c,x({operation:n,plan:null,loading:!0,failure:null});try{let i=await QT(e,t,n,c.signal,r,o,a);if(c.signal.aborted||d!==C.current)return;S.current=null,x({operation:n,plan:i,loading:!1,failure:null,droidReasoningDefaults:o})}catch(e){if(c.signal.aborted||d!==C.current)return;if(S.current=null,HT(e)){x(null),j();return}x({operation:n,plan:null,loading:!1,failure:s(`integrations.preview.failed`)})}},P=()=>{C.current+=1,S.current?.abort(),S.current=null,x(null)},F=async n=>{if(k&&!u){d(!0),h(null);try{await eE(e,t,{enabled:n.operation!==`disable`,overwriteConflict:n.operation===`overwrite`,profileId:r,hermesProfile:a,binding:UT(n),...n.operation!==`disable`&&b?.droidReasoningDefaults!==void 0?{droidReasoningDefaults:b.droidReasoningDefaults}:{}}),x(null),t===`droid`&&p(null)}catch(e){throw j(),e instanceof RT&&e.stalePlan?e:Error(EE(s,e),{cause:e})}finally{j(),d(!1)}}},I=()=>void N(z?`disable`:`apply`);if(!k)return(0,Z.jsx)(`section`,{className:`integration-client-page`,children:E.state.showError?(0,Z.jsxs)(Q,{tone:`err`,children:[s(`integrations.error.load`),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:E.state.refreshing,children:s(`common.retry`)})]}):(0,Z.jsx)(`p`,{className:`page-sub`,children:s(`common.loading`)})});let L=vT(k),R=k.state===`current`||k.state===`stale`||L,z=r===void 0?R:k.enabled===!0,B=r!==void 0&&(E.state.showError||E.state.refreshing),V=(!k.installed||(k.state===`conflict`||k.state===`unsafe`)&&!L)&&!(r!==void 0&&z);return(0,Z.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Z.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Z.jsx)(WR,{src:UR(t),label:s(ZH[t]),size:24}),(0,Z.jsx)(`h3`,{children:i??s(ZH[t])}),(0,Z.jsx)(aH,{state:k.state,installed:k.installed,id:`integration-state-${t}${r===void 0?``:`-${r}`}${a===void 0?``:`-${a}`}`}),(0,Z.jsx)(kn,{on:z,onClick:I,disabled:V||u||B,label:s(z?`integrations.action.disable`:`integrations.action.apply`)})]}),r!==void 0&&E.state.showError&&(0,Z.jsxs)(Q,{tone:`err`,children:[s(`integrations.aside.loadError`),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:u||E.state.refreshing,children:s(`common.retry`)})]}),k.state===`stale`&&z&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void N(`apply`),disabled:u,children:s(`integrations.action.refresh`)}),t===`droid`&&k.droidReasoning&&(0,Z.jsx)(KH,{reasoning:k.droidReasoning,defaults:f?.scopeKey===l?f.values:k.droidReasoning.defaults,disabled:u||b!==null,onChange:e=>p({scopeKey:l,values:e}),onReview:()=>void N(`apply`)}),k.installed&&k.state===`conflict`&&k.reason!==`candidate-conflict`&&(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void N(`overwrite`),disabled:u,children:s(`integrations.action.overwrite`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:s(XH[t])}),(0,Z.jsx)(`p`,{className:`integration-path`,children:k.configPath}),k.reason===`candidate-conflict`&&k.conflictPaths?.map(e=>(0,Z.jsx)(Q,{tone:`err`,children:s(`integrations.status.candidateConflict`,{path:e})},e)),k.raycast&&(0,Z.jsx)(GH,{install:k.raycast}),k.supersededBy&&(0,Z.jsx)(Q,{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,Z.jsxs)(`p`,{className:`integration-meta`,children:[s(`integrations.status.appliedAt`),`: `,new Date(k.appliedAt).toLocaleString()]}),k.retentionDegraded&&(0,Z.jsx)(Q,{tone:`err`,children:s(`integrations.retention.degraded`)}),m&&(0,Z.jsx)(Q,{tone:`err`,children:m}),(0,Z.jsx)(`h4`,{children:s(`integrations.rollback.title`)}),D.state.showSkeleton?(0,Z.jsx)(NE,{label:s(`integrations.rollback.title`),rows:2}):D.state.kind===`failed-cold`?(0,Z.jsxs)(Q,{tone:`err`,children:[s(`integrations.rollback.failed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void D.refresh(),children:s(`common.retry`)})]}):A.length===0?(0,Z.jsx)(`p`,{className:`page-sub`,children:s(`integrations.rollback.empty`)}):(0,Z.jsx)(MH,{rows:A,onRestore:_,onDelete:y}),g&&(0,Z.jsx)(hH,{apiBase:e,row:g,profileId:r,hermesProfile:a,onClose:()=>_(null),onRestored:()=>{t===`droid`?M():j()},onReconcile:j}),v&&(0,Z.jsx)(mH,{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:v.configPath}},onClose:()=>y(null),onConfirm:async()=>{try{await nE(e,v.opId,void 0,r,a)}catch(e){if(zT(e)){y(null),await D.refresh();return}throw Error(EE(s,e),{cause:e})}y(null),await D.refresh()}}),b&&(0,Z.jsx)(mH,{copy:b.operation===`overwrite`?qH(k.reason,k.configPath):b.operation===`disable`?YH:JH,plan:b.plan,planLoading:b.loading,planFailure:b.failure,missingStorePath:k.supersededReason===`missing-store`?k.supersededBy:void 0,onClose:P,onConfirm:async e=>{e&&await F(e)}})]})}function eU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tU(){throw new RT(502,{code:`invalid_aside_profile_response`})}async function nU(e,t){let n=await VT(await fetch(`${e}/api/client-integrations/aside/profiles`,{signal:t}));(!eU(n)||!Array.isArray(n.profiles)||typeof n.allEnabled!=`boolean`)&&tU();let r=n.profiles.map(e=>hT(e)??tU());new Set(r.map(e=>e.profileId)).size!==r.length&&tU();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))&&tU(),{profiles:r,allEnabled:n.allEnabled,enabledCount:i,appliedCount:a,total:r.length,...typeof n.error==`string`?{error:n.error}:{}}}async function rU(e,t){let n=await VT(await fetch(`${e}/api/client-integrations/aside/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,signal:t}));(!eU(n)||typeof n.ok!=`boolean`||!Array.isArray(n.results))&&tU(),n.results.some(e=>!eU(e)||e.client!==`aside`)&&tU();let r=gT(n.results)??tU();return n.ok!==r.every(e=>e.ok)&&tU(),{ok:n.ok,results:r}}var iU={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`},aU={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 oU({apiBase:e,active:t=!0}){let n=c(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(null),s=(0,X.useRef)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(new Map),[p,m]=(0,X.useState)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(0);(0,X.useEffect)(()=>()=>{g.current+=1,h.current?.abort()},[]);let _=(0,X.useCallback)(t=>nU(e,t),[e]),v=Fd(`aside-profiles:${e}`,[e],_,{enabled:t,isEmpty:e=>!e.error&&e.profiles.length===0,sessionCacheKey:`ocx.integrations.aside-profiles.v1:${e}`}),y=v.state.data,b=y?.profiles??[],x=v.state.showError||!!y?.error,S=a!==null||v.state.refreshing||p!==null,C=e=>e.name||n(`integrations.aside.profile`,{id:e.profileId}),w=e=>f(t=>{let r=new Map(t);for(let t of e)t.ok?r.delete(t.profileId):r.set(t.profileId,DE(n,t));return r}),T=(e,t)=>{e instanceof RT&&`results`in e.body&&e.body.results?.length?(w(e.body.results),u(n(`integrations.aside.partial`))):t===void 0?u(EE(n,e)):f(r=>new Map(r).set(t,EE(n,e)))},E=async(t,r,i)=>{if(!s.current){s.current=!0,o(r??`all`),u(null);try{let n=await eE(e,`aside`,{enabled:t,profileId:r,...i?{binding:UT(i)}:{}});w(n.results??(r===void 0?b.map(e=>e.profileId):[r]).map(e=>({profileId:e,ok:!0})))}catch(e){if(i&&e instanceof RT&&e.stalePlan)throw e;if(T(e,r),i)throw Error(EE(n,e),{cause:e})}finally{v.refresh(),s.current=!1,o(null)}}},D=async(t,r)=>{if(s.current||p)return;let i=new AbortController,a=g.current+1;g.current=a,h.current?.abort(),h.current=i,m({profile:t,enabled:r,plan:null,loading:!0,failure:null});try{let n=await QT(e,`aside`,r?`apply`:`disable`,i.signal,t.profileId);if(i.signal.aborted||a!==g.current)return;h.current=null,m({profile:t,enabled:r,plan:n,loading:!1,failure:null})}catch(e){if(i.signal.aborted||a!==g.current)return;if(h.current=null,HT(e)){m(null),v.refresh();return}m({profile:t,enabled:r,plan:null,loading:!1,failure:n(`integrations.preview.failed`)})}},O=()=>{g.current+=1,h.current?.abort(),h.current=null,m(null)},k=async()=>{if(!s.current){s.current=!0,o(`sync`),u(null);try{let t=await rU(e);w(t.results),t.ok||u(n(`integrations.aside.partial`))}catch(e){T(e)}finally{v.refresh(),s.current=!1,o(null)}}};return r?(0,Z.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,autoFocus:!0,onClick:()=>{i(null),v.refresh()},children:n(`integrations.aside.back`)}),d.has(r.profileId)&&(0,Z.jsx)(Q,{tone:`err`,children:(0,Z.jsx)(`span`,{className:`aside-profile-failure`,children:d.get(r.profileId)})}),(0,Z.jsx)(QH,{apiBase:e,client:`aside`,active:t,profileId:r.profileId,profileLabel:C(r)},r.profileId)]}):(0,Z.jsxs)(`section`,{className:`integration-client-page`,"aria-busy":S,children:[(0,Z.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Z.jsx)(WR,{src:UR(`aside`),label:n(`integrations.tab.aside`),size:24}),(0,Z.jsx)(`h3`,{children:n(`integrations.aside.profilesTitle`)})]}),(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.profilesHint`)}),(0,Z.jsxs)(`div`,{className:`aside-profile-toolbar`,children:[(0,Z.jsx)(kn,{on:y?.allEnabled??!1,mixed:!!(y&&y.enabledCount>0&&y.enabledCount<y.total),onClick:()=>void E(!y?.allEnabled),disabled:S||x||b.length===0,label:n(`integrations.aside.all`),showLabel:!0}),(0,Z.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.applied`,{count:y?.appliedCount??0,total:y?.total??0})}),(0,Z.jsx)(`button`,{type:`button`,className:`btn`,disabled:S||x||!y?.enabledCount,onClick:()=>void k(),children:n(`integrations.aside.syncNow`)})]}),l&&(0,Z.jsx)(Q,{tone:`err`,children:(0,Z.jsx)(`span`,{className:`aside-profile-failure`,children:l})}),[...d].filter(([e])=>!b.some(t=>t.profileId===e)).map(([e,t])=>(0,Z.jsx)(Q,{tone:`err`,children:(0,Z.jsxs)(`span`,{className:`aside-profile-failure`,children:[n(`integrations.aside.profile`,{id:e}),`: `,t]})},e)),x&&(0,Z.jsxs)(Q,{tone:`err`,children:[(0,Z.jsx)(`span`,{children:n(`integrations.aside.loadError`)}),y?.error&&(0,Z.jsx)(`span`,{className:`text-caption`,children:y.error}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v.refresh(),disabled:S,children:n(`common.retry`)})]}),v.state.showSkeleton&&(0,Z.jsx)(NE,{label:n(`common.loading`),rows:3}),!v.state.showSkeleton&&!x&&y&&b.length===0&&(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.empty`)}),b.length>0&&(0,Z.jsx)(`div`,{className:`aside-profile-list`,children:b.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,Z.jsxs)(`div`,{className:`aside-profile-row`,"aria-busy":a===e.profileId,children:[(0,Z.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Z.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,Z.jsxs)(`div`,{className:`aside-profile-meta`,children:[(0,Z.jsx)(`code`,{children:e.profileId}),e.current&&(0,Z.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.current`)})]}),o&&(0,Z.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.pending`)}),e.error&&(0,Z.jsx)(`span`,{className:`text-caption muted`,children:e.error}),d.has(e.profileId)&&(0,Z.jsx)(Q,{tone:`err`,children:(0,Z.jsx)(`span`,{className:`aside-profile-failure`,children:d.get(e.profileId)})})]}),(0,Z.jsxs)(`div`,{className:`aside-profile-controls`,children:[(0,Z.jsx)(aH,{state:e.state,installed:e.installed,id:`aside-profile-state-${e.profileId}`}),o&&(0,Z.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,Z.jsx)(kn,{on:e.enabled,onClick:()=>void D(e,!e.enabled),disabled:S||x||s,label:n(`integrations.aside.toggle`,{name:t})})]})]},e.profileId)})}),p&&(0,Z.jsx)(mH,{copy:p.enabled?iU:aU,plan:p.plan,planLoading:p.loading,planFailure:p.failure,onClose:O,onConfirm:async e=>{e&&(await E(p.enabled,p.profile.profileId,e),m(null))}})]})}var sU=[`absent`,`current`,`stale`,`conflict`,`unsafe`];function cU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lU(){throw new RT(502,{code:`invalid_hermes_profile_response`})}async function uU(e,t){let n=await VT(await fetch(e+`/api/client-integrations/hermes/profiles`,{signal:t}));(!cU(n)||!Array.isArray(n.profiles))&&lU();let r=n.profiles.map(e=>((!cU(e)||typeof e.hermesProfile!=`string`||typeof e.configPath!=`string`||typeof e.installed!=`boolean`||!sU.includes(e.state))&&lU(),{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)&&lU(),r}function dU({apiBase:e,active:t=!0}){let n=c(),[r,i]=(0,X.useState)(`default`),a=(0,X.useCallback)(t=>uU(e,t),[e]),o=Fd(`hermes-profiles:${e}`,[e],a,{enabled:t,isEmpty:e=>e.length===0,sessionCacheKey:`ocx.integrations.hermes-profiles.v1:${e}`}),s=o.state.data??[],l=s.some(e=>e.hermesProfile===r)?r:`default`,u=e=>e==="default"?n(`integrations.hermes.defaultProfile`):e,d=l==="default"?void 0:l;return(0,Z.jsxs)(`section`,{className:`integration-client-page`,children:[s.length>1&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h3`,{children:n(`integrations.hermes.profilesTitle`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.hermes.profilesHint`)}),(0,Z.jsx)(`ul`,{className:`aside-profile-list hermes-profile-list`,children:s.map(e=>(0,Z.jsxs)(`li`,{className:`aside-profile-row`,children:[(0,Z.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-pressed":e.hermesProfile===l,"aria-label":n(`integrations.hermes.select`,{name:u(e.hermesProfile)}),onClick:()=>i(e.hermesProfile),children:u(e.hermesProfile)}),(0,Z.jsx)(`div`,{className:`aside-profile-meta`,children:(0,Z.jsx)(`code`,{children:e.configPath})}),e.error&&(0,Z.jsx)(`span`,{className:`text-caption muted`,children:e.error})]}),(0,Z.jsx)(`div`,{className:`aside-profile-controls`,children:(0,Z.jsx)(aH,{state:e.state,installed:e.installed,id:`hermes-profile-state-${e.hermesProfile}`})})]},e.hermesProfile))})]}),o.state.showError&&(0,Z.jsxs)(Q,{tone:`err`,children:[(0,Z.jsx)(`span`,{children:n(`integrations.hermes.loadError`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void o.refresh(),disabled:o.state.refreshing,children:n(`common.retry`)})]}),(0,Z.jsx)(QH,{apiBase:e,client:`hermes`,active:t,hermesProfile:d,profileLabel:d===void 0?void 0:n(`integrations.hermes.profileTitle`,{name:d}),onRefresh:()=>void o.refresh()})]})}function fU(e){return e.proposedModel===e.model&&(e.proposedEffort==null||e.proposedEffort===e.effort)}function pU({apiBase:e,busy:t,apply:n}){let r=c(),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)({}),[h,g]=(0,X.useState)(null),_=async()=>{a(!0),u(null),g(null);try{let t=await zn(await fetch(`${e}/api/codex-agent-roles/auto-assign`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),r(`integrations.lazycodexRoles.auto.failed`));f(t??null),m({})}catch(e){f(null),u(e instanceof Error&&e.message?e.message:r(`integrations.lazycodexRoles.auto.failed`))}finally{a(!1)}},v=(d?.proposals??[]).filter(e=>e.status===`proposed`&&e.proposedModel&&!p[e.role]&&!fU(e)),y=async(e,t)=>{let r=await n(e.role,e.proposedModel,e.proposedEffort??void 0,t);return r&&m(t=>({...t,[e.role]:!0})),r},b=async()=>{s(!0);try{let e=0,t=v.length,n;for(let t of v){let r=await y(t,n);r&&(n??=r.batch,e+=1)}g(r(`integrations.lazycodexRoles.auto.appliedCount`,{count:String(e),total:String(t)}))}finally{s(!1)}},x=i||o||t;return(0,Z.jsxs)(`div`,{className:`lazycodex-auto-assign`,children:[(0,Z.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Z.jsx)(`p`,{className:`page-sub`,children:r(`integrations.lazycodexRoles.auto.hint`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:x,onClick:()=>void _(),children:r(i?`integrations.lazycodexRoles.auto.running`:`integrations.lazycodexRoles.auto.button`)})]}),l&&(0,Z.jsx)(Q,{tone:`err`,children:l}),d&&(0,Z.jsxs)(`section`,{className:`lazycodex-auto-assign-panel`,"aria-labelledby":`lazycodex-auto-assign-title`,children:[(0,Z.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Z.jsx)(`h5`,{id:`lazycodex-auto-assign-title`,children:r(`integrations.lazycodexRoles.auto.title`)}),(0,Z.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.sizedWith`,{model:d.sizingModel})}),(0,Z.jsxs)(`div`,{className:`lazycodex-auto-assign-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:x||v.length===0,onClick:()=>void b(),children:r(`integrations.lazycodexRoles.auto.applyAll`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:o,onClick:()=>{f(null),g(null)},children:r(`integrations.lazycodexRoles.auto.discard`)})]})]}),d.sizingError&&(0,Z.jsx)(Q,{tone:`warn`,children:r(`integrations.lazycodexRoles.auto.sizingFailed`,{error:d.sizingError})}),h&&(0,Z.jsx)(Q,{tone:`ok`,children:h}),(0,Z.jsx)(`ul`,{className:`lazycodex-auto-assign-list`,children:d.proposals.map(e=>(0,Z.jsxs)(`li`,{"aria-label":r(`integrations.lazycodexRoles.auto.proposalFor`,{role:e.role}),children:[(0,Z.jsxs)(`div`,{className:`lazycodex-auto-assign-head`,children:[(0,Z.jsx)(`code`,{children:e.role}),e.tier&&e.effortIntent&&(0,Z.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.tierEffort`,{tier:r(uj[e.tier]),effort:r(dj[e.effortIntent])})})]}),e.status===`unsized`?(0,Z.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.unsized`,{reason:e.reason??``})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`lazycodex-auto-assign-change`,children:[(0,Z.jsx)(`span`,{children:e.model?(0,Z.jsx)(`code`,{children:e.model}):r(`integrations.lazycodexRoles.none`)}),(0,Z.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),e.proposedModel?(0,Z.jsxs)(`code`,{children:[e.proposedModel,e.proposedEffort?` · ${e.proposedEffort}`:``]}):(0,Z.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.unassigned`,{reason:e.reason??``})}),e.status===`proposed`&&(p[e.role]||fU(e)?(0,Z.jsx)(`span`,{className:`lazycodex-auto-assign-done`,children:p[e.role]?r(`integrations.lazycodexRoles.auto.applied`):r(`integrations.lazycodexRoles.auto.alreadySet`)}):(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:x,onClick:()=>void y(e),children:r(`integrations.lazycodexRoles.auto.apply`)}))]}),e.rationale&&(0,Z.jsx)(`p`,{children:e.rationale}),e.moveUpIf&&(0,Z.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.moveUp`,{text:e.moveUpIf})}),e.moveDownIf&&(0,Z.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.moveDown`,{text:e.moveDownIf})})]})]},e.role))})]})]})}function mU(e){let t=new Map;for(let n of e)t.set(n.batch,[...t.get(n.batch)??[],n]);return[...t.values()]}function hU(e){let t=new Map;for(let n of e)t.set(n.role,n.before);return t}function gU({history:e,unavailable:t,busy:n,restore:r}){let{locale:i,t:o}=a(),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null);if(t)return(0,Z.jsx)(Q,{tone:`warn`,children:o(`integrations.lazycodexRoles.history.unavailable`)});if(e.length===0)return null;let d=e=>{let t=e.model??o(`integrations.lazycodexRoles.none`);return e.effort?`${t} · ${e.effort}`:t},f=async e=>{c(e[0].batch),u(null);try{let t,n=[...hU(e)],a=0;for(let[i,o]of n){let n=await r(i,o.model??void 0,o.effort,t,e[0].batch);if(!n)break;t??=n.batch,a+=1}let s=new Date(e[0].at).toLocaleString(i);u(a===n.length?{tone:`ok`,text:o(`integrations.lazycodexRoles.history.restored`,{count:String(a),time:s})}:{tone:`warn`,text:o(`integrations.lazycodexRoles.history.partial`,{count:String(a),total:String(n.length),role:n[a][0]})})}finally{c(null)}};return(0,Z.jsxs)(`div`,{className:`lazycodex-role-history`,children:[(0,Z.jsx)(`h5`,{children:o(`integrations.lazycodexRoles.history.title`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:o(`integrations.lazycodexRoles.history.hint`)}),l&&(0,Z.jsx)(Q,{tone:l.tone,children:l.text}),(0,Z.jsx)(`ul`,{children:mU(e).map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`span`,{className:`integration-meta`,children:new Date(e[0].at).toLocaleString(i)}),(0,Z.jsx)(`ul`,{children:e.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(`code`,{children:e.role}),`: `,(0,Z.jsx)(`code`,{children:d(e.before)}),` → `,(0,Z.jsx)(`code`,{children:d(e.after)})]},`${e.at}-${e.role}`))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:n||s!==null,onClick:()=>void f(e),children:s===e[0].batch?o(`common.saving`):o(`integrations.lazycodexRoles.history.restore`)})]},e[0].batch))})]})}var _U={absent:`integrations.lazycodexRoles.omoAbsent`,skipped_comments:`integrations.lazycodexRoles.omoComments`,invalid:`integrations.lazycodexRoles.omoInvalid`,write_failed:`integrations.lazycodexRoles.omoFailed`};function vU({apiBase:e,active:t}){let n=c(),[r,i]=(0,X.useState)({}),[a,o]=(0,X.useState)({}),[s,l]=(0,X.useState)({}),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),m=(0,X.useCallback)(async t=>{let r=await zn(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=>zn(e,n(`integrations.lazycodexRoles.loadFailed`))),fetch(`${e}/api/injection-model`,{signal:t}).then(e=>zn(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]),h=`lazycodex-role-models:${e}`,g=Fd(h,[e],m,{isEmpty:e=>e.roles.length===0,enabled:t}),_=g.state.data,v=(0,X.useRef)(_);(0,X.useLayoutEffect)(()=>{v.current=_},[_]);let y=async(t,r,a=void 0,c,f,m)=>{if(u!==null)return null;let _=a===void 0?s[t]?.sent:a;if(r===void 0&&_===void 0)return null;d(t),p(null);try{let a=await zn(await fetch(`${e}/api/codex-agent-roles/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...r===void 0?{}:{model:r},..._===void 0?{}:{effort:_},...f===void 0?{}:{batch:f},...m===void 0?{}:{restores:m}})}),n(`integrations.lazycodexRoles.saveFailed`,{role:t})),s=a?.omoJsonc?.status,u=v.current,d=u?.roles.find(e=>e.role===t),y=_===void 0?d?d.effort??null:c||null:_,b=y??``,x=r??d?.model??null;if(u){let e={...u,roles:u.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)};v.current=e,pn(h,e)}let S=s?_U[s]:void 0,C=x??n(`integrations.lazycodexRoles.none`),w=b?`${C} · ${b}`:C;p(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)),l(e=>E(e,{sent:_})),await g.refresh(),{batch:a?.batch}}catch{return p({tone:`err`,text:n(`integrations.lazycodexRoles.saveFailed`,{role:t})}),null}finally{d(null)}},b=(e,t)=>{let r=[...new Set([...e.model?[e.model]:[],..._?.available??[]])];return[...t===``?[{value:``,label:n(`integrations.lazycodexRoles.choose`)}]:[],...r.map(e=>({value:e,label:e}))]};return g.state.kind===`failed-cold`?(0,Z.jsxs)(Q,{tone:`err`,children:[n(`integrations.lazycodexRoles.loadFailed`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void g.refresh(),children:n(`common.retry`)})]}):_?.detected?(0,Z.jsxs)(`section`,{id:`lazycodex-role-models`,className:`lazycodex-role-models`,"aria-labelledby":`lazycodex-role-models-title`,children:[(0,Z.jsx)(`h4`,{id:`lazycodex-role-models-title`,children:n(`integrations.lazycodexRoles.title`)}),(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.lazycodexRoles.hint`)}),_.omoJsonc?.state===`comments`&&(0,Z.jsx)(Q,{tone:`warn`,children:n(`integrations.lazycodexRoles.omoCommentsState`)}),f&&(0,Z.jsx)(Q,{tone:f.tone,children:f.text}),_.roles.length===0?(0,Z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.lazycodexRoles.empty`)}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(pU,{apiBase:e,busy:u!==null,apply:(e,t,n,r)=>y(e,t,n,void 0,r)}),(0,Z.jsx)(`div`,{className:`tbl-wrap`,children:(0,Z.jsxs)(`table`,{className:`tbl`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:n(`integrations.lazycodexRoles.role`)}),(0,Z.jsx)(`th`,{children:n(`integrations.lazycodexRoles.current`)}),(0,Z.jsxs)(`th`,{children:[n(`integrations.lazycodexRoles.model`),` · `,n(`integrations.lazycodexRoles.effort`)]})]})}),(0,Z.jsx)(`tbody`,{children:_.roles.map(e=>{let t=r[e.role]??e.model??``,c=a[e.role]??e.effort??``,l=c!==(e.effort??``),d=t!==``&&t!==e.model||l,f=s[e.role],p=f!==void 0&&(t!==``||f.sent!==void 0);return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`code`,{children:e.role})}),(0,Z.jsx)(`td`,{children:e.model?(0,Z.jsx)(`code`,{children:e.effort?`${e.model} · ${e.effort}`:e.model}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`integration-meta`,children:n(`integrations.lazycodexRoles.none`)}),e.effort&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(`code`,{children:e.effort})]})]})}),(0,Z.jsx)(`td`,{children:(0,Z.jsxs)(`div`,{className:`lazycodex-role-models-edit`,children:[(0,Z.jsx)($,{value:t,options:b(e,t),label:n(`integrations.lazycodexRoles.modelFor`,{role:e.role}),disabled:u!==null,onChange:t=>i(n=>({...n,[e.role]:t}))}),(0,Z.jsx)($,{value:c,options:[{value:``,label:n(`integrations.lazycodexRoles.effortDefault`)},...[...new Set([...e.effort?[e.effort]:[],..._.efforts])].map(e=>({value:e,label:e}))],label:n(`integrations.lazycodexRoles.effortFor`,{role:e.role}),disabled:u!==null,onChange:t=>o(n=>({...n,[e.role]:t}))}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!(d||p)||u!==null,onClick:()=>void y(e.role,t||void 0,l?c||null:void 0,e.effort??``),children:u===e.role?n(`common.saving`):n(p&&!d?`integrations.lazycodexRoles.retryMirror`:`common.save`)})]})})]},e.role)})})]})}),(0,Z.jsx)(gU,{history:_.history,unavailable:_.historyUnavailable,busy:u!==null,restore:(e,t,n,r,i)=>y(e,t,n,void 0,r,i)})]})]}):null}var yU=[{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`}],bU=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 xU(e=window.location.hash){let t=hC(e);return t===`claude/desktop`?`claudeDesktop`:t===`claude`||t.startsWith(`claude/`)?`claude`:yU.find(e=>e.hash===t)?.id??`overview`}function SU(e){return`integrations-tab-${e}`}function CU(e){return`integrations-panel-${e}`}function wU(e){return e===`overview`||e===`keys`?null:BR[e]??null}function TU({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=c(),[i,a]=(0,X.useState)(xU),[o,s]=(0,X.useState)(()=>new Set([xU()])),l=(0,X.useRef)(null),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)(!1);l.current===null&&(l.current=new Map),(0,X.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)&&d(t.selectedClients.filter(e=>typeof e==`string`))}).catch(()=>{}),()=>e.abort()},[n,t]);let m=async()=>{p(!0);try{await fetch(`${t}/api/machine/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`})}finally{p(!1)}},h=e=>{a(e),s(t=>t.has(e)?t:new Set([...t,e]))};(0,X.useEffect)(()=>{let e=()=>h(xU());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let g=(e,t)=>{let n=yU.find(t=>t.id===e);n&&(_n(n.hash),h(e),t&&window.requestAnimationFrame(()=>{l.current.get(e)?.focus({preventScroll:!0})}))},_=e=>{let t=yU.findIndex(e=>e.id===i),n=null;e.key===`ArrowLeft`?n=(t-1+yU.length)%yU.length:e.key===`ArrowRight`?n=(t+1)%yU.length:e.key===`Home`?n=0:e.key===`End`&&(n=yU.length-1),n!==null&&(e.preventDefault(),g(yU[n].id,!0))};return(0,Z.jsxs)(`section`,{className:`integrations-page`,children:[(0,Z.jsx)(`div`,{className:`page-head`,children:(0,Z.jsx)(`h2`,{children:r(`nav.connect`)})}),(0,Z.jsx)(`p`,{className:`page-sub`,children:r(`connectV2.subtitle`)}),n&&(0,Z.jsxs)(`section`,{className:`notice`,"aria-label":r(`connection.clients.title`),children:[(0,Z.jsx)(`strong`,{children:r(`connection.clients.title`)}),(0,Z.jsx)(`span`,{children:u.length>0?u.join(`, `):r(`connection.clients.none`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:f,onClick:()=>void m(),children:r(f?`connection.clients.syncing`:`connection.clients.sync`)})]}),(0,Z.jsx)(`div`,{className:`page-tabs connect-tabs`,role:`tablist`,"aria-label":r(`integrations.tabsLabel`),children:yU.map(e=>(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`button`,{ref:t=>{t?l.current.set(e.id,t):l.current.delete(e.id)},type:`button`,role:`tab`,id:SU(e.id),"aria-selected":i===e.id,"aria-controls":CU(e.id),tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>g(e.id,!0),onKeyDown:_,children:[e.id!==`overview`&&e.id!==`keys`&&(0,Z.jsx)(WR,{src:wU(e.id),label:r(e.labelKey),size:14}),r(e.labelKey)]}),e.id===`keys`&&(0,Z.jsx)(`span`,{className:`connect-tabs-divider`,role:`presentation`})]},e.id))}),yU.map(t=>{if(!o.has(t.id))return null;let n=i===t.id;return(0,Z.jsxs)(`div`,{role:`tabpanel`,id:CU(t.id),"aria-labelledby":SU(t.id),hidden:!n,children:[t.id===`overview`&&(0,Z.jsx)(UH,{apiBase:e,active:n}),t.id===`keys`&&(0,Z.jsx)(Bz,{apiBase:e,active:n}),t.id===`codex`&&(0,Z.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,Z.jsx)(`h3`,{id:`codex-integration-title`,children:r(`integrations.codex.title`)}),(0,Z.jsx)(`p`,{children:r(`integrations.codex.body`)}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>_n(`startup`),children:r(`integrations.codex.openService`)})]}),t.id===`grok`&&(0,Z.jsx)(YV,{apiBase:e,active:n}),t.id===`claude`&&(0,Z.jsx)(JB,{apiBase:e,active:n,embedded:!0}),t.id===`claudeDesktop`&&(0,Z.jsx)(`div`,{className:`claude-page claude-page--embedded`,children:(0,Z.jsx)(UV,{apiBase:e,active:n},e)}),t.id===`cursor`&&(0,Z.jsx)(tH,{apiBase:e,active:n}),bU.has(t.id)&&(t.id===`aside`?(0,Z.jsx)(oU,{apiBase:e,active:n}):t.id===`hermes`?(0,Z.jsx)(dU,{apiBase:e,active:n}):(0,Z.jsx)(QH,{apiBase:e,client:t.id,active:n})),t.id===`omo`&&(0,Z.jsx)(vU,{apiBase:e,active:n})]},t.id)})]})}var EU={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 DU({tone:e,children:t,className:n}){return(0,Z.jsxs)(`span`,{className:Y(`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`,EU[e],n),children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`size-1.5 shrink-0 rounded-full bg-current`}),(0,Z.jsx)(`span`,{className:`truncate`,children:t})]})}function OU({children:e}){return(0,Z.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 kU({title:e,meta:t,description:n,actions:r,icon:i,children:a,className:o,bodyClassName:s,id:c}){let l=(0,X.useId)(),u=c??l;return(0,Z.jsxs)(`section`,{"aria-labelledby":e?u:void 0,className:Y(`flex min-w-0 flex-col rounded-[12px] bg-surface p-1 ring-1 ring-line`,o),children:[(e||r)&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-2 px-4 pt-3 pb-3`,children:[i&&(0,Z.jsx)(AU,{children:i}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[e&&(0,Z.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,Z.jsx)(`span`,{className:`text-[12px] font-normal text-fg-subtle tabular-nums`,children:t})]}),n&&(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:n})]}),r&&(0,Z.jsx)(`div`,{className:`ml-auto flex flex-wrap items-center justify-end gap-1.5`,children:r})]}),a!=null&&a!==!1&&(0,Z.jsx)(`div`,{className:Y(`flex min-w-0 flex-col rounded-[8px] bg-bg ring-1 ring-line`,s),children:a})]})}function AU({children:e,className:t}){return(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`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 jU={ok:`text-success`,warn:`text-warning`,err:`text-danger`};function MU({tone:e,children:t,action:n,role:r=`status`,className:i}){let a=e===`ok`?ut:e===`info`?q:at;return(0,Z.jsxs)(`div`,{role:r,className:Y(`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,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`mt-px shrink-0 [&_svg]:size-4`,e===`info`?`text-fg-muted`:jU[e]),children:(0,Z.jsx)(a,{})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 [overflow-wrap:anywhere]`,children:t}),n&&(0,Z.jsx)(`div`,{className:`-my-1 flex shrink-0 flex-wrap items-center gap-1.5`,children:n})]})}function NU({label:e,onClick:t,children:n,disabled:r,tone:i=`neutral`,className:a}){return(0,Z.jsx)(`button`,{type:`button`,"aria-label":e,title:e,onClick:t,disabled:r,className:Y(`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 PU({copied:e,onCopy:t,className:n}){let r=c();return(0,Z.jsx)(NU,{label:r(e?`startup.copied`:`startup.copy`),onClick:t,className:n,children:(0,Z.jsx)(xc,{icon:e?Pc:Ec,size:16,strokeWidth:1.8,"aria-hidden":`true`,className:e?`text-success`:void 0})})}function FU({label:e,command:t,copied:n,onCopy:r}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[e&&(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 font-medium text-fg`,children:e}),(0,Z.jsx)(`code`,{className:`block min-w-0 font-mono text-[12.5px] leading-5 text-fg-muted [overflow-wrap:anywhere]`,children:t})]}),(0,Z.jsx)(PU,{copied:n,onCopy:r})]})}function IU({open:e,controls:t,name:n,onToggle:r}){let i=c()(`startupV2.about`,{name:n});return(0,Z.jsx)(`button`,{type:`button`,"aria-expanded":e,"aria-controls":t,"aria-label":i,title:i,onClick:r,className:Y(`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,Z.jsx)(q,{"aria-hidden":`true`})})}function LU({id:e,open:t,children:n,className:r}){return(0,Z.jsx)(`div`,{id:e,hidden:!t,className:Y(`rounded-[8px] bg-surface-2/60 px-3 py-2.5 text-[13px] leading-[19px] text-fg-muted`,r),children:n})}function RU({title:e,subtitle:t,actions:n}){return(0,Z.jsxs)(`header`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Z.jsx)(`h2`,{className:`m-0 text-title font-semibold tracking-[-0.025em] text-fg`,children:e}),t&&(0,Z.jsx)(`p`,{className:`m-0 max-w-[68ch] text-[14px] leading-5 text-fg-muted`,children:t})]}),n&&(0,Z.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:n})]})}function zU({icon:e,title:t,term:n,tag:r,badge:i,children:a,actions:o,option:s}){return(0,Z.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,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(AU,{children:e}),(0,Z.jsx)(DU,{tone:i.tone,children:i.label})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Z.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,Z.jsx)(OU,{children:r})]}),n&&(0,Z.jsx)(`span`,{className:`text-[12px] leading-4 text-fg-subtle`,children:n})]}),(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2 text-[13px] leading-5 text-fg-muted`,children:a}),o&&(0,Z.jsx)(`div`,{className:Y(`mt-auto flex flex-wrap items-center gap-2 pt-1`),children:o})]})}function BU(){let[e,t]=(0,X.useState)(!1);return{open:e,id:(0,X.useId)(),toggle:()=>t(e=>!e)}}function VU(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 HU={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},UU={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},WU={desktop:`startup.protection.desktop`,service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`},GU=e=>(0,Z.jsx)(xc,{icon:e,size:18,strokeWidth:1.8,"aria-hidden":`true`});function KU({failed:e,data:t}){let{t:n}=a(),r=BU(),i=e||t.status===`at-risk`,o=i?at:ut,s=[[`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(WU[t.protection])],[`startup.preference`,n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)]];return(0,Z.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,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`grid size-11 shrink-0 place-items-center rounded-full [&_svg]:size-[22px]`,i?`bg-warning-soft text-warning`:`bg-success-soft text-success`),children:(0,Z.jsx)(o,{})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,children:[(0,Z.jsx)(DU,{tone:i?`warn`:`ok`,className:`self-start`,children:n(e?`startup.status.atRisk`:HU[t.status])}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,Z.jsx)(`h3`,{className:`m-0 text-[20px] leading-7 font-semibold tracking-[-0.02em] text-fg`,children:n(e?`startup.error`:UU[t.status])}),(0,Z.jsx)(`span`,{className:`mt-0.5`,children:(0,Z.jsx)(IU,{open:r.open,controls:r.id,name:n(`startup.title`),onToggle:r.toggle})})]}),(0,Z.jsx)(`p`,{className:`m-0 max-w-[72ch] text-[14px] leading-[21px] text-fg-muted`,children:e?n(`startup.staleData`):t.status===`at-risk`?n(Xd(t)):n(`startup.safeDetail`)}),(0,Z.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:s.map(([e,t],r)=>(0,Z.jsxs)(X.Fragment,{children:[r>0&&(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`text-fg-subtle`,children:`·`}),(0,Z.jsxs)(`span`,{className:`inline-flex flex-wrap gap-x-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-fg-subtle`,children:n(e)}),(0,Z.jsx)(`span`,{className:`font-medium text-fg`,children:t})]})]},e))}),(0,Z.jsx)(LU,{id:r.id,open:r.open,className:`mt-1 max-w-[72ch]`,children:n(`startup.subtitle`)})]})]})}function qU({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:o,tray:s}){let{t:c}=a(),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=Jd(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+ +!!s,y=(e,t,n,i)=>(0,Z.jsx)(lp,{variant:`primary`,size:`sm`,"aria-label":`${t} - ${c(n?`startup.repair`:`startup.install`)}`,disabled:i,onClick:()=>o(e,n?{repair:!0}:void 0),children:c(r===e?n?`startup.repairing`:`startup.installing`:n?`startup.repair`:`startup.install`)});return(0,Z.jsxs)(`section`,{className:`startup-options flex min-w-0 flex-col gap-3`,"aria-labelledby":`startup-options-title`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-x-4 gap-y-1 px-1`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Z.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,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:c(`startupV2.optionsHint`)})]}),(0,Z.jsx)(`span`,{className:`font-mono text-[12px] text-fg-subtle`,title:c(`startup.details`),children:e.platform})]}),(0,Z.jsxs)(`div`,{className:Y(`grid gap-3 sm:grid-cols-2`,v===3&&`lg:grid-cols-3`),children:[e.desktop&&(0,Z.jsx)(zU,{option:`desktop`,icon:GU(Ac),title:c(`startup.protection.desktop`),badge:{tone:_?`ok`:`warn`,label:c(Yd(e.desktop,t))},children:(0,Z.jsx)(`p`,{className:`m-0`,children:c(_?`startup.desktopHint`:Xd(e))})}),(0,Z.jsx)(zU,{option:`service`,icon:GU(Nc),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,Z.jsx)(`p`,{className:`m-0`,children:c(`startup.serviceHint`)})}),(0,Z.jsx)(zU,{option:`shim`,icon:GU(wc),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,Z.jsx)(`p`,{className:`m-0`,children:c(u?`startup.shimActivationHint`:`startup.shimHint`)})}),s]}),i&&(0,Z.jsx)(MU,{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 JU({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:o}=a(),s=async()=>{await Nu({message:o(`startup.tray.uninstall`),tone:`danger`})&&i(`uninstall`)},c=!t&&!n&&e!==null,l=c?e.running&&!e.stale?{tone:`ok`,label:o(`startup.tray.running`)}:{tone:e.stale?`warn`:`neutral`,label:o(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)}:{tone:t?`neutral`:`warn`,label:o(t?`startup.tray.loading`:`startup.tray.unavailable`)},u=c?(0,Z.jsxs)(Z.Fragment,{children:[!e.installed&&!e.stale&&(0,Z.jsx)(lp,{variant:`primary`,size:`sm`,disabled:r,onClick:()=>i(`install`),children:o(`startup.tray.install`)}),e.installed&&!e.stale&&!e.running&&(0,Z.jsx)(lp,{variant:`primary`,size:`sm`,disabled:r,onClick:()=>i(`start`),children:o(`startup.tray.start`)}),e.running&&!e.stale&&(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,disabled:r,onClick:()=>i(`stop`),children:o(`startup.tray.stop`)}),(e.installed||e.stale)&&(0,Z.jsx)(lp,{variant:`ghost`,size:`sm`,className:`hover:bg-danger-soft hover:text-danger`,disabled:r,onClick:()=>{s()},children:o(`startup.tray.uninstall`)})]}):void 0;return(0,Z.jsxs)(zU,{option:`tray`,icon:GU(Tc),title:o(`startup.tray.title`),term:o(`startup.tray.login`),tag:o(`startupV2.optional`),badge:l,actions:u,children:[(0,Z.jsx)(`p`,{className:`m-0`,children:o(`startup.tray.hint`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[12px] leading-[18px] text-fg-subtle`,children:o(`startup.tray.notProtection`)}),(n||e?.stale)&&(0,Z.jsx)(MU,{tone:`warn`,role:`alert`,children:o(`startup.tray.error`)})]})}function YU({data:e,copied:t,onCopy:n}){let{t:r}=a(),i=Jd(e),o=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService,s=[...e.serviceSupported&&!i?[[`startup.command.service`,o]]:[],[`startup.command.shim`,e.commands.installShim],[`startup.command.native`,e.commands.restoreNative]];return(0,Z.jsx)(`section`,{className:`startup-recovery-panel rounded-[12px] bg-surface p-1 ring-1 ring-line`,"aria-label":r(`startup.recovery`),children:(0,Z.jsxs)(`details`,{className:`startup-recovery group`,open:e.status!==`protected`,children:[(0,Z.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,Z.jsx)(AU,{className:`size-8 rounded-[8px] [&_svg]:size-4`,children:(0,Z.jsx)(ve,{})}),(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,Z.jsx)(`span`,{className:`text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:r(`startup.recovery`)}),(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:r(i?`startup.protection.desktop`:`startupV2.recoveryMeta`)})]}),(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`text-fg-subtle transition-transform duration-200 group-open:rotate-90 [&_svg]:size-4`,children:(0,Z.jsx)(St,{})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 px-3 pt-1 pb-3`,children:[(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:r(i?Xd(e):`startup.recoveryHint`)}),(0,Z.jsx)(`div`,{className:`flex flex-col divide-y divide-line rounded-[8px] bg-bg ring-1 ring-line`,children:s.map(([e,i])=>(0,Z.jsx)(FU,{label:r(e),command:i,copied:t===i,onCopy:()=>n(i)},e))}),e.status===`at-risk`&&e.recommendedCommand&&!i&&(0,Z.jsx)(MU,{tone:`warn`,role:`alert`,children:r(`startup.recommended`,{cmd:e.recommendedCommand})})]})]})})}var XU=`ocx.startup.page.v1:`;function ZU(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function QU(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=ZU([`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 $U({apiBase:e,machineApiBase:t=e,connected:n=!1}){let{t:r}=a(),i=`${XU}${e}`,o=(0,X.useMemo)(()=>kd(i),[i]),s=`startup-page:${e}`,[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(()=>o?.tray??null),[f,p]=(0,X.useState)(()=>!o?.data),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(()=>o?.warning??null),[w,T]=(0,X.useState)(()=>o?.fix??null),[E,D]=(0,X.useState)(()=>!o?.data),O=(0,X.useRef)(!!o?.data),k=(0,X.useRef)(0),[A,j]=(0,X.useState)(null),[M,N]=(0,X.useState)(!1);(0,X.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,X.useEffect)(()=>()=>{k.current+=1},[e]);let F=(0,X.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=kd(i);Nd(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(!VU(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=QU(e.codexRuntime,r,s.platform);C(t.warning),T(t.fix),Nd(i,{data:s,warning:t.warning,fix:t.fix,tray:o});return}let c=kd(i);Nd(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=Fd(s,[e],F,{isEmpty:()=>!1,initialData:o?.data??void 0}),L=I.state,R=I.refresh,z=L.data??o?.data??null,B=L.refreshing,V=!!z?.diagnosticStale||L.showError;(0,X.useEffect)(()=>{if(!z?.diagnosticStale)return;let e=window.setTimeout(R,2e3);return()=>window.clearTimeout(e)},[z,R]);let H=async e=>{try{await navigator.clipboard.writeText(e),l(e),window.setTimeout(()=>l(t=>t===e?null:t),1600)}catch{l(null)}},U=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(!VU(r.status))throw Error(`invalid tray action status`);d(r.status),_(!1)}catch{d(null),_(!0)}finally{h(!1)}},W=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,Z.jsxs)(`div`,{className:`startup-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Z.jsx)(RU,{title:r(`startup.title`),actions:(0,Z.jsxs)(lp,{variant:`ghost`,size:`sm`,onClick:()=>R(),disabled:B,children:[(0,Z.jsx)(Mt,{}),` `,r(`startup.refresh`)]})}),n&&(0,Z.jsxs)(MU,{tone:A?.healthy?`ok`:`warn`,className:`startup-machine`,action:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,disabled:M,onClick:()=>void P(`repair`),children:r(`connection.machine.repairShim`)}),A?.installed&&(0,Z.jsx)(lp,{variant:`ghost`,size:`sm`,disabled:M,onClick:()=>void P(`uninstall`),children:r(`connection.machine.removeShim`)})]}),children:[(0,Z.jsx)(`strong`,{className:`font-semibold`,children:r(`connection.machine.title`)}),` `,(0,Z.jsx)(`span`,{className:`text-fg-muted`,children:A?.healthy?r(`connection.machine.shimHealthy`):r(`connection.machine.shimNeedsAttention`)})]}),L.showSkeleton&&!z?(0,Z.jsx)(NE,{label:r(`startup.loading`),rows:5}):L.kind===`failed-cold`?(0,Z.jsx)(MU,{tone:`err`,action:(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:()=>R(),children:r(`common.retry`)}),children:L.error instanceof Error?L.error.message:r(`startup.error`)}):z?(0,Z.jsxs)(Z.Fragment,{children:[L.showError&&(0,Z.jsx)(MU,{tone:`err`,children:r(`startup.error`)}),V&&(0,Z.jsx)(MU,{tone:`warn`,role:`alert`,children:r(`startup.staleData`)}),(E||S)&&(0,Z.jsx)(`div`,{className:Y(`startup-runtime-slot`,E&&!S&&`min-h-[60px]`),"aria-hidden":E&&!S?!0:void 0,children:S&&(0,Z.jsxs)(MU,{tone:`warn`,className:`startup-runtime-notice`,children:[(0,Z.jsx)(`p`,{className:`m-0`,children:S}),w&&(0,Z.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,Z.jsx)(`code`,{className:`min-w-0 flex-1 font-mono text-[12.5px] text-fg-muted [overflow-wrap:anywhere]`,children:w}),(0,Z.jsx)(PU,{copied:c===w,onCopy:()=>void H(w)})]})]})}),(0,Z.jsx)(KU,{failed:V,data:z}),(0,Z.jsx)(qU,{data:z,failed:V,loading:B,installBusy:v,installResult:b,onInstall:(e,t)=>{W(e,t)},tray:z.platform===`win32`?(0,Z.jsx)(JU,{tray:u,trayLoading:f,trayError:g,trayBusy:m,onTrayAction:e=>{U(e)}}):null}),(0,Z.jsx)(YU,{data:z,copied:c,onCopy:e=>{H(e)}})]}):null]})}function eW(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function tW(e){return`'${e.replace(/'/g,`''`)}'`}function nW(e,t){return{posix:`printf '%s\\n' ${eW(e)} | ocx remote-workspace pair ${eW(t)} --pairing-code-stdin --root "$PWD" && ocx remote-workspace agent`,powershell:`$pairingCode = ${tW(e)}; $pairingCode | ocx remote-workspace pair ${tW(t)} --pairing-code-stdin --root (Get-Location).Path; if ($LASTEXITCODE -eq 0) { ocx remote-workspace agent }`}}var rW=[`codex`,`claude`,`pi`],iW={codex:`Codex`,claude:`Claude Code`,pi:`Pi`},aW={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`},oW={status:`remote.event.status`,tool:`remote.event.tool`,error:`remote.event.error`},sW=8,cW=e=>e?e.type===`pane`?[e.sessionId]:[...cW(e.first),...cW(e.second)]:[],lW=e=>({type:`pane`,sessionId:e});function uW(e){if(e.type===`pane`)return 260;let t=uW(e.first),n=uW(e.second);return e.axis===`row`?t+sW+n:Math.max(t,n)}function dW(e,t){if(!e)return null;if(e.type===`pane`)return e.sessionId===t?null:e;let n=dW(e.first,t),r=dW(e.second,t);return n?r?n===e.first&&r===e.second?e:{...e,first:n,second:r}:n:r}function fW(e,t,n){return e.type===`pane`?e.sessionId===t?n:e:{...e,first:fW(e.first,t,n),second:fW(e.second,t,n)}}function pW(e,t,n){return e?cW(e).includes(t)?e:fW(e,cW(e).includes(n)?n:cW(e)[0],lW(t)):lW(t)}function mW(e,t,n,r){if(!e)return lW(t);let i=cW(e);if(t===n||!i.includes(n)||i.length>=4&&!i.includes(t))return e;let a=dW(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 fW(a,n,{type:`split`,id:`split-${l}`,axis:r===`left`||r===`right`?`row`:`column`,ratio:.5,first:lW(o?t:n),second:lW(o?n:t)})}function hW(e,t,n){return e.type===`pane`?e:e.id===t?{...e,ratio:Math.min(.8,Math.max(.2,n))}:{...e,first:hW(e.first,t,n),second:hW(e.second,t,n)}}function gW(e,t,n){let r=new Set(t),i=e;for(let t of cW(e))r.has(t)||(i=dW(i,t));return i??(n&&r.has(n)?lW(n):t.length?lW(t[t.length-1]):null)}function _W(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?lW(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 vW(e,t,n,r,i){let a=c(),[o,s]=(0,X.useState)({}),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)({}),[p,m]=(0,X.useState)({}),h=(0,X.useRef)(new Set),g=(0,X.useRef)(new Set),_=(0,X.useRef)(new Set),v=t.map(e=>{let t=l[e.id];return t?.status===`stopped`?{...e,status:`stopped`}:t&&(t.events.at(-1)?.sequence??0)>(e.events.at(-1)?.sequence??0)?t:e}),y=(e,t)=>s(n=>({...n,[e]:t})),b=(e,t)=>m(n=>({...n,[e]:t})),x=(e,t,n)=>f(r=>({...r,[e]:{...r[e],[t]:n}})),S=e=>!(!(o[e.id]??``).trim()||d[e.id]?.prompt||d[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:v,drafts:o,setDraft:y,pending:d,errors:p,canSend:S,send:async t=>{let n=t.id;if(!S(t)||g.current.has(n)||_.current.has(n))return;let r=o[n]??``;g.current.add(n),x(n,`prompt`,!0),b(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 zn(t,a(`remote.requestFailed`));if(!o)throw Error(a(`remote.requestFailed`));s(e=>e[n]===r?{...e,[n]:``}:e),h.current.has(n)||u(e=>({...e,[n]:o})),i()}catch(e){h.current.has(n)||(b(n,c!==void 0&&c>=400&&c<500?e instanceof Error?e.message:a(`remote.requestFailed`):a(`remote.submissionUnknown`)),i())}finally{g.current.delete(n),x(n,`prompt`,!1)}},stop:async t=>{let n=t.id;if(!(_.current.has(n)||t.status===`stopped`)){_.current.add(n),x(n,`stop`,!0);try{await zn(await fetch(`${e}/api/remote-workspace/sessions/${n}`,{method:`DELETE`}),a(`remote.requestFailed`)),h.current.add(n),u(e=>({...e,[n]:{...t,status:`stopped`}})),i()}catch(e){b(n,e instanceof Error?e.message:a(`remote.requestFailed`))}finally{_.current.delete(n),x(n,`stop`,!1)}}}}}var yW=`application/x-opencodex-session`,bW=[`left`,`right`,`up`,`down`],xW=e=>e.type===`split`?uW(e):0;function SW({node:e,renderPane:t,resize:n}){let r=c(),i=(0,X.useRef)(null),a=(0,X.useRef)(!1);if(e.type===`pane`)return t(e.sessionId);let o={"--split-ratio":e.ratio,"--split-min-width":uW(e),"--split-first-min":xW(e.first),"--split-second-min":xW(e.second)};return(0,Z.jsxs)(`div`,{ref:i,className:`remote-split-branch remote-split-branch--${e.axis}`,style:o,children:[(0,Z.jsx)(`div`,{className:`remote-split-child`,children:(0,Z.jsx)(SW,{node:e.first,renderPane:t,resize:n})}),(0,Z.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,Z.jsx)(`div`,{className:`remote-split-child`,children:(0,Z.jsx)(SW,{node:e.second,renderPane:t,resize:n})})]})}function CW({apiBase:e,sessions:t,devices:n,selectedSessionId:r,stale:i,refresh:a}){let o=c(),s=`ocx-remote-workspace-layout:${e}`,[l,u]=(0,X.useState)(()=>{try{return _W(localStorage.getItem(s))}catch{return null}}),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(r),x=(0,X.useRef)(null),S=vW(e,t,n,i,a),C=S.sessions.map(e=>e.id),w=gW(l,C,[...S.sessions].reverse().find(e=>e.status!==`stopped`)?.id??C.at(-1)),T=cW(w),E=T.includes(d)?d:T[0]??``;y===r?l!==w&&u(w):(b(r),r&&C.includes(r)&&(u(pW(w,r,E)),f(r))),(0,X.useEffect)(()=>{try{localStorage.setItem(s,JSON.stringify(w))}catch{}},[w,s]),(0,X.useEffect)(()=>{_&&[...x.current?.querySelectorAll(`[data-pane-heading]`)??[]].find(e=>e.dataset.paneHeading===_.id)?.focus()},[_]);let D=e=>{u(pW(w,e,E)),f(e)},O=(e,t,n)=>{if(!C.includes(e))return;let r=mW(w,e,t,n);u(r),cW(r).includes(e)&&f(e),m(null),g(null)},k=e=>{let t=dW(w,e),n=cW(t)[0]??``;u(t),f(n),v({id:n})},A=(e,t)=>{e.dataTransfer.setData(yW,t),e.dataTransfer.effectAllowed=`move`,m(t)},j=()=>{m(null),g(null)},M=(e,t)=>e!==t&&(T.includes(e)||T.length<4);return(0,Z.jsxs)(`section`,{ref:x,className:`remote-chats-workspace`,"aria-label":o(`remote.split.title`),children:[(0,Z.jsxs)(`div`,{className:`remote-chats-toolbar`,children:[(0,Z.jsx)(`h3`,{children:o(`remote.sessions`)}),(0,Z.jsx)(`p`,{children:o(`remote.split.hint`)})]}),(0,Z.jsxs)(`div`,{className:`remote-chats-layout`,children:[(0,Z.jsxs)(`aside`,{className:`remote-session-rail`,"aria-label":o(`remote.sessions`),children:[S.sessions.map(e=>(0,Z.jsxs)(`div`,{className:`remote-session-row${E===e.id?` is-active`:``}`,draggable:!0,onDragStart:t=>A(t,e.id),onDragEnd:j,children:[(0,Z.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,Z.jsx)(Xe,{}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsxs)(`strong`,{children:[iW[e.profile],` · `,e.rootLabel]}),(0,Z.jsxs)(`small`,{children:[e.deviceName,` · `,o(aW[e.status])]})]})]}),(0,Z.jsxs)(`div`,{className:`remote-session-split-actions`,children:[(0,Z.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,Z.jsx)(St,{})}),(0,Z.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,Z.jsx)(Je,{})})]})]},e.id)),T.length>=4?(0,Z.jsx)(`p`,{className:`remote-split-limit`,children:o(`remote.split.limit`)}):null]}),(0,Z.jsx)(`div`,{className:`remote-pane-surface`,children:w?(0,Z.jsx)(SW,{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,Z.jsxs)(`section`,{className:`remote-chat-pane remote-console-panel${e===E?` is-active`:``}`,"data-session-id":e,"aria-label":`${iW[t.profile]} · ${t.deviceName}/${t.rootLabel}`,onFocusCapture:()=>f(e),onPointerDown:()=>f(e),children:[(0,Z.jsxs)(`header`,{className:`remote-chat-pane-head`,children:[(0,Z.jsxs)(`div`,{tabIndex:-1,"data-pane-heading":e,className:`remote-chat-pane-name`,draggable:!0,onDragStart:t=>A(t,e),onDragEnd:j,children:[(0,Z.jsx)(Xe,{}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`strong`,{children:iW[t.profile]}),(0,Z.jsxs)(`small`,{children:[t.deviceName,`/`,t.rootLabel]})]})]}),(0,Z.jsx)(`span`,{className:`remote-status remote-status--${t.status}`,children:o(aW[t.status])}),(0,Z.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,Z.jsx)(We,{})})]}),(0,Z.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,Z.jsx)(`div`,{className:`remote-events`,"aria-live":`polite`,"aria-label":o(`remote.events`),children:t.events.length===0?(0,Z.jsx)(`p`,{className:`remote-empty`,children:o(`remote.noEvents`)}):t.events.map(e=>(0,Z.jsxs)(`div`,{className:`remote-event remote-event--${e.type}`,children:[(0,Z.jsx)(`span`,{children:e.type===`assistant`?iW[t.profile]:o(oW[e.type])}),(0,Z.jsx)(`p`,{children:e.text})]},e.sequence))}),t.status===`failed`&&t.resumable===!1?(0,Z.jsx)(Q,{tone:`err`,children:o(`remote.notResumable`)}):null,S.errors[e]?(0,Z.jsx)(Q,{tone:`err`,children:S.errors[e]}):null,(0,Z.jsxs)(`label`,{className:`remote-composer`,children:[(0,Z.jsx)(`span`,{className:`field-label`,children:o(`remote.prompt`)}),(0,Z.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,Z.jsxs)(`div`,{className:`remote-console-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!S.canSend(t),onClick:()=>void S.send(t),children:o(`remote.send`)}),(0,Z.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`)})]}),p&&M(p,e)?(0,Z.jsx)(`div`,{className:`remote-pane-drop-targets`,children:bW.map(t=>(0,Z.jsx)(`div`,{className:`remote-pane-drop remote-pane-drop--${t}${h?.id===e&&h.edge===t?` is-over`:``}`,onDragOver:n=>{n.preventDefault(),n.dataTransfer.dropEffect=`move`,g({id:e,edge:t})},onDrop:n=>{n.preventDefault();let r=n.dataTransfer.getData(yW);r===p?O(r,e,t):j()},children:o(`remote.split.${t}`)},t))}):null]},e)},resize:(e,t)=>u(hW(w,e,t))}):(0,Z.jsx)(`p`,{className:`remote-empty remote-empty--console`,children:o(`remote.noSessions`)})})]})]})}function wW(e){return e===`codex`||e===`claude`||e===`pi`}function TW(e){return e===`read-only`||e===`workspace`}async function EW(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function DW(e,t){return(0,Z.jsxs)(`label`,{className:`flex min-w-0 flex-col gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-[12px] leading-4 font-medium text-fg-muted`,children:e}),t]})}function OW({apiBase:e,hubOrigin:t}){let n=c(),r=dn(`remote-workspace:${e}`,[e],async t=>await zn(await fetch(`${e}/api/remote-workspace`,{signal:t,cache:`no-store`}),n(`remote.loadFailed`)),{pollMs:3e3,deadlineMs:1e4}),i=r.data,[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(`codex`),[f,p]=(0,X.useState)(`read-only`),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(null),[w,T]=(0,X.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=f===`workspace`&&(D?.capabilities.includes(`workspace.exec`)??!1),A=D&&!D.capabilities.includes(`workspace.exec`)?n(`remote.access.workspaceFilesOnly`):n(`remote.access.workspace`),j=rW.filter(e=>i?.runtimes?.[e]?.available),M=j.includes(u)?u:j[0]??u,N=i?.sessions??[],P=g&&!N.some(e=>e.id===g.id)?[...N,g]:N;g&&i?.sessions.some(e=>e.id===g.id)&&_(null);let F=!(!i||r.lastAttemptOk),I=(0,X.useMemo)(()=>v?nW(v.code,t):{posix:``,powershell:``},[v,t]),L=async(t,n,r)=>{let i=await zn(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`));y(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:f})},n(`remote.requestFailed`));_(e),h(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 Nu({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 EW(t)?e:null)};return!i&&!r.error?(0,Z.jsx)(MU,{tone:`info`,children:n(`remote.loading`)}):r.error&&!i?(0,Z.jsx)(MU,{tone:`err`,action:(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:()=>void r.refresh(),children:n(`common.retry`)}),children:n(`remote.loadFailed`)}):i?.available===!1?(0,Z.jsx)(MU,{tone:`err`,children:n(`remote.hubRequired`)}):(0,Z.jsxs)(`section`,{className:`remote-workspace-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Z.jsx)(RU,{title:n(`remote.title`),subtitle:n(`remote.subtitle`),actions:(0,Z.jsxs)(lp,{variant:`ghost`,size:`sm`,onClick:()=>void r.refresh(),disabled:r.refreshing,children:[(0,Z.jsx)(Mt,{}),` `,n(`remote.refresh`)]})}),F?(0,Z.jsx)(MU,{tone:`err`,children:n(`remote.loadFailed`)}):null,S?(0,Z.jsx)(MU,{tone:S.tone,children:S.text}):null,(0,Z.jsxs)(`div`,{className:`grid min-w-0 items-start gap-4 lg:grid-cols-[minmax(280px,0.85fr)_minmax(0,1.3fr)]`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,Z.jsx)(kU,{icon:(0,Z.jsx)(Fe,{}),title:n(`remote.addComputer`),description:n(`remote.addComputerHint`),children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(lp,{variant:`outline`,className:`self-start`,onClick:()=>void R(),disabled:b!==null,children:[(0,Z.jsx)(be,{}),` `,n(`remote.createPairing`)]}),v?(0,Z.jsxs)(`div`,{className:`remote-pairing-result flex flex-col gap-3 border-t border-line pt-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Z.jsx)(`span`,{className:`text-[12px] font-medium text-fg-muted`,children:n(`remote.pairingCode`)}),(0,Z.jsx)(`span`,{className:`font-mono text-[24px] leading-8 font-semibold tracking-[0.1em] text-fg`,children:v.code}),(0,Z.jsx)(`span`,{className:`text-[12px] text-fg-subtle`,children:n(`remote.pairingExpires`,{time:new Date(v.expiresAt).toLocaleTimeString()})})]}),[[`posix`,n(`remote.pairingCommandPosix`),I.posix],[`powershell`,n(`remote.pairingCommandWindows`),I.powershell]].map(([e,t,r])=>(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-[12px] font-medium text-fg-muted`,children:t}),(0,Z.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,Z.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,Z.jsx)(`code`,{children:r})}),(0,Z.jsx)(lp,{variant:`ghost`,size:`sm`,onClick:()=>void V(e,r),children:n(w===e?`remote.copied`:`remote.copyCommand`)})]})]},e))]}):null]})}),(0,Z.jsx)(kU,{title:n(`remote.devices`),meta:E.length,children:E.length===0?(0,Z.jsx)(`p`,{className:`m-0 px-4 py-6 text-center text-[13px] text-fg-muted`,children:n(`remote.noDevices`)}):(0,Z.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,Z.jsxs)(`li`,{className:Y(`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,Z.jsxs)(`button`,{type:`button`,"aria-pressed":t,onClick:()=>{o(e.id),l(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,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`size-2 shrink-0 rounded-full`,e.online?`bg-success`:`bg-fg-subtle`)}),(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-col`,children:[(0,Z.jsx)(`strong`,{className:`truncate text-[14px] font-semibold`,children:e.name}),(0,Z.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,Z.jsx)(`span`,{"aria-hidden":`true`,className:`ml-auto text-fg [&_svg]:size-4`,children:(0,Z.jsx)(ut,{})})]}),(0,Z.jsx)(NU,{label:n(`remote.revoke`),tone:`danger`,disabled:b!==null,onClick:()=>void B(e),children:(0,Z.jsx)(ge,{})})]},e.id)})})})]}),(0,Z.jsx)(kU,{icon:(0,Z.jsx)(ne,{}),title:n(`remote.newSession`),children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[DW(n(`remote.device`),(0,Z.jsx)($,{fullWidth:!0,value:D?.id??``,options:E.map(e=>({value:e.id,label:e.name})),onChange:e=>{o(e),l(E.find(t=>t.id===e)?.roots[0]?.id??``)},label:n(`remote.device`),disabled:E.length===0})),DW(n(`remote.folder`),(0,Z.jsx)($,{fullWidth:!0,value:O?.id??``,options:(D?.roots??[]).map(e=>({value:e.id,label:e.label})),onChange:l,label:n(`remote.folder`),disabled:!D})),DW(n(`remote.runtime`),(0,Z.jsx)($,{fullWidth:!0,value:M,options:rW.map(e=>({value:e,label:i?.runtimes?.[e]?.available?iW[e]:`${iW[e]} · ${n(`remote.unavailable`)}`})),onChange:e=>{wW(e)&&d(e)},label:n(`remote.runtime`)})),DW(n(`remote.access`),(0,Z.jsx)($,{fullWidth:!0,value:f,options:[{value:`read-only`,label:n(`remote.access.readOnly`)},{value:`workspace`,label:A}],onChange:e=>{TW(e)&&p(e)},label:n(`remote.access`)}))]}),D?(0,Z.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[[iW[M],n(`remote.runsOnHub`)],[D.name,n(f===`read-only`?`remote.runsReadOnly`:k?`remote.runsFilesCommands`:`remote.runsFilesOnly`)]].map(([e,t])=>(0,Z.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,Z.jsx)(`strong`,{className:`truncate text-[13px] font-semibold text-fg`,children:e}),t]},t))}):null,f===`workspace`&&!k&&D?(0,Z.jsx)(MU,{tone:`err`,children:n(`remote.execUnavailable`)}):null,!i?.runtimes?.[M]?.available&&i?.runtimes?.[M]?.reason?(0,Z.jsx)(`p`,{className:`m-0 text-[12px] leading-[18px] text-danger`,children:i.runtimes[M].reason}):null,(0,Z.jsxs)(lp,{variant:`primary`,className:`w-full`,onClick:()=>void z(),disabled:!D?.online||!O||!i?.runtimes?.[M]?.available||b!==null,children:[(0,Z.jsx)(ve,{}),` `,n(`remote.startSession`)]})]})})]}),(0,Z.jsx)(CW,{apiBase:e,sessions:P,devices:E,selectedSessionId:m,stale:F,refresh:r.refresh},e)]})}var kW=(0,Z.jsx)(xc,{icon:Oc,size:18,strokeWidth:1.8,"aria-hidden":`true`}),AW=(0,Z.jsx)(xc,{icon:Ac,size:18,strokeWidth:1.8,"aria-hidden":`true`});function jW({on:e,onToggle:t,disabled:n}){let r=c();return(0,Z.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 MW({on:e,onToggle:t,hint:n}){let r=c();return(0,Z.jsxs)(`div`,{className:`flex items-center gap-4 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-[15px] leading-6 font-semibold tracking-[-0.01em] text-fg`,children:[r(`link.switch`),(0,Z.jsx)(`span`,{className:Y(`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,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:n})]}),(0,Z.jsx)(jW,{on:e,onToggle:t})]})}function NW(e,t,n){return(0,Z.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,Z.jsx)(AU,{children:e}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,Z.jsx)(`span`,{className:`text-[14px] leading-5 font-semibold text-fg`,children:t}),(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:n})]})]})}function PW({onTurnOn:e}){let t=c();return(0,Z.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,Z.jsx)(MW,{on:!1,onToggle:e,hint:t(`link.switchOffHint`)}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-5 rounded-[8px] bg-bg p-5 ring-1 ring-line`,children:[(0,Z.jsxs)(`div`,{className:`flex max-w-[68ch] flex-col gap-1.5`,children:[(0,Z.jsx)(`h3`,{className:`m-0 text-[17px] leading-6 font-semibold tracking-[-0.015em] text-fg`,children:t(`startupV2.linkIntroTitle`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[14px] leading-[21px] text-fg-muted`,children:t(`startupV2.linkIntroBody`)})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col items-stretch gap-2 sm:flex-row sm:items-center`,children:[NW(kW,t(`link.role.home`),t(`link.role.homeHint`)),(0,Z.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,Z.jsx)(`span`,{className:`hidden h-px w-10 bg-line-strong sm:block`}),t(`startupV2.sshTunnel`),(0,Z.jsx)(`span`,{className:`hidden h-px w-10 bg-line-strong sm:block`})]}),NW(AW,t(`link.role.child`),t(`link.role.childHint`))]}),(0,Z.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,Z.jsx)(`span`,{className:`min-w-0 flex-1`,children:t(`link.setup.requirements`)}),(0,Z.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,Z.jsx)(dt,{"aria-hidden":`true`})]})]})]})]})}function FW({role:e,checked:t,disabled:n,tabIndex:r,onSelect:i,onKeyDown:a,buttonRef:o}){let s=c();return(0,Z.jsxs)(`button`,{ref:o,type:`button`,role:`radio`,tabIndex:r,"aria-checked":t,"aria-disabled":n,onClick:i,onKeyDown:a,className:Y(`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,Z.jsx)(AU,{children:e===`home`?kW:AW}),(0,Z.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsx)(`span`,{className:`text-[14px] leading-5 font-semibold text-fg`,children:s(e===`home`?`link.role.home`:`link.role.child`)}),(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:s(e===`home`?`link.role.homeHint`:`link.role.childHint`)})]}),(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`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,Z.jsx)(ut,{})})]})}var IW={connected:`bg-success`,reconnecting:`bg-warning`,connecting:`bg-warning`,failed:`bg-danger`,idle:`bg-fg-subtle`};function LW({state:e,children:t}){return(0,Z.jsxs)(`span`,{className:Y(`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,Z.jsx)(`span`,{"aria-hidden":`true`,className:Y(`size-2 shrink-0 rounded-full`,IW[e]??IW.idle)}),t]})}function RW({name:e}){let t=e.replace(/[^\p{L}\p{N}]/gu,``).slice(0,2).toUpperCase()||`?`;return(0,Z.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 zW({step:e}){let t=c(),n=[t(`startupV2.stepHost`),t(`startupV2.stepVerify`),t(`startupV2.stepConnect`)];return(0,Z.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,Z.jsxs)(`li`,{"aria-current":n===e?`step`:void 0,className:`flex items-center gap-2`,children:[n>0&&(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`h-px w-5 bg-line-strong`}),(0,Z.jsx)(`span`,{className:Y(`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,Z.jsx)(ut,{"aria-hidden":`true`}):n+1}),(0,Z.jsx)(`span`,{className:Y(n===e?`font-medium text-fg`:`text-fg-muted`),children:t})]},t))})}function BW(){window.location.reload()}var VW={connecting:`remoteLink.status.connecting`,connected:`remoteLink.status.connected`,reconnecting:`remoteLink.status.reconnecting`,failed:`remoteLink.status.failed`,idle:`remoteLink.status.idle`},HW={admission_failed:`remoteLink.error.admission_failed`,admission_timeout:`remoteLink.error.admission_timeout`,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_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`,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.generic`,link_remove_failed:`remoteLink.error.link_remove_failed`,link_unavailable:`remoteLink.error.link_unavailable`,listener_unavailable:`remoteLink.error.listener_unavailable`,probe_failed:`remoteLink.error.probe_failed`,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_port_failed:`remoteLink.error.remote_port_failed`,standalone_required:`remoteLink.error.standalone_required`,tailscale_session_refused:`remoteLink.error.tailscale_session_refused`,version_probe_failed:`remoteLink.error.version_probe_failed`},UW={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`},WW={pairing_required:`remoteLink.joinDenied.pairing_required`,standalone_required:`remoteLink.childDisabled`,join_port_mismatch:`remoteLink.error.join_port_mismatch`};function GW(e){return typeof e==`object`&&!!e}function KW(e){return typeof e==`string`&&e.length>0}function qW(e){if(!GW(e)||!Array.isArray(e.candidates))throw Error(`invalid candidates`);return e.candidates.map(e=>{if(!GW(e)||!KW(e.alias)||!KW(e.source))throw Error(`invalid candidate`);return{alias:e.alias,source:e.source}})}function JW(e){if(!GW(e)||!KW(e.alias)||!KW(e.fingerprint)||!KW(e.keyType))throw Error(`invalid probe`);return{alias:e.alias,fingerprint:e.fingerprint,keyType:e.keyType}}function YW(e){if(!GW(e)||!KW(e.alias)||!KW(e.fingerprint)||!KW(e.ocxVersion))throw Error(`invalid confirmation`);return{alias:e.alias,fingerprint:e.fingerprint,ocxVersion:e.ocxVersion}}function XW(e){return e instanceof RL&&e.code in HW?HW[e.code]:`remoteLink.error.generic`}function ZW(e){return{key:XW(e),hint:e instanceof RL?e.hint:null}}function QW({error:e}){let t=c();return(0,Z.jsxs)(MU,{tone:`err`,children:[(0,Z.jsx)(`span`,{className:`remote-link-error`,children:t(e.key)}),e.hint&&(0,Z.jsxs)(`span`,{className:`remote-link-hint mt-1 block text-[12px] text-fg-muted [overflow-wrap:anywhere]`,children:[t(`remoteLink.reason.generic`),` `,(0,Z.jsx)(`code`,{className:`font-mono`,children:e.hint})]})]})}function $W({apiBase:e,sessionReady:t,pairingRecoveryAvailable:n=!1,onRequestPairing:i,workspaceAvailable:a=!1,onOpenWorkspace:o,onChildReady:s=BW,restartWait:l}){let u=c(),[d,f]=(0,X.useState)(`off`),[p,m]=(0,X.useState)(`home`),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(`idle`),[T,E]=(0,X.useState)([]),[D,O]=(0,X.useState)(``),[k,j]=(0,X.useState)(null),[M,P]=(0,X.useState)(null),[F,I]=(0,X.useState)(!1),[L,R]=(0,X.useState)(null),[z,B]=(0,X.useState)(null),[V,H]=(0,X.useState)(null),[U,W]=(0,X.useState)(null),[ee,te]=(0,X.useState)(null),ne=(0,X.useRef)(null),G=(0,X.useRef)(null),K=(0,X.useRef)(null),re=(0,X.useRef)(null),q=(0,X.useRef)([]),ie=(0,X.useRef)(null),ae=(0,X.useRef)(0),oe=(0,X.useRef)(null),se=(0,X.useRef)(0),ce=(0,X.useRef)(null),le=(0,X.useRef)(!1),[ue,J]=(0,X.useState)(!1),de=n&&i&&(!t||y)?(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:i,children:u(`connection.pairing.title`)}):null,fe=(0,X.useCallback)(()=>{oe.current?.controller.abort();let e={controller:new AbortController,sequence:++se.current};return oe.current=e,e},[]),pe=(0,X.useCallback)(()=>{se.current+=1,oe.current?.controller.abort(),oe.current=null},[]),me=e=>oe.current?.sequence===e.sequence&&!e.controller.signal.aborted,he=(0,X.useCallback)(()=>{ae.current+=1,ie.current?.controller.abort(),ie.current=null},[]),_e=(0,X.useCallback)(async()=>{if(!t||document.visibilityState===`hidden`||le.current)return;ie.current?.controller.abort();let n=new AbortController,r=++ae.current;ie.current={controller:n,sequence:r};try{let t=GL(await qL(e,`/api/link/status`,{signal:n.signal}));if(n.signal.aborted||ae.current!==r)return;g(t),v(null),b(!1),V?f(`failed`):t.role===`child`?f(`connected`):t.links.length===0?f(e=>[`role-select`,`adding-child`,`confirming-host`,`applying`,`joining`,`restart-waiting`].includes(e)?e:`off`):t.links.some(e=>e.state===`failed`)?f(`failed`):t.links.some(e=>e.state===`reconnecting`)?f(`reconnecting`):t.links.some(e=>e.state===`connected`)&&f(`connected`)}catch(e){if(n.signal.aborted||ae.current!==r)return;v(XW(e)),b(e instanceof RL&&(e.status===401||e.status===403))}finally{ie.current?.sequence===r&&(ie.current=null)}},[e,V,t]),ve=(0,X.useEffectEvent)(()=>{_e()});(0,X.useEffect)(()=>{if(!t)return;Promise.resolve().then(ve);let e=window.setInterval(ve,5e3),n=()=>{document.visibilityState===`visible`?ve():he()};return document.addEventListener(`visibilitychange`,n),()=>{window.clearInterval(e),document.removeEventListener(`visibilitychange`,n),he()}},[he,t]),(0,X.useEffect)(()=>{if(d!==`restart-waiting`)return;let t=new AbortController;return eR(e,ce.current,t.signal,{...l,onSlow:()=>J(!0)}).then(e=>{e===`ready`&&s()}),()=>t.abort()},[e,s,l,d]),(0,X.useEffect)(()=>{if(!x){let e=G.current?.open;G.current?.close?.(),e&&ne.current?.focus();return}let e=G.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)},[x]),(0,X.useEffect)(()=>{let e=K.current;U?e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``)):e?.close?.()},[U]);let ye=()=>{pe(),S(!1),w(`idle`),E([]),j(null),P(null),I(!1),B(null),H(null),R(null),f(e=>[`failed`,`adding-child`,`confirming-host`,`applying`,`joining`].includes(e)?`adding-child`:e)},xe=r(),Se=xe&&h?.joinAvailable===!0,Ce=h?.joinDenied?WW[h.joinDenied]:`remoteLink.joinDenied.unavailable`,we=A(e).shared,Te=xe&&window.location.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(window.location.hostname)&&we.serverOrigin===window.location.origin,Ee=async()=>{let t=fe();w(`loading`),E([]),B(null),H(null),R(`candidates`),j(null),P(null),I(!1);try{let n=await qL(e,`/api/link/candidates`,{signal:t.controller.signal});if(!me(t))return;E(qW(n)),w(`ready`)}catch(e){if(!me(t))return;w(`failed`),B(ZW(e))}finally{me(t)&&R(null)}},De=async()=>{S(!0),f(`adding-child`),await Ee()},Oe=async(t=D.trim(),n=oe.current??fe())=>{let r=t.trim();if(r){C===`failed`&&w(`idle`),R(`probe`),B(null),j(null),P(null),I(!1),H(null),f(`adding-child`);try{let t=await qL(e,`/api/link/probe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal});if(!me(n))return;j(JW(t))}catch(e){if(!me(n))return;B(ZW(e)),H({phase:`probe`,alias:r}),f(`failed`)}finally{me(n)&&R(null)}}},ke=async()=>{if(!k||!F)return;let t=oe.current;if(t){R(`confirm`),B(null);try{let n=await qL(e,`/api/link/confirm-host`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:k.alias,fingerprint:k.fingerprint}),signal:t.controller.signal});if(!me(t))return;P(YW(n))}catch(e){if(!me(t))return;B(ZW(e))}finally{me(t)&&R(null)}}},Ae=async(t=oe.current)=>{let n=M;if(n&&t){R(`apply`),B(null),H(null),f(`applying`);try{if(await qL(e,`/api/link/apply`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:n.alias}),signal:t.controller.signal}),!me(t))return;ye(),_e()}catch(e){if(!me(t))return;B(ZW(e)),H({phase:`apply`,alias:n.alias}),f(`failed`)}finally{me(t)&&R(null)}}},je=async(t=M?.alias,n=oe.current??fe())=>{let r=t?.trim();if(r&&Se){R(`join`),B(null),H(null),f(`joining`);try{if(ce.current=(await JL(e,n.controller.signal))?.pid??null,!me(n)||(await qL(e,`/api/link/join`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal}),!me(n)))return;le.current=!0,he(),ye(),J(!1),f(`restart-waiting`)}catch(e){if(!me(n))return;B(ZW(e)),H({phase:`join`,alias:r}),f(`failed`)}finally{me(n)&&R(null)}}},Me=async()=>{let t=(h?.links??[]).filter(e=>e.direction===`hub-initiated`&&(e.state===`failed`||e.state===`reconnecting`));if(t.length===0)await _e();else{R(`reconnect`),B(null);try{let n=(await Promise.allSettled(t.map(t=>qL(e,`/api/link/${encodeURIComponent(t.id)}/reconnect`,{method:`POST`})))).find(e=>e.status===`rejected`);n&&B(ZW(n.reason))}finally{await _e(),R(null)}}},Ne=()=>{if(!V){Me();return}let e=fe();V.phase===`probe`?(O(V.alias),Oe(V.alias,e)):V.phase===`join`?je(V.alias,e):Ae(e)},Pe=()=>{W(null),te(null),window.setTimeout(()=>re.current?.focus(),0)},Ie=(e,t)=>{let n=t===`Home`?0:t===`End`?1:t===`ArrowRight`||t===`ArrowDown`||t===`ArrowLeft`||t===`ArrowUp`?(e+1)%2:e;(n!==1||Se)&&n!==e&&(q.current[n]?.focus(),m(n===0?`home`:`child`))},Le=async()=>{if(!U)return;let t=U;R(`remove`),te(null);try{await qL(e,`/api/link/${encodeURIComponent(t.row.id)}`,t.force?{method:`DELETE`,headers:{"content-type":`application/json`},body:JSON.stringify({force:!0})}:{method:`DELETE`}),Pe(),await _e()}catch(e){!t.force&&e instanceof RL&&e.code===`remote_disconnect_failed`?W({row:t.row,force:!0}):te(XW(e))}finally{R(null)}},Re=h?.links??[],ze=p===`home`&&(d===`adding-child`||d===`confirming-host`||d===`applying`),Be=h?.role===`home`||ze?`remoteLink.role.home`:h?.role===`child`?`remoteLink.role.child`:`remoteLink.role.standalone`,Ve=p===`child`&&!Se,He=(0,Z.jsxs)(lp,{variant:`ghost`,size:`sm`,onClick:()=>void _e(),disabled:L!==null,children:[(0,Z.jsx)(Mt,{}),u(`link.refresh`)]});if(!t)return(0,Z.jsxs)(`div`,{className:`remote-link-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Z.jsx)(RU,{title:u(`link.title`),subtitle:u(`link.subtitle`)}),(0,Z.jsx)(MU,{tone:`warn`,action:de,children:u(`link.sessionRequired`)})]});let Ue=p===`child`&&xe,Ge=d===`connected`||d===`reconnecting`||d===`failed`||d===`restart-waiting`||h?.role===`child`||Re.length>0||d===`adding-child`||d===`confirming-host`||d===`applying`||d===`joining`,Ke=!x&&(d===`reconnecting`||d===`failed`&&(V!==null&&z?.key!==`remoteLink.error.join_restart_failed`||Re.some(e=>e.state===`failed`))),qe=(e,t,n)=>{n&&[`ArrowRight`,`ArrowDown`,`ArrowLeft`,`ArrowUp`,`Home`,`End`].includes(e.key)&&(e.preventDefault(),Ie(t,e.key))};return(0,Z.jsxs)(`div`,{className:`remote-link-page flex min-w-0 flex-col gap-5 font-sans text-fg`,children:[(0,Z.jsx)(RU,{title:u(`link.title`),subtitle:u(`link.subtitle`),actions:He}),a&&(0,Z.jsxs)(MU,{tone:`info`,className:`remote-link-workspace-card`,action:(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:o??(()=>{window.location.hash=`remote-workspace`}),children:u(`remoteLink.workspaceMoved.open`)}),children:[(0,Z.jsx)(`strong`,{className:`font-semibold`,children:u(`remoteLink.workspaceMoved.title`)}),` `,(0,Z.jsx)(`span`,{className:`text-fg-muted`,children:u(`remoteLink.workspaceMoved.body`)})]}),_&&(0,Z.jsx)(MU,{tone:`err`,action:de,children:(0,Z.jsx)(`span`,{className:`remote-link-error`,children:u(_)})}),Re.length===0&&d===`off`&&(0,Z.jsx)(PW,{onTurnOn:()=>f(`role-select`)}),d===`role-select`&&(0,Z.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,Z.jsx)(MW,{on:!0,onToggle:()=>f(`off`),hint:u(`link.role.title`)}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4 rounded-[8px] bg-bg p-4 ring-1 ring-line`,children:[(0,Z.jsx)(`p`,{className:`m-0 max-w-[72ch] text-[13px] leading-5 text-fg-muted`,children:u(`link.role.hint`)}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,role:`radiogroup`,"aria-label":u(`link.role.title`),children:[(0,Z.jsx)(FW,{role:`home`,buttonRef:e=>{q.current[0]=e},tabIndex:p===`home`?0:-1,checked:p===`home`,onSelect:()=>m(`home`),onKeyDown:e=>qe(e,0,!0)}),(0,Z.jsx)(FW,{role:`child`,buttonRef:e=>{q.current[1]=e},tabIndex:Se&&p===`child`?0:-1,checked:p===`child`,disabled:!Se,onSelect:()=>{Se&&(m(`child`),De())},onKeyDown:e=>qe(e,1,Se)})]}),!xe&&(0,Z.jsx)(MU,{tone:`warn`,children:u(`remoteLink.childDisabled`)}),xe&&h!==null&&!h.joinAvailable&&(0,Z.jsx)(MU,{tone:`warn`,children:u(Ce)})]}),(0,Z.jsx)(`div`,{className:`flex justify-end px-3 py-2.5`,children:(0,Z.jsx)(lp,{variant:`primary`,"data-action":`continue`,disabled:Ve||h?.role===`child`,onClick:()=>void De(),children:u(p===`child`?`remoteLink.findHome.action`:`link.continue`)})})]}),d===`role-select`&&Te&&h?.joinAvailable===!1&&h.joinDenied===`pairing_required`&&(0,Z.jsx)(TR,{local:!0,target:we,onConnected:()=>{_e()}}),Ge&&(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsx)(`h3`,{id:`remote-link-list-title`,className:`m-0 text-[15px] leading-6 font-semibold tracking-[-0.01em]`,children:u(Ue?`remoteLink.findHome.title`:`link.children`)}),(0,Z.jsx)(`span`,{className:`text-[13px] leading-5 text-fg-muted`,children:u(d===`restart-waiting`?`remoteLink.restart.waiting`:Be)})]}),(0,Z.jsxs)(lp,{ref:ne,variant:`primary`,size:`sm`,onClick:()=>void De(),disabled:L!==null||d===`applying`||d===`joining`||d===`restart-waiting`||h?.role===`child`,children:[(0,Z.jsx)(be,{}),u(Ue?`remoteLink.findHome.action`:`link.addChild`)]})]}),(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col rounded-[8px] bg-bg ring-1 ring-line`,children:d===`restart-waiting`?(0,Z.jsxs)(`div`,{className:`remote-link-restart flex flex-col gap-1.5 px-4 py-4`,"aria-live":`polite`,children:[(0,Z.jsx)(`strong`,{className:`text-[14px] font-semibold`,children:u(`remoteLink.restart.title`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:u(`remoteLink.restart.body`)}),ue&&(0,Z.jsx)(MU,{tone:`warn`,className:`mt-1`,children:u(`remoteLink.restart.slow`)})]}):h?.role===`child`?(0,Z.jsx)(`ul`,{className:`remote-link-children m-0 list-none p-0`,"aria-live":`polite`,children:(0,Z.jsxs)(`li`,{className:`remote-link-row flex min-w-0 items-center gap-3 px-4 py-3`,children:[(0,Z.jsx)(RW,{name:h.child?.alias??u(`remoteLink.role.child`)}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-[14px] font-semibold`,children:h.child?.alias??u(`remoteLink.role.child`)}),h.child&&(0,Z.jsx)(LW,{state:h.child.state,children:u(VW[h.child.state])})]})]})}):Re.length>0?(0,Z.jsx)(`ul`,{className:`remote-link-children m-0 flex list-none flex-col divide-y divide-line p-0`,"aria-live":`polite`,children:Re.map(e=>(0,Z.jsxs)(`li`,{className:`remote-link-row flex min-w-0 items-center gap-3 px-4 py-3`,children:[(0,Z.jsx)(RW,{name:e.alias}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-[14px] font-semibold`,children:e.alias}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[12px] leading-5 text-fg-muted`,children:[(0,Z.jsx)(LW,{state:e.state,children:u(VW[e.state])}),(0,Z.jsx)(`span`,{children:e.direction===`hub-initiated`?u(`remoteLink.direction.hub`):u(`remoteLink.direction.client`)}),e.reason&&(0,Z.jsx)(`span`,{className:`remote-link-error text-danger`,children:e.reason in UW?u(UW[e.reason]):(0,Z.jsxs)(Z.Fragment,{children:[u(`remoteLink.reason.generic`),` `,(0,Z.jsx)(`code`,{className:`font-mono`,children:e.reason})]})})]})]}),(0,Z.jsxs)(lp,{variant:`ghost`,size:`sm`,className:`hover:bg-danger-soft hover:text-danger`,onClick:t=>{re.current=t.currentTarget,W({row:e,force:!1})},disabled:L!==null,children:[(0,Z.jsx)(ge,{}),u(`link.disconnect`)]})]},e.id))}):(0,Z.jsx)(`p`,{className:`m-0 px-4 py-6 text-center text-[13px] text-fg-muted`,children:u(Ue?`remoteLink.findHome.empty`:`link.noChildren`)})}),(Ke||d===`joining`||!x&&z)&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-3 py-2.5`,children:[Ke&&(0,Z.jsxs)(`div`,{className:`remote-link-status-message flex items-center justify-between gap-3`,"aria-live":`polite`,children:[(0,Z.jsx)(LW,{state:d===`failed`?`failed`:`reconnecting`,children:u(VW[d===`failed`?`failed`:`reconnecting`])}),(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,onClick:Ne,disabled:L!==null,children:u(`link.retry`)})]}),d===`joining`&&(0,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,"aria-live":`polite`,children:u(`remoteLink.joining`)}),!x&&z&&(0,Z.jsx)(QW,{error:z})]})]}),(h?.role===`child`||Re.length>0)&&(0,Z.jsx)(ld,{apiBase:e,section:`devices`,readOnly:h?.role===`child`}),(0,Z.jsxs)(`dialog`,{ref:G,"aria-labelledby":`remote-link-sheet-title`,onCancel:e=>{e.preventDefault(),ye()},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,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-[10px] bg-bg ring-1 ring-line`,children:[(0,Z.jsxs)(`header`,{className:`flex flex-col gap-3 border-b border-line px-5 pt-4 pb-3.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsx)(`h3`,{id:`remote-link-sheet-title`,className:`m-0 text-[16px] leading-6 font-semibold tracking-[-0.015em]`,children:u(Ue?`remoteLink.findHome.title`:`link.sheetTitle`)}),(0,Z.jsx)(NU,{label:u(`link.close`),onClick:ye,children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(zW,{step:M?2:+!!k})]}),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col gap-5 overflow-y-auto px-5 py-4`,children:[p===`home`&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 text-[13px] leading-5 text-fg-muted`,children:[(0,Z.jsx)(`p`,{className:`m-0`,children:u(`link.setup.relationship`)}),(0,Z.jsx)(`p`,{className:`m-0`,children:u(`link.setup.requirements`)})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsx)(`h4`,{className:`m-0 text-[13px] leading-5 font-semibold`,children:u(Ue?`remoteLink.findHome.body`:`link.candidates`)}),C===`loading`&&(0,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,role:`status`,children:u(`link.loading`)}),C===`failed`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:u(`link.discoveryFailed`)}),x&&z&&(0,Z.jsx)(QW,{error:z})]}),C===`ready`&&(T.length>0?(0,Z.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:T.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>O(e.alias),"aria-pressed":D===e.alias,className:Y(`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`,D===e.alias&&`bg-raised ring-2 ring-fg`),children:[(0,Z.jsx)(`span`,{className:`truncate font-mono text-[13px] text-fg`,children:e.alias}),(0,Z.jsx)(`small`,{className:`shrink-0 text-[12px] text-fg-subtle`,children:e.source})]},`${e.source}:${e.alias}`))}):(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 text-[13px] leading-5 text-fg-muted`,children:[(0,Z.jsx)(`p`,{className:`m-0`,children:u(`link.noCandidates`)}),(0,Z.jsx)(`p`,{className:`m-0`,children:u(p===`home`?`link.setup.emptyHome`:`link.setup.emptyLocal`)}),(0,Z.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,Z.jsx)(`code`,{children:`Host devbox
|
|
57
|
+
HostName devbox.example.com
|
|
58
|
+
User you
|
|
59
|
+
IdentityFile ~/.ssh/id_ed25519`})})]})),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,Z.jsx)(`a`,{href:`https://opencodex.me/guides/remote-link/`,target:`_blank`,rel:`noopener noreferrer`,className:`text-[13px] font-medium text-highlight hover:underline`,children:u(`link.setup.guide`)}),(0,Z.jsxs)(lp,{variant:`ghost`,size:`sm`,onClick:()=>void Ee(),disabled:L!==null,children:[(0,Z.jsx)(Mt,{}),u(C===`failed`?`link.retry`:`link.rescan`)]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-[13px] leading-5 font-semibold`,htmlFor:`remote-link-alias`,children:u(`link.alias`)}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`input`,{id:`remote-link-alias`,"aria-describedby":`remote-link-alias-help`,className:`input min-w-0 flex-1 font-mono`,spellCheck:!1,value:D,onChange:e=>O(e.target.value),placeholder:u(`link.aliasPlaceholder`),autoComplete:`off`}),(0,Z.jsxs)(lp,{variant:`outline`,onClick:()=>void Oe(),disabled:!D.trim()||L!==null,children:[(0,Z.jsx)(Fe,{}),u(L===`probe`?`link.probing`:`link.probe`)]})]}),(0,Z.jsx)(`p`,{id:`remote-link-alias-help`,className:`m-0 text-[12px] leading-[18px] text-fg-subtle`,children:u(`link.aliasRequired`)})]}),k&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-[10px] bg-surface p-4 ring-1 ring-line`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsxs)(`span`,{className:`text-[13px] font-semibold`,children:[u(`link.hostFingerprint`),` `,(0,Z.jsx)(`span`,{className:`font-normal text-fg-subtle`,children:k.keyType})]}),(0,Z.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,Z.jsx)(`code`,{children:k.fingerprint})})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-[13px]`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:F,onChange:e=>I(e.target.checked)}),` `,u(`link.confirmFingerprint`)]}),(0,Z.jsx)(lp,{variant:`primary`,className:`self-start`,onClick:()=>void ke(),disabled:!F||L!==null,children:u(L===`confirm`?`link.confirming`:`link.confirm`)})]}),M&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-[10px] bg-surface p-4 ring-1 ring-line`,children:[(0,Z.jsx)(`p`,{className:`m-0 text-[13px] text-fg-muted`,children:u(`link.ocxVersion`,{version:M.ocxVersion})}),Ue&&(0,Z.jsx)(MU,{tone:`warn`,children:u(`remoteLink.findHome.notice`)}),(0,Z.jsx)(lp,{variant:`primary`,className:`self-start`,onClick:()=>void(Ue?je():Ae()),disabled:L!==null||p===`child`&&!Se,children:u(Ue?L===`join`?`remoteLink.joining`:`remoteLink.findHome.connect`:L===`apply`?`link.applying`:`link.apply`)})]}),x&&C!==`failed`&&z&&(0,Z.jsx)(QW,{error:z}),V&&z?.key!==`remoteLink.error.join_restart_failed`&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[V.phase===`probe`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`m-0 text-[13px] leading-5 text-fg-muted`,children:u(`link.probeHelp`)}),(0,Z.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,Z.jsx)(`code`,{children:`ssh -o BatchMode=yes <alias> true`})})]}),(0,Z.jsx)(lp,{variant:`outline`,size:`sm`,className:`self-start`,onClick:Ne,disabled:L!==null,children:u(`link.retry`)})]})]})]}),(0,Z.jsx)(`footer`,{className:`flex shrink-0 justify-end gap-2 px-2 py-2`,children:(0,Z.jsx)(lp,{variant:`ghost`,onClick:ye,children:u(`link.cancel`)})})]}),(0,Z.jsx)(`dialog`,{ref:K,"aria-labelledby":`remote-link-confirm-title`,onCancel:e=>{e.preventDefault(),Pe()},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:U&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-[10px] bg-bg px-5 py-4 ring-1 ring-line`,children:[(0,Z.jsx)(`h3`,{id:`remote-link-confirm-title`,className:`m-0 text-[16px] leading-6 font-semibold tracking-[-0.015em]`,children:U.force?u(`remoteLink.forceRemove.title`,{alias:U.row.alias}):u(`link.disconnect`)}),(0,Z.jsx)(`p`,{className:`m-0 text-[14px] leading-[21px] text-fg-muted`,children:U.force?(0,Z.jsx)(N,{k:`remoteLink.forceRemove.body`,cmd:`ocx disconnect`,vars:{alias:U.row.alias}}):u(`link.disconnectConfirm`,{alias:U.row.alias})}),ee&&(0,Z.jsx)(`p`,{className:`remote-link-error m-0 text-[13px] text-danger`,role:`alert`,children:u(ee)})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 px-2 py-2`,children:[(0,Z.jsx)(lp,{variant:`ghost`,"data-action":`cancel`,onClick:Pe,children:u(`link.cancel`)}),(0,Z.jsx)(lp,{variant:`danger`,"data-action":`confirm`,onClick:()=>void Le(),disabled:L===`remove`,children:U.force?u(`remoteLink.forceRemove.confirm`):u(`link.disconnect`)})]})]})})]})}var eG=`meta-muse`,tG=`meta-muse:rate-limit-observation`,nG=6912e5;function rG(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 iG(e,t,n=Date.now()){if(!e||typeof e!=`object`||Array.isArray(e))return null;let r=e;if(r.provider!==eG||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>nG?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 aG(e){let t=e[eG];if(t?.source!==tG)return;let n=ct(t)?.customWindows?.[0]?.resetAt;return typeof n==`number`&&Number.isFinite(n)?n:void 0}function oG(e,t=Date.now()){let n=aG(e);if(n===void 0||n>t)return e;let{[eG]:r,...i}=e;return i}async function sG(e,t,n,r=fetch){if(e[eG])return e;try{let[i,a]=await Promise.all([r(`${t}/api/providers`,{signal:n}),r(`${t}/api/oauth/accounts?provider=${eG}`,{signal:n})]);if(!i.ok||!a.ok)return e;let o=await i.json();if(!Array.isArray(o)||!o.some(e=>e?.name===eG&&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(`${eG}\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=${eG}&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===eG&&t.accountLogLabel===u&&typeof t.timestamp==`number`&&Number.isFinite(t.timestamp)&&t.timestamp>=m&&(p=t,m=t.timestamp)}let h=iG(p,u);return h?{...e,[eG]:h}:e}catch{return e}}function cG(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 lG=6e4,uG=7,dG=8,fG=.8;function pG(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 mG(e,t){return e.labelKey?t(e.labelKey):e.label??e.id}function hG(e,t){return e===`critical`?t(`quotaSummary.critical`):e===`warn`?t(`quotaSummary.warn`):``}function gG(e){try{return e.matches(`:focus-visible`)}catch{return!0}}function _G(e,t,n){(0,X.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(dG,o-a-dG),c=Math.min(Math.max(i.left,dG),s);r.style.setProperty(`--qs-pop-top`,String(Math.round(i.bottom+uG))),r.style.setProperty(`--qs-pop-left`,String(Math.round(c))),r.style.setProperty(`--qs-pop-gap`,String(Math.round(i.bottom+uG)-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 vG({row:e,t,locale:n}){let[r,i]=(0,X.useState)(Date.now);(0,X.useEffect)(()=>{if(e.provider!==`meta-muse`||e.headline.resetAt===void 0)return;let t=window.setInterval(()=>i(Date.now()),1e3);return()=>window.clearInterval(t)},[e.provider,e.headline.resetAt]);let[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),p=(0,X.useRef)(null),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(``),_=(0,X.useId)(),v=!d&&(a||s||l),y=(0,X.useCallback)(()=>{o(!1),c(!1),u(!1)},[]);(0,X.useEffect)(()=>{if(!v)return;let e=e=>{p.current&&!p.current.contains(e.target)&&u(!1)},t=e=>{if(e.key===`Escape`){let e=h.current?.contains(document.activeElement);y(),e&&(m.current?.focus(),f(!0))}};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[v,y]),_G(v,m,h);let b=e=>{e.pointerType!==`touch`&&o(!0)},x=e=>{e.pointerType!==`touch`&&o(!1),f(!1)},S=t=>{if(t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;t.preventDefault();let n=g.current===`touch`;g.current=``,n&&!v?u(!0):(y(),n||f(!0),BC(e.provider))},{headline:C}=e,w=hG(e.severity,t);return(0,Z.jsxs)(`li`,{ref:p,className:`quota-summary-item quota-summary-item--${e.severity}`,onPointerEnter:b,onPointerLeave:x,onFocus:e=>{gG(e.target)&&(f(!1),c(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||c(!1)},children:[(0,Z.jsxs)(`a`,{ref:m,href:`#${FC(e.provider)}`,className:`quota-summary-chip${v?` quota-summary-chip--open`:``}`,"aria-expanded":v,"aria-controls":v?_:void 0,"aria-describedby":v?`${_}-table`:void 0,onPointerDown:e=>{g.current=e.pointerType},onClick:S,children:[(0,Z.jsx)(`span`,{className:`quota-summary-name`,children:e.label}),(0,Z.jsx)(`span`,{className:`quota-summary-pct`,children:_t(C.percent)}),e.provider===`meta-muse`&&C.resetAt!==void 0&&(0,Z.jsx)(`span`,{className:`quota-summary-name`,title:im(C.resetAt,t,n),children:rG(C.resetAt,r)}),w&&(0,Z.jsx)(`span`,{className:`quota-summary-flag`,"aria-hidden":`true`,children:`!`}),w&&(0,Z.jsx)(`span`,{className:`sr-only`,children:w}),(0,Z.jsx)(`span`,{className:`sr-only`,children:t(`quotaSummary.openAccounts`)})]}),v&&(0,Z.jsxs)(`div`,{ref:h,id:_,className:`quota-summary-popover`,role:`group`,"aria-label":e.label,children:[(0,Z.jsxs)(`div`,{className:`quota-summary-popover-head`,children:[(0,Z.jsx)(`strong`,{children:e.label}),w&&(0,Z.jsx)(`span`,{className:`quota-summary-badge quota-summary-badge--${e.severity}`,children:w})]}),(0,Z.jsx)(`table`,{id:`${_}-table`,className:`quota-summary-table`,children:(0,Z.jsx)(`tbody`,{children:e.windows.map(e=>(0,Z.jsxs)(`tr`,{className:`quota-summary-row--${e.severity}`,children:[(0,Z.jsx)(`th`,{scope:`row`,children:mG(e,t)}),(0,Z.jsx)(`td`,{className:`quota-summary-row-pct`,children:_t(e.percent)}),(0,Z.jsx)(`td`,{className:`quota-summary-row-reset`,children:e.resetAt===void 0?`-`:im(e.resetAt,t,n)})]},e.id))})}),(0,Z.jsxs)(`div`,{className:`quota-summary-popover-foot`,children:[e.updatedAt!==void 0&&(0,Z.jsx)(`span`,{children:t(e.observed?`quotaSummary.observedAt`:`quotaSummary.dataAt`,{time:pG(e.updatedAt,n)})}),(0,Z.jsx)(`a`,{href:`#${FC(e.provider)}`,className:`quota-summary-popover-link`,onPointerDown:e=>{g.current=e.pointerType},onClick:S,children:t(`quotaSummary.openAccounts`)})]})]})]})}var yG={overflow:!1,atStart:!0,atEnd:!0};function bG({rows:e,t,locale:n}){let r=(0,X.useRef)(null),[i,a]=(0,X.useState)(yG),o=(0,X.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}:yG;a(e=>e.overflow===n.overflow&&e.atStart===n.atStart&&e.atEnd===n.atEnd?e:n)},[]),s=e.map(e=>`${e.provider}:${e.label}:${_t(e.headline.percent)}:${e.severity}`).join(`|`);(0,X.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*fG,80),behavior:i?`auto`:`smooth`})};return(0,Z.jsxs)(`div`,{className:`quota-summary-scroller${i.overflow?` quota-summary-scroller--overflow`:``}`,children:[i.overflow&&(0,Z.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,Z.jsx)(`span`,{"aria-hidden":`true`,children:`«`})}),(0,Z.jsx)(`ul`,{ref:r,className:`quota-summary-list`,onScroll:o,children:e.map(e=>(0,Z.jsx)(vG,{row:e,t,locale:n},e.provider))}),i.overflow&&(0,Z.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,Z.jsx)(`span`,{"aria-hidden":`true`,children:`»`})})]})}function xG({apiBase:e}){let{t,locale:n}=a(),r=(0,X.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 sG(De(r?.reports),e,t);return{fetchedAt:Date.now(),reports:i}},[e]),i=Fd(`ocx.quota-summary.provider-quotas.v1:${e}`,[e],r,{isEmpty:e=>Object.keys(e.reports).length===0,pollMs:lG,pauseWhenHidden:!0}),o=i.data,[s,c]=(0,X.useState)(Date.now),l=o?aG(o.reports):void 0;if((0,X.useEffect)(()=>{if(l===void 0||s>=l)return;let e=window.setTimeout(()=>c(Date.now()),Math.max(0,l-Date.now()));return()=>window.clearTimeout(e)},[l,s]),!o)return null;let u=oG(o.reports,s),d=ft(u,e=>Ge(e,t));if(d.length===0)return null;let f=!i.lastAttemptOk;return(0,Z.jsxs)(`section`,{className:`quota-summary-bar`,"aria-label":t(`quotaSummary.aria`),ref:cG,children:[(0,Z.jsx)(bG,{rows:d,t,locale:n}),(0,Z.jsx)(`span`,{className:`quota-summary-updated${f?` quota-summary-updated--stale`:``}`,title:f?t(`quotaSummary.refreshFailed`):void 0,children:t(`quotaSummary.updated`,{time:pG(o.fetchedAt,n)})}),(0,Z.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,children:f?t(`quotaSummary.refreshFailed`):``})]})}var SG=3e5,CG=6e5,wG=`https://github.com/lidge-jun/opencodex`;async function TG(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function EG({apiBase:e,onOpenUpdate:t,onOpenTerminalCommand:n,version:r}){let i=c(),[a,o]=(0,X.useState)(!1),[s,l]=(0,X.useState)(null),u=dn(`sidebar-star:${e}`,[e],t=>TG(`${e}/api/github/star`,t),{pollMs:SG}),d=Vd(e),f=dn(`sidebar-update-badge:`+d,[d],e=>TG(d,e),{pollMs:Rd()?6e4:CG}),p=u.data?.state??null,m=s!==null&&s.basedOn===p?s.state:p??`not-starred`,h=u.data?.url??wG,g=m===`starred`,_=f.data,v=_?.updateAvailable===!0,y=_?.latestVersion??null,b=()=>window.open(h,`_blank`,`noopener,noreferrer`),x=async()=>{if(!(g||a)){if(m===`unauthenticated`)b();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){l({state:`starred`,basedOn:p});return}n?.state&&l({state:n.state,basedOn:p}),b()}catch{b()}finally{o(!1),u.refresh()}}}},S=i(g?`sidebar.starred`:m===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),C=v&&y?i(`sidebar.updateAvailable`,{version:y}):Rd()?i(`sidebar.desktopUpdate`):i(`sidebar.checkUpdate`);return(0,Z.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Z.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:h,target:`_blank`,rel:`noreferrer`,children:[(0,Z.jsx)(qe,{}),` `,i(`common.github`)]}),r,(0,Z.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb${g?` sidebar-orb--starred`:``}`,onClick:()=>{x()},disabled:a||g,"aria-label":S,"aria-pressed":g,title:S,children:(0,Z.jsx)(Ve,{"aria-hidden":`true`,...g?{fill:`currentColor`}:{}})}),(0,Z.jsxs)(`button`,{type:`button`,className:`sidebar-orb${v?` sidebar-orb--update`:``}`,onClick:t,"aria-label":C,title:C,children:[(0,Z.jsx)(mt,{"aria-hidden":`true`}),v&&(0,Z.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]}),Rd()&&(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:n,"aria-label":i(`sidebar.terminalCommand`),title:i(`sidebar.terminalCommand`),children:(0,Z.jsx)(ve,{"aria-hidden":`true`})})]})]})}var DG=`ocx-desktop-star-onboarding`,OG=`https://github.com/lidge-jun/opencodex`,kG=1200;function AG(){try{return window.localStorage.getItem(DG)!==null}catch{return!0}}function jG(){try{window.localStorage.setItem(DG,`seen`)}catch{}}function MG(e){window.location.assign(e)}function NG({apiBase:e,enabled:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(AG);(0,X.useEffect)(()=>{if(!t||i||!Rd())return;let n=new AbortController,o=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`?(jG(),a(!0)):r(e))})},kG);return()=>{window.clearTimeout(o),n.abort()}},[e,t,i]);let o=(0,X.useCallback)(()=>{jG(),a(!0)},[]);return i||!t||!n?null:(0,Z.jsx)(PG,{apiBase:e,status:n,onClose:o})}function PG({apiBase:e,status:t,onClose:n}){let r=c(),i=(0,X.useId)(),a=(0,X.useId)(),o=(0,X.useRef)(null),[s,l]=(0,X.useState)(`prompt`),u=t.url??OG,d=t.state===`not-starred`;(0,X.useEffect)(()=>{let e=o.current;e&&!e.open&&e.showModal()},[]);let f=(0,X.useCallback)(e=>{e.preventDefault(),s!==`starring`&&n()},[n,s]),p=()=>{MG(u),n()},m=async()=>{l(`starring`);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`});if((t.ok?await t.json():null)?.ok===!0){pn(`sidebar-star:${e}`,{state:`starred`,url:u}),l(`thanks`);return}}catch{}l(`failed`)},h=s===`thanks`,g=s===`failed`;return(0,Z.jsxs)(`dialog`,{ref:o,"aria-labelledby":i,"aria-describedby":a,className:`modal-overlay star-onboarding-overlay`,onCancel:f,children:[(0,Z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>{s!==`starring`&&n()}}),(0,Z.jsxs)(`div`,{className:`modal-card star-onboarding`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`span`,{className:`star-onboarding-mark${h?` star-onboarding-mark--done`:``}`,"aria-hidden":`true`,children:(0,Z.jsx)(Ve,{...h?{fill:`currentColor`}:{}})}),(0,Z.jsx)(`h3`,{id:i,className:`star-onboarding-title`,children:r(h?`onboarding.star.thanks`:`onboarding.star.title`)}),(0,Z.jsx)(`p`,{id:a,className:`star-onboarding-body`,children:r(h?`onboarding.star.thanksBody`:g?`onboarding.star.failed`:`onboarding.star.body`)}),h?(0,Z.jsx)(`div`,{className:`star-onboarding-actions`,children:(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:n,autoFocus:!0,children:r(`onboarding.star.done`)})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`star-onboarding-actions`,children:[d&&!g?(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:s===`starring`,onClick:()=>{m()},autoFocus:!0,children:[(0,Z.jsx)(Ve,{"aria-hidden":`true`}),r(s===`starring`?`onboarding.star.starring`:`onboarding.star.cta`)]}):(0,Z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,autoFocus:!0,children:[(0,Z.jsx)(qe,{"aria-hidden":`true`}),r(g?`onboarding.star.openPage`:`onboarding.star.cta`)]}),(0,Z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:s===`starring`,onClick:n,children:r(`onboarding.star.later`)})]}),(0,Z.jsxs)(`p`,{className:`star-onboarding-hint`,children:[r(d&&!g?`onboarding.star.ghHint`:`onboarding.star.browserHint`),d&&!g&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`button`,{type:`button`,className:`star-onboarding-link`,disabled:s===`starring`,onClick:p,children:r(`onboarding.star.openPage`)})]})]})]})]})]})}var FG=`ocx-ui`;function IG(e){try{localStorage.setItem(FG,e)}catch{}window.location.assign(e===`classic`?`/classic/`:`/`)}var LG=[{tier:`daily`,tkey:`shellV2.tierDaily`},{tier:`advanced`,tkey:`shellV2.tierAdvanced`}],RG=[{id:`home`,tier:`daily`,tkey:`shellV2.navHome`,Icon:At,pages:[`home`,`startup`]},{id:`connect`,tier:`daily`,tkey:`nav.connect`,Icon:K,pages:[`integrations`,`setup`],embedded:[`claude`]},{id:`providers`,tier:`daily`,tkey:`nav.providers`,Icon:me,pages:[`providers`]},{id:`models`,tier:`daily`,tkey:`nav.models`,Icon:Ze,pages:[`models`]},{id:`accounts`,tier:`daily`,tkey:`shellV2.navAccounts`,Icon:et,pages:[`codex-set`]},{id:`subagents`,tier:`daily`,tkey:`nav.subagents`,Icon:yt,pages:[`subagents`]},{id:`usage-logs`,tier:`daily`,tkey:`nav.usageLogs`,Icon:vt,pages:[`usage`,`logs`,`storage`]},{id:`remote`,tier:`daily`,tkey:`nav.remote`,Icon:ne,pages:[`remote`,`remote-workspace`]},{id:`proxy`,tier:`advanced`,tkey:`shellV2.pageProxyDetails`,Icon:fe,pages:[`dashboard`]},{id:`advisor`,tier:`advanced`,tkey:`nav.advisor`,Icon:Ve,pages:[`advisor`]},{id:`advanced`,tier:`advanced`,tkey:`shellV2.pageAllSettings`,Icon:se,pages:[`advanced`]}];function zG(e){return RG.find(t=>t.pages.includes(e)||t.embedded?.includes(e))??null}function BG(e,t){return e.pages.filter(e=>e!==`remote-workspace`||t.remoteWorkspaceAvailable)}function VG(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function HG(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 UG(e,t){switch(e){case`desktop-mac`:return`⌘${t}`;case`desktop`:return`Ctrl+${t}`;case`browser-mac`:return`⌥${t}`;default:return`Alt+${t}`}}function WG(e){return e===`desktop-mac`||e===`browser-mac`?`⌘K`:`Ctrl+K`}function GG(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 KG(e){return e===`desktop-mac`?`⌘,`:`Ctrl+,`}var qG=`ocx-nav-advanced-open`,JG=`advanced`;function YG(){try{return localStorage.getItem(qG)===`1`}catch{return!1}}function XG({activeGroupId:e,pageLabel:t,pageAvailable:n,onNavigate:r,onReveal:i,desktopShell:a,t:o}){let s=(0,X.useMemo)(()=>HG(a),[a]),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(YG),g=(0,X.useRef)(null),_=(0,X.useRef)(null),v=(0,X.useRef)(null),y=(0,X.useRef)(null),b=(0,X.useRef)(!1),x=(0,X.useId)();(0,X.useEffect)(()=>{try{localStorage.setItem(qG,m?`1`:`0`)}catch{}},[m]);let S=(0,X.useMemo)(()=>RG.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,X.useMemo)(()=>C?S.filter(e=>e.haystack.includes(C)):[],[S,C]),T=(0,X.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,X.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,X.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,X.useCallback)(e=>{l(``),p(0),d(!1),e&&requestAnimationFrame(()=>{let e=b.current?_.current:y.current;e?.isConnected?e.focus():_.current?.focus()})},[]);(0,X.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,X.useCallback)(e=>{E(!1),r(e)},[E,r]),O=(0,X.useMemo)(()=>RG.filter(e=>e.tier===`daily`),[]);(0,X.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&&!VG(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||!GG(s,e)||s.startsWith(`browser`)&&VG(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=WG(s),N=(t,n)=>{let{id:i,tkey:a,Icon:s}=t,c=e===i,l=o(a);return(0,Z.jsx)(`div`,{className:`nav-entry`,children:(0,Z.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,Z.jsx)(s,{}),` `,(0,Z.jsx)(`span`,{className:`nav-item-label`,children:l}),n&&(0,Z.jsx)(`kbd`,{className:`nav-kbd`,"aria-hidden":`true`,children:n})]})},i)};return(0,Z.jsx)(Z.Fragment,{children:LG.map(({tier:t,tkey:n})=>{let r=RG.filter(e=>e.tier===t);if(t===`daily`)return(0,Z.jsxs)(`div`,{className:`nav-tier`,"data-tier":t,children:[u?(0,Z.jsxs)(`div`,{ref:v,role:`dialog`,"aria-modal":`true`,"aria-label":j,onKeyDown:k,children:[(0,Z.jsxs)(`div`,{className:`nav-search`,children:[(0,Z.jsx)(ze,{"aria-hidden":`true`}),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`nav-search-close`,onClick:()=>E(!0),"aria-label":o(`common.close`),title:o(`common.close`),children:(0,Z.jsx)(We,{})})]}),C&&w.length===0&&(0,Z.jsx)(`div`,{className:`nav-search-empty`,role:`status`,children:o(`shellV2.navSearchEmpty`)}),(0,Z.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,Z.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,Z.jsx)(n,{}),` `,(0,Z.jsx)(`span`,{className:`nav-item-label`,children:e.label}),e.context&&(0,Z.jsx)(`span`,{className:`nav-search-context`,children:e.context})]},e.page)})})]}):(0,Z.jsxs)(`div`,{className:`nav-tier-head`,children:[(0,Z.jsx)(`div`,{className:`nav-tier-label`,"aria-hidden":`true`,children:o(n)}),(0,Z.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,Z.jsx)(ze,{"aria-hidden":`true`}),(0,Z.jsx)(`kbd`,{className:`nav-kbd nav-kbd--search`,"aria-hidden":`true`,children:M})]})]}),!C&&r.map((e,t)=>N(e,t<9?UG(s,String(t+1)):null))]},t);if(C)return null;if(t!==JG)return(0,Z.jsxs)(`div`,{className:`nav-tier`,"data-tier":t,children:[(0,Z.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,Z.jsxs)(`div`,{className:`nav-tier nav-tier--folding${m?` is-open`:``}`,"data-tier":t,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`nav-tier-toggle`,"aria-expanded":m,onClick:()=>h(e=>!e),children:[(0,Z.jsx)(`span`,{className:`nav-tier-label`,children:o(n)}),(0,Z.jsx)(St,{"aria-hidden":`true`,className:`nav-tier-chevron`})]}),i.map(e=>N(e,a&&e.id===`advanced`?KG(s):null))]},t)})})}function ZG({items:e,currentPage:t,onNavigate:n,ariaLabel:r,onFocusOrphaned:i}){let a=(0,X.useRef)(null),o=(0,X.useRef)(null),s=(0,X.useRef)(i);(0,X.useLayoutEffect)(()=>{s.current=i}),(0,X.useLayoutEffect)(()=>{let e=a.current;return()=>{e&&e.contains(e.ownerDocument.activeElement)&&s.current?.()}},[]),(0,X.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,Z.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,Z.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))})}var QG=[`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 $G(){try{for(let e of QG)localStorage.removeItem(e)}catch{}}function eK(){let[e,t]=(0,X.useState)(mC);(0,X.useEffect)(()=>{$G()},[]);let n=(0,X.useCallback)(e=>{let n=TC(e);n.replaceTo&&gn(n.replaceTo),t(n.page)},[]);return(0,X.useEffect)(()=>{let e=()=>{n(mn(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,X.useEffect)(()=>{let n=TC(mn(window.location.hash));n.replaceTo&&gn(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{_n(n?`${e}/${n}`:e),t(e)}}}var tK=15e3,nK=3e3;function rK(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 iK(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 aK(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=tK,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=nK}=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 iK(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:rK(u,l.status,i)}:d?{status:`accepted`}:{status:`unknown`,message:o()}}function oK(e,t){return t==null&&e!==null}var sK=`ocx-desktop-zoom`,cK=.5,lK=.1;function uK(e){return e===`macos`||e===`linux`}function dK(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,cK),3)*100)/100:1}function fK(e,t){return t===`reset`?1:dK(e+(t===`in`?lK:-.1))}function pK(e){return Math.round(e*100)}function mK(e=typeof localStorage>`u`?void 0:localStorage){try{let t=e?.getItem(sK);return t==null?1:dK(Number(t))}catch{return 1}}function hK(e,t=typeof localStorage>`u`?void 0:localStorage){try{t?.setItem(sK,String(e))}catch{}}function gK(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 _K(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 vK(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 yK=`ocx-sidebar-collapsed`;function bK(e=typeof localStorage>`u`?void 0:localStorage){try{return e?.getItem(yK)===`1`}catch{return!1}}function xK(e){try{localStorage.setItem(yK,e?`1`:`0`)}catch{}}function SK(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function CK({shortcut:e=!1}={}){let[t,n]=(0,X.useState)(bK),r=(0,X.useCallback)(()=>n(e=>!e),[]);return(0,X.useEffect)(()=>{xK(t)},[t]),(0,X.useEffect)(()=>{if(!e)return;let t=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||(e.key===`b`||e.key===`B`)&&(SK(e.target)||(e.preventDefault(),r()))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[r,e]),{collapsed:t,toggle:r}}function wK({managed:e}){let[t,n]=(0,X.useState)(mK),r=(0,X.useCallback)(e=>n(t=>fK(t,e)),[]),i=(0,X.useRef)(0);return(0,X.useEffect)(()=>{e&&(vK(t),hK(t))},[e,t]),(0,X.useEffect)(()=>{if(!e)return;let t=Hd(),n=e=>{let n=gK(e,t);n&&(e.preventDefault(),e.stopImmediatePropagation(),r(n))},a=e=>{if(!e.ctrlKey)return;e.preventDefault(),e.stopImmediatePropagation();let t=_K(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:pK(t),canZoomIn:t<3,canZoomOut:t>cK,step:r}}function TK({percent:e,canZoomIn:t,canZoomOut:n,onStep:r}){let i=c();return(0,Z.jsxs)(`div`,{className:`zoom-control`,role:`group`,"aria-label":i(`zoom.label`),title:i(`zoom.label`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!n,onClick:()=>r(`out`),"aria-label":i(`zoom.out`),title:i(`zoom.out`),children:(0,Z.jsx)(lt,{"aria-hidden":!0})}),(0,Z.jsxs)(`button`,{type:`button`,className:`zoom-control__value`,onClick:()=>r(`reset`),"aria-label":i(`zoom.reset`),title:i(`zoom.reset`),children:[e,`%`]}),(0,Z.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!t,onClick:()=>r(`in`),"aria-label":i(`zoom.in`),title:i(`zoom.in`),children:(0,Z.jsx)(be,{"aria-hidden":!0})})]})}var EK=[{mode:`light`,tkey:`theme.light`,Icon:J},{mode:`dark`,tkey:`theme.dark`,Icon:st},{mode:`system`,tkey:`theme.system`,Icon:ne}];function DK({theme:e,onChange:t}){let n=c(),r=Math.max(0,EK.findIndex(t=>t.mode===e)),i=EK[r],a=EK[(r+1)%EK.length],o=n(`shellV2.themeCycle`,{mode:n(i.tkey),next:n(a.tkey)});return(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-theme-toggle`,"data-mode":e,onClick:()=>t(a.mode),"aria-label":o,title:o,children:(0,Z.jsx)(i.Icon,{"aria-hidden":`true`})})}var OK=14,kK=26,AK=.3,jK=.82,MK={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)`},NK=e=>e>=jK?`stop`:e>=AK?`restart`:`rest`;function PK({restartLabel:e,stopLabel:t,hint:n,restarting:r,settled:i=!1,stopping:a,onRestart:o,onStop:s,onPreview:c}){let[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),p=(0,X.useRef)(null),m=(0,X.useRef)(!1),h=(0,X.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`:NK(d),x=()=>{_||(u(!0),Promise.resolve(s()).finally(()=>u(!1)))},S=()=>{_||r||o()},C=e=>{let t=NK(e);t===`stop`?x():t===`restart`&&S()};return(0,Z.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/kK));f(r),g(NK(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:Y(`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,Z.jsx)(`span`,{className:Y(`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,Z.jsx)(`span`,{className:`pointer-events-none absolute left-[21px] h-px w-[3px] bg-line-strong`,style:{top:7+e*OK},"aria-hidden":!0},e)),(0,Z.jsx)(`span`,{"aria-hidden":!0,className:Y(`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*OK}px)`,transition:d===null?`transform ${MK[b]}, background-color 150ms, box-shadow 200ms`:`background-color 150ms`}})]})}function FK({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=LK(d),_=r&&!u,v=u?a:d?s:t,y=u||d,[b,x]=(0,X.useState)(null),S=y||b===null?null:b===`hover`?l.hover:b===`rest`?l.cancel:l[b];return(0,Z.jsxs)(`div`,{className:Y(`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,Z.jsx)(`span`,{className:Y(`ocx-sweep`,b===`restart`&&`ocx-sweep-loop`),"aria-hidden":!0}),(0,Z.jsxs)(`span`,{className:Y(`relative flex min-w-0 flex-1 items-center gap-[9px]`,u?`ocx-halt`:b===`stop`&&`ocx-tremble ocx-dim`),children:[(0,Z.jsx)(`span`,{className:`grid size-4 shrink-0 place-items-center`,"aria-hidden":!0,children:(0,Z.jsx)(`span`,{className:Y(`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,Z.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-baseline gap-1.5 text-[13px] leading-5`,children:[(0,Z.jsx)(`span`,{className:`shrink-0 font-medium text-fg`,children:e}),(0,Z.jsx)(`span`,{className:`sr-only`,children:v}),(0,Z.jsx)(`span`,{className:Y(`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,Z.jsx)(`span`,{className:`ocx-brake`,children:v}):y?v:n??t})]}):(0,Z.jsx)(`span`,{"aria-hidden":!0,className:Y(`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,Z.jsx)(IK,{onClick:m.onClick,disabled:m.busy,label:m.busy?m.busyLabel:m.label,title:m.label,children:(0,Z.jsx)(We,{})}),(0,Z.jsx)(PK,{restartLabel:d?s:o,stopLabel:u?a:i,hint:c,restarting:d,settled:g,stopping:u,onRestart:p,onStop:f,onPreview:x})]})}function IK({onClick:e,disabled:t,label:n,title:r,children:i}){return(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:t,"aria-label":n,title:r,className:Y(`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 LK(e,t=1600){let[n,r]=(0,X.useState)(!1),i=(0,X.useRef)(e);return(0,X.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 RK(e){try{window.__TAURI__?.core?.invoke?.(e).catch(()=>{})}catch{}}var zK=`a, button, input, select, textarea, summary, [role='button'], [role='link'], [contenteditable]`;function BK(e){return e instanceof Element&&e.closest(zK)!==null}function VK(){return{onMouseDown:e=>{e.button!==0||BK(e.target)||RK(`plugin:window|start_dragging`)},onDoubleClick:e=>{BK(e.target)||RK(`plugin:window|toggle_maximize`)}}}function HK(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 UK({collapsed:e,onToggle:t,brand:n}){let r=c()(e?`nav.expandSidebar`:`nav.collapseSidebar`);return(0,Z.jsxs)(`div`,{className:`sidebar-top`,...VK(),children:[n,(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-collapse`,onClick:t,"aria-expanded":!e,"aria-controls":`app-sidebar`,"aria-label":r,title:r,children:(0,Z.jsx)(Se,{})})]})}function WK({children:e}){return(0,Z.jsx)(`div`,{className:`main-top`,...VK(),children:e})}var GK=y({RemoteWorkspaceRoute:()=>XK,default:()=>tq}),KK={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`},qK=``,JK=A(qK);w(JK),b();var YK=`ocx-theme`;function XK({available:e,apiBase:t,hubOrigin:n,onOpenRemoteLink:r}){let i=c();return e?(0,Z.jsx)(OW,{apiBase:t,hubOrigin:n}):(0,Z.jsxs)(`section`,{className:`panel`,children:[(0,Z.jsx)(`h2`,{children:i(`nav.remoteWorkspace`)}),(0,Z.jsxs)(Q,{tone:`warn`,children:[i(`link.workspaceUnavailable`),` `,(0,Z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:r,children:i(`nav.remote`)})]})]})}function ZK(e){if(!e||typeof e!=`object`||!(`version`in e))return null;let t=e.version;return typeof t==`string`&&t.length>0?t:null}function QK(e){let t=e&&typeof e==`object`?e.uptime:void 0;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function $K(){let e=localStorage.getItem(YK);return e===`light`||e===`dark`?e:`system`}function eq(){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 tq(){let{page:e,navigateToPage:t}=eK(),[r,o]=(0,X.useState)(Yk);(0,X.useEffect)(()=>{let e=()=>o(Yk());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[s,l]=(0,X.useState)($K),{locale:u,setLocale:p}=a(),m=c(),[g,_]=(0,X.useState)(JK),[v,y]=(0,X.useState)(()=>!i()),[b,S]=(0,X.useState)(null),[C,T]=(0,X.useState)(()=>D(`shared`)),[k,A]=(0,X.useState)(0),[j,M]=(0,X.useState)(!1),[N,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(!1),[R,H]=(0,X.useState)(null),[U,ee]=(0,X.useState)(0),te=(0,X.useCallback)((e,t)=>{H({tone:t,text:e}),ee(e=>e+1)},[]);(0,X.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!D(`shared`)&&T(!1)},t=e=>{e.detail?.plane===`shared`&&D(`shared`)&&T(!0)};window.addEventListener(P,e),window.addEventListener(x,t);let n=e=>{e.detail?.plane===`shared`&&A(e=>e+1)};return window.addEventListener(O,n),()=>{window.removeEventListener(P,e),window.removeEventListener(x,t),window.removeEventListener(O,n)}},[]),(0,X.useEffect)(()=>{let e=new AbortController;return V(qK,e.signal).then(async t=>{w(t),_(t),t.connected&&!D(`shared`)&&await z(`shared`,e.signal),!e.signal.aborted&&(T(D(`shared`)),S(null),y(!0))}).catch(t=>{e.signal.aborted||(S(t instanceof h?`client-state-changed`:`unavailable`),y(!0))}),()=>e.abort()},[]);let ne=n(`machine`,g),G=n(`shared`,g);(0,X.useEffect)(()=>{if(!C)return;let e=new AbortController;return fetch(`${G}/api/remote-workspace`,{signal:e.signal,cache:`no-store`}).then(e=>e.ok?e.json():Promise.reject(Error(`unavailable`))).then(t=>{e.signal.aborted||F(t.available===!0)}).catch(()=>{e.signal.aborted||F(!1)}),()=>e.abort()},[e,C,G]);let K=C&&N,re=zG(e),q=re?BG(re,{remoteWorkspaceAvailable:K}):[],ie=e===`claude`?`integrations`:e,ae=e===`remote`&&f()===`hub`,oe=ae&&j,[se,ce]=(0,X.useState)(!1),le=Rd(),{collapsed:ue,toggle:J}=CK({shortcut:le}),de=le&&Hd()===`macos`,fe=le&&uK(Hd()),pe=wK({managed:fe}),me=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(de&&me.current)return HK(me.current)},[de]);let he=(0,X.useRef)(null),ge=(0,X.useCallback)(()=>{ue&&J(),typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 760px)`).matches&&ce(!0)},[ue,J]),_e=e=>{t(e),ce(!1)},ve=e=>m(KK[e]),ye=e=>e!==`remote-workspace`||K,be=(0,X.useRef)(null),xe=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=()=>ce(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,X.useEffect)(()=>{if(!Rd())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;qd(r)&&(e.preventDefault(),window.location.assign(r))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[]),(0,X.useEffect)(()=>{let e=document.documentElement;s===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(YK)):(e.setAttribute(`data-theme`,s),localStorage.setItem(YK,s))},[s]),(0,X.useEffect)(()=>{if(R?.tone!==`ok`)return;let e=window.setTimeout(()=>H(null),4500);return()=>window.clearTimeout(e)},[R,U]);let Se=dn(`app-healthz:${ne}`,[ne,v],async e=>{let t=await fetch(`${ne}/healthz`,{signal:e});if(!t.ok)return null;let n=await t.json();return{version:ZK(n),uptime:QK(n)}},{pollMs:3e4,enabled:v}),Ce=(0,Z.jsx)(DK,{theme:s,onChange:l}),we=Se.data?.version??`2.98.0-preview.20261107`,Te=oK(Se.data,Se.error),De=Te?Se.data?.uptime??null:null,Oe=De===null?void 0:m(`shellV2.uptimeValue`,{h:String(Math.floor(De/3600)),m:String(Math.floor(De%3600/60))}),[ke,Ae]=(0,X.useState)(!1);(0,X.useEffect)(()=>{if(!se)return;let e=e=>{e.key===`Escape`&&ce(!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}},[se]),(0,X.useEffect)(()=>{if(se){xe.current=!0;let e=setTimeout(()=>{be.current?.contains(document.activeElement)||be.current?.focus()},200);return()=>clearTimeout(e)}xe.current&&(xe.current=!1,he.current?.focus())},[se]),(0,X.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&ce(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[Me,Pe]=(0,X.useState)(0),{restarting:Fe,restart:Ie}=nT(G,{onSettled:()=>Pe(e=>e+1),report:te}),Le=async()=>{if(!await Nu({message:m(g.connected?`connection.disconnectConfirm`:`dash.stopConfirm`),confirmLabel:m(g.connected?`connection.disconnect`:`dash.stop`),tone:`danger`}))return;Ae(!0);let e=await aK(ne,{formatFailure:e=>m(`dash.stopFailed`,{status:String(e)}),formatStillRunning:()=>m(`dash.stopStillRunning`),formatUnknown:()=>m(`dash.stopUnknown`),mode:g.connected?`client`:`standalone`});e.status!==`accepted`&&(Ae(!1),te(e.message,e.status===`rejected`?`err`:`warn`))},Re=async()=>{if(I)return;L(!0);let e=await B(`shared`);L(!1),e?T(!1):te(m(E(`shared`)?`connection.forgetDeviceFailed`:`connection.sessionLogoutFailed`),`err`)},ze=E(`shared`),Be=m(ze?`connection.forgetDevice`:`connection.sessionLogout`),Ve=(0,Z.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{t(`home`),ce(!1)},"aria-label":m(`nav.goHome`),title:m(`nav.goHome`),...e===`home`?{"aria-current":`page`}:{},children:[(0,Z.jsx)(bt,{className:`ui-v2 brand-logo-v2 h-[24px] w-[27px]`,label:m(`app.logoAria`)}),(0,Z.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Z.jsxs)(`span`,{className:`ver`,title:we,children:[`v`,we]})]}),He=(0,Z.jsxs)(`button`,{type:`button`,className:`brand brand-home brand--strip`,onClick:()=>t(`home`),"aria-label":m(`nav.goHome`),title:m(`nav.goHome`),...e===`home`?{"aria-current":`page`}:{},children:[(0,Z.jsx)(bt,{className:`ui-v2 brand-logo-v2 h-[22px] w-[25px]`,label:m(`app.logoAria`)}),(0,Z.jsx)(`span`,{className:`name`,children:`opencodex`})]}),Ue=v&&e!==`startup`&&(!g.connected||C)&&(0,Z.jsx)(FE,{pageName:m(`quotaSummary.aria`),title:m(`errorBoundary.title`),message:m(`errorBoundary.message`),detailsLabel:m(`errorBoundary.details`),reloadLabel:m(`errorBoundary.reload`),children:(0,Z.jsx)(xG,{apiBase:G})},G);return(0,Z.jsxs)(`div`,{ref:me,className:`app${le?` app--desktop`:``}${de?` app--macos`:``}${ue?` app--nav-collapsed`:``}`,children:[(0,Z.jsx)(NG,{apiBase:G,enabled:v&&!g.connected}),R&&(0,Z.jsx)(An,{tone:R.tone,onDismiss:()=>H(null),dismissLabel:m(`common.close`),children:R.text}),(0,Z.jsxs)(`header`,{className:`mobile-topbar`,inert:se,...le?VK():{},children:[(0,Z.jsx)(`button`,{ref:he,type:`button`,className:`menu-toggle`,onClick:()=>ce(e=>!e),"aria-expanded":se,"aria-controls":`app-sidebar`,"aria-label":m(se?`nav.closeMenu`:`nav.openMenu`),title:m(se?`nav.closeMenu`:`nav.openMenu`),children:(0,Z.jsx)(Ee,{})}),Ve,(0,Z.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(g.connected||ze)&&C&&(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Re()},disabled:I,"aria-label":I?m(`connection.sessionLoggingOut`):Be,title:Be,children:(0,Z.jsx)(We,{})}),(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:Le,disabled:ke,"aria-label":m(g.connected?`connection.disconnect`:`dash.stop`),title:m(g.connected?`connection.disconnect`:`dash.stop`),children:(0,Z.jsx)(je,{})}),(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ie()},disabled:Fe,"aria-label":m(`dash.codexRestart`),title:m(`dash.codexRestart`),children:(0,Z.jsx)(Mt,{})})]})]}),se&&(0,Z.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>ce(!1),"aria-hidden":`true`}),(0,Z.jsx)(UK,{collapsed:ue,onToggle:J,brand:He}),(0,Z.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${se?` open`:``}`,ref:be,tabIndex:-1,children:[(0,Z.jsxs)(`div`,{className:`drawer-head`,children:[Ve,(0,Z.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>ce(!1),"aria-label":m(`nav.closeMenu`),title:m(`nav.closeMenu`),children:(0,Z.jsx)(We,{})})]}),(0,Z.jsx)(`nav`,{children:(0,Z.jsx)(XG,{activeGroupId:re?.id??null,pageLabel:ve,pageAvailable:ye,onNavigate:_e,onReveal:ge,desktopShell:le,t:m})}),(0,Z.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Z.jsx)(FK,{label:m(`dash.actions`),statusLabel:m(Te?`dash.online`:`dash.offline`),online:Te,detail:Oe,stopLabel:m(g.connected?`connection.disconnect`:`dash.stop`),stoppingLabel:m(`dash.stopping`),restartLabel:m(`dash.codexRestart`),restartingLabel:m(`dash.codexRestarting`),leverHint:m(`shellV2.leverHint`,{restart:m(`dash.codexRestart`),stop:m(g.connected?`connection.disconnect`:`dash.stop`)}),leverText:{hover:m(`shellV2.leverHover`),cancel:m(`shellV2.leverCancel`),restart:m(`shellV2.leverRelease`,{action:m(`shellV2.leverReload`)}),stop:m(`shellV2.leverRelease`,{action:g.connected?m(`connection.disconnect`):m(`shellV2.leverStop`)})},stopping:ke,restarting:Fe,onStop:Le,onRestart:()=>{Ie()},session:(g.connected||ze)&&C?{label:Be,busyLabel:m(`connection.sessionLoggingOut`),busy:I,onClick:()=>{Re()}}:void 0}),(0,Z.jsxs)(`div`,{className:`sidebar-pref-row`,children:[(0,Z.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Z.jsx)(wt,{"aria-hidden":!0}),(0,Z.jsx)($,{value:u,options:d.map(e=>({value:e.code,label:W(e.code)})),onChange:e=>p(e),label:m(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,Z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>IG(`classic`),"aria-label":m(`shellV2.uiClassic`),title:m(`shellV2.uiClassicHint`),children:(0,Z.jsx)(Ne,{})}),Ce]}),(0,Z.jsx)(EG,{apiBase:G,onOpenUpdate:()=>{ce(!1),!Wd()&&t(`dashboard`,`update`)},onOpenTerminalCommand:()=>{ce(!1),Kd()},version:(0,Z.jsxs)(`span`,{className:`sidebar-version`,title:we,children:[`v`,we]})}),fe&&(0,Z.jsx)(`div`,{className:`sidebar-meta-row`,children:(0,Z.jsx)(TK,{percent:pe.percent,canZoomIn:pe.canZoomIn,canZoomOut:pe.canZoomOut,onStep:pe.step})})]})]}),(0,Z.jsxs)(`main`,{className:`main`,inert:se,children:[le?(0,Z.jsx)(WK,{children:Ue}):Ue,(0,Z.jsxs)(`div`,{className:`main-inner${e===`models`&&r===`combos`?` main-inner--combos`:``}`,children:[v&&q.length>1&&(0,Z.jsx)(ZG,{items:q.map(e=>({page:e,label:m(KK[e])})),currentPage:e,onNavigate:t,ariaLabel:m(`nav.sectionNavigation`),onFocusOrphaned:eq}),v&&g.link&&(0,Z.jsx)(Q,{tone:`warn`,children:g.link.home?m(`connection.linkManaged`,{home:g.link.home,linkId:g.link.linkId}):m(`connection.linkManagedUnnamed`,{linkId:g.link.linkId})}),(0,Z.jsx)(FE,{pageName:m(KK[ie]),title:m(`errorBoundary.title`),message:m(`errorBoundary.message`),detailsLabel:m(`errorBoundary.details`),reloadLabel:m(`errorBoundary.reload`),children:v?(0,Z.jsxs)(Z.Fragment,{children:[b&&(0,Z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m(b===`client-state-changed`?`connection.clientStateChanged`:`connection.machineUnavailable`)}),(g.connected&&!C||oe)&&(0,Z.jsx)(TR,{target:g.shared,focusOnMount:oe,onConnected:async e=>{oe&&await lR(G,void 0,e),e.throwIfAborted(),M(!1),T(D(`shared`)),A(e=>e+1)}},`${g.shared.serverOrigin}:${g.shared.bootstrapPath}`),e===`home`&&(0,Z.jsx)(hp,{apiBase:G,navigate:t,onReloadCodex:()=>{Ie()},reloadingCodex:Fe}),e===`setup`&&(0,Z.jsx)(Cp,{apiBase:G,navigate:t}),e===`advanced`&&(0,Z.jsx)(Dp,{navigate:t}),e===`dashboard`&&(0,Z.jsx)(op,{apiBase:G,readOnly:g.link!==void 0,connected:g.connected,authenticationPending:g.connected&&!C,refreshEpoch:k}),e===`startup`&&(0,Z.jsx)($U,{apiBase:G,machineApiBase:ne,connected:g.connected}),e===`providers`&&(0,Z.jsx)(WC,{apiBase:G}),e===`models`&&(0,Z.jsx)(TA,{apiBase:G,restartEpoch:Me,connected:g.connected,catalogSyncedAt:g.catalogSyncedAt,reportRestart:te},G),e===`subagents`&&(0,Z.jsx)(Sj,{apiBase:G},G),e===`advisor`&&(0,Z.jsx)(FA,{apiBase:G},G),e===`logs`&&(0,Z.jsx)(_P,{apiBase:G}),e===`usage`&&(0,Z.jsx)(pI,{apiBase:G,connected:g.connected||i(),apiKeyId:g.apiKeyId,topology:b||i()&&!g.connected?`unknown`:g.usageTopology}),e===`storage`&&(0,Z.jsx)(HI,{apiBase:G}),e===`remote`&&!oe&&(0,Z.jsx)($W,{apiBase:G,sessionReady:C,pairingRecoveryAvailable:ae,onRequestPairing:()=>M(!0),workspaceAvailable:K,onOpenWorkspace:()=>t(`remote-workspace`)},`${G}:${k}`),e===`remote-workspace`&&(0,Z.jsx)(XK,{available:K,apiBase:G,hubOrigin:g.shared.serverOrigin,onOpenRemoteLink:()=>t(`remote`)}),e===`codex-set`&&(0,Z.jsx)(PR,{apiBase:G,machineApiBase:ne,connected:g.connected}),ie===`integrations`&&(0,Z.jsx)(TU,{apiBase:G,machineApiBase:ne,connected:g.connected})]}):(0,Z.jsx)(`div`,{className:`alert`,children:m(`connection.discovering`)})},ie)]})]})]})}export{ea as $,vo as A,qr as At,Va as B,Lo as C,ti as Ct,wo as D,Xr as Dt,ko as E,Zr as Et,so as F,_a as G,ja as H,Ka as I,pa as J,va as K,eo as L,go as M,fo as N,Co as O,Jr as Ot,lo as P,Qi as Q,Wa as R,XK as RemoteWorkspaceRoute,zo as S,ni as St,Ao as T,Qr as Tt,ka as U,Ua as V,ya as W,ua as X,da as Y,fa as Z,qo as _,si as _t,Ss as a,Pi as at,Vo as b,ii as bt,os as c,Li as ct,ns as d,tq as default,vi as dt,aa as et,ts as f,_i as ft,Jo as g,ui as gt,Xo as h,di as ht,Cs as i,Ni as it,_o as j,Wr as jt,xo as k,Yr as kt,as as l,ji as lt,Zo as m,hi as mt,ic as n,Bi as nt,xs as o,Fi as ot,$o as p,pi as pt,ha as q,Ys as r,zi as rt,ys as s,Ii as st,GK as t,Zi as tt,is as u,Oi as ut,Ko as v,oi as vt,Mo as w,$r as wt,Bo as x,ri as xt,Ho as y,ai as yt,Ga as z};
|