@bitkyc08/opencodex 2.83.0 → 2.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -4
- package/bin/ocx.mjs +61 -3
- package/gui/dist/assets/App-BjlttVLy.js +58 -0
- package/gui/dist/assets/Tray-DyR9yBee.js +1 -0
- package/gui/dist/assets/{index-BAbcj51J.css → index-BB6uK6tU.css} +1 -1
- package/gui/dist/assets/index-BMssP4k3.js +94 -0
- package/gui/dist/assets/quota-summary-D8M1bc_R.js +1 -0
- package/gui/dist/index.html +2 -2
- package/package.json +2 -3
- package/src/adapters/anthropic/beta-allowlist.ts +87 -8
- package/src/adapters/anthropic/client-identity.ts +1 -1
- package/src/adapters/anthropic/passthrough.ts +33 -4
- package/src/adapters/azure.ts +19 -1
- package/src/adapters/client-fingerprint.ts +24 -0
- package/src/adapters/coding-agent/protocol.ts +15 -8
- package/src/adapters/coding-agent/turn.ts +22 -9
- package/src/adapters/cursor/arg-codec.ts +17 -5
- package/src/adapters/cursor/catalog.ts +8 -0
- package/src/adapters/cursor/effort-map.ts +3 -0
- package/src/adapters/cursor/freeform-args.ts +75 -0
- package/src/adapters/cursor/protobuf-events.ts +36 -23
- package/src/adapters/google-antigravity-wire.ts +22 -1
- package/src/adapters/google.ts +2 -2
- package/src/adapters/ollama-native.ts +29 -1
- package/src/adapters/openai-chat/messages.ts +8 -4
- package/src/adapters/openai-chat/response-events.ts +59 -1
- package/src/adapters/openai-chat.ts +8 -5
- package/src/adapters/openai-responses/empty-assistant.ts +32 -0
- package/src/adapters/openai-responses/passthrough.ts +3 -0
- package/src/adapters/openai-responses/request-strips.ts +10 -2
- package/src/adapters/qoder/adapter.ts +56 -15
- package/src/advisor/consult.ts +220 -0
- package/src/advisor/context.ts +226 -0
- package/src/advisor/disclosure.ts +20 -0
- package/src/advisor/runtime.ts +305 -0
- package/src/advisor/settings.ts +135 -0
- package/src/advisor/state.ts +369 -0
- package/src/advisor/synthetic-tool.ts +33 -0
- package/src/bridge/errors.ts +24 -0
- package/src/bridge.ts +1 -1
- package/src/chat/inbound.ts +30 -6
- package/src/chat/outbound.ts +5 -0
- package/src/claude/context-windows.ts +54 -1
- package/src/claude/desktop-3p-library.ts +43 -3
- package/src/claude/desktop-3p.ts +22 -8
- package/src/claude/desktop-picker-profile.ts +11 -4
- package/src/claude/desktop-profile.ts +10 -1
- package/src/claude/desktop-remote-store-io.ts +5 -3
- package/src/claude/inbound.ts +121 -50
- package/src/claude/intercept/connect-proxy.ts +10 -3
- package/src/claude/intercept/local-ca.ts +8 -1
- package/src/claude/intercept/picker-ca-persistence.ts +3 -1
- package/src/claude/intercept/picker-listener.ts +49 -1
- package/src/claude/intercept/settings-no-proxy.ts +146 -0
- package/src/claude/intercept/settings.ts +101 -9
- package/src/claude/model-default-settings.ts +154 -0
- package/src/claude/model-info.ts +7 -7
- package/src/claude/outbound.ts +13 -6
- package/src/cli/account-api.ts +65 -0
- package/src/cli/account-auth.ts +26 -2
- package/src/cli/account.ts +41 -5
- package/src/cli/advisor.ts +151 -0
- package/src/cli/auxiliary-listener-preflight.ts +37 -0
- package/src/cli/capabilities-access-remote.ts +8 -0
- package/src/cli/capabilities-agents-routing.ts +18 -0
- package/src/cli/capabilities-base.ts +14 -2
- package/src/cli/catalog-command-result.ts +2 -1
- package/src/cli/chatgpt-command.ts +35 -14
- package/src/cli/claude.ts +60 -11
- package/src/cli/config-command.ts +8 -2
- package/src/cli/debug.ts +8 -0
- package/src/cli/dispatch.ts +21 -4
- package/src/cli/doctor.ts +9 -0
- package/src/cli/ensure-desktop-cold-start.ts +329 -0
- package/src/cli/export-command.ts +15 -2
- package/src/cli/help.ts +2 -1
- package/src/cli/hub-disable.ts +99 -0
- package/src/cli/hub.ts +4 -2
- package/src/cli/index.ts +26 -8
- package/src/cli/integration-plan-dto.ts +2 -0
- package/src/cli/link-child.ts +104 -0
- package/src/cli/link-enrollment.ts +96 -0
- package/src/cli/link.ts +39 -24
- package/src/cli/observe-stream.ts +6 -1
- package/src/cli/observe.ts +10 -2
- package/src/cli/provider.ts +12 -0
- package/src/cli/registry.ts +20 -7
- package/src/cli/restart-scope.ts +3 -1
- package/src/cli/runtime-api.ts +27 -2
- package/src/cli/status.ts +104 -20
- package/src/client/connect.ts +39 -4
- package/src/client/hub-client.ts +14 -7
- package/src/client/hub-state.ts +25 -14
- package/src/client/link-home.ts +248 -0
- package/src/client/link-management-relay.ts +61 -0
- package/src/client/link-relay.ts +6 -1
- package/src/client/link-status.ts +14 -0
- package/src/client/machine-api.ts +14 -7
- package/src/client/machine-listener.ts +29 -4
- package/src/clients/config-export/contracts.ts +1 -0
- package/src/clients/config-export/model-metadata.ts +3 -2
- package/src/clients/config-export/qoder.ts +93 -0
- package/src/clients/config-export.ts +59 -16
- package/src/clients/omo-role-models.ts +6 -3
- package/src/codex/agent-role-models.ts +26 -8
- package/src/codex/auth-api/account-list.ts +17 -2
- package/src/codex/auth-api/account-selection.ts +17 -7
- package/src/codex/auth-api/pool-mode-gate.ts +5 -2
- package/src/codex/auth-api/routes.ts +5 -1
- package/src/codex/auth-context.ts +79 -5
- package/src/codex/autostart-health.ts +7 -1
- package/src/codex/catalog/build-entries.ts +11 -2
- package/src/codex/catalog/bundled.ts +5 -1
- package/src/codex/catalog/configured-tiers.ts +50 -0
- package/src/codex/catalog/effort.ts +6 -3
- package/src/codex/catalog/metadata.ts +4 -2
- package/src/codex/catalog/model-hints.ts +21 -3
- package/src/codex/catalog/native-models.ts +16 -2
- package/src/codex/catalog/native-ultrafast.ts +106 -0
- package/src/codex/catalog/parsing.ts +5 -0
- package/src/codex/catalog/provider-models.ts +4 -0
- package/src/codex/catalog/retained-sync.ts +2 -0
- package/src/codex/catalog/routed-gather.ts +22 -4
- package/src/codex/catalog/vendor-context.ts +82 -0
- package/src/codex/config-write-lock.ts +40 -2
- package/src/codex/convergence.ts +2 -0
- package/src/codex/desktop-app/types.ts +2 -0
- package/src/codex/desktop-app/windows.ts +29 -16
- package/src/codex/desktop-app-restart.ts +4 -2
- package/src/codex/desktop-compatibility/certificate-service.ts +99 -0
- package/src/codex/desktop-compatibility/certificate-store.ts +193 -0
- package/src/codex/desktop-compatibility/connection-store.ts +87 -0
- package/src/codex/desktop-compatibility/installed-build.ts +55 -0
- package/src/codex/desktop-compatibility/json-body.ts +29 -0
- package/src/codex/desktop-compatibility/native-identity.ts +62 -0
- package/src/codex/desktop-compatibility/relay-listener.ts +93 -0
- package/src/codex/desktop-compatibility/routing-binding.ts +10 -0
- package/src/codex/desktop-compatibility/routing-preflight.ts +69 -0
- package/src/codex/desktop-compatibility/runtime-ownership.ts +28 -0
- package/src/codex/desktop-compatibility/runtime.ts +173 -0
- package/src/codex/desktop-compatibility/service.ts +30 -0
- package/src/codex/desktop-compatibility/startup-settings.ts +50 -0
- package/src/codex/desktop-compatibility/usage-activation.ts +86 -0
- package/src/codex/desktop-compatibility/usage-controlled-fetch.ts +59 -0
- package/src/codex/desktop-compatibility/usage-controller.ts +107 -0
- package/src/codex/desktop-compatibility/usage-policy.ts +59 -0
- package/src/codex/desktop-compatibility/usage-refresh.ts +33 -0
- package/src/codex/desktop-compatibility/usage-sse-controller.ts +86 -0
- package/src/codex/desktop-compatibility/windows-activation-source.ts +44 -0
- package/src/codex/desktop-compatibility/windows-certificate-trust.ts +81 -0
- package/src/codex/desktop-compatibility/windows-key-protection.ts +59 -0
- package/src/codex/desktop-compatibility/windows-package-command.ts +86 -0
- package/src/codex/desktop-compatibility/windows-package-launch.ts +28 -0
- package/src/codex/history-provider.ts +1 -1
- package/src/codex/inject/config-write-section.ts +4 -1
- package/src/codex/inject/remove.ts +18 -6
- package/src/codex/journal.ts +16 -1
- package/src/codex/main-account.ts +99 -15
- package/src/codex/native-main-refresh-mode.ts +217 -0
- package/src/codex/native-profile-startup.ts +4 -1
- package/src/codex/prompt-journal.ts +20 -2
- package/src/codex/prompt-layers/encoding.ts +49 -0
- package/src/codex/prompt-layers/import-source.ts +30 -0
- package/src/codex/prompt-layers/toml-edit.ts +269 -37
- package/src/codex/prompt-layers/toml-read.ts +52 -4
- package/src/codex/prompt-layers.ts +383 -20
- package/src/codex/prompt-lock-claim.ts +13 -3
- package/src/codex/prompt-lock-evidence.ts +3 -3
- package/src/codex/prompt-lock-owner.ts +14 -6
- package/src/codex/prompt-text-probe.ts +34 -5
- package/src/codex/quota.ts +13 -6
- package/src/codex/role-auto-assign.ts +2 -5
- package/src/codex/routing/active-account.ts +21 -0
- package/src/codex/routing/health-store.ts +1 -1
- package/src/codex/routing/pool-recovery.ts +79 -0
- package/src/codex/routing.ts +1 -1
- package/src/codex/runtime.ts +196 -8
- package/src/codex/shim-diagnostics.ts +6 -0
- package/src/codex/shim-overlay.ts +15 -6
- package/src/codex/shim.ts +1 -1
- package/src/combos/failover.ts +3 -0
- package/src/config/api-key-reconcile.ts +34 -0
- package/src/config/diagnostics.ts +18 -1
- package/src/config/feature-flags.ts +5 -0
- package/src/config/live-reconcile.ts +56 -29
- package/src/config/live-topology.ts +29 -0
- package/src/config/load-degrade.ts +8 -2
- package/src/config/paths.ts +13 -3
- package/src/config/salvage.ts +3 -1
- package/src/config/schema/config-schema.ts +19 -0
- package/src/config/schema/desktop-compatibility.ts +9 -0
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/generated/compatibility-version.json +713 -285
- package/src/generated/model-metadata.ts +1 -1
- package/src/grok/grpc-web.ts +23 -1
- package/src/grok/reset-coupon-ledger.ts +75 -5
- package/src/grok/reset-coupons.ts +4 -2
- package/src/integrations/catalog-refresh.ts +1 -1
- package/src/integrations/config-io.ts +20 -2
- package/src/integrations/journal.ts +15 -1
- package/src/integrations/mutation-plan.ts +14 -7
- package/src/integrations/registry.ts +52 -11
- package/src/integrations/state.ts +19 -7
- package/src/integrations/store.ts +3 -0
- package/src/integrations/target.ts +42 -5
- package/src/integrations/writer.ts +24 -7
- package/src/lib/advisor-activation.ts +16 -0
- package/src/lib/app-owned-memory-stores.ts +4 -0
- package/src/lib/app-owned-memory.ts +11 -0
- package/src/lib/background-work.ts +65 -0
- package/src/lib/bounded-file-read.ts +58 -0
- package/src/lib/bun-path-runtime.d.mts +10 -1
- package/src/lib/bun-path-runtime.mjs +62 -3
- package/src/lib/desktop-proxy-route.ts +30 -0
- package/src/lib/desktop-upstream-tunnel.ts +107 -0
- package/src/lib/errors.ts +7 -0
- package/src/lib/json-byte-size.ts +31 -0
- package/src/lib/local-internal-call-capability.ts +55 -0
- package/src/lib/optional-shutdown-hooks.ts +35 -0
- package/src/lib/outbound-credential-registry.ts +210 -0
- package/src/lib/package-tree-integrity.ts +2 -2
- package/src/lib/passive-read.ts +35 -0
- package/src/lib/shadow-call.ts +44 -5
- package/src/lib/socks5-fetch.ts +48 -71
- package/src/lib/socks5-handshake.ts +112 -0
- package/src/lib/translator-budget.ts +7 -1
- package/src/link/codex-settings.ts +155 -0
- package/src/link/management-routes.ts +89 -0
- package/src/link/remote-probe.ts +38 -0
- package/src/link/ssh-argv.ts +26 -5
- package/src/link/ssh-runner.ts +58 -27
- package/src/link/status-projection.ts +22 -4
- package/src/link/supervisor.ts +144 -49
- package/src/link/tunnel-state.ts +11 -4
- package/src/oauth/anthropic-continuity.ts +4 -3
- package/src/oauth/anthropic-identity.ts +13 -2
- package/src/oauth/anthropic-model-quota.ts +13 -1
- package/src/oauth/anthropic-routing.ts +230 -23
- package/src/oauth/anthropic.ts +18 -4
- package/src/oauth/generic-account-failover.ts +29 -5
- package/src/oauth/google-antigravity.ts +24 -7
- package/src/oauth/index.ts +28 -17
- package/src/oauth/kiro-account-identity.ts +106 -0
- package/src/oauth/kiro-device-login.ts +2 -1
- package/src/oauth/kiro.ts +55 -6
- package/src/oauth/plan.ts +29 -0
- package/src/oauth/store.ts +40 -3
- package/src/oauth/types.ts +2 -0
- package/src/plugins/loader.ts +11 -0
- package/src/protocols/codecs/chat-ir.ts +467 -0
- package/src/protocols/codecs/chat.ts +10 -1
- package/src/protocols/codecs/messages-ir.ts +500 -0
- package/src/protocols/features.ts +10 -2
- package/src/protocols/path.ts +11 -1
- package/src/protocols/plan-snapshot.ts +39 -16
- package/src/protocols/plan.ts +9 -1
- package/src/protocols/settings.ts +8 -0
- package/src/providers/anthropic-billing-ownership.ts +74 -0
- package/src/providers/anthropic-billing-recovery.ts +31 -0
- package/src/providers/anthropic-billing-refusal.ts +55 -0
- package/src/providers/anthropic-reset-admission.ts +62 -0
- package/src/providers/anthropic-reset-grant-ledger.ts +28 -6
- package/src/providers/antigravity-account-roster.ts +102 -0
- package/src/providers/antigravity-models.ts +85 -7
- package/src/providers/api-key-resolve.ts +17 -2
- package/src/providers/key-failover.ts +52 -5
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/model-rename-migration.ts +5 -3
- package/src/providers/model-rename-startup.ts +5 -3
- package/src/providers/quota/account-cache.ts +11 -0
- package/src/providers/quota/anthropic-account-quota.ts +4 -2
- package/src/providers/quota/report-cache.ts +14 -0
- package/src/providers/quota/vendor-probes-oauth.ts +3 -3
- package/src/providers/quota.ts +4 -1
- package/src/providers/registry/entries-core.ts +21 -20
- package/src/providers/registry/entries-extended.ts +19 -1
- package/src/providers/registry/model-seeds.ts +17 -0
- package/src/providers/request-pacing.ts +9 -0
- package/src/providers/stale-no-vision-seed-migration.ts +72 -0
- package/src/responses/compaction.ts +14 -0
- package/src/responses/parser.ts +37 -20
- package/src/responses/state.ts +32 -29
- package/src/routing/history/build-file.ts +92 -0
- package/src/routing/history/indexer.ts +248 -216
- package/src/routing/history/ingest.ts +238 -0
- package/src/routing/history/rebuild-job.ts +111 -0
- package/src/routing/history/rebuild-protocol.ts +15 -0
- package/src/routing/history/rebuild-worker.ts +34 -0
- package/src/server/admission-model-scope.ts +4 -1
- package/src/server/antigravity-direct-eligibility.ts +208 -0
- package/src/server/auth-cors.ts +46 -0
- package/src/server/chat-completions.ts +75 -9
- package/src/server/claude-messages.ts +110 -20
- package/src/server/configured-credentials.ts +194 -0
- package/src/server/index/desktop-compatibility-startup.ts +56 -0
- package/src/server/index/link-management.ts +58 -0
- package/src/server/index/optional-listeners.ts +5 -1
- package/src/server/index/serve-options.ts +15 -2
- package/src/server/index/startup-warnings.ts +9 -0
- package/src/server/index/websocket-handler.ts +9 -0
- package/src/server/index.ts +13 -10
- package/src/server/inference/client-encoder-delivery.ts +6 -5
- package/src/server/lifecycle.ts +2 -1
- package/src/server/login-shell-path.ts +146 -0
- package/src/server/management/advisor-routes.ts +191 -0
- package/src/server/management/agent-settings-routes.ts +50 -14
- package/src/server/management/anthropic-reset-grant-routes.ts +17 -1
- package/src/server/management/codex-agent-role-routes.ts +19 -6
- package/src/server/management/codex-prompt-routes.ts +136 -5
- package/src/server/management/codex-role-auto-assign.ts +1 -1
- package/src/server/management/companion-routes.ts +4 -0
- package/src/server/management/config-routes.ts +2 -2
- package/src/server/management/context.ts +4 -0
- package/src/server/management/desktop-compatibility-routes.ts +46 -0
- package/src/server/management/desktop-compatibility-runtime-routes.ts +46 -0
- package/src/server/management/desktop-compatibility-settings-routes.ts +27 -0
- package/src/server/management/grok-coupon-routes.ts +78 -27
- package/src/server/management/link-enrollment.ts +192 -0
- package/src/server/management/link-route-state.ts +185 -0
- package/src/server/management/link-routes.ts +82 -402
- package/src/server/management/model-routes.ts +2 -2
- package/src/server/management/model-rows.ts +3 -1
- package/src/server/management/protocol-settings-patch.ts +1 -0
- package/src/server/management/provider-overwrite-carry.ts +10 -0
- package/src/server/management/provider-routes.ts +1 -0
- package/src/server/management/route-registry.ts +16 -3
- package/src/server/management/shared.ts +3 -0
- package/src/server/management/sibling-guard.ts +1 -0
- package/src/server/management-api.ts +9 -1
- package/src/server/messages-antigravity-direct.ts +195 -0
- package/src/server/messages-native.ts +73 -43
- package/src/server/relay-eager.ts +2 -0
- package/src/server/request-log-filter.ts +6 -1
- package/src/server/request-log-terminal-status.ts +63 -6
- package/src/server/request-log.ts +7 -0
- package/src/server/responses/adapter-continuation.ts +35 -18
- package/src/server/responses/adapter-delivery.ts +24 -2
- package/src/server/responses/adapter-dispatch.ts +261 -81
- package/src/server/responses/advisor-plan-slot.ts +27 -0
- package/src/server/responses/advisor-slot.ts +336 -0
- package/src/server/responses/code-mode-collab-surface.ts +313 -0
- package/src/server/responses/codex-ws-exchange.ts +147 -6
- package/src/server/responses/codex-ws-wire.ts +203 -0
- package/src/server/responses/collaboration.ts +36 -7
- package/src/server/responses/compact.ts +126 -48
- package/src/server/responses/context-overflow.ts +13 -1
- package/src/server/responses/core-codex-account.ts +105 -1
- package/src/server/responses/core-combo-failure.ts +24 -1
- package/src/server/responses/core-combo.ts +28 -2
- package/src/server/responses/core-errors.ts +29 -1
- package/src/server/responses/core-lifetime.ts +2 -0
- package/src/server/responses/core-normalize.ts +11 -0
- package/src/server/responses/core-options.ts +48 -0
- package/src/server/responses/core-replay.ts +7 -4
- package/src/server/responses/core.ts +1 -1
- package/src/server/responses/deferred-collab-surface.ts +158 -0
- package/src/server/responses/deferred-send-reporter.ts +25 -0
- package/src/server/responses/fetch-helpers.ts +12 -1
- package/src/server/responses/passthrough-delivery.ts +20 -11
- package/src/server/responses/passthrough-dispatch.ts +29 -7
- package/src/server/responses/request-prepare.ts +74 -9
- package/src/server/responses/request-transport.ts +22 -8
- package/src/server/responses/run-turn-execution.ts +70 -8
- package/src/server/responses/sidecar-execution.ts +89 -5
- package/src/server/responses/terminal-guard.ts +2 -1
- package/src/server/responses/ws-upstream.ts +9 -1
- package/src/server/responses-undeclared-tool-guard.ts +30 -9
- package/src/server/startup-action-control.ts +38 -4
- package/src/server/startup-health-cache.ts +5 -0
- package/src/server/system-env-shell.ts +7 -2
- package/src/server/system-env.ts +11 -1
- package/src/service/cli.ts +5 -1
- package/src/service/desktop-startup.ts +161 -34
- package/src/service/desktop-supervision.d.mts +27 -1
- package/src/service/desktop-supervision.mjs +111 -5
- package/src/service/health-sentinel-launch.ts +176 -0
- package/src/service/health-sentinel-main.ts +466 -0
- package/src/service/health-sentinel-policy.ts +241 -0
- package/src/service/health-sentinel-probe.ts +71 -0
- package/src/service/health-sentinel-windows.ts +87 -0
- package/src/service/linux-linger.ts +20 -0
- package/src/service/logging.ts +72 -0
- package/src/tray/windows-tray.ps1 +43 -24
- package/src/types/config.ts +68 -6
- package/src/types/provider.ts +7 -0
- package/src/types/request.ts +15 -0
- package/src/types/tools.ts +2 -0
- package/src/update/async-check.ts +1 -1
- package/src/update/badge.ts +2 -2
- package/src/update/index.ts +88 -15
- package/src/update/job-supervised-restart.ts +107 -0
- package/src/update/job.ts +32 -32
- package/src/update/notify.ts +1 -1
- package/src/update/refresh-scheduler.ts +2 -2
- package/src/update/supervised-recovery.d.mts +27 -0
- package/src/update/supervised-recovery.mjs +157 -0
- package/src/usage/cache-diagnostic.ts +2 -0
- package/src/usage/expected-prices.ts +16 -0
- package/src/usage/log.ts +19 -1
- package/src/web-search/gemini-executor.ts +2 -2
- package/assets/sponsors/packycode.png +0 -0
- package/gui/dist/assets/App-Ba8uG696.js +0 -54
- package/gui/dist/assets/Tray-IImbNPRy.js +0 -1
- package/gui/dist/assets/index-BHRZdJuv.js +0 -94
- package/gui/dist/assets/quota-summary-DiJO6sYY.js +0 -1
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import{A as e,C as t,D as n,E as r,O as i,S as a,T as o,_ as s,a as c,b as l,c as u,d,f,g as p,h as m,i as h,j as g,k as _,l as v,m as y,n as b,o as x,p as S,r as C,s as w,t as T,u as E,v as D,w as O,x as k,y as A}from"./index-BMssP4k3.js";import{$ as j,A as M,At as N,B as P,Bt as F,C as I,Ct as L,D as R,Dt as z,E as B,Et as V,F as H,Ft as U,G as W,H as G,I as ee,It as K,J as q,K as te,L as ne,Lt as J,M as Y,Mt as re,N as ie,Nt as X,O as ae,Ot as oe,P as se,Pt as ce,Q as le,R as ue,Rt as de,S as fe,St as pe,T as me,Tt as he,U as ge,V as _e,Vt as ve,W as ye,X as be,Y as xe,Z as Se,_ as Ce,_t as we,at as Te,b as Ee,bt as De,ct as Oe,dt as ke,et as Ae,ft as je,g as Me,gt as Ne,h as Pe,ht as Fe,it as Ie,j as Le,jt as Re,k as ze,kt as Be,lt as Ve,m as He,mt as Ue,n as We,nt as Ge,ot as Ke,pt as qe,q as Je,rt as Ye,st as Xe,t as Ze,tt as Qe,ut as $e,v as et,vt as tt,w as nt,wt as rt,x as it,xt as at,y as ot,yt as st,z as ct,zt as lt}from"./quota-summary-D8M1bc_R.js";var Z=g(e(),1);function ut(){return typeof document<`u`&&document.visibilityState===`hidden`||typeof window<`u`&&window.__OPENCODEX_HOST_VISIBLE__===!1}function dt(e){let t=ut(),n=()=>{let n=ut();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,pt=new Set,mt=3e4,ht=`ocx-resource-deadline`,gt={data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1};function _t(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 yt=new Map;function bt(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0&&e.pauseWhenHiddenByListener.get(t)===!1)return!0;return!1}function xt(e){if(e.stores.size===0)return!1;if(!Dt())return!0;for(let t of e.stores)if(bt(t))return!0;return!1}function St(e){for(let t of e.stores){let e=Ot(t);e&&Pt(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}function Ct(e,t){let n=xt(t);if(n&&t.timer===null){t.timer=setInterval(()=>St(t),e);return}!n&&t.timer!==null&&(clearInterval(t.timer),t.timer=null),t.stores.size===0&&yt.delete(e)}function wt(){for(let[e,t]of[...yt])Ct(e,t)}function Tt(e){let t=e.pollIntervalMs;if(t===void 0)return;let n=yt.get(t);e.pollIntervalMs=void 0,n&&(n.stores.delete(e),Ct(t,n))}function Et(e,t){let n=yt.get(t);n||(n={timer:null,stores:new Set},yt.set(t,n)),n.stores.add(e),e.pollIntervalMs=t,Ct(t,n)}function Dt(){return ut()}function Ot(e){if(!Dt())return kt(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 kt(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 At(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){Tt(e),Nt(e);return}if(t===e.pollIntervalMs){let n=yt.get(t);n&&Ct(t,n),Mt(e);return}Tt(e),Et(e,t),Mt(e)}var jt=null;function Mt(e){typeof document>`u`||jt||(jt=dt(()=>{if(wt(),!Dt())for(let e of yt.values())for(let t of e.stores){let e=kt(t);e&&Pt(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}))}function Nt(e){jt&&(yt.size>0||(jt(),jt=null))}async function Pt(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??mt,s=!1,c=setTimeout(()=>{s=!0,i.abort(ht)},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,pt.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 Ft(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 It(e,t){Tt(t),Nt(t),setTimeout(()=>{t.subscriberCount===0&&ft.get(e)===t&&(t.inflight?.abort(),t.inflight=null,t.inflightOwner=null,ft.delete(e))},0)}function Lt(e,t,n){let{fetcher:r,pollMs:i,pauseWhenHidden:a=!0,deadlineMs:o,staleAfterMs:s}=n,c=_t(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||pt.has(e)||n)&&Pt(c,r,{replaceInflight:!0,owner:t,deadlineMs:o})}return At(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=Ft(c,t);if(c.subscriberCount===0){It(e,c);return}if(n){let e=kt(c);e&&Pt(c,e.fetcher,{replaceInflight:!0,owner:e.owner,deadlineMs:e.deadlineMs})}At(c)}}function Rt(e,t,n,r){let i=_t(e);i.subscriberCount===0&&i.snapshot.data===void 0&&(Ut(e,t),!pt.has(e)&&typeof r==`number`&&typeof n==`number`&&Date.now()-n<r&&(i.seedNeedsRevalidate=!1,i.lastSettledAt=n))}function zt(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&&Rt(e,n.initialData,n.initialDataCachedAt,s);let c=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{c.current=t});let l=(0,Z.useCallback)(e=>c.current(e),[]),u=(0,Z.useRef)(null),d=(0,Z.useCallback)(t=>r?(u.current=t,Lt(e,t,{fetcher:l,pollMs:i,pauseWhenHidden:a,deadlineMs:o,staleAfterMs:s})):()=>{},[e,l,i,r,a,o,s]),f=(0,Z.useCallback)(()=>r?_t(e).snapshot:gt,[e,r]),p=(0,Z.useSyncExternalStore)(d,f,f),m=(0,Z.useCallback)(t=>{if(!r)return;let n=_t(e);Pt(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 Bt(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 Vt(e,t,n,r){let i=zt(e,n,r),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let n=a.current,r=o.current;a.current=t,o.current=e,Bt(n,t)&&(r===null||r===e)&&i.refresh({forceLoading:!0})}),i}function Ht(e){pt.add(e);let t=ft.get(e);if(!t)return;let n=kt(t);n&&Pt(t,n.fetcher,{replaceInflight:!0,owner:n.owner,deadlineMs:n.deadlineMs})}function Ut(e,t){let n=_t(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 Wt(e){return e.replace(/^#\/?/,``)}function Gt(e){let t=e.indexOf(`?`);return t<0?{path:e,query:``}:{path:e.slice(0,t),query:e.slice(t+1)}}function Kt(e,t=window){let n=Wt(e);if(Wt(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function qt(e,t=window){let n=Wt(e);Wt(t.location.hash)!==n&&(t.location.hash=n)}var Jt=_(),Yt=4,Xt=8,Zt=8,Qt=280,$t=120,en=160,tn=12;function nn(){return typeof window<`u`?window.innerHeight:800}function rn(){return typeof window<`u`?window.innerWidth:1024}function an(e,{align:t,placement:n=`below`,menuHeight:r=Qt}={}){let i=Math.min(Math.max(r,$t),Qt),a=nn(),o=rn();if(n===`right`){let t=a-e.top-Zt,n=e.top-Zt,r=i+Xt>t&&n>t,s=Math.max(Zt,Math.min(e.right+tn,o-en-Zt));return r?{position:`fixed`,left:s,bottom:a-e.top+Xt,minWidth:en,maxHeight:Math.max($t,Math.min(Qt,e.top-Zt-Yt))}:{position:`fixed`,top:e.top,left:s,minWidth:en,maxHeight:Math.max($t,Math.min(Qt,a-e.top-Zt))}}let s=t??(e.right>o/2?`right`:`left`),c=Math.max(e.width,0),l=a-e.bottom-Zt,u=e.top-Zt;if(i+Yt>l&&u>l){let t={position:`fixed`,bottom:a-e.top+Xt,minWidth:c,maxHeight:Math.max(0,Math.min(Qt,u-Yt))};return s===`right`?t.right=Math.max(Zt,o-e.right):t.left=Math.max(Zt,Math.min(e.left,o-Zt-c)),t}let d={position:`fixed`,top:e.bottom+Yt,minWidth:c,maxHeight:Math.max(0,Math.min(Qt,l-Yt))};return s===`right`?d.right=Math.max(Zt,o-e.right):d.left=Math.max(Zt,Math.min(e.left,o-Zt-c)),d}var Q=b();function on({on:e,mixed:t=!1,onClick:n,disabled:r,label:i,showLabel:a=!1,title:o}){let s=a&&!!i;return(0,Q.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,Q.jsx)(`span`,{className:`knob`}),s?(0,Q.jsx)(`span`,{className:`switch-labeled-text text-label muted`,children:i}):null]})}function $({tone:e,children:t}){return(0,Q.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,Q.jsx)(Te,{}):(0,Q.jsx)(Ae,{}),(0,Q.jsx)(`span`,{children:t})]})}function sn({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,Jt.createPortal)((0,Q.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,Q.jsxs)(`div`,{className:`toast-notice notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[e===`ok`?(0,Q.jsx)(Te,{}):(0,Q.jsx)(Ae,{}),(0,Q.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,Q.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function cn({value:e,options:t,onChange:n,disabled:r,id:i,label:a,describedBy:o,title:s,style:c,align:l,placement:u,dropdownStyle:d,portal:f=!0}){let p=(0,Z.useId)(),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(),b=(0,Z.useRef)(null),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useCallback)(e=>`${p}-${e}`,[p]),w=t.find(t=>t.value===e),T=t.length===0?0:Math.max(0,t.findIndex(t=>t.value===e)),E=!m||t.length===0?T:Math.min(g??T,t.length-1),D=(0,Z.useCallback)((e=!1)=>{h(!1),_(null),e&&x.current?.focus()},[]),O=(0,Z.useCallback)(e=>{if(r||t.length===0)return;let n=Math.max(0,Math.min(t.length-1,e));_(n),h(!0)},[r,t.length]),k=(0,Z.useCallback)(e=>{if(!f)return;let t=x.current;t&&y(an(t.getBoundingClientRect(),{align:l,placement:u,menuHeight:e}))},[l,u,f]);(0,Z.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.target;b.current?.contains(t)||S.current?.contains(t)||D()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[D,m]),(0,Z.useLayoutEffect)(()=>{if(!m||!f)return;k();let e=()=>k(S.current?.offsetHeight);return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[m,t.length,f,k]),(0,Z.useLayoutEffect)(()=>{if(!m||!f||!S.current||!x.current)return;let e=S.current.offsetHeight;if(!e)return;let t=an(x.current.getBoundingClientRect(),{align:l,placement:u,menuHeight:e});y(e=>e?.top===t.top&&e?.bottom===t.bottom&&e?.maxHeight===t.maxHeight?e:t)},[l,m,t.length,u,f]),(0,Z.useLayoutEffect)(()=>{!m||!S.current||S.current.querySelector(`[id="${C(E)}"]`)?.scrollIntoView({block:`nearest`})},[E,m,C]);let A=e=>{if(r)return;let i=t[e];i&&(n(i.value),D(!0))},j=e=>{if(!r)switch(e.key){case`ArrowDown`:e.preventDefault(),O(m?Math.min(t.length-1,E+1):T);break;case`ArrowUp`:e.preventDefault(),O(m?Math.max(0,E-1):T);break;case`Home`:e.preventDefault(),O(0);break;case`End`:e.preventDefault(),O(t.length-1);break;case`Enter`:case` `:e.preventDefault(),m?A(E):O(T);break;case`Escape`:m&&(e.preventDefault(),D(!0));break;case`Tab`:if(m){let e=t[E];e&&n(e.value),h(!1)}}},M=m&&t[E]?C(E):void 0,N=m&&!r?(0,Q.jsx)(`div`,{ref:S,id:p,className:`select-dropdown${f?` select-dropdown-portal`:``}${!f&&l===`right`?` select-dropdown-right`:``}${!f&&u===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":a,style:f?{...v,zIndex:60,...d}:d,children:t.map((t,n)=>(0,Q.jsx)(`button`,{id:C(n),type:`button`,role:`option`,tabIndex:-1,disabled:r,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}${n===E?` select-option-active`:``}`,onMouseEnter:()=>_(n),onClick:()=>A(n),children:t.label},t.value))}):null;return(0,Q.jsxs)(`div`,{ref:b,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...c},children:[(0,Q.jsxs)(`button`,{ref:x,id:i,type:`button`,role:`combobox`,title:s,"aria-describedby":o,className:`select-trigger`,onClick:()=>{r||(m?D():O(T))},onKeyDown:j,disabled:r,"aria-haspopup":`listbox`,"aria-expanded":m,"aria-controls":m?p:void 0,"aria-activedescendant":M,"aria-label":a,children:[(0,Q.jsx)(`span`,{children:w?.label??e}),(0,Q.jsx)(Ke,{style:{width:12,height:12,color:`var(--muted)`,transform:m?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),f?N&&(0,Jt.createPortal)(N,document.body):N]})}function ln({icon:e,title:t,children:n,className:r,style:i}){return(0,Q.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,Q.jsx)(`div`,{className:`title`,children:t}),n&&(0,Q.jsx)(`div`,{className:`text-control`,children:n})]})}function un({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,Z.useState)(!1),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=()=>{s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>a(!0),150)},l=()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null),a(!1)};return(0,Z.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-tooltip`,onMouseEnter:c,onMouseLeave:l,onFocus:c,onBlur:l,onKeyDown:e=>{e.key===`Escape`&&l()},"aria-describedby":i?o:void 0,style:{display:`inline`,border:0,background:`transparent`,padding:0,margin:0,color:`inherit`,font:`inherit`,cursor:`inherit`},children:[t,i&&(0,Q.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var dn=45e3,fn=2147483647;async function pn(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 mn(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function hn(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=mn(await e.json(),t)}catch{}throw Error(n)}return pn(e)}async function gn(e){if(!e.ok)return null;try{return await pn(e)}catch{return null}}var _n=[`gpt-6-luna`,`gpt-5.6-luna`];function vn(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length>0?t:_n}function yn(e){return vn(e).join(`, `)}function bn(e){return vn(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}var xn=`dashboard/update`;function Sn(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function Cn(){return window.location.hash.replace(/^#\/?/,``)===xn}function wn(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function Tn(e,t){let n=await hn(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var En=[`low`,`medium`,`high`,`xhigh`];function Dn(e){return e?.includes(`-preview.`)?`preview`:`latest`}function On(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 kn(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 An(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 jn(e){return{vision:{reasoning:e}}}function Mn(e){return{vision:{enabled:e}}}function Nn(e){return{webSearch:{enabled:e}}}function Pn(e){return e?.applied===!1&&e.reason!==`not_requested`}function Fn(e,t){return t?.reason===`not_requested`&&Pn(e)?e:t}function In(e){return{vision:{maxDescriptionsPerTurn:e}}}function Ln(e){return{vision:{timeoutMs:e}}}var Rn=dn,zn=fn,Bn=1;function Vn(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Hn(e){let t=Vn(e);if(!(t===void 0||t<Bn||t>zn))return t}var Un=[`low`,`medium`,`high`,`xhigh`,`max`];function Wn(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...Un];let r=Un.filter(e=>n.includes(e));return r.length>0?r:[...Un]}function Gn(e,t){let n=Kn(e,t);return e.includes(n)?e:[n,...e]}function Kn(e,t){if(e.length===0||e.includes(t))return t;let n=Un.indexOf(t),r=e[0],i=Un.indexOf(r);for(let t of e){let e=Un.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function qn(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 Jn(e,t,n,r){if(e===void 0){let e=qn(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 Yn(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):qn(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function Xn(e,t,n){let r=vn(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 Zn(e,t){let n=e.find(e=>e.id===t)?.provider;return n===`anthropic`||n===`anthropic2`?`anthropic`:`openai`}function Qn(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 $n(e,t,n){let r=t.find(e=>e.value===n);return{backend:r?.backend??Zn(e,n),model:r?.model??n}}function er(e,t,n){return t.find(e=>e.value===n)?.backend||(n.includes(`/`)?`routed`:Zn(e,n))}var tr=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{tr=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{tr=!1},{capture:!0,passive:!0}));function nr(e){if(e){if(tr){e.focus({preventScroll:!0});return}try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function rr(e,t){let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let r=n.current;if(r){if(e){r.open||r.showModal();return}r.open&&r.close(),nr(t.current)}},[e,t]),(0,Z.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),nr(t.current)},[t]),n}var ir=`https://opencodex.me/guides/subagent-v1-default/`;function ar(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:ir}}function or(e){return e==="default"?`base`:e}function sr({reason:e,mode:t,docsUrl:n,busy:r=!1,onContinue:i,onChooseV1:a,onDismiss:o}){let s=O(),c=(0,Z.useId)(),l=(0,Z.useId)(),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=u.current;e&&!e.open&&e.showModal()},[]);let d=(0,Z.useCallback)(e=>{e.preventDefault(),!r&&o()},[r,o]),f=or(t),p=e===`advisory`;return(0,Q.jsxs)(`dialog`,{ref:u,"aria-labelledby":c,"aria-describedby":l,className:`modal-overlay`,"data-subagent-surface-reason":e,onCancel:d,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,disabled:r,onClick:()=>{r||o()}}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:480},children:[(0,Q.jsx)(`h3`,{id:c,children:s(p?`subagentSurface.advisoryTitle`:`subagentSurface.selectionTitle`,{mode:f})}),(0,Q.jsxs)(`div`,{id:l,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(Ae,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:s(p?`subagentSurface.advisoryBody`:`subagentSurface.selectionBody`,{mode:f})})]}),(0,Q.jsx)(`p`,{className:`text-label`,style:{marginTop:12},children:(0,Q.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:s(`subagentSurface.learnMore`)})}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:i,children:s(`subagentSurface.continue`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:a,children:s(`subagentSurface.switchToV1`)})]})]})]})}function cr(e){let{t,updateOpen:n,closeUpdateDialog:r,updateDialogRef:i,updateChannel:a,changeUpdateChannel:o,updateLoading:s,updateError:c,updateCheck:l,fetchUpdateCheck:u,updateRestart:d,setUpdateRestart:f,runUpdate:p,maHelpOpen:m,setMaHelpOpen:h,maHelpDialogRef:g,effortCapHelpOpen:_,setEffortCapHelpOpen:v,effortCapHelpDialogRef:y,shadowCallHelpOpen:b,setShadowCallHelpOpen:x,shadowCallHelpDialogRef:S,shadowCall:C,maAdvisory:w,maAdvisoryOpen:T,pendingMaMode:E,maBusy:D,keepMaMode:O,chooseMaV1:k,dismissMaSurfaceDialog:A}=e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dialog`,{ref:i,id:`dashboard-update-dialog`,className:`modal-overlay`,style:{display:n?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`update-title`,onCancel:e=>{e.preventDefault(),r()},children:(0,Q.jsxs)(`div`,{className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,Q.jsxs)(`div`,{className:`update-row`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,Q.jsx)(cn,{value:a,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>o(e),disabled:s,label:t(`dash.updateChannel`),portal:!1})]}),s&&(0,Q.jsx)(ln,{className:`update-empty`,icon:(0,Q.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,Q.jsx)(Ae,{}),(0,Q.jsx)(`span`,{children:c})]}),l&&!s&&(0,Q.jsxs)(`div`,{className:`update-box`,children:[(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,Q.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),l.command&&(0,Q.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,Q.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ae,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ae,{}),` `,t(`dash.updateUnavailable`),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,Q.jsx)(re,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,Q.jsxs)(`div`,{className:`update-recheck`,children:[(0,Q.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:On(l.reason,t)})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,Q.jsx)(re,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,Q.jsxs)(`div`,{className:`spread update-restart`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,Q.jsxs)(`dialog`,{ref:g,id:`multi-agent-help-dialog`,className:`modal-overlay`,style:{display:m?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`multi-agent-help-title`,onCancel:e=>{e.preventDefault(),h(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,Q.jsx)(`div`,{style:{marginTop:12},children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:y,id:`effort-cap-help-dialog`,className:`modal-overlay`,style:{display:_?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`effort-cap-help-title`,onCancel:e=>{e.preventDefault(),v(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:S,id:`shadow-call-help-dialog`,className:`modal-overlay`,style:{display:b?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`shadow-call-help-title`,onCancel:e=>{e.preventDefault(),x(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:yn(C?.sourceModels)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]}),(E||T)&&(0,Q.jsx)(sr,{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 lr({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,Q.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,Q.jsx)(ln,{title:e(`dash.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(X,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:e(`models.search`),value:r,onChange:e=>i(e.target.value),"aria-label":e(`models.search`)})]}),a.length===0?(0,Q.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,Q.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,Q.jsxs)(`div`,{className:`dash-model-group`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`dash-model-head`,onClick:()=>s(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),"aria-expanded":i,children:[(0,Q.jsx)(Ke,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`font-semibold`,children:be(t,e)}),(0,Q.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,Q.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,Q.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}function ur(e,t){let n=Math.max(0,Math.floor(e)),i=r(t,`uptime.day`),a=r(t,`uptime.hour`),o=r(t,`uptime.minute`),s=r(t,`uptime.second`);if(n<300)return`${n}${s}`;let c=Math.floor(n/60);if(c<60)return`${c}${o}`;let l=Math.floor(c/60);if(l<24){let e=c%60;return e>0?`${l}${a} ${e}${o}`:`${l}${a}`}let u=Math.floor(l/24),d=l%24;return d>0?`${u}${i} ${d}${a}`:`${u}${i}`}function dr(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 fr(e){return!!e&&typeof e==`object`&&`error`in e&&e.error===`read_failed`}var pr=class extends Error{constructor(){super(`usage ledger read failed`),this.name=`UsageReadFailedError`}};async function mr(e,t){let n;try{n=await e.json()}catch{throw Error(t??`${e.status} ${e.statusText}`.trim())}if(fr(n))throw new pr;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 gr({data:e}){let t=O();return dr(e).usageIncomplete?(0,Q.jsx)($,{tone:`warn`,children:t(`usage.incomplete`)}):null}function _r({locale:e,health:t,providers:n,usage30d:r,usageLoading:i,healthLoading:a,startupHealth:o,projectConfigWarnings:s,maMode:c,maBusy:l,maHelpTriggerRef:u,maHelpOpen:d,setMaHelpOpen:f,switchMaMode:p,maError:m}){let h=O(),g=t?.status===`ok`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[h(`dash.multiAgent`),(0,Q.jsx)(`button`,{ref:u,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)`},onClick:()=>f(!0),"aria-label":h(`dash.multiAgent`),"aria-haspopup":`dialog`,"aria-controls":`multi-agent-help-dialog`,"aria-expanded":d,children:(0,Q.jsx)(we,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`},children:(0,Q.jsx)(`div`,{className:`dash-ma-switch`,role:`radiogroup`,"aria-label":h(`dash.multiAgent`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":c===e,className:`btn btn-sm text-caption dash-ma-option${c===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,border:`none`,background:c===e?void 0:`transparent`,color:c===e?void 0:`var(--muted)`},disabled:l,onClick:()=>void p(e),children:h(`models.v2Mode_${e}`)},e))})}),m&&(0,Q.jsx)(`div`,{role:`alert`,className:`text-caption`,style:{color:`var(--red)`,marginTop:4,textAlign:`center`,maxWidth:280,wordBreak:`break-word`},children:m})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:h(`dash.status`)}),(0,Q.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:g?`var(--green)`:`var(--red)`},children:[(0,Q.jsx)(`span`,{className:`dot ${g?`dot-green`:`dot-red`}`}),h(g?`dash.online`:`dash.offline`)]})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:h(`dash.version`)}),(0,Q.jsx)(`div`,{className:`value mono dash-stat-version`,title:t?.version,children:t?.version??`—`})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:h(`dash.uptime`)}),(0,Q.jsx)(`div`,{className:`value mono`,children:t?ur(t.uptime,e):`—`})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:h(`dash.providers`)}),(0,Q.jsx)(`div`,{className:`value`,children:n.length})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":i||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:h(`dash.tokens30d`)}),(0,Q.jsx)(`div`,{className:`value mono`,children:r&&r.summary.requests>0?q(r.summary.totalTokens,e):`—`}),(0,Q.jsx)(`div`,{className:`muted text-label dash-stat-coverage`,children:r&&r.summary.requests>0?h(`dash.coverage`).replace(`{pct}`,`${Math.round(r.summary.coverageRatio*100)}%`):`\xA0`})]})]}),(0,Q.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,Q.jsxs)(`button`,{type:`button`,className:`startup-health-bar`,onClick:()=>qt(`startup`),children:[(0,Q.jsx)(`span`,{className:`dot ${o===`error`?`dot-red`:o===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`startup-health-bar__summary`,children:h(o===`error`?`startup.error`:o===`at-risk`?`startup.summary.atRisk`:o===`protected`?`startup.summary.protected`:`startup.summary.native`)})]}):(0,Q.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`dot dot-amber`}),(0,Q.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),(0,Q.jsx)(gr,{data:r}),s.length>0&&(0,Q.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,Q.jsx)(Ae,{}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:h(`dash.projectConfigTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:h(`dash.projectConfigHint`)}),(0,Q.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,Q.jsxs)(`li`,{style:{marginBottom:8},children:[(0,Q.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,Q.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}var vr=`gpt-daybreak-blue-latest`,yr=`gpt-6-astra`,br=`gpt-6-sol`,xr=`gpt-6-luna`,Sr=`gpt-6.1-sol`,Cr=`gpt-6-astra-minor`,wr=Object.freeze({contextWindow:272e3,maxContextWindow:872e3,maxInputTokens:872e3});Object.freeze({...wr,contextWindow:5e5});var Tr=new Set([vr,Cr]),Er=Object.freeze({[vr]:`gpt-5.6-sol`,[Cr]:yr});Object.freeze(Object.keys(Er)),Object.freeze({[vr]:{displayName:`Daybreak Blue`,description:`Frontier general-purpose model with safeguards for defensive cybersecurity work.`},[Cr]:{displayName:`GPT-6-Astra-Minor`,description:`Unreleased GPT-6 Astra variant; shown only when your account's Codex roster lists it.`}});var Dr=[...Object.freeze([`gpt-5.5`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`,vr,yr,br,xr,Sr,Cr])],Or=new Set(Dr);[...Tr];var kr=18e5,Ar=[`account_unavailable`,`access_denied`,`rate_limited`,`upstream_error`,`redirect_blocked`,`destination_blocked`,`dns_failed`,`timeout`,`transport_error`,`response_unusable`];function jr(e){return Ar.find(t=>t===e)}var Mr=1e3,Nr=12e4,Pr=4e3;function Fr(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 Ir(e){return e?e.adapter===`jev-decision`?e.disabled===!0?`disabled`:Fr(e.baseUrl??``)?!e.defaultModel?.trim()&&!e.models?.[0]?.trim()?`model`:null:`endpoint`:`notDecision`:`missing`}function Lr(e){return e.name===`jev`?e.adapter===`jev-decision`&&e.disabled!==!0&&e.hasApiKey===!0:Ir(e)===null}var Rr={typesafe:`cws.jev.backend.typesafe`,systemone:`cws.jev.backend.systemone`,model:`cws.jev.backend.model`,unknown:`cws.jev.backend.unknown`};function zr(e){return e.decisionModel==null?e.decisionProvider!=null&&e.decisionProvider.trim()!==`jev`?`systemone`:`typesafe`:`model`}function Br(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 Vr(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=>!Br(e,n,r)).sort((e,t)=>e.localeCompare(t))}var Hr=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],Ur=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`,`jev`],Wr={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`},Gr={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`},Kr={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`},qr=new Set(Ur),Jr={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 Yr(e,t,n=`strict`){let r=e.filter(e=>e.provider.trim()&&e.model.trim());if(r.length===0)return[...Hr];let i=new Set(Hr),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[...Hr];let o=new Set(a);return Hr.filter(e=>o.has(e))}var Xr=kr,Zr=0;function Qr(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-${++Zr}`}}function $r(e){return e===`disabled`?`disabled`:`auto`}function ei(e){return e===`adaptive`?`adaptive`:`strict`}var ti=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,ni=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,ri=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function ii(e){return ti.test(e.trim())}function ai(e){return`combo/${e.trim()}`}function oi(e,t){return(typeof t==`string`?t.trim():``)||ai(e)}function si(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!ri.test(n));return{...e,alias:n?t:null,model:oi(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function ci(e){let t=typeof e==`string`?e.trim():``;return t&&t!==`jev`?t:null}function li(e){return typeof e==`number`&&Number.isInteger(e)?e:null}function ui(e){return typeof e==`string`&&e.trim()?e.trim():null}function di(e){return typeof e==`string`&&qr.has(e)?e:`failover`}function fi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function pi(e){return typeof e==`string`&&Hr.includes(e)?e:null}function mi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function hi(e){if(!Array.isArray(e)||e.length===0)return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`||!Hr.includes(r))return;let e=r;if(n.has(e))return;n.add(e),t.push(e)}return t}function gi(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=mi(t.weight),o=hi(t.reasoningEfforts);a.push(Qr({provider:n,model:r,...i===void 0?{}:{weight:i},...o===void 0?{}:{reasoningEfforts:o},...typeof t.modelProfile==`string`?{modelProfile:t.modelProfile}:{}}))}let o=ci(t.decisionProvider),s=ui(t.decisionModel),c=li(t.decisionTimeoutMs);n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():oi(r,ui(t.alias)),alias:ui(t.alias),nativeAlias:t.nativeAlias===!0,displayName:ui(t.displayName),strategy:di(t.strategy),stickyLimit:fi(t.stickyLimit),defaultEffort:pi(t.defaultEffort),imageInput:$r(t.imageInput),reasoningEffortMode:ei(t.reasoningEffortMode),...o===null?{}:{decisionProvider:o},...s===null?{}:{decisionModel:s},...c===null?{}:{decisionTimeoutMs:c},targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function _i(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 vi(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 yi(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function bi(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function xi(e,t){let n=yi(e.routingQuota);if(!n||n.state!==`available`&&n.state!==`exhausted`)return null;let r=bi(n.updatedAt),i=bi(n.validUntil);return r===null||r<0||r>t||t-r>=Xr||i===null||i<=t||i>r+Xr?null:{state:n.state,validUntil:i}}function Si(e,t){return xi(e,t)?.state??`unknown`}function Ci(e,t=Date.now()){if(!Array.isArray(e))return;let n;for(let r of e){let e=yi(r);if(!e||typeof e.provider!=`string`||!e.provider.trim())continue;let i=xi(e,t);i&&(n===void 0||i.validUntil<n)&&(n=i.validUntil)}return n}function wi(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=yi(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Si(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function Ti(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 Ei(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&&Ti(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function Di(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 Oi(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.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)&&Di(e,r)&&(e.modelProfile??``)===(r.modelProfile??``)})}function ki(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},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:ci(e.decisionProvider),decisionModel:e.decisionModel?.trim()||null,decisionTimeoutMs:e.decisionTimeoutMs??null}:{}}}}function Ai(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!ii(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(!ni.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&ri.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&&!Or.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=>!Hr.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.decisionTimeoutMs!=null&&(!Number.isInteger(e.decisionTimeoutMs)||e.decisionTimeoutMs<1e3||e.decisionTimeoutMs>12e4))return`invalidDecisionTimeout`;if(e.strategy===`jev`&&zr(e)===`model`){let n=e.decisionModel?.trim()??``;if(!n||n.length>512||e.decisionProvider!=null||Br(n,t.combos??[],e)||t.decisionModels&&!t.decisionModels.includes(n))return`invalidDecisionModel`}return e.strategy===`jev`&&zr(e)===`systemone`&&(!e.decisionProvider?.trim()||Pi(e.decisionProvider,t.providers)!==null)?`invalidDecisionProvider`:e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function ji(e=``){return{id:e,model:e?ai(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`strict`,targets:[Qr()]}}var Mi=[`gpt-6-astra`,`gpt-5.6-sol`,`gpt-5.6-luna`];function Ni(e,t,n){let r=Mi.flatMap(n=>{let r=e.find(e=>e.id===n&&(t===void 0||t.has(e.provider)));return r?[Qr({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:ci(n),targets:r.length>0?r:[Qr()]}}function Pi(e,t){let n=ci(e);return n===null?null:Ir(Object.hasOwn(t,n)?t[n]:void 0)}function Fi(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=Ir(e);return{id:e.name,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t?{issue:t}:{}}}),r=ci(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 Ii(e,t){if(e.strategy!==`jev`)return null;let n=ci(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 Li=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],Ri=[`manual`,`auto`],zi=300,Bi=[`manual`,`manual+auto`,`auto`],Vi={manual:`compactionRouting.triggersManual`,"manual+auto":`compactionRouting.triggersBoth`,auto:`compactionRouting.triggersAuto`},Hi=[`all`,`selected`],Ui={all:`compactionRouting.sourcesAll`,selected:`compactionRouting.sourcesSelected`};function Wi(e){if(!e)return`manual`;let t=e.includes(`auto`);return e.includes(`manual`)?t?`manual+auto`:`manual`:t?`auto`:`manual`}function Gi(e){if(e===`auto`)return[`auto`];if(e===`manual+auto`)return[`manual`,`auto`]}function Ki(e){let t=new Map;for(let n of gi(e))t.set(n.model,[...new Set(n.targets.flatMap(e=>e.provider?[e.provider]:[]))]);return t}function qi(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`||!Li.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`&&Ri.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 Ji(e){if(!e)return``;try{return new URL(e).hostname||e}catch{return e}}function Yi(e,t){let n=t.get(e);return n?`${e} (${n})`:e}function Xi(e){return(0,Q.jsx)(Zi,{...e},e.apiBase)}function Zi({apiBase:e,models:t,providers:n=[]}){let r=O(),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(`manual`),[f,p]=(0,Z.useState)(`all`),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(()=>new Map),E=(0,Z.useRef)(!1),D=(0,Z.useRef)(null),k=(0,Z.useCallback)(e=>{a(e),s(e?.model??``),l(e?.reasoningEffort??``),d(Wi(e?.triggers)),p(e?.sourceModels?`selected`:`all`),h(e?.sourceModels??[])},[]),j=e=>{h(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),C(null)},M=(0,Z.useCallback)(async()=>{if(D.current)return;let t=A(15e3);D.current=t,x(!1);try{let n=qi(await Tn(await fetch(`${e}/api/settings`,{signal:t.signal})));E.current&&D.current===t&&k(n);let r=await fetch(`${e}/api/combos`,{signal:t.signal}).then(Tn).then(Ki).catch(()=>new Map);E.current&&D.current===t&&T(r)}catch{E.current&&D.current===t&&x(!0)}finally{t.clear(),D.current===t&&(D.current=null)}},[e,k]);(0,Z.useEffect)(()=>{E.current=!0;let e=window.setTimeout(()=>{M()},0);return()=>{window.clearTimeout(e),E.current=!1,D.current?.controller.abort(),D.current?.clear(),D.current=null}},[M]);let N=async()=>{if(D.current||i===void 0)return;let t=A(15e3);D.current=t,y(!0),C(null);try{let n=qi(await Tn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({compactionRouting:o?{model:o,...c?{reasoningEffort:c}:{},...Gi(u)?{triggers:Gi(u)}:{},...f===`selected`&&m.length>0?{sourceModels:m}:{}}:null}),signal:t.signal})));E.current&&D.current===t&&(k(n),C(`saved`))}catch{E.current&&D.current===t&&C(`failed`)}finally{t.clear(),E.current&&D.current===t&&y(!1),D.current===t&&(D.current=null)}},P=[{value:``,label:r(`compactionRouting.currentModel`)},...[...new Set([...t.map(e=>e.namespaced),...o?[o]:[]])].map(e=>({value:e,label:xe(e,r)}))],F=[...new Set([...n.map(e=>e.name),...t.flatMap(e=>e.provider?[e.provider]:[])])].map(e=>`${e}/*`),I=new Set([...F,...t.map(e=>e.namespaced)]),L=(i?.sourceModels??[]).filter(e=>!I.has(e)),R=v||i===void 0||b,z=i?.sourceModels?`selected`:`all`,B=new Set(i?.sourceModels),V=o!==(i?.model??``)||c!==(i?.reasoningEffort??``)||u!==Wi(i?.triggers)||f!==z||f===`selected`&&(m.length!==(i?.sourceModels?.length??0)||m.some(e=>!B.has(e))),H=f===`selected`&&m.length===0,U=new Set(m),W=[...new Set(t.map(e=>e.namespaced))].filter(e=>e.toLowerCase().includes(g.trim().toLowerCase())),G=e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:U.has(e),disabled:R,onChange:()=>{j(e)}}),(0,Q.jsx)(`span`,{children:e})]},e),ee=w.get(o),K=ee!==void 0||o.startsWith(ai(``)),q=o.slice(0,Math.max(o.indexOf(`/`),0)),te=new Map(n.map(e=>[e.name,Ji(e.baseUrl)]).filter(([,e])=>e)),ne=K?``:Yi(q||o,te),J=ee?.map(e=>Yi(e,te)).join(`, `)||r(`compactionRouting.comboProvidersUnknown`),Y=u!==`manual`,re=m.join(`, `),ie=!o||H?null:K?f===`selected`?r(`compactionRouting.comboWarningScoped`,{combo:o,providers:J,sources:re}):r(`compactionRouting.comboWarning`,{combo:o,providers:J}):f===`selected`?r(`compactionRouting.providerWarningScoped`,{provider:ne,sources:re}):r(`compactionRouting.providerWarning`,{provider:ne});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`compaction-routing-title`,"aria-busy":v||i===void 0&&!b,children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`flex-start`,flexWrap:`wrap`},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 20rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`compaction-routing-title`,children:r(`compactionRouting.title`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.description`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.dataNotice`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.effortHint`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.sourcesHint`)})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls compaction-routing-controls`,style:{flex:`0 1 auto`},children:[(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-model`,children:r(`compactionRouting.model`)}),(0,Q.jsx)(cn,{id:`compaction-routing-model`,value:o,options:P,disabled:R,label:r(`compactionRouting.model`),onChange:e=>{s(e),e||(l(``),d(`manual`),p(`all`),h([])),C(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-triggers`,children:r(`compactionRouting.triggers`)}),(0,Q.jsx)(cn,{id:`compaction-routing-triggers`,value:u,disabled:R||!o,align:`right`,label:r(`compactionRouting.triggers`),options:Bi.map(e=>({value:e,label:r(Vi[e])})),onChange:e=>{d(e),C(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-sources`,children:r(`compactionRouting.sources`)}),(0,Q.jsx)(cn,{id:`compaction-routing-sources`,value:f,disabled:R||!o,align:`right`,label:r(`compactionRouting.sources`),options:Hi.map(e=>({value:e,label:r(Ui[e])})),onChange:e=>{p(e),C(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-effort`,children:r(`compactionRouting.effort`)}),(0,Q.jsx)(cn,{id:`compaction-routing-effort`,value:c,disabled:R||!o,align:`right`,label:r(`compactionRouting.effort`),options:[{value:``,label:r(`compactionRouting.currentEffort`)},...Li.map(e=>({value:e,label:r(`models.reasoningEffort.${e}`)}))],onChange:e=>{l(e),C(null)}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:R||!V||H,onClick:()=>{N()},children:r(v?`common.saving`:`common.save`)})]})]}),o&&f===`selected`&&(0,Q.jsxs)(`div`,{className:`compaction-sources-block`,children:[(0,Q.jsx)(`div`,{className:`field-label compaction-sources-title`,children:r(`compactionRouting.sourcesGridTitle`)}),(0,Q.jsxs)(`div`,{className:`source-scope-groups`,children:[F.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:r(`compactionRouting.sourcesProviders`)}),F.map(G)]}),t.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:r(`compactionRouting.sourcesModels`)}),(0,Q.jsx)(`input`,{type:`search`,className:`input`,value:g,disabled:R,"aria-label":r(`pws.modelSearchPlaceholder`),placeholder:r(`pws.modelSearchPlaceholder`),onChange:e=>_(e.target.value)}),W.slice(0,zi).map(G),W.length>zi&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:r(`pws.modelsTruncated`,{shown:zi,total:W.length})})]}),L.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:r(`compactionRouting.sourcesSaved`)}),L.map(G)]}),H&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`compactionRouting.sourcesNone`)})]})]}),ie&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ae,{width:14}),` `,ie]}),o&&Y&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ae,{width:14}),` `,r(`compactionRouting.autoNotice`)]}),b&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[r(`compactionRouting.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{M()},children:r(`common.retry`)})]}),S===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:r(`compactionRouting.saveFailed`)}),S===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:r(`compactionRouting.saved`)})]})}var Qi=0;function $i(e){let t=e.split(/\n{2,}/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}function ea(e,t,n,r){let i=o[e],a=`opencodex-action-dialog-${++Qi}`,s=document.activeElement,c=typeof s?.focus==`function`?s:null,l=!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(!l){l=!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(),c?.isConnected&&c.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 ta(e,t,n,r=`div`){let i=document.createElement(r);i.id=t;for(let e of $i(n)){let t=document.createElement(`p`);t.className=`modal-desc`,t.textContent=e,i.append(t)}return e.append(i),i}function na(e){let t=e.locale??a(),n=o[t],r=e.tone===`danger`;return new Promise(i=>{if(e.signal?.aborted){i(!1);return}let{form:a,bodyId:o,finish:s}=ea(t,!1,i,e.signal);ta(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 ra(e){let t=e.locale??a(),n=o[t];return new Promise(r=>{if(e.signal?.aborted){r(null);return}let{form:i,bodyId:a,finish:o}=ea(t,null,r,e.signal),s=document.createElement(`input`),c=`${a}-input`,l=ta(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;if(f(r),r!==null){h.disabled=!0,s.focus();return}o(n)}),s.addEventListener(`input`,()=>{h.disabled&&=!1,u.hidden||f(null)}),p.append(m,h),i.append(s,u,p),queueMicrotask(()=>s.focus())})}function ia(){return ut()}function aa(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function oa(e){if(typeof window<`u`&&typeof window.clearInterval==`function`){window.clearInterval(e);return}clearInterval(e)}function sa(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=aa(o,t))},c=()=>{i!==null&&(oa(i),i=null)},l=()=>{if(r){if(ia()){c();return}o(),s()}};r&&ia()||s();let u=r?dt(l):null;return n?.immediate&&o(),()=>{a=!0,c(),u?.()}}var ca=new Map;function la(e,t){let n=`${e}:${t}`,r=ca.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),ca.set(n,r)),r}var ua=new Map;function da(e){let t=ua.get(e);return t||(t=new Intl.NumberFormat(e),ua.set(e,t)),t}function fa(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`${la(t,r===0?0:1).format(i)} ${n[r]}`}function pa(e,t){return!Number.isFinite(e)||e<0?`—`:ur(e/1e3,t)}function ma(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function ha(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 ga(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:(ma(n)-ma(t))/r*36e5}function _a({label:e,value:t,sub:n,tone:r}){return(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`label`,children:e}),(0,Q.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,Q.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function va({observedBytes:e,thresholdBytes:t,metric:n,locale:r,t:i}){let a=e!==null&&t!==null&&t>0?e/t:null,o=a===null?`unknown`:a>=1?`over`:a>=.75?`warn`:`ok`,s=a===null?null:Math.round(a*100);return(0,Q.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,Q.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,Q.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,Q.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,Q.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:fa(e,r),t!==null&&(0,Q.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,fa(t,r)]})]})]}),(0,Q.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,Q.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,Q.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var ya=60,ba=1500,xa=12e4;function Sa({apiBase:e}){let{locale:n,t:r}=t(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(`idle`),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await fetch(`${e}/api/startup-health`);if(!n.ok||t)return;let r=await n.json();t||p(r.protection===`none`)}catch{}})(),()=>{t=!0}},[e]),(0,Z.useEffect)(()=>{let t=!1,n=!1,r=null,i=async()=>{if(n)return;n=!0;let i=A(1e4);r=i;try{let n=await fetch(`${e}/api/system/memory`,{signal:i.signal});if(!n.ok)throw Error(`memory unavailable`);let r=await n.json();if(t)return;a(r),s(!1),h(typeof r.activeTurnCount==`number`),r.isDraining&&c===`idle`&&l(`draining`),(c===`draining`||c===`reconnecting`)&&g!=null&&typeof r.pid==`number`&&r.pid!==g&&!r.isDraining&&(l(`idle`),_(null),d(null))}catch{if(t)return;c===`draining`||c===`reconnecting`?l(`reconnecting`):s(!0)}finally{i.clear(),r===i&&(r=null),n=!1}};i();let o=sa(()=>void i(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),o()}},[e,c,g]),(0,Z.useEffect)(()=>{if(c!==`reconnecting`)return;let t=!1,n=!1,i=null,a=Date.now(),o=()=>{if(n||t)return;n=!0;let o=A(5e3);i=o,fetch(`${e}/api/system/health`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=xa&&(l(`error`),d(r(`dash.mem.restartFailed`)));return}let n=g==null;if(g!=null)try{let t=await e.json();n=typeof t.pid==`number`&&t.pid!==g}catch{n=!0}if(!t){if(n){l(`idle`),_(null),d(null);return}Date.now()-a>=xa&&(l(`error`),d(r(`dash.mem.restartFailed`)))}}).catch(()=>{t||Date.now()-a>=xa&&(l(`error`),d(r(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),n=!1})};o();let s=setInterval(o,ba);return()=>{t=!0,i?.controller.abort(),i?.clear(),clearInterval(s)}},[e,c,g,r]);let v=async()=>{let t=i?.activeTurnCount??0,n=[r(`dash.mem.restartConfirm`,{count:t,seconds:ya})];if(f&&n.push(r(`dash.mem.restartNoSupervisor`)),await na({message:n.join(`
|
|
2
|
+
|
|
3
|
+
`),tone:`danger`})){d(null),_(typeof i?.pid==`number`?i.pid:null),l(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{l(`error`),_(null),d(r(`dash.mem.restartFailed`))}}};if(o&&!i&&c===`idle`)return(0,Q.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(j,{width:16,height:16,"aria-hidden":`true`}),r(`dash.mem.title`)]}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:r(`dash.mem.unavailable`)})]});let y=i?.watchdog?ga(i.watchdog.samples):null,b=i?i.observedBytes??i.watchdog?.observedBytes??ma(i):null,x=i?ha(i):null,S=(()=>{let e=i?.watchdog?.warnThresholdBytes;if(y===null||y<=0||b===null||!e)return;let t=e-b;if(t<=0)return`danger`;let n=t/y;if(n<=1)return`danger`;if(n<=8)return`warn`})(),C=i?.responseState,w=i?.activeTurnCount,T=c===`draining`||c===`reconnecting`;return(0,Q.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Q.jsxs)(`div`,{className:`mem-head`,children:[(0,Q.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,Q.jsx)(j,{width:16,height:16,"aria-hidden":`true`}),r(`dash.mem.title`)]}),m&&(0,Q.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,Q.jsxs)(`span`,{className:`mem-inflight`,children:[(0,Q.jsx)(`span`,{className:`mem-inflight-label`,children:r(`dash.mem.inFlight`)}),(0,Q.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?da(n).format(w):`—`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:()=>{v()},children:r(`dash.mem.restart`)})]})]}),(0,Q.jsx)(va,{observedBytes:b,thresholdBytes:i?.watchdog?.warnThresholdBytes??null,metric:x,locale:n,t:r}),(0,Q.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,Q.jsx)(_a,{label:r(`dash.mem.rss`),value:i?fa(i.rss,n):`—`}),(0,Q.jsx)(_a,{label:r(`dash.mem.jsHeap`),value:i?fa(i.heapUsed,n):`—`,sub:i?r(`dash.mem.jsHeapArena`,{total:fa(i.heapTotal,n)}):void 0}),(0,Q.jsx)(_a,{label:r(`dash.mem.jscHeap`),value:i?.jscHeap?fa(i.jscHeap.heapSize,n):`—`}),(0,Q.jsx)(_a,{label:r(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${fa(Math.abs(y),n)}${r(`dash.mem.perHour`)}`,tone:S})]}),(0,Q.jsxs)(`details`,{style:{marginTop:10},children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:r(`dash.mem.details`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:r(`dash.mem.hint`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:r(`dash.mem.runtime`)}),(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsx)(_a,{label:r(`dash.mem.observed`),value:b===null?`—`:`${fa(b,n)} (${x})`}),(0,Q.jsx)(_a,{label:r(`dash.mem.external`),value:i?.external===void 0?`—`:fa(i.external,n)}),(0,Q.jsx)(_a,{label:r(`dash.mem.arrayBuffers`),value:i?.arrayBuffers===void 0?`—`:fa(i.arrayBuffers,n)})]}),(0,Q.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:r(`dash.mem.store`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:r(`dash.mem.storeHint`)}),(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsx)(_a,{label:r(`dash.mem.storeEntries`),value:C?da(n).format(C.count):`—`}),(0,Q.jsx)(_a,{label:r(`dash.mem.storeTotal`),value:C?fa(C.totalBytes,n):`—`}),(0,Q.jsx)(_a,{label:r(`dash.mem.storeLargest`),value:C?fa(C.largestBytes,n):`—`}),(0,Q.jsx)(_a,{label:r(`dash.mem.storeOldest`),value:C?C.count===0?`—`:pa(C.oldestAgeMs,n):`—`})]}),i?.watchdog&&(0,Q.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,Q.jsx)(_a,{label:r(`dash.mem.threshold`),value:fa(i.watchdog.warnThresholdBytes,n)}),(0,Q.jsx)(_a,{label:r(`dash.mem.lastWarn`),value:i.watchdog.lastWarnAt?new Date(i.watchdog.lastWarnAt).toLocaleString(n):r(`dash.mem.never`)})]})]}),m&&(0,Q.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[c===`draining`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:r(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),c===`reconnecting`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:r(`dash.mem.reconnecting`)}),c===`error`&&u&&(0,Q.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:u}),f&&c===`idle`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:r(`dash.mem.restartNoSupervisor`)})]})]})}var Ca=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function wa(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`||!Ca.includes(a)))throw Error(`invalid effort`);n[e]={model:i,...a?{reasoningEffort:a}:{}}}return n}function Ta(e,t){return e?{model:e,...t?{reasoningEffort:t}:{}}:void 0}function Ea(e){return(0,Q.jsx)(Da,{...e},e.apiBase)}function Da({apiBase:e,models:t}){let n=O(),[r,i]=(0,Z.useState)(void 0),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(``),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(null),x=(0,Z.useRef)(!1),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=rr(a,C),T=(0,Z.useCallback)(e=>{i(e),c(e.extract?.model??``),u(e.extract?.reasoningEffort??``),f(e.consolidation?.model??``),m(e.consolidation?.reasoningEffort??``)},[]),E=(0,Z.useCallback)(async()=>{if(S.current)return;let t=A(15e3);S.current=t,v(!1);try{let n=wa(await Tn(await fetch(`${e}/api/settings`,{signal:t.signal})));x.current&&S.current===t&&T(n)}catch{x.current&&S.current===t&&v(!0)}finally{t.clear(),S.current===t&&(S.current=null)}},[e,T]);(0,Z.useEffect)(()=>{x.current=!0;let e=window.setTimeout(()=>{E()},0);return()=>{window.clearTimeout(e),x.current=!1,S.current?.controller.abort(),S.current?.clear(),S.current=null}},[E]);let D=async()=>{if(S.current||r===void 0)return;let t=A(15e3);S.current=t,g(!0),b(null);let n=Ta(s,l),i=Ta(d,p);try{let r=wa(await Tn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({memoryModels:n||i?{...n?{extract:n}:{},...i?{consolidation:i}:{}}:null}),signal:t.signal})));x.current&&S.current===t&&(T(r),b(`saved`))}catch{x.current&&S.current===t&&b(`failed`)}finally{t.clear(),x.current&&S.current===t&&g(!1),S.current===t&&(S.current=null)}},k=[{value:``,label:n(`memoryModels.off`)},...[...new Set([...t.map(e=>e.namespaced),...[s,d].filter(Boolean)])].map(e=>({value:e,label:xe(e,n)}))],j=[{value:``,label:n(`memoryModels.defaultEffort`)},...Ca.map(e=>({value:e,label:n(`models.reasoningEffort.${e}`)}))],M=h||r===void 0||_,N=s!==(r?.extract?.model??``)||l!==(r?.extract?.reasoningEffort??``)||d!==(r?.consolidation?.model??``)||p!==(r?.consolidation?.reasoningEffort??``),P=!!s!=!!d,F=n(`memoryModels.info`),I=(e,t,r,i,a)=>(0,Q.jsxs)(`div`,{className:`spread memory-models-row`,style:{flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 18rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:n(`memoryModels.${e}`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:n(`memoryModels.${e}Hint`)})]}),(0,Q.jsxs)(`div`,{className:`memory-models-controls`,children:[(0,Q.jsx)(cn,{id:`memory-models-${e}`,value:t,options:k,disabled:M,label:n(`memoryModels.model`),onChange:e=>{i(e),e||a(``),b(null)}}),(0,Q.jsx)(cn,{id:`memory-models-${e}-effort`,value:r,options:j,disabled:M||!t,align:`right`,label:n(`memoryModels.effort`),onChange:e=>{a(e),b(null)}})]})]});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`memory-models-title`,"aria-busy":h||r===void 0&&!_,children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,id:`memory-models-title`,style:{display:`flex`,alignItems:`center`,gap:6},children:[n(`memoryModels.title`),(0,Q.jsx)(`button`,{ref:C,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>o(e=>!e),"aria-label":n(`memoryModels.infoLabel`),"aria-expanded":a,"aria-haspopup":`dialog`,"aria-controls":`memory-models-help-dialog`,children:(0,Q.jsx)(we,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:n(`memoryModels.description`)}),I(`extract`,s,l,c,u),I(`consolidation`,d,p,f,m),(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`,flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Q.jsx)(`div`,{className:`muted setting-hint`,style:{flex:`1 1 18rem`,minWidth:0},children:n(`memoryModels.dataNotice`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:M||!N,onClick:()=>{D()},children:n(h?`common.saving`:`common.save`)})]}),P&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ae,{width:14}),` `,n(`memoryModels.accountNotice`)]}),_&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[n(`memoryModels.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{E()},children:n(`common.retry`)})]}),y===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:n(`memoryModels.saveFailed`)}),y===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:n(`memoryModels.saved`)}),(0,Q.jsxs)(`dialog`,{ref:w,id:`memory-models-help-dialog`,className:`modal-overlay`,style:{display:a?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`memory-models-help-title`,onCancel:e=>{e.preventDefault(),o(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:()=>o(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`memory-models-help-title`,children:n(`memoryModels.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>o(!1),"aria-label":n(`common.close`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:F}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!1),children:n(`common.ok`)})})]})]})]})}function Oa({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;return!i||r===`v1`?null:(0,Q.jsx)(`div`,{className:`panel dash-effort-panel`,children:(0,Q.jsxs)(`div`,{className:`injection-head`,children:[(0,Q.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,Q.jsx)(`button`,{ref:a,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":n(`dash.effortCapLabel`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`effort-cap-help-dialog`,children:(0,Q.jsx)(we,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Q.jsxs)(`div`,{className:`dash-effort-controls`,children:[(0,Q.jsx)(cn,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...En.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Tn(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({effortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.effortCapLabel`),align:`right`}),(0,Q.jsx)(cn,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...En.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Tn(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subagentEffortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.subagentEffortCapLabel`),align:`right`})]})]})})}function ka({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,Q.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsx)(cn,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:xe(`${e.provider}/${e.model}`,t)}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`),align:`right`}),n&&i.length>0&&(0,Q.jsx)(cn,{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`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>qt(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function Aa({d:e}){let{t,runSync:n,syncing:r,settingsSaving:i,updateTriggerRef:a,openUpdateDialog:o,updateLoading:s,updateOpen:c,syncResult:l,syncError:u,updateJob:d,reconnecting:f,clearSyncFeedback:p}=e,m=!!l&&(!!l.warning||!!l.nativeSubagentDefaultsWarning||!!l.staleAppServerHint),[h,g]=(0,Z.useState)(!1),_=(0,Z.useRef)(null);(0,Z.useEffect)(()=>(_.current&&=(clearTimeout(_.current),null),(l||u)&&!m&&(_.current=setTimeout(()=>{_.current=null,g(!0),p()},u?8e3:6e3)),()=>{_.current&&clearTimeout(_.current)}),[l,u,m,p]);let v=()=>{g(!1),n()},y=()=>{g(!0),p()};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,Q.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,Q.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,Q.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,Q.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:r||i,children:[(0,Q.jsx)(re,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,Q.jsx)(`button`,{ref:a,type:`button`,className:`maintenance-update-anchor`,onClick:o,disabled:s,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":c,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]})]}),d&&(0,Q.jsxs)(`div`,{className:`notice ${d.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[d.status===`failed`?(0,Q.jsx)(Ae,{}):(0,Q.jsx)(re,{}),(0,Q.jsxs)(`span`,{children:[kn(d.status,t),d.latestVersion?` ${t(`dash.updateVersionTransition`,{currentVersion:d.currentVersion,latestVersion:d.latestVersion})}`:``,f?` ${t(`dash.updateReconnecting`)}`:``,d.error?` ${d.error}`:``]})]})]}),!h&&l&&(0,Q.jsxs)(`div`,{className:`action-toast notice ${m?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[m?(0,Q.jsx)(Ae,{}):(0,Q.jsx)(Te,{}),(0,Q.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:l.added}),l.warning?` ${l.warning}`:``,l.nativeSubagentDefaultsWarning?` ${l.nativeSubagentDefaultsWarning}`:``,l.staleAppServerHint?(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(T,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Q.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})]}),!h&&u&&(0,Q.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,Q.jsx)(Ae,{}),(0,Q.jsx)(`span`,{children:t(`dash.syncFailed`,{error:u})}),(0,Q.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Q.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})]})]})}function ja({t:e,open:t,triggerRef:n,onClose:r,maxValue:i,maxInvalid:a,timeoutValue:o,timeoutInvalid:s,disabled:c,setMaxDraft:l,setMaxInvalid:u,setTimeoutDraft:d,setTimeoutInvalid:f,commitMaxDescriptions:p,commitTimeout:m}){let h=(0,Z.useRef)(null),g=(0,Z.useRef)(null),[_,v]=(0,Z.useState)(),y=(0,Z.useCallback)(()=>{n.current&&v(an(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,Z.useLayoutEffect)(()=>{if(!t)return;y();let e=()=>y();return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[t,y,a,s]),(0,Z.useEffect)(()=>{if(!t)return;let e=e=>{let t=e.target;if(h.current?.contains(t)||n.current?.contains(t))return;let i=document.activeElement;i&&h.current?.contains(i)&&i.blur(),r()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t,r,n]),(0,Z.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),r(),n.current?.focus())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,r,n]),(0,Z.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,Q.jsxs)(`div`,{ref:h,id:`dash-vision-advanced-popover`,className:`dash-vision-advanced-popover`,role:`dialog`,"aria-modal":`false`,"aria-label":e(`dash.visionAdvancedPopover`),style:{..._,zIndex:60},children:[(0,Q.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,Q.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Q.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,Q.jsx)(`input`,{ref:g,className:`input mono codex-auto-switch-input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:i,disabled:c,"aria-invalid":a||void 0,"aria-label":e(`dash.visionMaxDescriptions`),"aria-describedby":a?`dash-vision-max-error dash-vision-max-label`:`dash-vision-max-label`,onChange:e=>{u(!1),l(e.target.value)},onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),p(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),l(null),u(!1)))}})}),a&&(0,Q.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,Q.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Q.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:Bn,max:zn,step:1e3,inputMode:`numeric`,value:o,disabled:c,"aria-invalid":s||void 0,"aria-label":e(`dash.visionTimeout`),"aria-describedby":s?`dash-vision-timeout-error dash-vision-timeout-label`:`dash-vision-timeout-label`,onChange:e=>{f(!1),d(e.target.value)},onBlur:e=>m(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),m(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),d(null),f(!1)))}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,Q.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:Bn,max:zn})})]})]}):null}function Ma({d:e}){let{t,settings:n,settingsSaving:r,syncing:i,toggleCodexAutoStart:a,toggleCodexDesktopAuthless:o,toggleCodexClientCompaction:s,sidecar:c,sidecarSaving:l,sidecarModels:u,visionModels:d,models:f,saveSidecar:p,sidecarCodexApply:m,shadowCall:h,shadowCallSaving:g,shadowCallHelpTriggerRef:_,shadowCallHelpOpen:v,setShadowCallHelpOpen:y,saveShadowCall:b}=e,x=c?.vision?.enabled!==!1,S=x?c?.vision?.model??`gpt-5.6-luna`:``,C=c?.vision.backend??d.find(e=>e.value===c?.vision.model)?.backend,w=c?.webSearch.backend??u.find(e=>e.value===c?.webSearch.model)?.backend,T=c?.webSearch?.enabled!==!1,E=T?c?.webSearch?.model??`gpt-5.6-luna`:``,D=c?.vision?.reasoning??`low`,O=Wn(f,S),k=Kn(O,D),A=String(c?.vision?.maxDescriptionsPerTurn??8),j=String(c?.vision?.timeoutMs??Rn),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(!1),[R,z]=(0,Z.useState)(!1),[B,V]=(0,Z.useState)(!1),H=(0,Z.useRef)(null),U=M??A,W=P??j,G=(e=U)=>{let t=Vn(e);if(t===void 0){N(e),L(!0);return}L(!1),N(null),t!==(c?.vision?.maxDescriptionsPerTurn??8)&&p(In(t))},ee=(e=W)=>{let t=Hn(e);if(t===void 0){F(e),z(!0);return}z(!1),F(null),t!==(c?.vision?.timeoutMs??Rn)&&p(Ln(t))};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`panel`,children:(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${n?.codexAutoStart??!0?`on`:``}`,onClick:a,disabled:!n||r||i,"aria-label":t(`dash.codexAutoStart`),"aria-pressed":n?.codexAutoStart??!0,children:(0,Q.jsx)(`span`,{className:`knob`})})]})}),(0,Q.jsx)(`div`,{className:`panel`,children:(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexDesktopAuthless`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexDesktopAuthlessHint`)}),n?.codexDesktopAuthless&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexRemoteHistoryHint`)}),n?.catalogRefreshPending&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${n?.codexDesktopAuthless??!1?`on`:``}`,onClick:o,disabled:!n||r||i,"aria-label":t(`dash.codexDesktopAuthless`),"aria-pressed":n?.codexDesktopAuthless??!1,children:(0,Q.jsx)(`span`,{className:`knob`})})]})}),(0,Q.jsx)(`div`,{className:`panel`,children:(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexClientCompaction`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexClientCompactionHint`)}),!n?.codexDesktopAuthless&&n?.codexClientCompaction&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexRemoteHistoryHint`)}),n?.catalogRefreshPending&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${n?.codexClientCompaction??!1?`on`:``}`,onClick:s,disabled:!n||r||i,"aria-label":t(`dash.codexClientCompaction`),"aria-pressed":n?.codexClientCompaction??!1,children:(0,Q.jsx)(`span`,{className:`knob`})})]})}),(0,Q.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,Q.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)}),Pn(m)&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ae,{}),(0,Q.jsx)(`span`,{children:t(`dash.webSearchCodexSync`)})]})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsx)(`div`,{className:`dash-sidecar-select-row`,children:(0,Q.jsx)(cn,{value:E,options:[{value:``,label:t(`dash.webSearchOff`)},...u],onChange:e=>{if(e===``){p(Nn(!1));return}let t={webSearch:$n(f,u,e)};T||(t.webSearch={...t.webSearch,enabled:!0}),p(t)},disabled:!c||l,label:t(`dash.sidecarModel`),align:`right`})}),c&&w===`anthropic`&&(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Q.jsx)(cn,{value:c.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:l,align:`right`,onChange:e=>{p({webSearch:{anthropicInstance:e===`anthropic`||e===`anthropic2`?e:null}})}}),c.webSearch.anthropicPool?.mixed&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,title:t(`dash.webSearchStreamHint`),children:[(0,Q.jsx)(`span`,{className:`muted setting-hint dash-sidecar-toggle-label`,children:t(`dash.webSearchStream`)}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${c?.webSearch?.streamRoutedModelOutput?`on`:``}`,onClick:()=>{p({webSearch:{streamRoutedModelOutput:!c?.webSearch?.streamRoutedModelOutput}})},disabled:!T||!c||l,"aria-label":t(`dash.webSearchStream`),"aria-pressed":c?.webSearch?.streamRoutedModelOutput===!0,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]})]}),(0,Q.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-select-row`,children:[(0,Q.jsx)(cn,{value:S,options:[{value:``,label:t(`dash.visionOff`)},...d],onChange:e=>{if(e===``){p(Mn(!1));return}let t=Kn(Wn(f,e),k),n={vision:{model:e,backend:er(f,d,e),reasoning:t}};x||(n.vision={...n.vision,enabled:!0}),p(n)},disabled:!c||l,label:t(`dash.sidecarModel`)}),(0,Q.jsx)(cn,{value:k,options:Gn(O,k).map(e=>({value:e,label:e})),onChange:e=>{p(jn(e))},disabled:!x||!c||l,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),c&&C===`anthropic`&&(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Q.jsx)(cn,{value:c.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:l,align:`right`,onChange:e=>{p({vision:{anthropicInstance:e===`anthropic`||e===`anthropic2`?e:null}})}}),c.vision.anthropicPool?.mixed&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Q.jsx)(`div`,{className:`dash-sidecar-trailing-row`,children:(0,Q.jsxs)(`button`,{type:`button`,ref:H,className:`dash-vision-advanced-trigger`,onClick:()=>V(e=>!e),disabled:!x||!c||l,"aria-expanded":B,"aria-haspopup":`dialog`,"aria-controls":`dash-vision-advanced-popover`,children:[(0,Q.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`,style:{transform:B?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,Jt.createPortal)((0,Q.jsx)(ja,{t,open:B,triggerRef:H,onClose:()=>V(!1),maxValue:U,maxInvalid:I,timeoutValue:W,timeoutInvalid:R,disabled:!x||!c||l,setMaxDraft:N,setMaxInvalid:L,setTimeoutDraft:F,setTimeoutInvalid:z,commitMaxDescriptions:G,commitTimeout:ee}),document.body)]})]}),(0,Q.jsx)(`div`,{className:`panel`,"aria-busy":!h||void 0,children:(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,Q.jsxs)(`div`,{className:`dash-shadow-label`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,Q.jsx)(`button`,{ref:_,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:()=>y(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":v,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,Q.jsx)(we,{width:13,height:13,"aria-hidden":`true`})}),(0,Q.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${bn(h?.sourceModels)}`})]}),(0,Q.jsxs)(`div`,{className:`setting-controls dash-shadow-controls`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`switch ${h?.enabled?`on`:``}`,onClick:()=>b({enabled:!h?.enabled}),disabled:!h||g,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":h?.enabled??!1,children:(0,Q.jsx)(`span`,{className:`knob`})}),(0,Q.jsx)(cn,{value:h?.model??``,options:Xn(f,h?.model,h?.sourceModels).map(e=>e.value===``?e:{...e,label:xe(e.value,t)}),onChange:e=>{b({model:e})},disabled:!h||g||!h?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function Na(e){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Oa,{apiBase:e.apiBase,d:e}),(0,Q.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,Q.jsx)(ka,{apiBase:e.apiBase,d:e}),(0,Q.jsx)(Aa,{d:e})]}),(0,Q.jsx)(Ma,{d:e}),(0,Q.jsx)(Xi,{apiBase:e.apiBase,models:e.models,providers:e.providers}),(0,Q.jsx)(Ea,{apiBase:e.apiBase,models:e.models}),(0,Q.jsx)(Sa,{apiBase:e.apiBase})]})}function Pa(e){return(0,Q.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,Q.jsx)(_r,{...e}),(0,Q.jsx)(Na,{...e})]})}function Fa({t:e,providers:t}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,Q.jsx)(ln,{title:(0,Q.jsx)(T,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:e(`dash.col.name`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,Q.jsx)(`tbody`,{children:t.map(t=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`font-semibold`,children:be(t.name,e)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,Q.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,Q.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var Ia=`__ocxCachedAt`;function La(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Ra(n)?n.data:n}catch{return null}}function Ra(e){return typeof e==`object`&&!!e&&typeof e[Ia]==`number`&&`data`in e}function za(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Ra(n)?{data:n.data,cachedAt:n[Ia]}:{data:n,cachedAt:null}}catch{return null}}function Ba(e,t){try{sessionStorage.setItem(e,JSON.stringify({[Ia]:Date.now(),data:t}))}catch{}}function Va(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function Ha(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 Ua(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,Z.useMemo)(()=>a?za(a):null,[a]),c=Vt(e,t,(0,Z.useCallback)(async e=>{let t=await n(e);return a&&Ba(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:Ha(c,i,r.enabled!==!1)}}function Wa(){return typeof navigator>`u`?``:navigator.userAgent}function Ga(e=Wa()){return e.match(/OpenCodexDesktop\/(\S+)/)?.[1]??null}function Ka(e=Wa()){return Ga(e)!==null}var qa=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function Ja(e=typeof location>`u`?``:location.search){let t=new URLSearchParams(e).get(`desktop_session`);return t&&qa.test(t)?t:null}function Ya(e,t,n){let r=e+`/api/update/badge`;if(!Ka(t))return r;let i=Ja(n);return r+`?surface=desktop`+(i?`&session=`+encodeURIComponent(i):``)}function Xa(e=Wa()){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 Za(e=Wa()){if(!Ka(e))return null;let t=Xa(e);return t===`windows`?`http://tauri.localhost/update.html`:t===`macos`||t===`linux`?`tauri://localhost/update.html`:null}function Qa(e=Wa()){let t=Za(e);return t?(window.location.assign(t),!0):!1}function $a(e=Wa()){if(!Ka(e))return null;let t=Xa(e);return t===`windows`?`http://tauri.localhost/cli.html`:t===`macos`||t===`linux`?`tauri://localhost/cli.html`:null}function eo(e=Wa()){let t=$a(e);return t?(window.location.assign(t),!0):!1}function to(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 no(e){return e.desktop!==void 0&&(e.desktop.owned||e.desktop.supervisor!==void 0)}function ro(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 io(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 ao(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function oo(e,t){return{request:++e.current,mutation:t.current}}var so=2e3;function co(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function lo(e){return e?e.stale&&e.status!==`error`:!1}function uo(e,t){return!t||t.diagnosticStale||e!==null&&e!==`error`?e:t.status}var fo=3e4;function po(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function mo(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function ho(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=co(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(mo(e,t))throw e;return{status:`error`,stale:!1}}}async function go(e,t){try{return(await gn(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function _o(e,t){return Tn(await fetch(`${e}/api/models`,{signal:t}))}async function vo(e,t){return mr(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function yo(e,t,n){let{request:r,mutation:i}=oo(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 Tn(a),c;try{if(o.ok){let e=await o.json();ao({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else ao({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{ao({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 bo(e,t,n){let{request:r,mutation:i}=oo(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Tn(await fetch(`${e}/api/settings`,{signal:t})),o,s;return ao({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 xo(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`};let r=await n.json(),i=ar(r.multiAgentSurfaceAdvisory);return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?{maMode:r.multiAgentMode,advisory:i}:{maMode:`default`,advisory:i}}catch(e){if(mo(e,t))throw e;return{maMode:`default`}}}async function So(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 Tn(d),t=await Tn(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(mo(e,t))throw e;return n(`invalid`)}}finally{r.abort()}}async function Co(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={...po(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}}var wo=`ocx.dash.controls.v1:`,To=`ocx.dash.overview.v1:`,Eo=`ocx.dash.usage30d.v1:`,Do=`ocx.dash.startup.v1:`,Oo=`ocx.dash.maMode.v1:`;function ko(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 Ao(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 jo(e){return`${wo}${e}`}function Mo(e,n=0){let{locale:r,t:i}=t(),[a,o]=(0,Z.useState)(Sn),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(new Set),d=(0,Z.useMemo)(()=>La(jo(e)),[e]),f=(0,Z.useMemo)(()=>La(`${To}${e}`),[e]),p=(0,Z.useMemo)(()=>La(`${Eo}${e}`),[e]),m=(0,Z.useMemo)(()=>{let t=La(`${Do}${e}`);return t===`error`?null:t},[e]),h=(0,Z.useMemo)(()=>La(`${Oo}${e}`),[e]),[g,_]=(0,Z.useState)(()=>f?.health??null),[v,y]=(0,Z.useState)(()=>m),[b,x]=(0,Z.useState)(()=>f?.providers??[]),[S,C]=(0,Z.useState)([]),[w,T]=(0,Z.useReducer)(ko,{settings:d?.settings??null,beforeSave:null}),{settings:E}=w,D=w.beforeSave!==null,[O,k]=(0,Z.useState)(()=>d?.sidecar??null),[A,j]=(0,Z.useState)(()=>d?.shadowCall??null),[M,N]=(0,Z.useState)(()=>p),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(),[R,z]=(0,Z.useState)(!1),[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(!1),[W,G]=(0,Z.useState)(()=>h??`default`),[ee,K]=(0,Z.useState)(!1),[q,te]=(0,Z.useState)(null),[ne,J]=(0,Z.useState)(null),[Y,re]=(0,Z.useState)(null),[ie,X]=(0,Z.useState)(null),ae=ne?.apiBase===e?ne.advisory:null,oe=Y===e,se=ie?.apiBase===e?ie.mode:null,[ce,le]=(0,Z.useState)(!1),[ue,de]=(0,Z.useState)(!1),[fe,pe]=(0,Z.useState)(!1),[me,he]=(0,Z.useState)(``),[ge,_e]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)([]),[be,xe]=(0,Z.useState)([]),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(!0),[Ee,De]=(0,Z.useState)(!1),[Oe,ke]=(0,Z.useState)(``),[Ae,je]=(0,Z.useState)(``),[Me,Ne]=(0,Z.useState)(!1),[Pe,Fe]=(0,Z.useState)(null),[Ie,Le]=(0,Z.useState)(null),[Re,ze]=(0,Z.useState)([]),[Be,Ve]=(0,Z.useState)(!1),[He,Ue]=(0,Z.useState)(`latest`),[We,Ge]=(0,Z.useState)(!0),[Ke,qe]=(0,Z.useState)(!1),Je=(0,Z.useRef)(0),Ye=(0,Z.useRef)(null),Xe=(0,Z.useRef)(0),Ze=(0,Z.useRef)(0),Qe=(0,Z.useRef)(0),$e=(0,Z.useRef)(!1),et=(0,Z.useRef)(0),tt=(0,Z.useRef)(0),nt=(0,Z.useRef)(!1),[rt,it]=(0,Z.useState)(null),[at,ot]=(0,Z.useState)(null),[st,ct]=(0,Z.useState)(null),[lt,ut]=(0,Z.useState)(!1),[dt,ft]=(0,Z.useState)(!1),pt=(0,Z.useRef)(null),mt=(0,Z.useRef)(null),ht=(0,Z.useRef)(null),gt=(0,Z.useRef)(null),_t=rr(ue,pt),vt=rr(Be,mt),yt=rr(ce,ht),bt=rr(fe,gt);(0,Z.useEffect)(()=>{let e=()=>o(Sn());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>()=>{Xe.current+=1,Ye.current!==null&&(window.clearTimeout(Ye.current),Ye.current=null)},[]);let xt=(0,Z.useRef)(m),St=(0,Z.useRef)(0),Ct=(0,Z.useRef)({settingsRequestEpochRef:Ze,settingsMutationEpochRef:Qe,settingsMutationInFlightRef:$e,shadowCallRequestEpochRef:et,shadowCallMutationEpochRef:tt,shadowCallMutationInFlightRef:nt}).current,wt=Vt(`dashboard-startup-health:${e}`,[e,n],t=>ho(e,t),{pollMs:3e4}),Tt=lo(wt.data),Et=wt.refresh;(0,Z.useEffect)(()=>{if(!Tt)return;let e=window.setTimeout(()=>{Et()},so);return()=>window.clearTimeout(e)},[Tt,Et]);let Dt=Vt(`dashboard-overview:${e}`,[e,n],t=>So(e,t),{pollMs:5e3}),Ot=Ha(Dt,e=>e.health===null,!0),kt=g!==null||Dt.data!==void 0,At=Vt(`dashboard-ma-mode:${e}`,[e,n],t=>xo(e,t),{pollMs:5e3}),jt=Vt(`dashboard-sidecars:${e}`,[e,n],async t=>{let n=St.current;return{...await yo(e,t,Ct),startupHealthGeneration:n}},{pollMs:5e3}),Mt=Vt(`dashboard-settings:${e}`,[e,n],async t=>{let n=St.current;return{...await bo(e,t,Ct),startupHealthGeneration:n}},{pollMs:5e3}),Nt=Vt(`dashboard-multi-agent:${e}`,[e,n],t=>Co(e,t),{pollMs:5e3,enabled:kt}),Pt=Vt(hr(e),[e,n],t=>vo(e,t),{enabled:kt,pollMs:6e4,deadlineMs:6e4}),Ft=Vt(`dashboard-diagnostics:${e}`,[e,n],t=>go(e,t),{pollMs:fo,enabled:kt}),It=Vt(`dashboard-models:${e}`,[e,dt,n],t=>_o(e,t),{enabled:kt&&!dt});(0,Z.useEffect)(()=>{if(wt.data!==void 0){let t=wt.data;St.current+=1,y(t.status),xt.current=t.status,t.status!==`error`&&!t.stale&&Va(`${Do}${e}`,t.status)}},[wt.data,e]),(0,Z.useEffect)(()=>{let t=Dt.data;t&&(t.health&&(_(t.health),x(t.providers),Va(`${To}${e}`,{health:t.health,providers:t.providers})),ft(t.error))},[Dt.data,e]),(0,Z.useEffect)(()=>{At.data!==void 0&&(G(At.data.maMode),J({advisory:At.data.advisory??null,apiBase:e}),Va(`${Oo}${e}`,At.data.maMode))},[At.data,e]);let Lt=At.data!==void 0||h!==null;(0,Z.useEffect)(()=>{let e=Nt.data;e&&(e.injection&&(Te(e.injection.multiAgentGuidanceEnabled),De(e.injection.syncCodexSubagentDefaults),he(e.injection.injectionModel),_e(e.injection.injectionEffort),ye(e.injection.injectionEfforts),xe(e.injection.injectionAvailable)),e.effortCaps&&(ke(e.effortCaps.effortCap),je(e.effortCaps.subagentEffortCap)))},[Nt.data]),(0,Z.useEffect)(()=>{let t=jt.data;if(!t)return;k(t.sidecar),t.shadowCall!==void 0&&j(t.shadowCall);let n=La(jo(e))??{};Va(jo(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[jt.data,e]),(0,Z.useEffect)(()=>{let t=Mt.data;if(t&&(t.settings!==void 0&&T({type:`polled`,settings:t.settings}),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===St.current)){let n=uo(xt.current,t.startupHealthSeed);y(n),xt.current=n,n&&Va(`${Do}${e}`,n)}},[Mt.data,e]),(0,Z.useEffect)(()=>{if(!E)return;let t=La(jo(e))??{};Va(jo(e),{...t,settings:E})},[E,e]),(0,Z.useEffect)(()=>{Pt.data!==void 0&&(N(Pt.data),Va(`${Eo}${e}`,Pt.data))},[Pt.data,e]),(0,Z.useEffect)(()=>{Ft.data&&ze(Ft.data)},[Ft.data]),(0,Z.useEffect)(()=>{It.data&&C(It.data),V(It.loading)},[It.data,It.loading]),(0,Z.useEffect)(()=>()=>{Ze.current+=1,et.current+=1},[]);let Rt=Vt(st?.id&&st.restart?`update-job:${e}:${st.id}`:`update-job:idle:${e}`,[e,st?.id,st?.restart,st?.latestVersion],async t=>{if(!st?.id||!st.restart)return{reconnecting:!1};let n=st.latestVersion;try{let r=await Tn(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(st.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Tn(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:!!(st?.id&&st.restart),pauseWhenHidden:!1});(0,Z.useEffect)(()=>{let e=Rt.data;e&&(`job`in e&&e.job&&ct(e.job),ut(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[Rt.data]);let zt=(0,Z.useMemo)(()=>Ao(S),[S]),Bt=(0,Z.useMemo)(()=>{let e=s.trim().toLowerCase();if(!e)return zt;let t=[];for(let[n,r]of zt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[zt,s]),Ht=(0,Z.useMemo)(()=>{let e=O?.webSearch?.backend;return Jn(O?.webSearchModels,S,O?.webSearch?.model,e===`routed`?void 0:e)},[S,O?.webSearchModels,O?.webSearch]),Ut=(0,Z.useMemo)(()=>Yn(O?.visionModels,S,O?.vision?.model,O?.vision?.backend),[O?.visionModels,S,O?.vision]),Wt=async t=>{if(!O||P)return;t=Qn(O,t);let n=O,r={webSearch:An(O.webSearch,t.webSearch),vision:An(O.vision,t.vision),...O.visionModels?{visionModels:O.visionModels}:{},...O.webSearchModels?{webSearchModels:O.webSearchModels}:{}};F(!0),k(r);try{let n=await Tn(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);L(e=>Fn(e,n.codexWebSearch)),k({webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=La(jo(e))??{};Va(jo(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 Gt(t){if(!A||R)return;let n=A,r={...A,...t};z(!0),nt.current=!0,j(r);try{if(!(await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`shadow-call save failed`);tt.current+=1}catch{j(n)}finally{nt.current=!1,z(!1)}}let qt=async(t,n=!1)=>{K(!0),te(null);try{let r={multiAgentMode:t};n&&(r.multiAgentSurfaceAdvisoryAcknowledged=!0);let a=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(a.ok)G(t),n&&re(e),Va(`${Oo}${e}`,t);else{let e=i(`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{}te(e)}}catch(e){te(e instanceof Error?e.message:i(`dash.maNetworkError`))}finally{K(!1)}},Jt=async t=>{if(!(ee||W===t)){if(t!==`v1`){X({mode:t,apiBase:e});return}await qt(`v1`)}},Yt=async()=>{re(e);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentSurfaceAdvisoryAcknowledged:!0})});t.ok||te(i(`dash.maSwitchFailed`,{status:String(t.status)}))}catch(e){te(e instanceof Error?e.message:i(`dash.maNetworkError`))}},Xt=async()=>{let e=se;if(X(null),e){await qt(e,!0);return}await Yt()},Zt=async()=>{if(X(null),W===`v1`){await Yt();return}await qt(`v1`,!0)},Qt=()=>{if(se){X(null);return}re(e)},$t=!se&&!oe&&ae?.required===!0,en=async t=>{if(!Se){Ce(!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 Tn(await fetch(`${e}/api/injection-model`)),r=po(n);Te(r.multiAgentGuidanceEnabled),De(r.syncCodexSubagentDefaults),he(r.injectionModel),_e(r.injectionEffort),Array.isArray(n.efforts)&&ye(n.efforts),Array.isArray(n.available)&&xe(n.available)}catch{}finally{Ce(!1)}}},tn=async t=>{if(!E||D||H)return;let n=!(E[t]??t===`codexAutoStart`);$e.current=!0,T({type:`save-started`,key:t,value:n});try{let r=await Tn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({[t]:n})}),`save failed`);Qe.current+=1,T({type:`save-succeeded`,key:t,settings:r}),(t===`codexDesktopAuthless`||t===`codexClientCompaction`)&&await on()}catch{T({type:`save-failed`}),ft(!0)}finally{$e.current=!1,T({type:`save-finished`})}},nn=()=>tn(`codexAutoStart`),rn=()=>tn(`codexDesktopAuthless`),an=()=>tn(`codexClientCompaction`),Q=(0,Z.useCallback)(()=>{Fe(null),Le(null)},[]),on=async()=>{if(!H){U(!0),Fe(null),Le(null);try{let t=await Tn(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Fe(t),t.ok&&t.status===`applied`&&(T({type:`applied`}),L(void 0)),t.projectConfigGrouped&&ze(t.projectConfigGrouped)}catch(e){Le(e instanceof Error?e.message:String(e))}finally{U(!1)}}},$=async(t,n=!1)=>{n&&(Je.current=0),Ye.current!==null&&(window.clearTimeout(Ye.current),Ye.current=null);let r=++Xe.current;qe(!0),ot(null),it(null);try{let n=await Tn(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Xe.current)return;if(it(n),n.reason===`latest_unavailable`&&Je.current<2){let e=++Je.current;Ye.current=window.setTimeout(()=>{r===Xe.current&&(Ye.current=null,$(t))},800*e);return}n.reason!==`latest_unavailable`&&(Je.current=0),qe(!1)}catch(e){if(r!==Xe.current)return;ot(e instanceof Error?e.message:String(e)),qe(!1)}},sn=()=>{Xe.current+=1,Ye.current!==null&&(window.clearTimeout(Ye.current),Ye.current=null),qe(!1),Ve(!1)},cn=()=>{if(Qa())return;let e=Dn(g?.version);Ue(e),Ge(!0),Ve(!0),$(e,!0)},ln=e=>{Ue(e),$(e,!0)},un=(0,Z.useRef)(cn);return(0,Z.useEffect)(()=>{un.current=cn}),(0,Z.useEffect)(()=>{let e=()=>{Cn()&&(Kt(`dashboard`),un.current())},t=Cn()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:r,t:i,selectedSection:a,setSelectedSection:o,modelQuery:s,setModelQuery:c,expandedProviders:l,setExpandedProviders:u,health:g,startupHealth:v,providers:b,models:S,settings:E,sidecar:O,shadowCall:A,usage30d:M,usageLoading:Pt.loading&&!M,healthLoading:Dt.loading&&!g,sidecarSaving:P,shadowCallSaving:R,modelsLoading:B,settingsSaving:D,syncing:H,maMode:W,maModeResolved:Lt,maBusy:ee,setMaHelpOpen:le,maHelpOpen:ce,maError:q,maAdvisory:ae,maAdvisoryOpen:$t,pendingMaMode:se,keepMaMode:Xt,chooseMaV1:Zt,dismissMaSurfaceDialog:Qt,effortCapHelpOpen:ue,setEffortCapHelpOpen:de,shadowCallHelpOpen:fe,setShadowCallHelpOpen:pe,injectionModel:me,injectionEffort:ge,injectionEfforts:ve,injectionAvailable:be,injectionSaving:Se,multiAgentGuidanceEnabled:we,syncCodexSubagentDefaults:Ee,saveInjection:en,effortCap:Oe,subagentEffortCap:Ae,effortCapSaving:Me,setEffortCap:ke,setSubagentEffortCap:je,setEffortCapSaving:Ne,syncResult:Pe,syncError:Ie,projectConfigWarnings:Re,updateOpen:Be,updateChannel:He,setUpdateRestart:Ge,updateRestart:We,updateLoading:Ke,updateCheck:rt,updateError:at,updateJob:st,reconnecting:lt,error:dt||Ot.showError,connectionFailure:Dt.data?.failure??(Ot.showError?`unavailable`:void 0),refreshDashboard:Dt.refresh,effortCapHelpTriggerRef:pt,updateTriggerRef:mt,maHelpTriggerRef:ht,shadowCallHelpTriggerRef:gt,effortCapHelpDialogRef:_t,updateDialogRef:vt,maHelpDialogRef:yt,shadowCallHelpDialogRef:bt,filteredGroups:Bt,sidecarModels:Ht,visionModels:Ut,sidecarCodexApply:I,saveSidecar:Wt,saveShadowCall:Gt,switchMaMode:Jt,toggleCodexAutoStart:nn,toggleCodexDesktopAuthless:rn,toggleCodexClientCompaction:an,runSync:on,clearSyncFeedback:Q,fetchUpdateCheck:$,closeUpdateDialog:sn,openUpdateDialog:cn,changeUpdateChannel:ln,runUpdate:async()=>{if(rt?.canUpdate){ot(null);try{let t=await Tn(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:He,restart:We})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);ct(t.job),ut(!1),sn()}catch(e){ot(e instanceof Error?e.message:String(e))}}}}}function No(e){qt(wn(e))}function Po({apiBase:e,connected:t=!1,authenticationPending:n=!1,refreshEpoch:r=0}){let i=Mo(e,r),{t:a,error:o,selectedSection:s,providers:c,models:l,modelsLoading:u,modelQuery:d,setModelQuery:f,filteredGroups:p,expandedProviders:m,setExpandedProviders:h}=i;if(n)return null;let g=i.connectionFailure===`auth`||i.connectionFailure===`denied`;if(o&&(g||!i.health))return(0,Q.jsxs)(ln,{style:{marginTop:40},icon:(0,Q.jsx)(Ae,{}),title:(0,Q.jsx)(`span`,{style:{color:`var(--red)`},children:a(i.connectionFailure===`denied`?`dash.permissionDenied`:i.connectionFailure===`auth`?`dash.authRequired`:`dash.dataUnavailable`)}),children:[!t&&i.connectionFailure===`unavailable`&&(0,Q.jsx)(T,{k:`dash.runStart`,cmd:`ocx start`}),(0,Q.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>i.refreshDashboard(),children:a(`common.retry`)})]});let _=(0,Q.jsx)(Pa,{...i}),v=(0,Q.jsx)(Fa,{t:a,providers:c}),y=(0,Q.jsx)(lr,{t:a,models:l,modelsLoading:u,modelQuery:d,setModelQuery:f,filteredGroups:p,expandedProviders:m,setExpandedProviders:h}),b=(0,Q.jsx)(cr,{...i}),x=[{id:`overview`,label:a(`dash.workspace.overview`),body:_},{id:`providers`,label:a(`dash.activeProviders`),body:v},{id:`models`,label:a(`dash.availableModels`),body:y}],S=x.find(e=>e.id===s)??x[0],C=No,w=e=>{let t=x.findIndex(e=>e.id===s),n=-1;if(e.key===`ArrowRight`?n=(t+1)%x.length:e.key===`ArrowLeft`?n=(t-1+x.length)%x.length:e.key===`Home`?n=0:e.key===`End`&&(n=x.length-1),n<0)return;e.preventDefault();let r=x[n];C(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,Q.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[o&&(0,Q.jsxs)($,{tone:`warn`,children:[a(`dash.staleData`),` `,(0,Q.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>i.refreshDashboard(),children:a(`common.retry`)})]}),(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:a(`nav.dashboard`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`dash.subtitle`)}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":a(`dash.workspace.sections`),children:x.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":s===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:s===e.id?0:-1,className:`page-tab${s===e.id?` page-tab--active`:``}`,onClick:()=>C(e.id),onKeyDown:w,children:e.label},e.id))}),(0,Q.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${S.id}`,"aria-labelledby":`dashboard-tab-${S.id}`,tabIndex:0,children:S.body}),b]})}function Fo(e){let t=Object.create(null);for(let n of e)t[n.provider]={requests:n.requests,totalTokens:n.totalTokens};return t}function Io(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 Lo(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 Ro={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function zo(e,t,n){let r=typeof t==`object`&&t?t:Ro,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 Bo(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 Vo(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 Ho(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function Uo(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 Wo(e,t=`en`){return Uo(e,t)}function Go(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function Ko(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:e===`Total subscription credits`?4.5:5}var qo=`Total subscription credits`;function Jo(e){return e.trim().toLowerCase()===qo.toLowerCase()?qo:e}function Yo(e,t){if(e===void 0||!t)return!1;let n=Jo(e);for(let e of t)if(Jo(e)===n)return!0;return!1}function Xo(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 Zo(e,t,n){let r=I(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=Jo(e.label),r=Xo(t,n);i.push({rank:Ko(t),row:{customLabel:t,label:r,limitLabel:r,percent:e.percent,resetAt:e.resetAt}})}if(r.creditsUsd&&typeof r.creditsUsd.percent==`number`&&!r.customWindows?.some(e=>Jo(e.label)===qo)){let e=Xo(qo,n);i.push({rank:Ko(qo),row:{customLabel:qo,label:e,limitLabel:e,percent:r.creditsUsd.percent,resetAt:r.creditsUsd.expiresAt}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function Qo(e){if(!e)return-1;let t=[e.fiveHourPercent,e.weeklyPercent,e.monthlyPercent].filter(e=>typeof e==`number`);for(let n of e.customWindows??[])typeof n.percent==`number`&&t.push(n.percent);return!e.customWindows?.some(e=>Jo(e.label)===qo)&&typeof e.creditsUsd?.percent==`number`&&t.push(e.creditsUsd.percent),t.length?Math.max(...t):-1}function $o(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 es(e){return e>=99.5}function ts(e,t){return t>0&&e>=t}function ns(e,t){return ts(e,t)||es(e)?`bar-warn`:`bar-green`}function rs(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function is(e){return{"--bar-scale":String(rs(e)/100)}}function as(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 os({quota:e,plan:n,threshold:r,t:i,className:a,layout:o=`compact`,pending:s=!1,incompleteWindowKeys:c,incompleteCustomWindowLabels:l,observedAt:u,afterWeekly:d}){let{locale:f}=t(),p=Zo(e,n,i),m=u===void 0?null:as(u,i),h=m===null?null:(0,Q.jsx)(`p`,{className:`quota-observed muted`,title:i(`quota.observedHint`),children:i(`quota.observedAgo`).replace(`{age}`,m)});return p.length===0?s?o===`stacked`?(0,Q.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${a?` ${a}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,Q.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,Q.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,Q.jsx)(`span`,{className:`sr-only`,children:i(`common.loading`)})]}):(0,Q.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${a?` ${a}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,Q.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:i(`common.loading`)})]}):o===`compact`&&d?(0,Q.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${a?` ${a}`:``}`,children:d}):null:o===`stacked`?(0,Q.jsxs)(`div`,{className:`quota-stacked${a?` ${a}`:``}`,children:[h,p.map(e=>(0,Q.jsx)(cs,{row:e,threshold:r,t:i,locale:f,incomplete:e.windowKey?c?.has(e.windowKey)===!0:Yo(e.customLabel,l)},e.limitLabel))]}):(0,Q.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact${a?` ${a}`:``}`,children:[h,p.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsx)(ss,{credits:e.customLabel===qo,label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:r,t:i,locale:f}),e.windowKey===`weekly`&&d]},e.label)),!p.some(e=>e.windowKey===`weekly`)&&d]})}function ss({credits:e,label:t,percent:n,resetAt:r,threshold:i,t:a,locale:o}){let s=es(n),c=ts(n,i),l=ns(n,i),u=us(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,Q.jsxs)(`div`,{className:`quota-row${e?` quota-row--credits`:``}${c?` quota-row--warn`:``}${s?` quota-row--exhausted`:``}`,children:[(0,Q.jsx)(`span`,{className:`quota-label`,title:d,children:t}),(0,Q.jsx)(`span`,{className:`quota-reset-label`,children:f?a(`codexAuth.resets`):``}),(0,Q.jsx)(`span`,{className:`quota-reset-day`,children:u.day}),(0,Q.jsx)(`span`,{className:`quota-reset-time`,children:u.time}),(0,Q.jsx)(`div`,{className:`bar`,title:d,children:(0,Q.jsx)(`div`,{className:`bar-fill ${l}`,style:is(n)})}),(0,Q.jsxs)(`span`,{className:`quota-val${c?` quota-val--warn`:``}`,title:s?a(`quota.limitReached`):d,"aria-label":d,children:[c&&(0,Q.jsx)(Ae,{width:12,height:12,"aria-hidden":`true`}),Math.round(n),`%`,s?` · ${a(`quota.limitReached`)}`:``]})]})}function cs({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=es(e.percent),o=ts(e.percent,t),s=ns(e.percent,t),c=ds(e.resetAt,n,r);return(0,Q.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,Q.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,Q.jsx)(`span`,{className:`quota-window-partial`,role:`note`,"aria-label":n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),title:n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),children:n(`pws.capacity.windowPartial`)})]}),(0,Q.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,Q.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Q.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,Q.jsx)(`div`,{className:`bar-fill ${s}`,style:is(e.percent)})}),(0,Q.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,Q.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,Q.jsx)(Ae,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function ls(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 us(e,t,n){let r=ls(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=$o(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 ds(e,t,n=`en`,r=Date.now()){let i=ls(e);if(!i)return``;let{date:a,ms:o}=i,s=$o(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 fs(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 ps(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function ms({report:e,pending:n}){let r=O(),{locale:i}=t(),a=ze(e),o=ae(e),s=se(e),c=o?.creditsUsd,l=a?.presentation===`aggregate`,u=new Set,d=new Set;if(l&&a){a.fiveHour?.incomplete&&u.add(`fiveHour`),a.weekly?.incomplete&&u.add(`weekly`),a.monthly?.incomplete&&u.add(`monthly`);for(let e of a.customWindows??[])e.incomplete&&d.add(e.label)}let f=l&&a?[...a.fiveHour?[{key:0,label:r(`codexAuth.fiveHour`),window:a.fiveHour}]:[],...a.weekly?[{key:1,label:r(`codexAuth.weekly`),window:a.weekly}]:[],...a.monthly?[{key:2,label:r(`codexAuth.monthly`),window:a.monthly}]:[],...(a.customWindows??[]).map((e,t)=>({key:t+3,label:e.label,window:e}))]:[],p=e=>new Intl.NumberFormat(i,{maximumFractionDigits:1}).format(e),m=e=>{let t=ps(e);return t===null?null:new Intl.DateTimeFormat(i,{dateStyle:`medium`,timeStyle:`short`}).format(t)},h=fs(i),g=e=>new Intl.NumberFormat(h,{style:`currency`,currency:`USD`}).format(e),_=c?.expiresAt===void 0?null:(e=>{let t=ps(e);return t===null?null:new Intl.DateTimeFormat(h,{dateStyle:`medium`}).format(t)})(c.expiresAt);return(0,Q.jsxs)(Q.Fragment,{children:[l&&(0,Q.jsx)(`div`,{className:`pws-capacity-label`,children:r(`pws.capacity.estimate`)}),(o||n)&&(0,Q.jsx)(os,{quota:o,threshold:80,t:r,layout:`stacked`,pending:n,...s===void 0?{}:{observedAt:s},incompleteWindowKeys:l?u:void 0,incompleteCustomWindowLabels:l?d:void 0}),(c||a)&&(0,Q.jsxs)(`div`,{className:`pws-capacity-details`,children:[c&&(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:r(`quota.creditsBalance`)}),(0,Q.jsx)(`strong`,{children:g(c.remaining)})]}),_!==null&&(0,Q.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Q.jsx)(`span`,{children:r(`quota.creditsPeriodEnds`,{date:_})})}),f.flatMap(({key:e,label:t,window:n})=>{let i=n.nextRecoveryAt===void 0?null:m(n.nextRecoveryAt);return i!==null&&n.nextRecoveryPercent!==void 0?[(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsxs)(`span`,{children:[r(`pws.capacity.nextRecovery`),` · `,t,` · `,i]}),(0,Q.jsx)(`strong`,{children:r(`pws.capacity.recoveryShare`,{percent:p(n.nextRecoveryPercent)})})]},e)]:[]}),l&&a&&a.currentAccount?.quota&&(0,Q.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,Q.jsxs)(`span`,{className:`pws-capacity-label`,children:[r(`pws.capacity.currentAccount`),a.currentAccount.plan?` · ${a.currentAccount.plan}`:``]}),(0,Q.jsx)(os,{quota:a.currentAccount.quota,threshold:80,t:r,layout:`stacked`})]}),a&&a.incomplete&&a.excludedAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:r(`pws.capacity.incomplete`,{excluded:a.excludedAccounts})}),a&&a.unknownPlanAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:r(`pws.capacity.uncalibratedPlan`,{count:a.unknownPlanAccounts})}),a&&a.partialWindowAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:r(`pws.capacity.partial`,{count:a.partialWindowAccounts})})]})]})}function hs({sections:e,quotaReports:n,usageTotals:r,usageLoading:i=!1,quotasLoading:a=!1,onSelectProvider:o,onEditConfig:s,onRefreshAllQuotas:c}){let l=O(),{locale:u}=t(),d=Bo(l),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),g=async()=>{if(!(!c||f)){p(!0),h(null);try{let e=await c();h({ok:e,text:l(e?`pws.quotaRefreshDone`:`codexAuth.quotaRefreshFailed`)})}catch{h({ok:!1,text:l(`codexAuth.quotaRefreshFailed`)})}finally{p(!1)}}},_=(0,Z.useMemo)(()=>[...e.ready,...e.needsSetup,...e.disabled],[e]),v=(0,Z.useMemo)(()=>new Set(_.map(e=>e.name)),[_]),y=(0,Z.useMemo)(()=>Vo(e,{}),[e]),b=y.length,x=(0,Z.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),S=e.ready.length-x,C=e.needsSetup.length+x,w=(0,Z.useMemo)(()=>{let e=[];for(let t of _){let r=n[t.name],i=r?ae(r):null,a=r?ze(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:t,report:r,urgency:i?Qo(i):-1})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[_,n]),T=(0,Z.useMemo)(()=>{let e={};for(let[t,n]of Object.entries(r))v.has(t)&&(e[t]=n);return Lo(e).slice(0,4)},[r,v]),E=e=>{let t=Ho(e);return t===`reauth`?l(`pws.attention.reauth`):t===`missing`?l(`pws.attention.missingCredentials`):e};return(0,Q.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,Q.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,Q.jsx)(`div`,{className:`pws-dashboard-header-text`,children:(0,Q.jsx)(`h2`,{className:`pws-dashboard-title`,children:l(`pws.dashboard.title`)})}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-header-actions`,children:[m&&(0,Q.jsx)(`span`,{role:`status`,className:m.ok?`pws-status-ok`:`pws-status-warn`,children:m.text}),c&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:f,onClick:()=>{g()},children:[(0,Q.jsx)(re,{width:14,height:14,"aria-hidden":`true`}),` `,l(f?`codexAuth.refreshingQuota`:`pws.refreshAllQuotas`)]}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:l(`prov.editJson`)})]})]}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,Q.jsx)(gs,{count:S,label:l(`pws.status.ready`),tone:`ok`}),(0,Q.jsx)(gs,{count:C,label:l(x>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,Q.jsx)(gs,{count:e.disabled.length,label:l(`prov.disabledBadge`),tone:`muted`})]}),b>0&&(0,Q.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":l(`pws.attentionTitle`),children:[(0,Q.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,Q.jsx)(Ae,{style:{width:14,height:14},"aria-hidden":`true`}),l(`pws.attentionTitle`)]}),(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>o(e.name),children:[(0,Q.jsx)(me,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:be(e.name,l)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:E(e.reason)})]}),(0,Q.jsx)(Ke,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,Q.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":l(`pws.dashboard.rateLimits`),"aria-busy":a||void 0,children:[(0,Q.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:l(`pws.dashboard.rateLimits`)}),w.length>0?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:w.map(({item:e,report:t})=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>o(e.name),children:[(0,Q.jsx)(me,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:be(e.name,l)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:l(`pws.dashboard.checkedAgo`,{time:zo(t.updatedAt,d)})})]}),(0,Q.jsx)(Ke,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Q.jsx)(ms,{report:t,pending:a&&!t.quota})})]},e.name))}):a?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Q.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,Q.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Q.jsx)(os,{quota:null,threshold:80,t:l,layout:`stacked`,pending:!0})})]},t))}):(0,Q.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:l(`pws.dashboard.noRateLimits`)})]}),(0,Q.jsx)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":l(`pws.dashboard.recentlyUsed`),"aria-busy":i||void 0,children:(0,Q.jsxs)(`details`,{className:`pws-dashboard-recent-details`,children:[(0,Q.jsx)(`summary`,{className:`pws-dashboard-section-title`,children:l(`pws.dashboard.recentlyUsed`)}),T.length>0?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:T.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>o(e.name),children:[(0,Q.jsx)(me,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:be(e.name,l)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:l(`pws.dashboard.requests`,{count:Uo(e.requests,u)})}),(0,Q.jsx)(Ke,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):i?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Q.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,Q.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:l(`pws.dashboard.noUsage`)})]})})]})]})}function gs({count:e,label:t,tone:n}){return(0,Q.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,Q.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function _s({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=O(),o=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,Q.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,Q.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,Q.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,Q.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,Q.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,Q.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,Q.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}function vs(e){if(!(!ys(e)||!Array.isArray(e.clientIntegrations)))return e.clientIntegrations.filter(e=>ys(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 ys(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bs(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function xs(e){if(!ys(e))throw Error(`invalid selected models response`);let t=e.selected;if(!ys(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,bs(t)]))}async function Ss(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 xs(await r.json())}function Cs(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function ws(e,t,n,r,i){return Cs(e,t,n,r)&&!i}async function Ts(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 Es(e,t){return e===t}function Ds(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid model response`);return e}function Os(e){if(typeof e!=`string`||!e.trim())throw Error(`Invalid model identity`);return e}function ks(e){if(!Array.isArray(e))throw Error(`Invalid model inventory`);let t=new Map,n=[];for(let r of e){let e=Ds(r),i=Os(e.provider),a=Os(e.id),o=Os(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&&Os(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 As(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 js(e){let t=Ds(e),n=Object.assign(Object.create(null),xs(t));for(let[e,t]of Object.entries(n))Os(e),t.forEach(Os);let r=Object.fromEntries(Object.entries(Ds(t.available)).map(([e,t])=>{if(Os(e),!Array.isArray(t))throw Error(`Invalid available models`);return[e,t.map(Os)]})),i=Object.hasOwn(t,`liveModelCounts`)?Ds(t.liveModelCounts):{},a=Object.fromEntries(Object.entries(i).map(([e,t])=>{if(Os(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 Ms(e){let t=Ds(e);return{id:Os(t.id),provider:Os(t.provider),modelId:Os(t.modelId)}}function Ns(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=Ms(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 Ps(e,t,n){let r=Ms(e);if(r.provider!==t||r.modelId!==n)throw Error(`Unexpected created model`);return r}function Fs(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`}var Is=[{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 Ls(e){return Y(La(e))}function Rs({providers:e,apiBase:t,defaultProvider:n,selectedName:r,onSelect:i,onRemoveProvider:a,onAddProvider:o,onEditConfig:s,jsonEditor:c,jsonSaving:l=!1,modelsRefreshToken:u=0,onModelsSettled:d,activeAccountNeedsReauth:f,quotaRefreshEpoch:p=0,quotaForceRefresh:m=!1,onQuotaRefreshSettled:h,onRefreshAllQuotas:g,detail:_}){let v=O(),[y,b]=(0,Z.useState)(``),[x,S]=(0,Z.useState)({ready:!0,needsSetup:!0,disabled:!0}),[C,w]=(0,Z.useState)({free:!0,paid:!0}),[T,E]=(0,Z.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[D,k]=(0,Z.useState)(`az`),[j,M]=(0,Z.useState)(!1),[N,I]=(0,Z.useState)(null),[L,R]=(0,Z.useState)(null),[z,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(!1),K=`ocx.providers.quotas.v1:${t}`,q=`ocx.providers.usage.v2:${t}`,[te,J]=(0,Z.useState)(()=>dr(La(q))),[re,ae]=(0,Z.useState)(()=>La(q)?.totals??{}),[oe,se]=(0,Z.useState)(()=>La(q)?.models??{}),[ce,le]=(0,Z.useState)(()=>Ls(K)??{}),[ue,de]=(0,Z.useState)(()=>!La(q)),[fe,pe]=(0,Z.useState)(()=>{let e=Ls(K);return!e||Object.keys(e).length===0}),[me,he]=(0,Z.useState)(0),ge=JSON.stringify([t,u,me]),_e=L?.revision===ge&&!z&&!H,ve=(0,Z.useMemo)(()=>As(L?.rows??[]),[L]),ye=(0,Z.useRef)(d);(0,Z.useEffect)(()=>{ye.current=d},[d]);let xe=(0,Z.useRef)(null),Se=Vt(hr(t),[t],async e=>await mr(await fetch(t+`/api/usage?range=30d`,{signal:e})),{deadlineMs:6e4}),Ce=(0,Z.useMemo)(()=>{let t=ct(P(e));return ne(t,f??{})},[e,f]),we=(0,Z.useCallback)(()=>{V(!0),U(!1),he(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=!1,n=A(6e4),r=window.setTimeout(()=>{V(!0),(async()=>{let r=!1;try{let[i,a]=await Promise.all([fetch(`${t}/api/selected-models`,{signal:n.signal}).then(hn).then(js),fetch(`${t}/api/models`,{signal:n.signal}).then(hn).then(ks)]);if(e)return;R({revision:ge,selection:i,rows:a}),U(!1),r=!0}catch{if(e)return;U(!0)}finally{n.controller.abort(),n.clear(),e||(V(!1),ye.current?.(r))}})()},0);return()=>{e=!0,window.clearTimeout(r),n.controller.abort(),n.clear()}},[t,ge]),(0,Z.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=Se.data;if(e)return;if(!t){Se.loading&&de(!La(q));return}let n=Fo(t.providers??[]);ae(n);let r=Io(t.models??[],n);se(r);let i=dr(t);J(i),Va(q,{totals:n,models:r,...i}),de(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,q,Se.data,Se.loading]),(0,Z.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=Ls(K);(!n||Object.keys(n).length===0)&&pe(!0);let i=A(2e4);r=()=>{i.controller.abort(),i.clear()},fetch(`${t}/api/provider-quotas${m?`?refresh=1`:``}`,{signal:i.signal}).then(e=>gn(e)).then(t=>{if(e)return;if(!t){m&&h?.(!1,p);return}let n=ie(t.reports);le(n),Va(K,n),m&&h?.(!0,p)}).catch(()=>{e||(le(e=>{let t=Y(e)??{};return Va(K,t),t}),m&&h?.(!1,p))}).finally(()=>{i.clear(),e||pe(!1)})},0),r;return()=>{e=!0,window.clearTimeout(n),r?.()}},[t,p,m,K,h]),(0,Z.useEffect)(()=>{if(!j)return;let e=e=>{xe.current&&!xe.current.contains(e.target)&&M(!1)},t=e=>{e.key===`Escape`&&M(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[j]);let Te=(0,Z.useMemo)(()=>[...Ce.ready,...Ce.needsSetup,...Ce.disabled],[Ce]),Ee=(0,Z.useMemo)(()=>Te.filter(G).length,[Te]),De=Te.length-Ee,Oe=(0,Z.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of Te)e[ee(t)]+=1;return e},[Te]),Ae=(0,Z.useMemo)(()=>{let e=y.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=G(t);return!(n&&!C.free||!n&&!C.paid||!T[ee(t)])});return W(n,D)};return{ready:x.ready?t(Ce.ready):[],needsSetup:x.needsSetup?t(Ce.needsSetup):[],disabled:x.disabled?t(Ce.disabled):[]}},[Ce,y,x,C,T,D]),je=!x.ready||!x.needsSetup||!x.disabled||!C.free||!C.paid||!T.cloud||!T.local||!T.selfHosted||!T.login||D!==`az`,Me=()=>{S({ready:!0,needsSetup:!0,disabled:!0}),w({free:!0,paid:!0}),E({cloud:!0,local:!0,selfHosted:!0,login:!0}),k(`az`)},Ne=(0,Z.useMemo)(()=>r?Te.find(e=>e.name===r)??null:null,[r,Te]),Pe=(0,Z.useMemo)(()=>{let e=new Map;for(let t of Te){let n=be(t.name,v);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},[Te,v]);if(Te.length===0)return(0,Q.jsx)(zs,{onAddProvider:o});let Fe=[{key:`ready`,label:v(`pws.status.ready`),count:Ce.ready.length},{key:`needsSetup`,label:v(`pws.status.needsSetup`),count:Ce.needsSetup.length},{key:`disabled`,label:v(`prov.disabledBadge`),count:Ce.disabled.length}],Ie=[{id:`ready`,label:v(`pws.status.ready`),count:Ae.ready.length,ariaLabel:v(`pws.groupReady`,{count:Ae.ready.length}),items:Ae.ready},{id:`needs-setup`,label:v(`pws.status.needsSetup`),count:Ae.needsSetup.length,ariaLabel:v(`pws.groupNeedsSetup`,{count:Ae.needsSetup.length}),items:Ae.needsSetup},{id:`disabled`,label:v(`prov.disabledBadge`),count:Ae.disabled.length,ariaLabel:v(`pws.groupDisabled`,{count:Ae.disabled.length}),items:Ae.disabled}],Le=Ie.flatMap(e=>e.items.map(e=>e.name)),Re=N&&Le.includes(N)?N:r&&Le.includes(r)?r:Le[0]??null;return(0,Q.jsx)(`div`,{className:`pws-shell-container`,children:(0,Q.jsxs)(`div`,{className:`pws-root`,children:[(0,Q.jsxs)(`aside`,{className:`pws-rail`,"aria-label":v(`pws.providerList`),children:[(0,Q.jsxs)(`div`,{className:`pws-search-row`,children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(X,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:v(`pws.searchPlaceholder`),value:y,onChange:e=>b(e.target.value),"aria-label":v(`pws.searchPlaceholder`)})]}),(0,Q.jsxs)(`div`,{className:`pws-filter-wrap`,ref:xe,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${je||j?` pws-filter-btn--active`:``}`,onClick:()=>M(e=>!e),"aria-label":v(`pws.filterAria`),"aria-expanded":j,"aria-controls":`pws-provider-filters`,children:[(0,Q.jsx)(ke,{width:18,height:18,"aria-hidden":`true`}),je&&(0,Q.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),j&&(0,Q.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":v(`pws.providerFiltersAria`),children:[(0,Q.jsx)(`div`,{className:`pws-filter-title`,children:v(`pws.filters`)}),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:v(`pws.filterStatus`)}),Fe.map(({key:e,label:t,count:n})=>(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:x[e],onChange:()=>S(t=>({...t,[e]:!t[e]}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:v(`pws.pricing`)}),(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:C.free,onChange:()=>w(e=>({...e,free:!e.free}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:v(`modal.badge.free`)}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:Ee})]}),(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:C.paid,onChange:()=>w(e=>({...e,paid:!e.paid}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:v(`pws.paid`)}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:De})]}),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:v(`pws.filterType`)}),[{key:`cloud`,label:v(`pws.type.cloud`),count:Oe.cloud},{key:`local`,label:v(`pws.type.local`),count:Oe.local},{key:`selfHosted`,label:v(`pws.type.selfHosted`),count:Oe.selfHosted},{key:`login`,label:v(`pws.type.login`),count:Oe.login}].map(({key:e,label:t,count:n})=>(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:T[e],onChange:()=>E(t=>({...t,[e]:!t[e]}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:v(`pws.sort`)}),(0,Q.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":v(`pws.sortProvidersAria`),children:Is.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`pws-sort-btn${D===e.id?` pws-sort-btn--active`:``}`,onClick:()=>k(e.id),"aria-pressed":D===e.id,children:v(e.labelKey)},e.id))}),(0,Q.jsx)(`div`,{className:`pws-filter-footer`,children:(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:Me,disabled:!je,children:v(`pws.resetAll`)})})]})]})]}),(0,Q.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":v(`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();return}if(e.key===`Home`){e.preventDefault(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus())},children:[Object.values(Ae).every(e=>e.length===0)&&(0,Q.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:v(y?`pws.noSearchResults`:je?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Ie.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,Q.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,Q.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,Q.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,Q.jsx)(B,{item:e,selected:r===e.name,tabbable:Re===e.name,modelCount:L?Object.hasOwn(ve,e.name)?ve[e.name]:0:void 0,isDefault:n===e.name,showConfigId:Pe.has(be(e.name,v)),onClick:()=>i(e.name),onFocus:()=>I(e.name)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),a(e.name)},title:v(`pws.removeConfirmTitle`),children:(0,Q.jsx)(F,{width:14,height:14})})]},e.name))]},e))]})]}),(0,Q.jsxs)(`main`,{className:`pws-main`,"aria-label":v(`pws.workspaceMainAria`),children:[!c?.open&&(0,Q.jsx)(gr,{data:te}),c?.open?(0,Q.jsx)(_s,{editor:c,providerName:v(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):Ne?_?.(Ne,{usageTotals:re[Ne.name],modelUsage:oe[Ne.name],quotaReport:ce[Ne.name],availableModels:L?.selection.available[Ne.name]??[],hasLiveModels:(L?.selection.liveModelCounts[Ne.name]??0)>0,selectedModels:L?.selection.selected[Ne.name]??[],modelRows:L?.rows.filter(e=>e.provider===Ne.name)??null,modelRevision:ge,modelRowsReady:_e,modelsLoading:z||!_e&&!H,modelsLoadFailed:H,onRetryModels:we})??(0,Q.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,Q.jsx)(`h3`,{children:be(Ne.name,v)}),(0,Q.jsx)(`p`,{className:`muted`,children:v(`pws.detailComingSoon`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:v(`modal.back`)})]}):(0,Q.jsx)(hs,{sections:Ce,quotaReports:ce,usageTotals:re,usageLoading:ue,quotasLoading:fe,onSelectProvider:e=>i(e),onEditConfig:s,...g?{onRefreshAllQuotas:g}:{}})]})]})})}function zs({onAddProvider:e}){let t=O();return(0,Q.jsx)(`div`,{className:`pws-empty-root`,children:(0,Q.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,children:(0,Q.jsx)(Ie,{style:{width:64,height:64}})}),(0,Q.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,Q.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(qe,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(at,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(tt,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function Bs(e){if(_e(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||H(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0,r=t===`key`||n||t===``,i=e.keyOptional===!0||Je(e);return!r||i&&!n?null:`api-keys`}function Vs(e,t,n){let r=t.alias?.trim();if(r)return r;let i=t.email?.trim();if(i)return i;let a=e.findIndex(e=>e.id===t.id);return n(`pws.accountOrdinal`,{count:String(a>=0?a+1:1)})}function Hs({quota:e,quotaMode:t,quotaUnavailable:n,quotaPending:r,quotaFailure:i}){let a=O(),o=ae({quota:e});if(t===`unsupported`)return(0,Q.jsx)(`p`,{className:`muted`,"data-quota-state":`unsupported`,children:a(`pws.quotaUnsupported`)});let s=t===`probe`&&n?jr(i):void 0,c=t===`probe`&&r===!0;return(0,Q.jsxs)(`div`,{"data-quota-state":n?`unavailable`:c?`pending`:o?`ready`:t===`passive`?`unobserved`:`unknown`,children:[n&&(0,Q.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:a(s?`pws.quotaFailure.${s}`:`pws.accountQuotaUnavailable`)}),o||c?(0,Q.jsx)(ms,{report:{quota:o,updatedAt:o?.updatedAt,...t===`passive`?{observed:!0}:{}},pending:c&&!o}):!n&&(0,Q.jsx)(`p`,{className:`muted`,children:a(t===`passive`?`pws.quotaUnobserved`:`pws.quotaUnavailable`)}),n&&o&&(0,Q.jsxs)(`p`,{className:`muted`,children:[a(`pws.stats.quotaUpdated`),`: `,zo(o.updatedAt,Bo(a))]})]})}function Us({report:e,reading:t,onRefreshQuota:n}){let r=O(),i=M(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:ae(i),...i?.observed===!0?{quotaMode:`passive`}:{}},s=ae({quota:o.quota}),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),f=async()=>{if(!(!n||c)){l(!0),d(null);try{d(await n())}catch{d(!1)}finally{l(!1)}}};return(0,Q.jsxs)(`section`,{className:`pws-usage-block`,"aria-label":r(`pws.currentAccountUsage`),children:[(0,Q.jsxs)(`div`,{className:`pws-usage-block-head`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:r(`pws.currentAccountUsage`)}),n&&o.quotaMode!==`unsupported`&&(0,Q.jsxs)(`div`,{className:`pws-quota-refresh`,children:[u!==null&&(0,Q.jsx)(`span`,{role:`status`,className:u?`pws-status-ok`:`pws-status-warn`,children:r(u?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:c,onClick:()=>{f()},children:[(0,Q.jsx)(re,{width:14,height:14,"aria-hidden":`true`}),` `,r(c?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Q.jsx)(Hs,{...o}),s&&!o.quotaUnavailable&&o.quotaMode!==`unsupported`&&(0,Q.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[!a&&i?.source?.trim()&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:r(`pws.stats.source`)}),(0,Q.jsx)(`dd`,{children:Le(i.source)})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:r(`pws.stats.quotaUpdated`)}),(0,Q.jsx)(`dd`,{children:zo(s.updatedAt,Bo(r))})]})]})]})}function Ws(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 Gs(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function Ks(e){return ye(e.id,Gs(e))}function qs(e){return H(Gs(e))}function Js(e){let t={accounts:[],free:[],local:[],paid:[]};for(let n of e){let e=Ks(n);t[e===`accounts`?`accounts`:qs(n)?`local`:e].push(n)}return t}function Ys(e){return!!e?.trim()}var Xs=new Set([`local`,`localhost`,`ollama`,`vllm`,`lmstudio`,`lm studio`,`self-hosted`,`selfhosted`]);function Zs(e,t){let n=t.trim().toLowerCase();return!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||e.adapter.toLowerCase()===n?!0:Xs.has(n)&&qs(e)}function Qs(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 $s(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 ec(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 tc={main:0,standard:1};function nc(e){let t=e.filter(e=>e.sponsor);return t.length===0?e:(t.sort((e,t)=>tc[e.sponsor]-tc[t.sponsor]||e.label.localeCompare(t.label,void 0,{sensitivity:`base`})||e.id.localeCompare(t.id)),[...t,...e.filter(e=>!e.sponsor)])}var rc={name:`OrcaRouter`,title:`pws.sponsor.orcaTitle`,description:`pws.sponsor.orcaDescription`},ic={orcarouter:rc,"orcarouter-oauth":rc,tokenlab:{name:`TokenLab`,title:`pws.sponsor.tokenlabTitle`,description:`pws.sponsor.tokenlabDescription`}};function ac(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 oc({item:e,preset:t}){let n=O();if(!t?.sponsor||!Ws(e,[t]))return null;let r=Object.hasOwn(ic,t.id)?ic[t.id]:void 0;if(!r)return null;let i=ac(t.sponsorUrl),a=ac(t.dashboardUrl);return(0,Q.jsxs)(`section`,{className:`pws-sponsor`,"aria-label":`${r.name} · ${n(`modal.badge.sponsor`)}`,children:[(0,Q.jsxs)(`div`,{className:`pws-sponsor-copy`,children:[(0,Q.jsxs)(`div`,{className:`pws-sponsor-byline`,children:[(0,Q.jsx)(`span`,{children:r.name}),(0,Q.jsx)(`span`,{className:`pws-sponsor-badge`,children:n(`modal.badge.sponsor`)})]}),(0,Q.jsx)(`h3`,{children:n(r.title)}),(0,Q.jsx)(`p`,{children:n(r.description)})]}),(i||a)&&(0,Q.jsxs)(`div`,{className:`pws-sponsor-actions`,children:[i&&(0,Q.jsxs)(`a`,{className:`btn btn-primary`,href:i,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.visit`,{provider:r.name}),(0,Q.jsx)(Ve,{width:14,height:14,"aria-hidden":`true`})]}),a&&a!==i&&(0,Q.jsxs)(`a`,{className:`pws-sponsor-console`,href:a,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.console`),(0,Q.jsx)(Ve,{width:13,height:13,"aria-hidden":`true`})]})]})]})}function sc({item:e,preset:n,usageTotals:r,quotaReport:i,currentQuotaReading:a,onRefreshQuota:o,oauthEmail:s,oauth:c,apiBase:l,connectionIdentity:u,onEditSettings:d,onViewUsage:f,onUpdateProvider:p,onCreateJevAuto:m,onReauthenticate:h,onCancelLogin:g,reauthBusy:_=!1}){let v=O(),{locale:y}=t(),b=ue(e),x=!!e.activeNeedsReauth,S=v(b===`ready`?`pws.status.connected`:b===`needs-setup`?x?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),C=r?.requests,w=r?.totalTokens,T=JSON.stringify([l??null,e.name,e.adapter,e.baseUrl,e.authMode??null,e.apiKeyTransport??null,e.liveModels??null,e.disabled===!0,e.hasApiKey===!0,e.hasHeaders===!0,e.allowPrivateNetwork===!0,e.keyOptional===!0,e.activeNeedsReauth===!0,u??null]),[E,D]=(0,Z.useState)(null),k=(0,Z.useRef)(null),A=E?.key===T&&E.testing,j=E?.key===T?E.result:null;(0,Z.useEffect)(()=>()=>{k.current?.key===T&&(k.current.controller.abort(),k.current=null)},[T]);let M=(0,Z.useCallback)(async()=>{if(!l)return;k.current?.controller.abort();let t=new AbortController;k.current={key:T,controller:t},D({key:T,testing:!0,result:null});try{let n=await hn(await fetch(`${l}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),v(`pws.connectionFailed`));if(!n)throw Error(v(`pws.connectionFailed`));t.signal.aborted||D({key:T,testing:!1,result:n})}catch(e){t.signal.aborted||D({key:T,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:v(`pws.connectionFailed`)}})}finally{k.current?.controller===t&&(k.current=null)}},[l,T,e.name,v]),N=j?.applicable===!1?`not-applicable`:j?.ok===!0?`ok`:`failed`,P=j?.applicable===!1?v(`pws.connectionNotApplicable`):j?.ok===!0?j.message||v(`pws.connectionOk`):j?.error||v(`pws.connectionFailed`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(oc,{item:e,preset:n}),(0,Q.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,Q.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":v(`pws.connection`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:v(`pws.connection`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:v(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:b===`ready`?`pws-status-ok`:`pws-status-warn`,children:[b===`ready`?(0,Q.jsx)(Te,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Q.jsx)(Ae,{style:{width:13,height:13},"aria-hidden":`true`}),S]})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:v(`modal.baseUrl`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:v(`pws.cell.auth`)}),(0,Q.jsx)(`dd`,{children:s?`${R(e,v)} · ${s}`:R(e,v)})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:v(`modal.defaultModel`)}),(0,Q.jsx)(`dd`,{children:e.defaultModel??(0,Q.jsx)(`span`,{className:`muted`,children:`—`})})]})]}),l&&(0,Q.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:A,onClick:()=>void M(),children:v(A?`pws.testing`:`pws.testConnection`)}),j&&(0,Q.jsx)(`span`,{role:`status`,className:N===`ok`?`pws-status-ok`:N===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":N,children:P})]}),d&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:d,children:v(`pws.editSettings`)})]}),e.adapter===`jev-decision`&&m&&(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":v(`cws.jev.create`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:v(`cws.jev.create`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:v(`cws.jev.setupHint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:m,children:v(`cws.jev.create`)})]}),(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":v(`pws.authSummary`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:v(`pws.authSummary`)}),x?(0,Q.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,Q.jsx)(Ae,{style:{width:14,height:14},"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:v(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?v(`pws.attention.reauthForward`):v(`pws.attention.reauth`)]}),h&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:_,onClick:()=>h(),children:v(_?`prov.waitingBrowser`:`pws.reauthenticate`)}),_&&g&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g(),children:v(`common.cancel`)})]})]}):(0,Q.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,Q.jsx)(`span`,{className:`pws-auth-dot`}),(0,Q.jsx)(`span`,{children:e.authMode===`forward`?v(`pws.passthrough`):e.authMode===`oauth`?s?v(`pws.loggedInAs`,{email:s}):c?.loggedIn?v(`pws.loggedInTitle`):v(`pws.notLoggedIn`):e.hasApiKey?v(`pws.apiKeyConfigured`):R(e,v)})]})]}),(0,Q.jsx)(cc,{item:e,onUpdateProvider:p})]}),(0,Q.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":v(`pws.statsAria`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:v(`pws.statsTitle`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[typeof C==`number`&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:v(`pws.stats.totalRequests`)}),(0,Q.jsx)(`dd`,{className:`pws-kv-mono`,children:Uo(C,y)})]}),typeof w==`number`&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:v(`pws.stats.totalTokens`)}),(0,Q.jsx)(`dd`,{className:`pws-kv-mono`,children:Wo(w,y)})]}),typeof C!=`number`&&typeof w!=`number`&&(0,Q.jsx)(`div`,{className:`muted`,children:v(`pws.usageUnavailable`)})]}),f&&(0,Q.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:f,children:[v(`pws.viewUsage`),` →`]})]}),(0,Q.jsx)(Us,{report:i,reading:a,onRefreshQuota:o},`${e.name}:${u??``}`)]})]})]})}function cc({item:e,onUpdateProvider:t}){let n=O(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``),d=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,Z.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``)){i(!1),u(``);return}c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}},[a,e.name,e.note,t,s,n]);return r?(0,Q.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Q.jsx)(`textarea`,{ref:d,className:`pws-notes-textarea`,value:a,onChange:e=>o(e.target.value),onBlur:()=>void f(),onKeyDown:t=>{t.key===`Escape`&&(o(e.note??``),u(``),i(!1))},placeholder:n(`pws.notePlaceholder`),rows:3,disabled:s}),l?(0,Q.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,Q.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Q.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,Q.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function lc(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 uc(e){return e.some(e=>e.pricingStatus!==void 0)}function dc(e,t){return t?e.filter(e=>e.pricingStatus===`free`):[...e]}function fc(e,t){return e&&uc(t)}function pc(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t>=127&&t<=159||t===8232||t===8233})}function mc(e){let t=e.trim();return t?t.length>128?`models.displayNameTooLong`:t.includes(`/`)?`models.displayNameNoSlash`:pc(t)?`models.displayNameNoControl`:null:`models.displayNameRequired`}var hc=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],gc=Array.from({length:18},(e,t)=>1e5+t*5e4),_c=new Set(gc),vc=[272e3,372e3,922e3],yc=new Set(vc),bc=`custom`,xc=[4,8,16,32,64,128,256,500,1e3],Sc=new Set(xc),Cc=`ocx-models-collapsed:v2`;function wc(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 Tc(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ec(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);ws(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?xe(a.namespaced,r):a.namespaced})}return i}function Dc(e=localStorage){try{let t=e.getItem(Cc);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 Oc(e,t=localStorage){try{t.setItem(Cc,JSON.stringify([...e]))}catch{}}function kc(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function Ac(e,t){let n=kc(e);for(let r of t)if(r!==e&&kc(r)===n)return!0;return!1}function jc({row:e,disambiguate:t,copied:n,isDefault:r,selected:i,action:a,disabled:o,onCopy:s,onRemove:c}){let l=O(),u=l(a===`delete`?`models.customDelete`:`models.hide`);return(0,Q.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:s,title:e.namespaced,"aria-label":l(n?`pws.modelCopied`:`pws.copyModelId`),children:(0,Q.jsx)(`span`,{className:`pws-model-id`,children:t?e.namespaced:e.id})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:l(`prov.defaultBadge`)}),i&&(0,Q.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:l(`pws.selected`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:e=>c(e.currentTarget),disabled:o,"aria-label":`${u}: ${e.namespaced}`,title:`${u}: ${e.namespaced}`,children:a===`delete`?(0,Q.jsx)(F,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Q.jsx)($e,{style:{width:13,height:13},"aria-hidden":`true`})})]})}var Mc=300;function Nc(e){return(0,Q.jsx)(Pc,{...e},JSON.stringify([e.apiBase,e.item.name]))}function Pc({item:e,apiBase:t,availableModels:n,selectedModels:r,modelRows:i,modelRevision:a,modelRowsReady:o,modelsLoading:s=!1,modelsLoadFailed:c=!1,needsReauth:l=!1,onRetryModels:u,onOpenAccounts:d,onOpenModels:f}){let p=O(),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(0),S=JSON.stringify([t,e.name,a,b]),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,k]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(null),F=(0,Z.useRef)(null),I=(0,Z.useRef)(!1),L=(0,Z.useRef)(!0),R=(0,Z.useRef)(a),z=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useRef)(null),H=C?.key===S&&T!==S,U=i!==null&&o&&!s&&!c&&H,W=U&&(!j||a!==j.revision),G=D||!!j&&!W,ee=(i??[]).filter(t=>t.provider===e.name),K=ee.some(e=>e.initialSelectionPending),q=!U||G||K,te=C?.rows.filter(t=>t.provider===e.name)??[],ne=new Set(r),J=[...n,...e.models??[],...te.map(e=>e.modelId),...e.defaultModel?[e.defaultModel]:[]],Y=v.trim(),re=!!Y&&(J.includes(Y)||Ac(Y,J)),ie=ee.filter(e=>!e.disabled),X=uc(ie),ae=fc(g,ie),oe=dc(ie,ae),se=m.trim().toLowerCase(),ce=oe.filter(e=>[e.id,e.namespaced].some(e=>e.toLowerCase().includes(se))),le=new Map;for(let e of ie)le.set(e.id,(le.get(e.id)??0)+1);(0,Z.useEffect)(()=>{R.current=a},[a]),(0,Z.useEffect)(()=>{L.current=!0;let e=e=>{V.current&&e.target!==V.current.button&&e.target!==document.body&&(V.current.retained=!1)};return document.addEventListener(`focusin`,e),()=>{L.current=!1,document.removeEventListener(`focusin`,e),F.current!==null&&clearTimeout(F.current)}},[]),(0,Z.useEffect)(()=>{let e=!1,n=A(2e4);return fetch(`${t}/api/custom-models`,{signal:n.signal}).then(hn).then(Ns).then(t=>{e||(w({key:S,rows:t}),E(null))}).catch(()=>{e||E(S)}).finally(()=>n.clear()),()=>{e=!0,n.controller.abort(),n.clear()}},[t,S]),(0,Z.useEffect)(()=>{!D&&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)},[D,W,i]);let ue=()=>{x(e=>e+1),u?.()},de=async e=>{try{if(await navigator.clipboard.writeText((le.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{}},fe=e=>e.custom===!0&&e.native!==!0&&te.some(t=>t.id===e.customId&&t.provider===e.provider&&t.modelId===e.id),pe=e=>!U||e.initialSelectionPending?null:e.custom?fe(e)?`delete`:null:e.native!==!0&&te.some(t=>t.modelId===e.id)?null:`hide`,me=e=>{if(!L.current){u?.();return}M({...e,revision:R.current}),k(!1),ue()},he=async()=>{if(q||I.current||!Y||re)return;I.current=!0,k(!0),M(null);let n=A(6e4),r={outcome:`unconfirmed`,refreshPending:!1};try{let i=await fetch(`${t}/api/custom-models`,{method:`POST`,signal:n.signal,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,modelId:Y})});if(i.status===201){let t=await hn(i),n=Ps(t,e.name,Y);if(C?.rows.some(e=>e.id===n.id))throw Error(`Reused custom identity`);r={outcome:`saved`,created:n,refreshPending:Fs(t)},L.current&&y(``)}else i.status>=400&&i.status<500&&(r={outcome:`rejected`,refreshPending:!1})}catch{}finally{n.clear(),me(r)}},ge=async(e,n)=>{let r=pe(e);if(q||I.current||!r)return;if(I.current=!0,!await na({message:p(r===`delete`?`models.customDeleteConfirm`:`models.hideConfirm`,{name:e.namespaced}),confirmLabel:p(r===`delete`?`common.delete`:`common.ok`),tone:`danger`})){I.current=!1;return}k(!0),M(null),V.current={button:n,retained:document.activeElement===n};let i=A(6e4),a={outcome:`unconfirmed`,refreshPending:!1};try{let n=r===`delete`?await fetch(`${t}/api/custom-models/${encodeURIComponent(e.customId)}`,{method:`DELETE`,signal:i.signal}):await Ts(t,`models`,e.provider,[{id:e.id,native:e.native===!0}],!1,(e,t)=>fetch(e,{...t,signal:i.signal}));if(n.ok){let e=await hn(n);e&&typeof e==`object`&&!Array.isArray(e)&&`ok`in e&&e.ok===!0&&(a={outcome:r===`delete`?`deleted`:`hidden`,refreshPending:Fs(e)})}else n.status>=400&&n.status<500&&(a={outcome:`rejected`,refreshPending:!1})}catch{}finally{i.clear(),me(a)}},_e=j?.created&&W&&ee.some(e=>e.customId===j.created?.id&&e.disabled),ve=j&&(j.refreshPending||c||T===S),ye=j?j.outcome===`unconfirmed`?p(`pws.modelMutationUnconfirmed`):j.outcome===`rejected`?p(`models.customSaveFailed`):j.outcome===`saved`?p(ve?`pws.modelSavedRefreshPending`:_e?`pws.modelSavedHidden`:`pws.modelSaved`):p(ve?`pws.modelRemovedRefreshPending`:j.outcome===`deleted`?`pws.modelDefinitionDeleted`:`pws.modelHidden`):null;return(0,Q.jsxs)(`div`,{className:`pws-section`,children:[(0,Q.jsxs)(`div`,{className:`pws-section-head`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.tab.models`)}),i!==null&&(0,Q.jsx)(`span`,{className:`muted`,children:p(`pws.modelsAvailable`,{count:ie.length})})]}),(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsx)(`button`,{ref:B,type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.manageModelVisibility`)})}),l&&(0,Q.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,Q.jsx)(`span`,{children:p(`pws.modelsNeedsReauth`)}),d&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:d,children:p(`pws.tab.accounts`)})]}),o&&n.length===0&&ie.length>0&&(e.models?.length??0)>0&&!l&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:p(`pws.modelsConfiguredFallback`)}),K&&(0,Q.jsx)(`p`,{role:`status`,className:`muted`,children:p(`pws.modelSelectionPending`)}),(0,Q.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:p(`models.customAdd`)}),(0,Q.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,Q.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&he()},placeholder:p(`models.customFieldModelIdPlaceholder`),"aria-label":p(`models.customAdd`),disabled:D}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{he()},disabled:q||!Y||re,children:p(D?`models.customSaving`:`models.customAddBtn`)})]}),re&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:p(`pws.modelKnown`)}),ye&&(0,Q.jsx)(`p`,{className:j?.outcome===`unconfirmed`||j?.outcome===`rejected`?`pws-inline-error`:`muted text-label`,role:j?.outcome===`unconfirmed`||j?.outcome===`rejected`?`alert`:`status`,children:ye}),_e&&ve&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:p(`pws.modelSavedHidden`)}),j?.refreshPending&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:p(`codexAuth.catalogRefreshPending`)}),c||T===S?(0,Q.jsxs)(`div`,{className:`pws-inline-error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:p(c?`pws.modelsLoadFailed`:`pws.modelOwnershipFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ue,disabled:D,children:p(`common.retry`)})]}):(!U||G)&&(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:p(!o||s?`pws.modelsLoading`:`pws.modelOwnershipLoading`)}),j&&(j.outcome===`unconfirmed`||j.refreshPending)&&!c&&T!==S&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ue,disabled:D,children:p(`common.retry`)}),X&&(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsx)(on,{on:g,onClick:()=>_(!g),label:p(`models.freeOnly`),showLabel:!0})}),(0,Q.jsx)(`input`,{ref:z,type:`search`,className:`input pws-model-search`,placeholder:p(`pws.modelSearchPlaceholder`),value:m,onChange:e=>h(e.target.value),"aria-label":p(`pws.modelSearchPlaceholder`)}),i!==null&&ie.length===0?(0,Q.jsx)(`p`,{className:`muted`,children:p(`pws.noModels`)}):ce.length===0&&i!==null?(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:p(ae&&oe.length===0?`models.noFreeMatch`:`pws.noModelMatch`)}):(0,Q.jsx)(`ul`,{className:`pws-model-list`,children:ce.slice(0,Mc).map(t=>(0,Q.jsx)(jc,{row:t,disambiguate:(le.get(t.id)??0)>1,copied:N===t.namespaced,isDefault:t.id===e.defaultModel,selected:t.native!==!0&&ne.has(t.id),action:pe(t),disabled:q,onCopy:()=>{de(t)},onRemove:e=>{ge(t,e)}},t.namespaced))}),ce.length>Mc&&(0,Q.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:p(`pws.modelsTruncated`,{shown:String(Mc),total:String(ce.length)})})]})}function Fc({item:e,usageTotals:n,quotaReport:r,currentQuotaReading:i,quotaIdentity:a,modelUsage:o,onRefreshQuota:s}){let c=O(),{locale:l}=t(),u=n?.requests!==void 0,[d,f]=(0,Z.useState)(null),p=(0,Z.useMemo)(()=>o?.length?o.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[o]),m=(0,Z.useMemo)(()=>{if(!p.length)return;let e=0,t=!1;for(let n of p)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[p]);return(0,Q.jsxs)(`div`,{className:`pws-section`,children:[(0,Q.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:c(`pws.usageLast30d`)}),u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":c(`pws.usageLast30d`),children:[(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Go(m,l)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:c(`pws.estimatedCost`)})]}),(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value`,children:Uo(n?.requests,l)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:c(`pws.metricRequests`)})]}),(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value`,children:Wo(n?.totalTokens,l)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:c(`pws.metricTokens`)})]})]}),(0,Q.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:c(`pws.costDisclaimer`)})]}):(0,Q.jsx)(`p`,{className:`muted`,children:c(`pws.usageUnavailable`)})]}),p.length>0&&(0,Q.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:c(`pws.modelBreakdown`)}),(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`pws-model-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:c(`pws.col.model`)}),(0,Q.jsx)(`th`,{className:`num`,children:c(`pws.col.cost`)}),(0,Q.jsx)(`th`,{className:`num`,children:c(`pws.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:c(`pws.col.requests`)}),(0,Q.jsx)(`th`,{children:c(`pws.col.share`)})]})}),(0,Q.jsx)(`tbody`,{children:p.map(e=>{let t=e.model,n=d===t;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,Q.jsxs)(`td`,{className:`mono`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>f(n?null:t),children:e.model}),e.hasUnresolvedRequestedModel&&(0,Q.jsx)(`div`,{className:`muted pws-model-attribution`,children:c(`pws.unresolvedRequestedModel`)})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:Go(e.estimatedCostUsd,l)}),(0,Q.jsx)(`td`,{className:`num mono`,children:Wo(e.totalTokens,l)}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`pws-share-bar`,children:(0,Q.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,Q.jsx)(`tr`,{className:`pws-model-detail`,children:(0,Q.jsx)(`td`,{colSpan:5,children:(0,Q.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:c(`pws.tokenInput`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[` `,Wo(e.inputTokens,l)]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:c(`pws.tokenOutput`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[` `,Wo(e.outputTokens,l)]})]})]})})})]},t)})})]})})]}),(0,Q.jsx)(Us,{report:r,reading:i,onRefreshQuota:s},`${e.name}:${a??``}`)]})}function Ic(e){return e===`anthropic`||e===`anthropic2`}function Lc(e,t){return e===`anthropic`?!0:e!==`anthropic2`||!t?!1:Object.hasOwn(t,`anthropicOAuthInstance`)&&t.anthropicOAuthInstance===`anthropic2`&&t.adapter===`anthropic`&&t.authMode===`oauth`}function Rc(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function zc(e){return Rc(e)??`account-…`}function Bc(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 Vc({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,Q.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,Q.jsx)(Ge,{width:10,height:10,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Q.jsx)(Qe,{width:10,height:10,"aria-hidden":`true`})})]})}function Hc({accountLabel:e,globalThreshold:t,override:n,disabled:r=!1,inputId:i,hintText:a,onChange:o}){let s=O(),c=(0,Z.useRef)(!1),l=(0,Z.useRef)(!1),[u,d]=(0,Z.useState)(!1),f=n!==null,[p,m]=(0,Z.useState)({override:n,draft:String(n??t)});p.override!==n&&m({override:n,draft:String(n??t)});let{draft:h}=p,g=e=>m(t=>({...t,draft:e})),_=()=>m(e=>({...e,draft:String(e.override??t)})),v=r||u,y=a??s(`accountPool.autoSwitchHint`),b=(0,Z.useId)(),x=async e=>{if(!(r||l.current)){l.current=!0,d(!0);try{await o(e)}finally{_(),l.current=!1,d(!1)}}},S=async()=>{if(!f||r||l.current)return;let e=h.trim(),t=e===``?NaN:Number(e);if(!Number.isInteger(t)||t<0||t>100){_();return}t!==n&&await x(t)},C=e=>{if(r||l.current)return;let t=Bc(h,e,0,100);g(t);let i=Number(t);i!==n&&x(i)};return(0,Q.jsxs)(`div`,{className:`codex-account-auto-switch`,title:y,"aria-busy":u,"aria-disabled":v,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c.current){c.current=!1;return}S()}},children:[(0,Q.jsx)(`label`,{className:`codex-account-auto-switch-label`,htmlFor:f?i:void 0,children:s(`accountPool.autoSwitchThreshold`)}),f&&(0,Q.jsxs)(`span`,{className:`codex-account-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{id:i,className:`input mono codex-auto-switch-input codex-account-auto-switch-input`,type:`number`,min:0,max:100,step:1,inputMode:`numeric`,value:h,readOnly:v,"aria-disabled":v,"aria-label":s(`accountPool.autoSwitchThresholdAria`,{email:e}),"aria-describedby":b,onChange:e=>{v||g(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),S()):e.key===`Escape`&&(e.preventDefault(),_()))}}),(0,Q.jsx)(`span`,{className:`codex-account-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(Vc,{disabled:r&&!u,incrementLabel:s(`codexAuth.autoSwitchThresholdInc`),decrementLabel:s(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>C(1),onDecrement:()=>C(-1)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle codex-account-auto-switch-toggle ${f?`on`:``}`,disabled:r&&!u,"aria-disabled":v,"aria-pressed":f,"aria-label":s(`accountPool.autoSwitchOverrideAria`,{email:e}),"aria-describedby":b,onPointerDownCapture:()=>{c.current=!0},onPointerUp:()=>{c.current=!1},onPointerCancel:()=>{c.current=!1},onClick:()=>{c.current=!1,x(f?null:t)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:b,className:`sr-only`,children:y})]})}function Uc(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Wc(e){let t=Uc(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function Gc(e){return e===`reauth_required`}function Kc(e){return!!e?.needsReauth||Gc(e?.health?.status)}function qc(e){return e===`cooldown`}function Jc(e){return e===`warning`||e===`reauth_required`}function Yc(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 Xc(e,t){let n=Yc(t);return n?e(n):null}function Zc(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):zc(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 Qc(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return $c(e)}function $c(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 el(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}function tl(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t===127})}function nl(e,t){let n=e.trim();return n.length>80||tl(n)?t(`prov.aliasInvalid`):null}var rl=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,deviceCode:``,instructions:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function il(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 al({id:e,error:t,onIdChange:n,onStartOAuth:r,onStartDeviceOAuth:i,onClose:a}){let o=O();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{style:{marginBottom:4},children:o(`codexAuth.addTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o(`codexAuth.addPickDesc`)}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:o(`codexAuth.addIdLabel`)}),(0,Q.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:o(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,Q.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Q.jsx)(qe,{width:20}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:o(`codexAuth.oauthLogin`)}),(0,Q.jsx)(`div`,{className:`sub`,children:o(`codexAuth.oauthDesc`)})]})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`list-row`,onClick:i,style:{marginBottom:8},children:(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Q.jsx)(st,{width:20}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:o(`codexAuth.deviceLogin`)}),(0,Q.jsx)(`div`,{className:`sub`,children:o(`codexAuth.deviceDesc`)})]})]})}),t&&(0,Q.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,style:{width:`100%`},children:o(`codexAuth.cancel`)})]})}var ol=2500;function sl(){let[e,t]=(0,Z.useState)(null),n=(0,Z.useRef)(null),r=(0,Z.useRef)(0),i=(0,Z.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,Z.useEffect)(()=>i,[i]),{outcomeFor:(0,Z.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,Z.useCallback)((e,a)=>{let o=++r.current;Qc(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)},ol))})},[i])}}function cl(e){try{let t=new URL(e).protocol;return t===`https:`||t===`http:`}catch{return!1}}function ll({url:e,openLabel:t}){let n=O(),{outcomeFor:r,copy:i}=sl();if(!e)return null;let a=r(e),o=n(a===`copied`?`prov.linkCopied`:a===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`),s=cl(e);return(0,Q.jsxs)(`div`,{className:`login-url-block`,children:[(0,Q.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,Q.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(e,e),children:[(0,Q.jsx)(st,{style:{width:13,height:13},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{"aria-live":`polite`,children:o})]}),s&&(0,Q.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,Q.jsx)(Ve,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t??n(`prov.didntOpen`)]})]})]})}function ul({hint:e,paste:t}){let n=O(),r=sl(),i=e.deviceCode??``,a=e.url??``;if(!i&&!a&&!e.instructions&&!t)return null;let o=r.outcomeFor(i),s=n(o===`copied`?`prov.codeCopied`:o===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),c=i||e.browserLaunch===`skipped`?n(`prov.openSignInPage`):void 0,l=i&&cl(a)?()=>{r.copy(i,i),window.open(a,`_blank`,`noopener,noreferrer`)}:null;return(0,Q.jsxs)(`div`,{className:`login-hint`,children:[e.browserLaunch===`failed`&&a&&(0,Q.jsx)(`div`,{className:`notice-warn login-hint-launch-failed`,role:`status`,children:n(`prov.browserLaunchFailed`)}),i&&(0,Q.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,Q.jsx)(`span`,{className:`text-label`,children:n(`prov.deviceCode`)}),(0,Q.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:i}),(0,Q.jsx)(`button`,{type:`button`,className:l?`btn btn-ghost btn-sm`:`btn btn-primary btn-sm`,onClick:()=>r.copy(i,i),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:s})}),l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm login-hint-copy-open`,onClick:l,children:n(`prov.copyCodeAndOpen`)})]}),(0,Q.jsx)(ll,{url:a,openLabel:c}),e.instructions&&(0,Q.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&!i&&(0,Q.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:n(`prov.pasteRedirectHint`)}),(0,Q.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,Q.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:t.value,onChange:e=>t.onChange(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),t.onSubmit())},placeholder:n(`prov.pasteRedirect`),"aria-label":n(`prov.pasteRedirect`),disabled:t.busy,className:`input text-label login-hint-paste-input`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:t.busy||t.disabled===!0||!t.value.trim(),onClick:t.onSubmit,children:t.busy?t.submittingLabel??n(`prov.pasteSubmitting`):n(`prov.pasteSubmit`)})]}),t.message&&(0,Q.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function dl({reauthAccountId:e,authUrl:t,deviceCode:n,instructions:r,browserLaunch:i,manualCode:a,manualCodeBusy:o,manualCodeWaiting:s,statusNotice:c,statusTone:l,flowId:u,error:d,onSwitchToDevice:f,onManualCodeChange:p,onSubmitManualCode:m,onClose:h}){let g=O();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{style:{marginBottom:4},children:g(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:g(`codexAuth.oauthWaiting`)}),(0,Q.jsx)(ul,{hint:{url:t,deviceCode:n,instructions:r,browserLaunch:i},paste:{value:a,busy:o,disabled:o||s||!a.trim()||!u,submittingLabel:g(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:p,onSubmit:m}}),c&&(0,Q.jsx)(`div`,{className:l===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:c}),d&&(0,Q.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:d}),f&&!n&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,style:{width:`100%`,marginTop:8},children:g(`codexAuth.deviceLogin`)}),(0,Q.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,Q.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:h,style:{width:`100%`},children:g(`codexAuth.cancel`)})]})}var fl=`ocx.oauth.openBrowser`;function pl(){try{let e=window.localStorage.getItem(fl);return e===`0`?!1:e===`1`||void 0}catch{return}}function ml(){let e=pl();return e===void 0?{}:{openBrowser:e}}function hl(e){try{window.localStorage.setItem(fl,e?`1`:`0`)}catch{}}function gl(e){return e===`started`||e===`failed`||e===`skipped`?e:void 0}function _l(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 vl=3e5,yl=96e4;function bl({apiBase:e,reauthAccountId:t,ui:n,dispatch:r,t:i}){let a=(0,Z.useRef)(!0),o=(0,Z.useRef)(0),s=(0,Z.useRef)(!1),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(n.manualCodeState),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(()=>{}),g=(0,Z.useRef)(()=>{}),_=n.manualCodeState===`submitting`,v=n.manualCodeState===`waiting`;(0,Z.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,Z.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let y=(0,Z.useCallback)(()=>{c.current&&=(c.current(),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),b=(0,Z.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),x=(0,Z.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,Z.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,Z.useCallback)((e,t)=>{h.current=e,g.current=t},[]),C=(0,Z.useCallback)(()=>{n.step===`oauth-waiting`&&x(),g.current()},[n.step,x]),w=(0,Z.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({...ml(),...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 hn(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:gl(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=sa(async()=>{if(s.current||S.signal.aborted)return;s.current=!0;let e=AbortSignal.any([S.signal,AbortSignal.timeout(1e4)]);try{let n=await gn(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(_l(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?yl:vl)}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,Z.useEffect)(()=>{if(!t){m.current=null;return}m.current!==t&&(m.current=t,w())},[t,w]),{manualCodeBusy:_,manualCodeWaiting:v,bindCallbacks:S,closeModal:C,startOAuth:w,submitManualCode:(0,Z.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 xl({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=O(),[a,o]=(0,Z.useReducer)(il,r,rl),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=bl({apiBase:e,reauthAccountId:r,ui:a,dispatch:o,t:i});(0,Z.useEffect)(()=>{d(n,t)},[d,n,t]),(0,Z.useEffect)(()=>{s.current=document.activeElement;let e=c.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 h=(0,Z.useCallback)(e=>{e.preventDefault(),f()},[f]),g=i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,Q.jsx)(`dialog`,{ref:c,"aria-label":g,className:`modal-overlay`,onCancel:h,children:(0,Q.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,Q.jsx)(al,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{p(a.id)},onStartDeviceOAuth:()=>{p(a.id,{device:!0})},onClose:f}),a.step===`oauth-waiting`&&(0,Q.jsx)(dl,{reauthAccountId:r,authUrl:a.authUrl,deviceCode:a.deviceCode,instructions:a.instructions,browserLaunch:a.browserLaunch,manualCode:a.manualCode,manualCodeBusy:l,manualCodeWaiting:u,statusNotice:a.statusNotice,statusTone:a.statusTone,flowId:a.flowId,error:a.error,onSwitchToDevice:()=>{p(a.id,{device:!0})},onManualCodeChange:e=>o({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{m()},onClose:f})]})})}var Sl=[2,1,0,-1,-2],Cl=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function wl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function Tl(e){let t=wl(e);return t>0?`+${t}`:String(t)}function El(e){return Cl.has(e)}function Dl(e){return Cl.get(e)??null}function Ol(e,t){let n=wl(t);return e(`accountPool.priorityOption`,{name:e(Dl(n)??`accountPool.priorityCustom`),value:Tl(n)})}var kl=[`quota`,`round-robin`,`fill-first`,`reset-first`],Al=[`five-hour`,`weekly`,`max-utilization`],jl=`quota`,Ml=`five-hour`,Nl=new Set(kl),Pl=new Set(Al);function Fl(e){return typeof e==`string`&&Nl.has(e)?e:jl}function Il(e){return typeof e==`string`&&Pl.has(e)?e:Ml}function Ll(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Rl(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}var zl=`openai`;function Bl(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:Fl(r.strategy??n?.strategy),stickyLimit:Ll(r.stickyLimit??n?.stickyLimit),autoSwitchThreshold:typeof i==`number`?i:null,quotaWindow:(r.quotaWindow??n?.quotaWindow)===void 0||r.quotaWindow===null?null:Il(r.quotaWindow??n?.quotaWindow),nativeMessages:Ic(t)?Object.hasOwn(r,`nativeMessages`)?r.nativeMessages===!0:n?.nativeMessages??!0:null,...r.warning===`config_bookkeeping_failed`?{warning:r.warning}:{}}}function Vl(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},...Ic(e)&&t.nativeMessages!==void 0?{nativeMessages:t.nativeMessages}:{}}}async function Hl(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?Bl(await i.json(),t):null}catch{return null}}var Ul=class extends Error{code=`config_save_state_unknown`;constructor(){super(`config_save_state_unknown`),this.name=`PoolSettingsSaveStateUnknownError`}};async function Wl(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(Vl(t,n))});if(!a.ok){if(Ic(t)&&a.status===409&&(await a.json().catch(()=>null))?.code===`config_save_state_unknown`)throw new Ul;return null}return Bl(await a.json().catch(()=>({})),t,n)}catch(e){if(e instanceof Ul)throw e;return null}}async function Gl(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};let r=await Wl(e,zl,{strategy:t.strategy,stickyLimit:t.stickyLimit},n);return r?{ok:!0,strategy:r.strategy,stickyLimit:r.stickyLimit}:{ok:!1}}var Kl=1e4;function ql(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Jl(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Yl(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Xl(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Zl(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Ql(e,t,n){if(e<=0){let t=Yl(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Jl(t)??Yl(0,n)}}async function $l(e,t,n=(e,t)=>fetch(e,t),r=Kl){return!Number.isInteger(t)||t<0||t>100?!1:await Wl(e,zl,{threshold:t},(e,t)=>n(e,t),{signal:AbortSignal.timeout(r)})!==null}var eu={short:90,long:98};function tu(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}:{...eu}}var nu=3e4,ru=new Map;function iu(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:null}function au(e,t=!0){let n=ru.get(e),[r,i]=(0,Z.useState)(()=>n?.accounts??[]),a=Vt(hr(e,`codex`),[e],async t=>mr(await fetch(`${e}/api/usage?range=30d&surface=codex`,{signal:t}),`account usage load failed`),{enabled:t}),[o,s]=(0,Z.useState)(()=>n?.activeId??null),[c,l]=(0,Z.useState)(()=>n==null?`loading`:`ready`),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(0),[O,k]=(0,Z.useState)(()=>n!=null),[j,M]=(0,Z.useState)(0),N=(0,Z.useRef)(null);N.current===null&&(N.current=new Set);let P=(0,Z.useRef)(null),F=(0,Z.useRef)(0),I=(0,Z.useRef)(null),L=(0,Z.useRef)(null);L.current===null&&(L.current=new Set);let R=(0,Z.useRef)(null),z=(0,Z.useRef)(null),B=(0,Z.useRef)(!!n?.accounts.length),V=(0,Z.useRef)(n!=null),H=(0,Z.useRef)(null),U=(0,Z.useRef)(null),W=(0,Z.useRef)(null),G=(0,Z.useRef)(!1),ee=(0,Z.useCallback)(e=>(L.current.add(e),()=>{L.current.delete(e)}),[]),K=(0,Z.useCallback)(()=>Zl(R.current?.value),[]),q=(0,Z.useCallback)(()=>R.current?.value,[]),te=(0,Z.useCallback)(async(t=!1,n={})=>{let r=++F.current,a=n.validatePending===!0,o=ru.get(e)?.accounts.length??0,c=A(a?3e4+12e4*Math.max(1,o):2e4),u=a?{}:null;u&&(N.current.add(u),M(N.current.size)),D(e=>e+1);try{let n=[...L.current],o=new Map;for(let e of n)o.set(e,e.beginActiveRead());!t&&!V.current&&l(`loading`);let u=null,f,p=(async()=>{try{let n=await fetch(`${e}/api/codex-auth/accounts${a?`/refresh`:t?`?refresh=1`:``}`,{method:a?`POST`:`GET`,signal:c.signal});if(!n.ok)throw Error(`account load failed`);let o=await n.json();return F.current===r&&(u=(o.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel,n=nt(e.quota);return{...e,...t?{logLabel:t}:{},priority:wl(e.priority),autoSwitchThresholdOverride:iu(e.autoSwitchThresholdOverride),quotaAutoRefresh:e.quotaAutoRefresh??{...n,fiveHourEnabled:!1,weeklyEnabled:!1}}}),i(u),B.current=u.length>0,V.current=!0,l(`ready`),d(!1)),!0}catch{return!1}})(),m=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`,{signal:c.signal});if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(F.current===r){let e=i.activeCodexAccountId??null,t=I.current;t&&t.staleReadsRemaining>0&&e!==t.id?--t.staleReadsRemaining:(I.current=null,f=e,s(e)),R.current={value:i},T(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of n)e.acceptActiveRead(i,o.get(e))}return!0}catch{if(F.current===r)for(let e of n)e.rejectActiveRead();return!1}})(),[h,g]=await Promise.all([p,m]);if(F.current!==r)return!1;if(h){l(`ready`),V.current=!0;let t=ru.get(e);return ru.set(e,{accounts:u??t?.accounts??[],activeId:f===void 0?t?.activeId??null:f}),g}return V.current||l(`error`),d(!0),!1}finally{c.clear(),u&&(N.current.delete(u),M(N.current.size)),D(e=>Math.max(0,e-1)),k(!0)}},[e]);(0,Z.useEffect)(()=>{t&&P.current!==e&&(P.current=e,Promise.resolve().then(()=>{te()}))},[e,t,te]);let ne=r.some(e=>e.hasCredential&&!e.quota);(0,Z.useEffect)(()=>{if(!t||!ne||j>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{N.current.size===0&&te(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,ne,j,te]),(0,Z.useEffect)(()=>{if(!(!t||j>0))return sa(()=>{N.current.size===0&&te()},nu)},[t,te,j]);let J=(0,Z.useCallback)(()=>{let e={};return N.current.add(e),M(N.current.size),e},[]),Y=(0,Z.useCallback)(e=>{N.current.delete(e)&&M(N.current.size)},[]),re=(0,Z.useCallback)(async(t,n)=>{if(z.current||U.current)return{ok:!1,reason:`busy`};z.current=t??`__main__`,p(t??`__main__`);let r=`request`;try{let i=await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t,...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??t;return I.current={id:a??null,staleReadsRemaining:1},s(a??null),T(a??null),te(),{ok:!0,activeId:a??null}}catch{return t===null&&(I.current=null,await te()),{ok:!1,reason:r}}finally{z.current=null,p(null)}},[e,te]),ie=(0,Z.useCallback)(async(t,n)=>{try{return(await fetch(`${e}/api/codex-auth/accounts/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,alias:n.trim()})})).ok?(await te(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,te]),X=(0,Z.useCallback)(async(t,n)=>{if(H.current)return{ok:!1,reason:`busy`};H.current={accountId:t},h(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,paused:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=a&&typeof a==`object`?a:{};if(i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,paused:n}:e)),Object.prototype.hasOwnProperty.call(o,`activeCodexAccountId`)){let e=o.activeCodexAccountId??null;I.current={id:e,staleReadsRemaining:1},s(e)}return n&&T(e=>e===t?null:e),te(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{H.current=null,h(null)}},[e,te]),ae=(0,Z.useCallback)(async(t,n)=>{if(U.current||z.current)return{ok:!1,reason:`busy`};U.current={accountId:t},_(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/priority`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,priority:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=wl((a&&typeof a==`object`?a:{}).priority??n);return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,priority:o}:e)),T(null),I.current=null,te(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{U.current=null,_(null)}},[e,te]),oe=(0,Z.useCallback)(async(t,n)=>{if(W.current)return{ok:!1,reason:`busy`};W.current={accountId:t},y(t);try{let r=await fetch(`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,threshold:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=a&&typeof a==`object`?a:{},s=Object.prototype.hasOwnProperty.call(o,`autoSwitchThresholdOverride`)?iu(o.autoSwitchThresholdOverride):n;return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,autoSwitchThresholdOverride:s}:e)),te(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{W.current=null,y(null)}},[e,te]),se=(0,Z.useCallback)(async(t,n,r)=>{if(G.current)return{ok:!1,reason:`busy`};G.current=!0,x(t);try{return(await fetch(`${e}/api/codex-auth/accounts/credits`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).ok?(i(e=>e.map(r)),te(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}finally{G.current=!1,x(null)}},[e,te]),ce=(0,Z.useCallback)((e,t)=>se(e,{id:e,creditsAfterLimit:t},n=>n.id===e||e===`__main__`&&n.isMain?{...n,creditsAfterLimit:t}:n),[se]),le=(0,Z.useCallback)(e=>se(`*`,{all:e},t=>({...t,creditsAfterLimit:e})),[se]),ue=(0,Z.useCallback)(async()=>{if(H.current)return{ok:!1,reason:`busy`};H.current=`bulk`,C(!0);try{let t=await fetch(`${e}/api/codex-auth/accounts/pause-exhausted`,{method:`PUT`});if(!t.ok)return{ok:!1,reason:`request`};let n=await t.json().catch(()=>({})),r=n&&typeof n==`object`?n:{},a=new Set(r.pausedAccountIds??[]);if(i(e=>e.map(e=>a.has(e.id)||a.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},s(e)}return T(e=>e!==null&&a.has(e)?null:e),te(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{H.current=null,C(!1)}},[e,te]),de=(0,Z.useCallback)(async t=>{try{let n=await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`});if(!n.ok)return{ok:!1,reason:`request`};let r=_l(await n.json().catch(()=>({})));return await te(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,te]),fe=(0,Z.useCallback)(async()=>await te()?{ok:!0}:{ok:!1,reason:`reload`},[te]),pe=o&&o!==`__main__`?r.find(e=>e.id===o):null,me=r.find(e=>e.isMain),he=pe??me,ge=!he?.paused&&Kc(he);return{accounts:(0,Z.useMemo)(()=>{let e=new Map((a.data?.accounts??[]).map(e=>[e.accountLogLabel,e]));return r.map(t=>{let n=t.isMain?`main`:t.logLabel,r=n?e.get(n):void 0;return r?{...t,usage30d:r}:t})},[r,a.data]),activeId:o,loadState:c,refreshing:E>0,refreshFailed:u,initialLoading:!O,switchingId:f,pauseUpdatingId:m,priorityUpdatingId:g,autoSwitchUpdatingId:v,creditsAfterLimitUpdatingId:b,pausingExhausted:S,activeNeedsReauth:ge,activePinnedId:w,load:te,switchAccount:re,setAccountPaused:X,setAccountPriority:ae,setAccountAutoSwitchThreshold:oe,setAccountCreditsAfterLimit:ce,setAllCreditsAfterLimit:le,pauseExhaustedAccounts:ue,saveAlias:ie,removeAccount:de,syncAfterAccountAdded:fe,pauseRefresh:J,resumeRefresh:Y,subscribeLoadObserver:ee,readLastThreshold:K,readLastActive:q}}function ou(e,t,n,r,i){let[a,o]=(0,Z.useState)({apiBase:e,busy:!1}),s=(0,Z.useRef)(null),c=(0,Z.useRef)(0),l=(0,Z.useEffectEvent)((e,t)=>{i?.onRead(e,t)}),u=i?.revision??0,d=(0,Z.useRef)(null);a.apiBase!==e&&o({apiBase:e,busy:!1});let f=a.apiBase===e?a.visible:void 0,p=a.apiBase===e&&a.busy;return(0,Z.useEffect)(()=>{let e=new AbortController;return s.current=e,()=>{e.abort(),d.current?.abort(),d.current=null}},[e]),(0,Z.useEffect)(()=>{let t=new AbortController,n=A(15e3),r=c.current,i=fetch(`${e}/api/settings`,{signal:n.signal}).then(e=>{if(!e.ok)throw Error(`read`);return e.json()});return l(i,t.signal),i.then(n=>{t.signal.aborted||d.current||c.current!==r||!n||typeof n!=`object`||!(`showCodexCredits`in n)||typeof n.showCodexCredits!=`boolean`||o({apiBase:e,visible:n.showCodexCredits,busy:!1})}).catch(()=>{}).finally(()=>n.clear()),()=>{t.abort(),n.controller.abort(),n.clear()}},[e,u]),{visible:f,busy:p,toggle:async()=>{let i=s.current;if(f===void 0||p||d.current||!i||i.signal.aborted)return;let a=new AbortController;d.current=a;let l=A(15e3),u=()=>l.controller.abort();a.signal.addEventListener(`abort`,u,{once:!0});let m=()=>s.current===i&&!i.signal.aborted,h=!f;c.current+=1,o({apiBase:e,visible:h,busy:!0});try{let i;try{let t=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:l.signal,body:JSON.stringify({showCodexCredits:h})});if(!t.ok)throw Error(`save`);let n=await t.json();if(typeof n?.showCodexCredits!=`boolean`)throw Error(`shape`);i=n.showCodexCredits}catch{m()&&(o({apiBase:e,visible:f,busy:!1}),n(r(`codexAuth.creditsToggleFailed`),`err`));return}if(!m())return;o({apiBase:e,visible:i,busy:!0}),n(r(i?`codexAuth.creditsShown`:`codexAuth.creditsHidden`),`ok`);try{let e=await t(!0);m()&&!e&&n(r(`codexAuth.quotaRefreshFailed`),`err`)}catch{m()&&n(r(`codexAuth.quotaRefreshFailed`),`err`)}}finally{l.clear(),a.signal.removeEventListener(`abort`,u),m()&&(d.current=null,o(e=>({...e,busy:!1})))}}}}var su=`https://auth.openai.com/codex/device`,cu=2e3,lu=1e4,uu=new Set([`identity_mismatch`,`credential_changed`,`native_main_unavailable`,`device_authorization_failed`,`publication_failed`,`reconciliation_failed`,`flow_in_progress`]);function du(e){return typeof e==`string`&&uu.has(e)?e:`request_failed`}function fu(e){return typeof e==`string`&&e.startsWith(su)?e:``}function pu(e){return typeof e==`string`&&/^[A-Z0-9-]{1,16}$/i.test(e)?e:``}function mu(e,t){let[n,r]=(0,Z.useState)({phase:`idle`}),i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(!1),l=(0,Z.useCallback)(()=>{s.current?.abort(),s.current=null},[]),u=(0,Z.useCallback)(async()=>{let n=i.current;if(!n){l(),r({phase:`idle`});return}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:du(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,Z.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:du(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(lu)])}),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:du(c.code)}),!e)return}else if(p=fu(c.verificationUrl)||p,m=pu(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:du(c.code)});return}}catch{if(!u()||i.current!==f)return}await new Promise(e=>setTimeout(e,cu))}},[e,t,l]);return(0,Z.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 hu={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 gu(e){return(t,n)=>{let r=hu[e][t];for(let[e,t]of Object.entries(n??{}))r=r.split(`{${e}}`).join(String(t));return r}}var _u=`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(`.`),vu=class extends Error{code;constructor(e){super(e),this.code=e}};function yu(e){return e instanceof vu?e.code:`NETWORK_ERROR`}function bu(){throw new vu(`INVALID_RESPONSE`)}function xu(e){return!e||typeof e!=`object`||Array.isArray(e)?bu():e}function Su(e){return typeof e!=`string`||!e.trim()?bu():e}function Cu(e){return e===null?null:Su(e)}function wu(e){return typeof e==`boolean`?e:bu()}function Tu(e,t){return typeof e==`string`&&t.includes(e)?e:bu()}function Eu(e){let t=xu(e);return{id:Su(t.id),label:Su(t.label),identityHint:Su(t.identityHint),state:Tu(t.state,[`active`,`inactive`])}}function Du(e){let t=xu(e);if(!Array.isArray(t.profiles)||t.profiles.length>32)return bu();let n=t.profiles.map(Eu),r=Cu(t.activeProfileId);if(new Set(n.map(e=>e.id)).size!==n.length)return bu();let i=n.filter(e=>e.state===`active`);return(r===null?n.length!==0:i.length!==1||i[0].id!==r)?bu():{effectiveCodexHome:Su(t.effectiveCodexHome),activeProfileId:r,profiles:n}}function Ou(e){let t=xu(e);return{effectiveCodexHome:Su(t.effectiveCodexHome),activeProfileId:Cu(t.activeProfileId),supported:wu(t.supported),authStatus:Tu(t.authStatus,[`ok`,`missing`,`invalid`,`unreadable`]),keyStore:Tu(t.keyStore,[`available`,`missing-key`,`unavailable`]),vaultStatus:Tu(t.vaultStatus,[`ok`,`missing`,`invalid`]),recoveryPending:wu(t.recoveryPending)}}async function ku(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 vu(`INVALID_RESPONSE`)}if(n.throwIfAborted(),!a.ok){let e=o&&typeof o==`object`?o.code:void 0;throw new vu(typeof e==`string`&&_u.includes(e)?e:`INTERNAL_ERROR`)}return o}async function Au(e,t,n){let[r,i]=await Promise.allSettled([ku(e,``,t,void 0,n).then(Du),ku(e,`/doctor`,t,void 0,n).then(Ou)]);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 vu(`STATE_CHANGED`);return{doctor:i.value,list:r.value}}function ju(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 Mu(e){let t=e.doctor;return!!e.list&&t.supported&&t.authStatus===`ok`&&t.keyStore===`available`&&t.vaultStatus!==`invalid`&&!t.recoveryPending}function Nu(e,t){let n=e.doctor;return n.supported?t.kind===`recover`?n.recoveryPending:Mu(e)&&!!e.list?.profiles.some(e=>e.id===t.target&&e.label===t.label&&e.state===`inactive`):!1}function Pu(e,t){return e.doctor.effectiveCodexHome===t.doctor.effectiveCodexHome&&e.doctor.activeProfileId===t.doctor.activeProfileId&&e.doctor.recoveryPending===t.doctor.recoveryPending}async function Fu(e,t,n,r){let i=xu(await ku(e,`/register`,n,{label:t.trim()},r)),a=Su(i.effectiveCodexHome);return Eu(i.profile).state===`active`?a:bu()}async function Iu(e,t,n,r,i){if(!n)throw new vu(`INVALID_REQUEST`);let a=xu(await ku(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 bu();if(t.kind===`switch`){let e=Eu(a.activeProfile);if(e.id!==t.target||e.state!==`active`)return bu()}let o=t.kind===`recover`&&a.restartRequired===void 0&&a.recovered===!1?!1:wu(a.restartRequired);return{effectiveCodexHome:Su(a.effectiveCodexHome),restartRequired:o,...typeof a.recovered==`boolean`?{recovered:a.recovered}:{}}}var Lu=2e4,Ru=Symbol(`account-refresh-timeout`),zu=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=Lu,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||!Nu(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:yu(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 Au(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(Ru)},this.accountRefreshTimeoutMs)});try{let t=await Promise.race([r,i]);this.current(e)&&(t===!1||t===Ru)&&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 Au(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||!Mu(e)||await this.mutate(e,{label:t})}async confirm(){let{snapshot:e,action:t,confirmedStopped:n,refreshFailed:r}=this.state;!e||!t||!n||r||!Nu(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 Au(this.apiBase,r,this.fetchImpl);if(r.throwIfAborted(),!this.current(n)||this.state.blocked)return;if(this.accept(a),!Pu(e,a)||(`action`in t?!Nu(a,t.action):!Mu(a)))throw new vu(`STATE_CHANGED`);if(i=!0,`label`in t){let i=await Fu(this.apiBase,t.label,r,this.fetchImpl);if(!this.current(n))return;if(i!==e.doctor.effectiveCodexHome)throw new vu(`STATE_CHANGED`);this.resultHome=i,this.set({label:``,result:this.restartRequired?`restart`:`saved`})}else{let i=await Iu(this.apiBase,t.action,!0,r,this.fetchImpl);if(!this.current(n))return;if(i.effectiveCodexHome!==e.doctor.effectiveCodexHome)throw new vu(`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:yu(e),previous:null})}finally{this.current(n)&&this.set({action:null,confirmedStopped:!1}),i&&await this.reconcile(n)}})}},Bu={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`},Vu=`ocx account main doctor`;function Hu({t:e}){let[t,n=``]=e(`nativeMain.doctorHint`).split(`{cmd}`);return(0,Q.jsxs)(Q.Fragment,{children:[t,(0,Q.jsx)(`code`,{className:`chip`,children:Vu}),n]})}function Uu({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?ju(a):null,T=a?.list?.profiles??[],E=T.find(e=>e.id===a?.doctor.activeProfileId),D=T.find(e=>e.id===l&&e.state===`inactive`);return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`${t}-heading`,style:{marginBottom:12},children:[(0,Q.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`},children:[(0,Q.jsx)(`strong`,{id:`${t}-heading`,children:e(`nativeMain.title`)}),(0,Q.jsx)(`button`,{ref:p,type:`button`,className:`btn btn-sm btn-ghost`,"aria-expanded":n,"aria-controls":`${t}-panel`,onClick:h,disabled:r,children:e(n?`nativeMain.close`:`nativeMain.manage`)})]}),n&&(0,Q.jsxs)(`div`,{id:`${t}-panel`,"aria-busy":r,children:[(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.separate`)}),a&&(0,Q.jsxs)(`dl`,{children:[(0,Q.jsx)(`dt`,{children:e(`nativeMain.home`)}),(0,Q.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:(0,Q.jsx)(`code`,{children:a.doctor.effectiveCodexHome})}),a.list&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{children:e(`nativeMain.current`)}),(0,Q.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:E?.label??e(`nativeMain.unregistered`)})]})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.physicalHint`)}),i&&(0,Q.jsx)(`p`,{role:`status`,className:`notice notice-warn`,children:e(`nativeMain.busyOther`)}),r&&(0,Q.jsx)(`p`,{role:`status`,children:e(`nativeMain.working`)}),u&&(0,Q.jsxs)(`div`,{role:`alert`,className:`notice notice-err native-main-notice`,children:[(0,Q.jsx)(`p`,{children:e(Bu[u])}),(0,Q.jsx)(`p`,{children:e(`nativeMain.retryHint`)}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`code`,{children:u}),` `,(0,Q.jsx)(Hu,{t:e})]})]}),d&&!r&&!u&&!s&&(0,Q.jsxs)(`div`,{role:`status`,className:`notice native-main-notice`,children:[(0,Q.jsx)(`strong`,{children:e(`nativeMain.lastResult`)}),(0,Q.jsx)(`p`,{children:e(d===`saved`?`nativeMain.saved`:d===`restart`?`nativeMain.restart`:`nativeMain.done`)}),d!==`saved`&&a&&!f&&(0,Q.jsx)(`p`,{children:e(`nativeMain.reopenHint`)})]}),f&&(0,Q.jsx)(`p`,{role:`alert`,className:`notice notice-warn`,children:e(`nativeMain.refreshFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,disabled:S||!!s,children:e(`nativeMain.refresh`)}),a&&!a.doctor.supported&&(0,Q.jsx)(`p`,{role:`alert`,children:e(`nativeMain.unsupported`)}),w&&a?.doctor.supported&&!a.doctor.recoveryPending&&(0,Q.jsxs)(`p`,{role:`status`,children:[e(`nativeMain.unavailable`),` `,(0,Q.jsx)(`code`,{children:w})]}),a?.doctor.recoveryPending&&(0,Q.jsxs)(`div`,{className:`notice notice-warn`,children:[(0,Q.jsx)(`p`,{children:e(`nativeMain.recoveryHint`)}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!a.doctor.supported,onClick:()=>y({kind:`recover`,rollback:!1}),children:e(`nativeMain.recover`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!a.doctor.supported,onClick:()=>y({kind:`recover`,rollback:!0}),children:e(`nativeMain.rollback`)})]})]}),a?.list&&(0,Q.jsxs)(Q.Fragment,{children:[T.length===0&&(0,Q.jsx)(`p`,{children:e(`nativeMain.empty`)}),(0,Q.jsx)(`ul`,{style:{listStyle:`none`,padding:0},children:T.map(t=>(0,Q.jsxs)(`li`,{className:`row`,style:{padding:`8px 0`,flexWrap:`wrap`},children:[(0,Q.jsx)(`strong`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.label}),` `,(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.identityHint}),t.state===`active`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:e(`nativeMain.active`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!Nu(a,{kind:`switch`,target:t.id,label:t.label}),"aria-label":e(`nativeMain.switchTo`,{label:t.label}),onClick:()=>y({kind:`switch`,target:t.id,label:t.label}),children:e(`nativeMain.switch`)})]},t.id))}),D&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!Nu(a,{kind:`switch`,target:D.id,label:D.label}),onClick:()=>y({kind:`switch`,target:D.id,label:D.label}),children:e(`nativeMain.restore`,{label:D.label})}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.restoreHint`)})]}),(0,Q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),v()},children:[(0,Q.jsx)(`label`,{htmlFor:`${t}-label`,children:e(`nativeMain.label`)}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Q.jsx)(`input`,{id:`${t}-label`,value:o,onChange:e=>_(e.target.value),disabled:C||!!s||!Mu(a),maxLength:80,autoComplete:`off`}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-sm`,disabled:C||!!s||!o.trim()||!Mu(a),children:e(`nativeMain.save`)})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.saveHint`)})]})]}),s&&a&&(0,Q.jsxs)(`div`,{ref:m,role:`group`,tabIndex:-1,"aria-labelledby":`${t}-confirm-title`,className:`notice notice-warn`,style:{marginTop:12,display:`block`},onKeyDown:e=>{e.key===`Escape`&&!r&&(e.preventDefault(),y(null))},children:[(0,Q.jsx)(`h3`,{id:`${t}-confirm-title`,style:{overflowWrap:`anywhere`},children:e(s.kind===`switch`?`nativeMain.switchTo`:s.rollback?`nativeMain.rollback`:`nativeMain.recover`,{label:s.kind===`switch`?s.label:``})}),(0,Q.jsx)(`p`,{children:e(`nativeMain.confirmHint`)}),(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:a.doctor.effectiveCodexHome}),(0,Q.jsxs)(`ol`,{children:[(0,Q.jsx)(`li`,{children:e(`nativeMain.stepClose`)}),(0,Q.jsx)(`li`,{children:e(`nativeMain.stepConfirm`)}),(0,Q.jsx)(`li`,{children:e(`nativeMain.stepResult`)})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsxs)(`label`,{htmlFor:`${t}-stopped`,children:[(0,Q.jsx)(`input`,{id:`${t}-stopped`,type:`checkbox`,checked:c,disabled:C,onChange:e=>b(e.target.checked)}),` `,e(`nativeMain.stopped`)]})}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:r,onClick:()=>y(null),children:e(`nativeMain.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-primary`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:C||!c||!Nu(a,s),onClick:x,children:e(`nativeMain.confirm`)})]})]})]})]})}function Wu(e){return(0,Q.jsx)(Gu,{...e},e.apiBase)}function Gu({apiBase:e,disabled:n=!1,onChanged:r}){let{locale:i}=t(),a=gu(i),o=(0,Z.useId)(),[s]=(0,Z.useState)(()=>new zu(e)),[c,l]=(0,Z.useState)(s.state),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(!1);return(0,Z.useLayoutEffect)(()=>s.attach(l),[s]),(0,Z.useLayoutEffect)(()=>{s.updateOptions(n,r)},[s,n,r]),(0,Z.useLayoutEffect)(()=>{c.action?(f.current=!0,d.current?.focus()):!c.busy&&f.current&&(f.current=!1,u.current?.focus())},[c.action,c.busy]),(0,Q.jsx)(Uu,{t:a,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 Ku={"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 qu({threshold:e,draft:t,strategy:n=`quota`,hydrated:r=!0,saving:i,loadError:a,feedback:o,onDraftChange:s,onEditingChange:c,onCommit:l,onCancel:u,onToggle:d,onRetry:f}){let p=O(),m=(0,Z.useRef)(!1),h=e>0,g=Ku[n][h?`on`:`off`],_=i||!r,v=i?p(`common.saving`):o?.message??``,y=i?`pending`:o?.tone,b=v?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,Q.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,Q.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,Q.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,Q.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,Q.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,Q.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c(!1),m.current){m.current=!1;return}h&&!_&&l()}},children:[a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,Q.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:_,"aria-disabled":_,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":b,onChange:e=>s(e.target.value),onFocus:()=>{_||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||_||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(Vc,{disabled:_,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(Bc(t,1,1,100))},onDecrement:()=>{c(!0),s(Bc(t,-1,1,100))}})]})]}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:_,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":b,title:p(`codexAuth.autoSwitch`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})})]}),v&&(0,Q.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${y===`err`?` is-error`:``}`,role:y===`err`?`alert`:`status`,"aria-atomic":`true`,children:v})]})}var Ju={"reset-first":`accountPool.strategyResetFirst`,quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},Yu={"reset-first":`accountPool.strategyHintResetFirst`,quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function Xu({strategy:e,codex:t=!1,threshold:n,stickyDraft:r,disabled:i=!1,strategySelectId:a=`account-pool-strategy`,stickyInputId:o=`account-pool-sticky-limit`,onStrategyChange:s,onStickyDraftChange:c,onStickyCommit:l}){let u=O(),d=kl.filter(e=>t||e!==`reset-first`).map(e=>({value:e,label:u(Ju[e])})),f=n===void 0?null:e===`round-robin`?u(`accountPool.thresholdNotUsed`):n>0?u(e===`fill-first`?`accountPool.drainAtThreshold`:e===`reset-first`?`accountPool.resetBelowThreshold`:`accountPool.switchAtThreshold`,{threshold:String(n)}):u(`accountPool.proactiveSwitchingOff`);return(0,Q.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`${a}-label`,children:u(`accountPool.strategy`)}),(0,Q.jsx)(`span`,{className:`desc`,children:u(`accountPool.strategyDesc`)}),(0,Q.jsx)(`span`,{className:`desc`,children:u(Yu[e])}),(0,Q.jsx)(`span`,{className:`desc`,children:u(`accountPool.unboundDefinition`)})]}),(0,Q.jsxs)(`div`,{className:`setting-controls`,children:[(0,Q.jsx)(cn,{id:a,value:e,options:d,disabled:i,label:u(`accountPool.strategy`),onChange:e=>s(e)}),f&&(0,Q.jsx)(`span`,{className:`badge badge-muted account-pool-threshold-badge`,"data-testid":`account-pool-threshold-summary`,children:f})]})]}),e===`round-robin`&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`label`,{className:`setting-label`,htmlFor:o,children:[(0,Q.jsx)(`span`,{className:`title`,children:u(`accountPool.stickyLimit`)}),(0,Q.jsx)(`span`,{className:`desc`,children:u(`accountPool.stickyLimitHelp`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{id:o,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:r,disabled:i,"aria-label":u(`accountPool.stickyLimitAria`),onChange:e=>c(e.target.value),onBlur:()=>l(),onKeyDown:e=>{e.nativeEvent.isComposing||i||e.key===`Enter`&&(e.preventDefault(),l())}}),(0,Q.jsx)(Vc,{disabled:i,incrementLabel:u(`accountPool.stickyLimitInc`),decrementLabel:u(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=Bc(r,1,1,100);c(e),l(e)},onDecrement:()=>{let e=Bc(r,-1,1,100);c(e),l(e)}})]})})]})]})}function Zu(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:Fl(t.accountPoolStrategy),stickyLimit:Ll(t.accountPoolStickyLimit),threshold:n}}function Qu({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r,threshold:i}){let a=O(),[o,s]=(0,Z.useState)(jl),[c,l]=(0,Z.useState)(1),[u,d]=(0,Z.useState)(`1`),[f,p]=(0,Z.useState)(void 0),[m,h]=(0,Z.useState)(!1),g=(0,Z.useRef)(!1),[_,v]=(0,Z.useState)(!1),y=(0,Z.useRef)(!1),b=(0,Z.useRef)(!1),x=(0,Z.useRef)(0),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),E=(0,Z.useCallback)(e=>{let t=Fl(e.accountPoolStrategy),n=Ll(e.accountPoolStickyLimit);typeof e.autoSwitchThreshold==`number`&&p(e.autoSwitchThreshold),s(t),r?.(t),l(n),d(String(n)),g.current=!0,h(!0),C(!1),T(null)},[r]),D=(0,Z.useCallback)(e=>{let t=Zu(e);t&&E({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit,autoSwitchThreshold:t.threshold})},[E]),k=(0,Z.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(y.current){b.current=!0;return}E(n)}catch{y.current||C(!0)}},[e,E]),A=(0,Z.useCallback)(()=>{b.current&&(b.current=!1,queueMicrotask(()=>{if(y.current){b.current=!0;return}k()}))},[k]);(0,Z.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>x.current,acceptActiveRead:(e,t)=>{if(t===x.current){if(y.current){b.current=!0;return}D(e)}},rejectActiveRead:()=>{g.current||C(!0)}});return!y.current&&n&&D(n()),e},[t,D,n]),(0,Z.useEffect)(()=>{!n||t||y.current||D(n())},[n,D,t]),(0,Z.useEffect)(()=>{t||k()},[k,t]);let j=(0,Z.useCallback)(async t=>{if(y.current)return;let n=o,i=c;t.strategy!==void 0&&(s(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(l(t.stickyLimit),d(String(t.stickyLimit))),y.current=!0,v(!0),T(null),x.current+=1;let u=await Gl(e,t);x.current+=1,u.ok?(s(u.strategy),r?.(u.strategy),l(u.stickyLimit),d(String(u.stickyLimit)),g.current=!0,h(!0)):(T(a(`accountPool.strategyUpdateFailed`)),s(n),r?.(n),l(i),d(String(i))),y.current=!1,v(!1),A()},[e,r,A,c,o,a]),M=_||S||!m;return(0,Q.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":_||!m&&!S,children:[S&&(0,Q.jsx)(`div`,{className:`card-sub`,role:`alert`,children:a(`accountPool.strategyLoadFailed`)}),S&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{k()},children:a(`common.retry`)}),!S&&(0,Q.jsx)(Xu,{codex:!0,strategy:o,threshold:i===void 0?f:i,stickyDraft:u,disabled:M,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{M||e===o||j({strategy:e})},onStickyDraftChange:d,onStickyCommit:e=>{if(M)return;let t=Rl(e??u);if(t===null){d(String(c)),T(a(`accountPool.stickyLimitInvalid`));return}if(t===c){d(String(t));return}j({stickyLimit:t})}}),w&&(0,Q.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:w})]})}function $u({t:e,open:t,onToggle:n,children:r}){return(0,Q.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,Q.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function ed(e,t){let[n,r]=(0,Z.useState)(80),[i,a]=(0,Z.useState)(`80`),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(80),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(80),_=(0,Z.useRef)(!1),v=(0,Z.useRef)(!1),y=(0,Z.useRef)(!1),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.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,Z.useCallback)(e=>{if(_.current||v.current){x.current=e;return}x.current=null,C(e)},[C]),T=(0,Z.useCallback)(()=>{let e=x.current;return e!==null&&(x.current=null,C(e),!0)},[C]),E=(0,Z.useCallback)(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null),p(null)},[]),D=(0,Z.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,Z.useEffect)(()=>()=>{S.current!==null&&window.clearTimeout(S.current)},[]);let O=(0,Z.useCallback)(()=>(h.current||l(!1),b.current),[]),k=(0,Z.useCallback)((e,t)=>{l(!1);let n=Zl(e),r=Xl(_.current,v.current,t,b.current);r===`defer`?x.current=ql(n):r===`apply`&&w(ql(n))},[w]),A=(0,Z.useCallback)(e=>{h.current||_.current||v.current||(l(!1),C(ql(Zl(e))))},[C]),j=(0,Z.useCallback)(()=>{h.current||l(!0)},[]),M=(0,Z.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 $l(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,Z.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,Z.useCallback)(()=>{_.current=!1,y.current=!0,E();let e=m.current;T()||a(String(e>0?e:g.current))},[E,T]),F=(0,Z.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=Jl(i);return t===null?(N(),!1):t===e?(T()||a(String(t)),!0):M(t,e)},[i,T,N,M]),I=(0,Z.useCallback)(async()=>{if(!h.current||v.current)return!1;let e=m.current;_.current=!1;let t=Ql(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,Z.useCallback)(e=>{h.current&&(_.current=!0,y.current=!1,E(),a(e))},[E]),setEditing:(0,Z.useCallback)(e=>{_.current=e},[]),commit:F,cancel:P,toggle:I,retry:(0,Z.useCallback)(()=>{l(!1),E()},[E])}}function td({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=O(),a=wl(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=Sl.map(e=>({value:String(e),label:Ol(i,e)})),l=El(a)?c:[{value:String(a),label:Ol(i,a)},...c];return(0,Q.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,Q.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,Q.jsx)(cn,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(wl(Number.parseInt(e,10)))}),(0,Q.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function nd({value:e}){let t=O(),n=wl(e);return n===0?null:(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:Ol(t,n)})}function rd({summary:e,busy:t,onToggleAll:n}){let r=O(),i=(0,Z.useId)(),a=e.total>0&&e.enabled===e.total,o=e.enabled>0&&!a;return(0,Q.jsxs)(`span`,{className:`codex-credit-spend`,"aria-busy":t||void 0,children:[(0,Q.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:r(`codexAuth.creditSpend`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${a?`on`:``}`,"aria-label":r(`codexAuth.creditSpendAria`),"aria-describedby":i,"aria-pressed":o?`mixed`:a,title:r(`codexAuth.creditsAfterLimitHint`),disabled:t||e.total===0,onClick:()=>n(!a),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:i,className:`sr-only`,children:r(`codexAuth.creditsAfterLimitHint`)})]})}function id({accountLabel:e,enabled:t,saving:n,disabled:r,hint:i,onChange:a}){let o=O(),s=(0,Z.useId)(),c=t===!0,l=i??o(`codexAuth.creditsAfterLimitHint`);return(0,Q.jsxs)(`div`,{className:`codex-account-credits`,title:l,"aria-busy":n||void 0,children:[(0,Q.jsx)(`span`,{className:`codex-account-credits__label`,children:o(`codexAuth.creditsAfterLimit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle codex-account-credits__toggle ${c?`on`:``}`,disabled:r||n,"aria-pressed":c,"aria-label":o(`codexAuth.creditsAfterLimitAria`,{email:e}),"aria-describedby":s,onClick:()=>a(!c),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:s,className:`sr-only`,children:l})]})}function ad({enabled:e}){let t=O();return e===!0?(0,Q.jsx)(`span`,{className:`badge badge-amber`,title:t(`codexAuth.creditsAfterLimitHint`),children:t(`codexAuth.creditsOn`)}):null}function od({credits:e,t,locale:n}){if(!e)return null;let r=e.balance!==void 0&&/^\d+(\.\d+)?$/.test(e.balance)?Number(e.balance):void 0,i=r!==void 0&&Number.isFinite(r);if(!i&&e.unlimited!==!0&&e.overageLimitReached!==!0)return null;let a=new Intl.NumberFormat(n,{maximumFractionDigits:2}),o=i?a.format(r):``,s=e.overageLimitReached===!0,c=e.unlimited===!0,l=s?`${o?`${o} · `:``}${t(`codexAuth.creditsOverage`)}`:c?t(`codexAuth.creditsUnlimited`):o,u=!s&&(c||i&&r>0),d=e=>e?e.map(e=>a.format(e)).join(`–`):`—`,f=e.approxLocalMessages||e.approxCloudMessages?t(`codexAuth.creditsApprox`,{local:d(e.approxLocalMessages),cloud:d(e.approxCloudMessages)}):void 0;return(0,Q.jsxs)(`div`,{className:`quota-row quota-row--codex-credits`,title:f,children:[(0,Q.jsx)(`span`,{className:`quota-label`,children:t(`codexAuth.credits`)}),(0,Q.jsx)(`span`,{className:`quota-reset-label`,children:t(`codexAuth.creditsRemaining`)}),(0,Q.jsx)(`span`,{className:`quota-reset-day`}),(0,Q.jsx)(`span`,{className:`quota-reset-time`}),(0,Q.jsx)(`div`,{className:`bar`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`bar-fill bar-green`,style:{"--bar-scale":u?`1`:`0`}})}),(0,Q.jsx)(`span`,{className:`quota-val`,children:l})]})}function sd(e,t){return`${e??``}\0${JSON.stringify(t)}`}var cd={month:`short`,day:`numeric`,year:`numeric`},ld={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},ud=new Map;function dd(e,t){let n=sd(e,t),r=ud.get(n);return r||(r=new Intl.DateTimeFormat(e,t),ud.set(n,r)),r}function fd(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:dd(t,cd).format(n)}function pd(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:dd(t,ld).format(n)}var md=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function hd(e,t){return!Number.isFinite(e)||e<0?`—`:`~${md.format(e)}`}function gd(e,t){return fd(e,t)}function _d(e,t){return pd(e,t)}function vd(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function yd({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=vd(n),s=o<=7;return(0,Q.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(lt,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,Q.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:gd(t,i)})}),(0,Q.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:_d(n,i),days:String(o)})})]})]})}function bd({t:e,onUnpin:t}){return(0,Q.jsx)(`button`,{type:`button`,className:`badge badge-muted badge-clickable`,onClick:e=>{e.stopPropagation(),t()},title:`${e(`codexAuth.pinnedHint`)} ${e(`codexAuth.unpinHint`)}`,"aria-label":`${e(`codexAuth.pinned`)} — ${e(`codexAuth.unpinHint`)}`,children:e(`codexAuth.pinned`)})}function xd({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(lt,{width:12}),`0`]}):r===void 0?null:(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,Q.jsx)(lt,{width:12}),r]})}function Sd({t:e,paused:t,saving:n}){let r=e(`codexAuth.pause`),i=e(`codexAuth.resume`),a=e(`common.saving`),o=n?a:t?i:r,s=Math.max(r.length,i.length,a.length);return(0,Q.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function Cd({pool:e,creditsVisible:n,loading:r=!1,activeId:i,accountModeState:a,switchActionLabel:o,threshold:s,onOpenReset:c,onSwitch:l,onTogglePause:u,pauseUpdatingId:d,pauseBusy:f,onPriorityChange:p,priorityUpdatingId:m,onAutoSwitchThresholdChange:h,autoSwitchDisabled:g,switchingId:_,pinnedId:v=null,onUnpin:y,onReauth:b,onEditAlias:x,onRemove:S,onToggleCreditsAfterLimit:C,creditsAfterLimitUpdatingId:w=null,onCopyDoctor:T,doctorCopyOutcomeFor:E}){let D=O(),{locale:k}=t(),A=e=>!e.paused&&i===e.id,j=sl(),[M,N]=(0,Z.useState)(new Set);return(0,Q.jsx)(Q.Fragment,{children:e.map(e=>{let t=n===!0&&e.credits!==void 0,i=e.health?.status,O=e.selectionExcludedReason===`plan_excluded`,P=!!e.needsReauth||Gc(i),F=qc(i),I=e.health?.reason===`validation_pending`,L=Xc(D,e.health),R=Zc(D,`codex`,e.id,e.health);return(0,Q.jsxs)(`div`,{className:`card ${A(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,Q.jsxs)(`div`,{className:`card-head`,children:[(0,Q.jsx)(`span`,{className:`dot ${P?`dot-amber`:A(e)?`dot-blue`:`dot-muted`}`}),(0,Q.jsx)(`strong`,{children:e.alias??e.email}),(0,Q.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),O&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:D(`codexAuth.planExcludedHint`,{plan:e.selectionExcludedPlan??e.plan??``}),children:D(`codexAuth.planExcluded`)}),e.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:D(`codexAuth.pausedHint`),children:D(`codexAuth.paused`)}),(0,Q.jsx)(nd,{value:e.priority}),(0,Q.jsx)(ad,{enabled:e.creditsAfterLimit}),e.id===v&&!e.paused&&(0,Q.jsx)(bd,{t:D,onUnpin:()=>y(e)}),(0,Q.jsx)(xd,{t:D,account:e,onClick:()=>c(e)}),L&&(0,Q.jsx)(`span`,{className:Wc(i),children:L}),P&&!L&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:D(`codexAuth.needsReauth`)}),A(e)&&!O&&!P&&!F&&!I&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:D(a===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!O&&(!A(e)||v!==e.id)&&!P&&!F&&!I&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>l(e),children:o}),P&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>b(e.id),children:D(`codexAuth.reauthenticate`)}),T&&Jc(i)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>T(e.id),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:el(D,E?.(e.id))})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>u(e),disabled:f,title:e.paused?D(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${D(`codexAuth.resume`)}. ${D(`codexAuth.pausedHint`)}`:D(`codexAuth.pause`),children:[e.paused?(0,Q.jsx)(Be,{width:14}):(0,Q.jsx)(z,{width:14}),(0,Q.jsx)(Sd,{t:D,paused:e.paused,saving:d===e.id})]}),(0,Q.jsxs)(`details`,{className:`codex-account-more card-right`,open:M.has(e.id),onToggle:t=>{let n=t.currentTarget.open;N(t=>{let r=new Set(t);return n?r.add(e.id):r.delete(e.id),r})},children:[(0,Q.jsx)(`summary`,{className:`btn btn-ghost btn-sm`,"aria-label":`${D(`codexAuth.moreActions`)} — ${e.email}`,title:D(`codexAuth.moreActions`),children:`⋯`}),(0,Q.jsxs)(`div`,{className:`codex-account-more-body`,children:[(0,Q.jsxs)(`span`,{className:`mono text-caption muted`,children:[D(`prov.accountId`),`: `,zc(e.id)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j.copy(e.id,e.id),children:j.outcomeFor(e.id)===`copied`?D(`startup.copied`):D(`codexAuth.copyId`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void x(e),children:D(`prov.editAlias`)}),C&&(0,Q.jsx)(id,{accountLabel:e.alias??e.email,enabled:e.creditsAfterLimit,saving:w===e.id,disabled:w!==null,onChange:t=>C(e,t)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger`,"aria-label":`${D(`common.remove`)} — ${e.email}`,title:`${D(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),S(e.id)},children:(0,Q.jsx)(ve,{width:14})})]})]})]}),(0,Q.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,Q.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Q.jsxs)(`div`,{className:`codex-account-controls`,children:[(wl(e.priority)!==0||M.has(e.id))&&(0,Q.jsx)(td,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:m!==null||_!==null,onChange:t=>p(e,t)}),(0,Q.jsx)(Hc,{accountLabel:e.alias??e.email,globalThreshold:s,override:e.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${e.id}`,disabled:g,onChange:t=>h(e,t)},e.id)]})]}),R&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:R}),F&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:D(`pws.healthCooldownHint`)}),P?(0,Q.jsx)(`div`,{className:`card-sub faint`,children:D(`codexAuth.tokenExpired`)}):!F&&(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(os,{quota:e.quota,plan:e.plan,threshold:e.autoSwitchThresholdOverride??s,t:D,pending:e.quota==null&&(r||!t),afterWeekly:t&&!r?(0,Q.jsx)(od,{credits:e.credits,t:D,locale:k}):void 0})})]},e.id)})})}function wd({onReauth:e}){let t=O();return(0,Q.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(Ae,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function Td({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,threshold:a,unpin:o=!1,onCancel:s,onConfirm:c}){let l=O(),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=u.current;e&&!e.open&&e.showModal()},[]);let d=(0,Z.useCallback)(e=>{e.preventDefault(),s()},[s]),f=fe(e.quota,e.plan),p=a!==void 0&&a>0&&f!==null&&f>=a;return(0,Q.jsxs)(`dialog`,{ref:u,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:d,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":l(`common.close`),tabIndex:-1,onClick:s}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsx)(`h3`,{id:`codex-switch-title`,children:o?l(`codexAuth.unpinTitle`):n===`direct`?l(`codexAuth.preparePoolTitle`):e.id===`__main__`?l(`codexAuth.switchBack`):l(`codexAuth.switchTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:o?l(`codexAuth.unpinDesc`):n===`direct`?l(`codexAuth.preparePoolDesc`):e.id===`__main__`?l(`codexAuth.switchBackDesc`):l(`codexAuth.switchDesc`)}),(0,Q.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,Q.jsx)(`strong`,{children:e.id===`__main__`?t||l(`codexAuth.codexApp`):e.email}),e.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),!o&&e.id!==`__main__`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,children:[(0,Q.jsx)(Ae,{width:14}),` `,l(`codexAuth.cacheWarning`)]}),!o&&p&&(0,Q.jsxs)(`div`,{className:`notice-warn`,"data-testid":`codex-switch-threshold-warning`,children:[(0,Q.jsx)(Ae,{width:14}),` `,l(`codexAuth.switchExceedsThresholdWarning`,{threshold:a})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:l(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r||i,onClick:c,children:l(r?`pws.accountSwitching`:o?`codexAuth.unpinAction`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function Ed({resetPopup:e,resetConfirm:n,creditDetails:r,creditDetailsLoading:i,redeeming:a,onClose:o,onShowConfirm:s,onCancelConfirm:c,onRedeem:l}){let{locale:u,t:d}=t(),f=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=f.current;e&&!e.open&&e.showModal()},[]);let p=(0,Z.useCallback)(e=>{e.preventDefault(),o()},[o]);return(0,Q.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:p,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,onClick:o}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ae,{width:22})}),(0,Q.jsx)(`h3`,{id:`codex-reset-title`,children:d(`codexAuth.confirmResetTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),r&&r[0]&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.confirmWhichCredit`,{date:gd(r[0].granted_at,u)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.irreversible`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:c,children:d(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:l,disabled:a,children:d(a?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,Q.jsx)(lt,{width:16}),` `,d(`codexAuth.resetCreditsTitle`)]}),(0,Q.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Q.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:d(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),i&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`common.loading`)}),r&&r.length>0&&(0,Q.jsx)(`div`,{className:`credit-list`,children:r.map((e,t)=>(0,Q.jsx)(yd,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:u,t:d},`${e.granted_at}:${e.expires_at}`))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:s,disabled:a,children:d(`codexAuth.useOneCredit`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:d(`codexAuth.fifoNote`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:d(`codexAuth.noResetCredits`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.earnCreditsHint`)})]})})]})})]})}function Dd({t:e,main:n,isMainActive:r,accountModeState:i,threshold:a,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}=t(),O=T===!0&&n?.credits!==void 0,k=e(`codexAuth.codexApp`),A=n?.id??`__main__`,j={id:`__main__`,email:n?.email||k,plan:n?.plan,isMain:!0,paused:n?.paused??!1,priority:n?.priority??0,autoSwitchThresholdOverride:n?.autoSwitchThresholdOverride??null,hasCredential:!0,quota:n?.quota??null,quotaAutoRefresh:n?.quotaAutoRefresh??{fiveHourAvailable:!1,weeklyAvailable:!1,fiveHourEnabled:!1,weeklyEnabled:!1}},M=!!n?.needsReauth||Gc(n?.health?.status),N=qc(n?.health?.status),P=n?.mainAccountHardLock,F=P?.enabled===!0&&P.state===`blocked`,I=Xc(e,n?.health),L=n?Zc(e,`codex`,A,n.health):null;return(0,Q.jsxs)(`div`,{className:`card ${r&&!F?`card-active`:``}`,style:{marginBottom:12},children:[(0,Q.jsxs)(`div`,{className:`card-head`,children:[(0,Q.jsx)(`span`,{className:`dot ${M||F?`dot-amber`:`dot-green`}`}),(0,Q.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,Q.jsxs)(`span`,{className:`card-badges`,children:[n?.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:n.plan}),n?.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,Q.jsx)(nd,{value:j.priority}),(0,Q.jsx)(ad,{enabled:n?.creditsAfterLimit}),g===`__main__`&&!n?.paused&&(0,Q.jsx)(bd,{t:e,onUnpin:()=>_(j)}),n&&(0,Q.jsx)(xd,{t:e,account:{...n,id:`__main__`},onClick:()=>v({...n,id:`__main__`})}),I&&(0,Q.jsx)(`span`,{className:Wc(n?.health?.status),children:I}),M&&!I&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!n?.paused&&!F&&(0,Q.jsx)(`span`,{className:`badge ${r?`badge-primary`:`badge-muted`}`,children:e(r?i===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!n?.paused&&!F&&(!r||g!==`__main__`)&&!M&&!N&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>s(j),children:o}),y&&Jc(n?.health?.status)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>y(A),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:el(e,b?.(A))})}),n&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>c(j),disabled:u,title:n.paused?e(`codexAuth.pausedHint`):void 0,"aria-label":n.paused?`${e(`codexAuth.resume`)}. ${e(`codexAuth.pausedHint`)}`:e(`codexAuth.pause`),children:[n.paused?(0,Q.jsx)(Be,{width:14}):(0,Q.jsx)(z,{width:14}),(0,Q.jsx)(Sd,{t:e,paused:!!n.paused,saving:l===`__main__`})]}),n?.hasCredential&&C&&(0,Q.jsxs)(`details`,{className:`codex-account-more card-right`,children:[(0,Q.jsx)(`summary`,{className:`btn btn-ghost btn-sm`,"aria-label":`${e(`codexAuth.moreActions`)} — ${e(`codexAuth.mainAccount`)}`,title:e(`codexAuth.moreActions`),children:`⋯`}),(0,Q.jsx)(`div`,{className:`codex-account-more-body`,children:(0,Q.jsx)(id,{accountLabel:n.alias??(n.email||e(`codexAuth.mainAccount`)),enabled:n.creditsAfterLimit,saving:w===`__main__`,disabled:w!==null,hint:e(`codexAuth.creditsAfterLimitMainHint`),onChange:e=>C(j,e)})})]}),(0,Q.jsxs)(`span`,{className:`card-right`,children:[(0,Q.jsx)(at,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,Q.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,Q.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[n?.email||e(`codexAuth.appLogin`),n?.plan?` · ${n.plan}`:``]}),n&&(0,Q.jsxs)(`div`,{className:`codex-account-controls`,children:[(0,Q.jsx)(td,{value:j.priority,selectId:`codex-account-priority-${j.id}`,disabled:f!==null||h!==null,onChange:e=>d(j,e)}),(0,Q.jsx)(Hc,{accountLabel:j.email,globalThreshold:a,override:j.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${j.id}`,disabled:m,onChange:e=>p(j,e)},j.id)]})]}),P?.enabled&&(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-status${F?` is-blocked`:``}`,children:[(0,Q.jsx)(`p`,{role:`status`,children:e(F?`codexAuth.mainHardLockBlocked`:P.state===`ready`?`codexAuth.mainHardLockMonitoring`:`codexAuth.mainHardLockUnknown`,tu(P.thresholds))}),x?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:x,children:e(`codexAuth.mainHardLockManage`)}):(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>qt(`codex-set`),children:e(`codexAuth.mainHardLockManage`)})]}),P?.externalUsage&&(0,Q.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Q.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainExternalUsageWarning`)})}),L&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:L}),N&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),M?(0,Q.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Q.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainTokenExpired`)}),S&&(S.state.phase===`idle`||S.state.phase===`failed`||S.state.phase===`cancelled`)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{S.start()},children:e(`codexAuth.mainReauthDevice`)}),S.state.phase===`failed`&&(0,Q.jsxs)(`span`,{className:`badge badge-amber`,children:[e(`codexAuth.mainReauthFailed`),`: `,S.state.code]})]}),S&&S.state.phase===`starting`&&(0,Q.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S&&(S.state.phase===`pending`||S.state.phase===`committing`)&&(0,Q.jsxs)(`span`,{className:`codex-main-reauth-pending`,children:[(0,Q.jsx)(ul,{hint:{url:S.state.verificationUrl,deviceCode:S.state.deviceCode}}),(0,Q.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S.state.cancelFailed&&(0,Q.jsx)(`span`,{role:`status`,className:`badge badge-amber`,children:e(`codexAuth.mainReauthFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{S.cancel()},children:e(`codexAuth.mainReauthCancel`)})]}),S&&S.state.phase===`succeeded`&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.mainReauthSucceeded`)})]}):!N&&(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(os,{quota:n?.quota??null,plan:n?.plan,threshold:j.autoSwitchThresholdOverride??a,t:e,pending:n!=null&&n.quota==null&&(E||!O),afterWeekly:O&&!E?(0,Q.jsx)(od,{credits:n?.credits,t:e,locale:D}):void 0})})]})}function Od({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c,creditsVisible:l,creditsBusy:u,onToggleCredits:d,creditSpendControl:f}){return(0,Q.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,Q.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,Q.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),l!==void 0&&d&&(0,Q.jsxs)(`span`,{className:`codex-auth-credits-toggle`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:e(`codexAuth.creditsToggle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${l?`on`:``}`,onClick:d,disabled:!!u,"aria-pressed":l,"aria-label":e(`codexAuth.creditsToggle`),title:e(`codexAuth.creditsToggleHint`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),f,t&&(0,Q.jsx)(kd,{t:e,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,onRefresh:s,onPauseExhausted:c})]})]})}function kd({t:e,refreshingQuota:t,pausingExhausted:n,pauseBusy:r,onRefresh:i,onPauseExhausted:a}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:a,disabled:t||n||!!r,children:[(0,Q.jsx)(z,{width:14}),` `,e(n?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:i,disabled:t||n||!!r,children:[(0,Q.jsx)(re,{width:14}),` `,e(t?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})}function Ad(e){return(0,Q.jsx)(`div`,{className:`codex-auth-actions-row`,children:(0,Q.jsx)(kd,{...e})})}function jd({t:e,loadState:t,refreshFailed:n,accountsCount:r,onRetry:i}){return t===`loading`&&r===0?(0,Q.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,Q.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`card-head`,children:[(0,Q.jsx)(`span`,{className:`dot dot-muted`}),(0,Q.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,Q.jsxs)(`span`,{className:`card-badges`,children:[(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(lt,{width:12}),`0`]}),(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,Q.jsx)(z,{width:14}),` `,e(`codexAuth.pause`)]}),(0,Q.jsxs)(`span`,{className:`card-right`,children:[(0,Q.jsx)(at,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,Q.jsxs)(`div`,{className:`card-sub`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,Q.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,Q.jsx)(os,{quota:null,threshold:0,t:e,pending:!0})]}),(0,Q.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,Q.jsx)(`div`,{className:`sep-line`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,Q.jsx)(N,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,Q.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)})]}):n&&r>0?(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--stale`,role:`status`,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.accountsRefreshFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)})]}):null}function Md(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Nd(e,t,n,r){try{let i=await gn(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:Md(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 Pd({windows:e,ready:t,busy:n,loadError:r,feedback:i,onToggle:a,onRetry:o}){let s=O(),c=e.filter(e=>e.available),l=e.some(e=>e.enabled),u=c.length?c.every(e=>e.enabled):l,d=l&&!u,f=c.length===0&&!l,p=n?s(`common.saving`):r?s(`codexAuth.quotaAutoRefreshLoadFailed`):t?i?.message??(f?s(`codexAuth.quotaAutoRefreshEmpty`):d?s(`codexAuth.quotaAutoRefreshMixed`):``):s(`common.loading`),m=!n&&(r||i?.failed);return(0,Q.jsxs)(`div`,{id:`codex-quota-activation`,className:`card card-row codex-quota-activation`,"aria-busy":n||!t&&!r||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-quota-activation__copy`,children:[(0,Q.jsx)(`strong`,{children:s(`codexAuth.quotaAutoRefresh`)}),(0,Q.jsx)(`div`,{id:`codex-quota-activation-desc`,className:`card-sub`,children:s(`codexAuth.quotaAutoRefreshAllHint`)}),p&&(0,Q.jsx)(`div`,{className:`card-sub${m?` is-error`:``}`,role:m?`alert`:`status`,children:p})]}),(0,Q.jsxs)(`div`,{className:`codex-quota-activation__controls`,children:[m&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:o,children:s(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${t&&u?`on`:``}`,"aria-label":s(`codexAuth.quotaAutoRefresh`),"aria-describedby":`codex-quota-activation-desc`,"aria-pressed":t?d?`mixed`:u:void 0,disabled:!t||n||f,onClick:()=>a(!u),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]})]})}function Fd(e){return{enabled:e.filter(e=>e.creditsAfterLimit===!0).length,total:e.length}}function Id(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 Ld(e,t){return e.flatMap(e=>{let n=e.isMain?`__main__`:e.id,r=e.quotaAutoRefresh??nt(e.quota);return[`fiveHour`,`weekly`].map(e=>({id:n,window:e,available:r[e===`fiveHour`?`fiveHourAvailable`:`weeklyAvailable`],enabled:t[n]?.[e]===!0}))})}function Rd(e){let t=O(),n=(0,Z.useId)(),r=(0,Z.useRef)(null),i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=document.activeElement;return i.current?.focus(),()=>{e?.isConnected&&typeof e.focus==`function`&&e.focus()}},[]);let a=e.selection?.status===`pending`,o=e.failed||!e.providerKnown,s=e.loading?t(`prov.modelsNoticeChecking`):o?t(`prov.modelsNoticeFailed`):a?t(`prov.modelsNoticePending`):e.initialRegistration&&e.selection?.status===`all-off`?t(`prov.modelsNoticeOff`):t(`prov.modelsNoticeReady`);return(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":n,onKeyDown:t=>{if(t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.onClose()),t.key!==`Tab`)return;let n=r.current?.querySelectorAll(`button:not([disabled])`),i=n?.[0],a=n?.[n.length-1];t.shiftKey&&document.activeElement===i?(t.preventDefault(),a?.focus()):!t.shiftKey&&document.activeElement===a&&(t.preventDefault(),i?.focus())},children:(0,Q.jsxs)(`div`,{className:`modal-card`,ref:r,children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h2`,{id:n,style:{fontSize:`var(--text-subtitle)`,margin:0},children:t(`prov.modelsNoticeTitle`)})}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`strong`,{style:{overflowWrap:`anywhere`},children:e.provider})}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:s}),e.initialRegistration&&e.selection?.modelCount!==void 0&&(0,Q.jsx)(`p`,{className:`muted`,children:t(`prov.modelsNoticeCount`,{count:e.selection.modelCount})}),e.catalogRefreshPending&&(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}),!e.loading&&(a||o)&&e.onRetry&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{e.onRetry?.(),i.current?.focus()},children:t(`common.retry`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:e.onClose,children:t(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,ref:i,onClick:e.onOpenModels,children:t(`prov.modelsNoticeOpen`)})]})]})})}var zd=`ocx doctor`;function Bd({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a,advancedExtras:o=null,hasMainHardLockSetting:s=!1}){let c=O(),l=ed(e,{updated:c(`codexAuth.autoSwitchUpdated`),updateFailed:c(`codexAuth.autoSwitchUpdateFailed`),invalid:c(`codexAuth.autoSwitchThresholdInvalid`)}),[u,d]=(0,Z.useState)(null),{beginServerRead:f,acceptServerRead:p,rejectServerRead:m,hydrateServerValue:h}=l,g=au(e,!a),_=a??g,{accounts:v,activeId:y,loadState:b,refreshFailed:x,switchingId:S,pauseUpdatingId:C,priorityUpdatingId:w,autoSwitchUpdatingId:T,pausingExhausted:E,activePinnedId:D,load:k}=_,j=mu(e,()=>{k()}),M=j.state.phase===`starting`||j.state.phase===`pending`||j.state.phase===`committing`,[P,F]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!1),[B,V]=(0,Z.useState)(null),[H,U]=(0,Z.useState)(!1),W=(0,Z.useRef)(!1),G=(0,Z.useCallback)(()=>{let e=document.getElementById(`codex-main-hard-lock-setting`);e?.focus(),e?.scrollIntoView({block:`nearest`})},[]);(0,Z.useEffect)(()=>{H&&W.current&&(W.current=!1,G())},[H,G]);let ee=()=>{H?G():(W.current=!0,U(!0))},[K,q]=(0,Z.useState)(null),[te,ne]=(0,Z.useState)(null),[J,Y]=(0,Z.useState)(null),re=(0,Z.useRef)(null),[ie,X]=(0,Z.useState)(!1),[ae,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(null),le=(0,Z.useRef)(0),ue=(0,Z.useRef)(null),de=(0,Z.useRef)(null),[fe,pe]=(0,Z.useState)(0),[me,he]=(0,Z.useState)(e),[ge,_e]=(0,Z.useState)(null),ve=(0,Z.useRef)(null),ye=se?.apiBase===e&&se.revision===fe?se:null,be=ye?.settings??null,xe=ye?.error??!1,Se=ae===e;me!==e&&(he(e),pe(e=>e+1),ce(null),oe(null),_e(null));let[Ce,we]=(0,Z.useState)(null),[Te,Ee]=(0,Z.useState)(!1),[De,Oe]=(0,Z.useState)(!1),[ke,Ae]=(0,Z.useState)(null),[je,Me]=(0,Z.useState)(!1),Ne=sl(),Pe=(0,Z.useCallback)((e,t=`ok`)=>{re.current&&clearTimeout(re.current),ne(e),Y(t),re.current=setTimeout(()=>{ne(null),Y(null),re.current=null},5e3)},[]);(0,Z.useEffect)(()=>()=>{re.current&&clearTimeout(re.current)},[]);let Fe=ou(e,k,Pe,c,{revision:fe,onRead:(t,n)=>{let r=le.current;t.then(t=>{n.aborted||le.current!==r||(ce({apiBase:e,revision:fe,settings:Id(t),error:!1}),oe(null))}).catch(()=>{n.aborted||le.current!==r||(ce({apiBase:e,revision:fe,settings:null,error:!0}),oe(null))})}}),Ie=(0,Z.useCallback)(e=>{Ne.copy(zd,e)},[Ne]),{subscribeLoadObserver:Le,readLastThreshold:Re}=_;(0,Z.useEffect)(()=>Le({beginActiveRead:f,acceptActiveRead:p,rejectActiveRead:m}),[Le,f,p,m]),(0,Z.useEffect)(()=>{let e=Re();e!==void 0&&h(e)},[Re,h]),(0,Z.useEffect)(()=>{if(!R&&!M)return;let e=_.pauseRefresh();return()=>_.resumeRefresh(e)},[_,R,M]);let ze=y&&y!==`__main__`?v.find(e=>e.id===y):null,Be=!ze?.paused&&Kc(ze);(0,Z.useEffect)(()=>{i?.(Be)},[Be,i]);let Ve=(0,Z.useCallback)(e=>{q(e),z(!0)},[]),He=(0,Z.useCallback)(()=>{z(!1),q(null)},[]),Ue=(0,Z.useCallback)(e=>{_.syncAfterAccountAdded(),Pe(c(e.validationPending?`pws.healthLabel.validationPending`:e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.validationPending||e.catalogRefreshPending?`warn`:`ok`),He(),V(e.validationPending?null:{catalogRefreshPending:e.catalogRefreshPending})},[He,_,Pe,c]),We=async e=>{let n=await _.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;Pe(c(`codexAuth.switchFailed`),`err`);return}F(null);let r=n.activeId,i=r&&r!==`__main__`?v.find(e=>e.id===r)?.email??c(`pws.accountOrdinal`,{count:`1`}):c(`codexAuth.mainAccount`);Pe(c(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},Ge=async()=>{if(!I)return;let e=await _.switchAccount(null,{expectedPinnedAccountId:I.id});if(!e.ok){if(e.reason===`busy`)return;L(null),Pe(c(e.reason===`pin_changed`?`codexAuth.unpinChanged`:`codexAuth.unpinFailed`),`err`);return}L(null),Pe(c(`codexAuth.unpinned`),`ok`)},Ke=async e=>{let t=await ra({message:c(`prov.aliasPrompt`),initialValue:e.alias??``,maxLength:80,validate:e=>nl(e,c)});if(t===null)return;let n=await _.saveAlias(e.id,t);Pe(c(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},qe=async e=>{let t=!e.paused,n=await _.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(F(t=>t?.id===e.id?null:t),Pe(c(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},Je=async e=>{let t=await _.setAllCreditsAfterLimit(e);!t.ok&&t.reason===`busy`||Pe(c(t.ok?e?`codexAuth.creditsAllOnSucceeded`:`codexAuth.creditsAllOffSucceeded`:`codexAuth.creditsAllUpdateFailed`),t.ok?`ok`:`err`)},Ye=async(e,t)=>{if(t===e.priority)return;let n=await _.setAccountPriority(e.id,t);!n.ok&&n.reason===`busy`||Pe(c(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},Xe=async(e,t)=>{if(t===e.autoSwitchThresholdOverride)return!0;let n=await _.setAccountAutoSwitchThreshold(e.id,t);return!n.ok&&n.reason===`busy`?!1:(Pe(c(n.ok?`accountPool.autoSwitchUpdated`:`accountPool.autoSwitchUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`),n.ok)},Ze=async(e,t)=>{let n=await _.setAccountCreditsAfterLimit(e.id,t);!n.ok&&n.reason===`busy`||Pe(c(n.ok?t?`codexAuth.creditsOnSucceeded`:`codexAuth.creditsOffSucceeded`:`codexAuth.creditsUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},Qe=async e=>{let t=v.find(t=>t.id===e)?.email??c(`pws.accountOrdinal`,{count:`1`});if(!await na({message:c(`codexAuth.removeConfirm`,{id:t}),confirmLabel:c(`common.remove`),tone:`danger`}))return;let n=await _.removeAccount(e);n.ok?n.catalogRefreshPending&&Pe(c(`codexAuth.catalogRefreshPending`),`warn`):Pe(c(`codexAuth.removeFailed`),`err`)},$e=async()=>{X(!0);try{let e=await k(!0,{validatePending:!0});Pe(c(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{X(!1)}},et=async t=>{let n=ue.current;if(de.current||!n||n.signal.aborted||be===null||b!==`ready`)return;let r=A(3e4);de.current=r,le.current+=1;let i=()=>ue.current===n&&!n.signal.aborted,a=Ld(v,be);oe(e),_e(null);let o=!1;try{for(let n of a){if(t&&!n.available)continue;let a=t;if(n.enabled!==a){if(!i())return;if(r.signal.aborted){o=!0;break}try{if(!(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:r.signal,body:JSON.stringify({codexQuotaAutoRefresh:{id:n.id,window:n.window,enabled:a}})})).ok)throw Error(`save`)}catch{o=!0}}}if(!i())return;r.clear();let n=A(15e3);de.current=n;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`read`);let s=Id(await r.json());if(!i())return;o||=a.some(e=>(!t||e.available)&&s[e.id]?.[e.window]===!0!==t),ce({apiBase:e,revision:fe,settings:s,error:!1})}catch{if(!i())return;o=!0,ce({apiBase:e,revision:fe,settings:null,error:!0})}finally{n.clear()}if(!i())return;ve.current=o?{apiBase:e,enabled:t}:null,_e({apiBase:e,message:c(o?`codexAuth.quotaAutoRefreshPartial`:`codexAuth.quotaAutoRefreshUpdated`),failed:o})}finally{r.clear(),i()&&(de.current=null,oe(null))}};(0,Z.useEffect)(()=>{let e=new AbortController;return ue.current=e,()=>{e.abort(),de.current?.controller.abort(),de.current?.clear(),de.current=null}},[e,fe]);let tt=async()=>{let e=await _.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||Pe(e.ok?e.pausedCount>0?c(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):c(`codexAuth.pauseExhaustedNone`):c(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},nt=async t=>{we(t),Ee(!1),Ae(null),Me(!0);try{let n=await gn(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));if(n){let e=(n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime());Ae(e)}}catch{}finally{Me(!1)}},rt=async t=>{Oe(!0);try{let n=await Nd(e,t,c,k);n.close&&(we(null),Ee(!1)),n.toast&&Pe(n.toast,n.ok?`ok`:`err`)}finally{Oe(!1)}},it=v.find(e=>e.isMain),at=v.filter(e=>!e.isMain),ot=Fd([...it?.hasCredential?[it]:[],...at]),st=!it?.paused&&(!y||y===`__main__`),ct=c(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),lt=C!==null||E,ut=l.threshold,dt=!l.hydrated||T!==null,ft=!r;return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(Od,{t:c,embedded:r,creditsVisible:Fe.visible,creditsBusy:Fe.busy,onToggleCredits:()=>{Fe.toggle()},creditSpendControl:b===`loading`&&v.length===0?void 0:(0,Q.jsx)(rd,{summary:ot,busy:_.creditsAfterLimitUpdatingId!==null,onToggleAll:e=>{Je(e)}}),refreshingQuota:ie,actionFeedback:te,actionFeedbackTone:J,pausingExhausted:E,pauseBusy:lt,onRefresh:()=>{$e()},onPauseExhausted:()=>{tt()}}),n,!r&&(0,Q.jsx)(Ad,{t:c,refreshingQuota:ie,pausingExhausted:E,pauseBusy:lt,onRefresh:()=>{$e()},onPauseExhausted:()=>{tt()}}),(0,Q.jsx)(jd,{t:c,loadState:b,refreshFailed:x,accountsCount:v.length,onRetry:()=>{k()}}),(b!==`loading`||v.length!==0)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Dd,{t:c,main:it,creditsVisible:Fe.visible,loading:b===`loading`,isMainActive:st,accountModeState:t,threshold:ut,switchActionLabel:ct,onSwitch:F,onUnpin:L,onTogglePause:qe,pauseUpdatingId:C,pauseBusy:lt,onPriorityChange:(e,t)=>{Ye(e,t)},priorityUpdatingId:w,onAutoSwitchThresholdChange:Xe,autoSwitchDisabled:dt,onToggleCreditsAfterLimit:(e,t)=>{Ze(e,t)},creditsAfterLimitUpdatingId:_.creditsAfterLimitUpdatingId,switchingId:S,pinnedId:D,onOpenReset:nt,onCopyDoctor:ft?Ie:void 0,doctorCopyOutcomeFor:ft?Ne.outcomeFor:void 0,onManageMainHardLock:s?ee:void 0,mainReauth:j}),(0,Q.jsx)(Wu,{apiBase:e,disabled:M,onChanged:()=>k(!1)}),(0,Q.jsxs)(`div`,{className:`section-sep`,children:[(0,Q.jsx)(`span`,{className:`section-label`,children:c(`codexAuth.accountPool`)}),(0,Q.jsx)(`div`,{className:`sep-line`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>z(!0),children:[(0,Q.jsx)(N,{width:14}),` `,c(`codexAuth.add`)]})]}),Be&&ze&&(0,Q.jsx)(wd,{onReauth:()=>Ve(ze.id)}),at.length===0&&(0,Q.jsx)(ln,{title:c(`codexAuth.noPool`)}),(0,Q.jsx)(Cd,{pool:at,creditsVisible:Fe.visible,loading:b===`loading`,activeId:y,accountModeState:t,switchActionLabel:ct,threshold:ut,onOpenReset:nt,onSwitch:F,onUnpin:L,onTogglePause:qe,pauseUpdatingId:C,pauseBusy:lt,onPriorityChange:(e,t)=>{Ye(e,t)},priorityUpdatingId:w,onAutoSwitchThresholdChange:Xe,autoSwitchDisabled:dt,onToggleCreditsAfterLimit:(e,t)=>{Ze(e,t)},creditsAfterLimitUpdatingId:_.creditsAfterLimitUpdatingId,switchingId:S,pinnedId:D,onReauth:Ve,onEditAlias:Ke,onRemove:Qe,onCopyDoctor:ft?Ie:void 0,doctorCopyOutcomeFor:ft?Ne.outcomeFor:void 0})]}),(0,Q.jsx)(Qu,{apiBase:e,subscribeLoadObserver:_.subscribeLoadObserver,readLastActive:_.readLastActive,onStrategyResolved:d,threshold:l.threshold}),(0,Q.jsxs)($u,{t:c,open:H,onToggle:()=>U(e=>!e),children:[(0,Q.jsx)(Pd,{windows:Ld(v,be??{}),ready:be!==null&&b===`ready`,busy:Se,loadError:xe||b===`error`,feedback:ge?.apiBase===e?ge:null,onToggle:e=>{et(e)},onRetry:()=>{xe||be===null||b!==`ready`?(pe(e=>e+1),k()):ve.current?.apiBase===e&&et(ve.current.enabled)}}),u!==null&&(0,Q.jsx)(qu,{threshold:l.threshold,draft:l.draft,strategy:u,hydrated:l.hydrated,saving:l.saving,loadError:l.loadError,feedback:l.feedback,onDraftChange:l.setDraft,onEditingChange:l.setEditing,onCommit:l.commit,onCancel:l.cancel,onToggle:l.toggle,onRetry:()=>{l.retry(),k()}}),o]}),P&&(0,Q.jsx)(Td,{confirm:P,mainEmail:it?.email,accountModeState:t,switchingId:S,orderBusy:w!==null,threshold:u&&u!==`round-robin`?ut:void 0,onCancel:()=>F(null),onConfirm:()=>{We(P.id===`__main__`?`__main__`:P.id)}}),I&&(0,Q.jsx)(Td,{unpin:!0,confirm:I,mainEmail:it?.email,accountModeState:t,switchingId:S,orderBusy:w!==null,onCancel:()=>L(null),onConfirm:()=>{Ge()}}),Ce&&(0,Q.jsx)(Ed,{resetPopup:Ce,resetConfirm:Te,creditDetails:ke,creditDetailsLoading:je,redeeming:De,onClose:()=>{we(null),Ee(!1),Ae(null)},onShowConfirm:()=>Ee(!0),onCancelConfirm:()=>Ee(!1),onRedeem:()=>{rt(Ce.id)}}),R&&(0,Q.jsx)(xl,{apiBase:e,reauthAccountId:K??void 0,onClose:He,onAdded:Ue}),B&&(0,Q.jsx)(Rd,{provider:`openai`,loading:!1,failed:!1,providerKnown:!0,initialRegistration:!1,catalogRefreshPending:B.catalogRefreshPending,onClose:()=>V(null),onOpenModels:()=>{V(null),qt(`models`)}})]})}var Vd=`https://opencodex.me/guides/claude-code/#claude-oauth-account-pool-experimental`,Hd={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function Ud(e,t,n,r){let i=e(Hd[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 Wd({apiBase:e,provider:t=`anthropic`,accountCount:n,onThresholdChange:r}){let i=O(),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(`80`),[l,u]=(0,Z.useState)(`1`),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(0),[C,w]=(0,Z.useState)(!1),T=(0,Z.useRef)(r),E=(0,Z.useRef)(!0),D=(0,Z.useRef)(e),k=(0,Z.useRef)(t),A=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>(E.current=!0,()=>{E.current=!1,A.current?.abort(),A.current=null}),[]),(0,Z.useLayoutEffect)(()=>{T.current=r,D.current=e,k.current=t},[e,t,r]),(0,Z.useEffect)(()=>{let n=!1,r=new AbortController;return Promise.resolve().then(()=>Hl(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=Ll(e.stickyLimit);o({enabled:e.enabled===!0,threshold:t,strategy:Fl(e.strategy),stickyLimit:r,quotaWindow:Il(e.quotaWindow),nativeMessages:e.nativeMessages===!0}),c(String(t)),T.current?.(t),u(String(r)),g(!1),b(!1),m(null),v(!1),w(!1)}).catch(()=>{n||r.signal.aborted||(g(!0),w(!1))}),()=>{n=!0,r.abort()}},[e,t,x]);let j=(0,Z.useCallback)(async n=>{let r=e,s=t;A.current?.abort();let l=new AbortController;A.current=l;let d=()=>E.current&&D.current===r&&k.current===s&&A.current===l&&!l.signal.aborted,p=a;f(!0),m(null),v(!1);try{let e=await Wl(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:l.signal});if(!d())return;if(!e)throw Error(`save`);let t=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:n.threshold,i=Fl(e?.strategy??n.strategy),a=Ll(e?.stickyLimit??n.stickyLimit),f=Il(e?.quotaWindow??n.quotaWindow);o({enabled:e.enabled??n.enabled,threshold:t,strategy:i,stickyLimit:a,quotaWindow:f,nativeMessages:e.nativeMessages===!0}),c(String(t)),T.current?.(t),u(String(a)),v(e.warning===`config_bookkeeping_failed`)}catch(e){if(!d())return;if(e instanceof Ul){o(null),b(!0),g(!1),m(null);return}m(i(`anthropicPool.saveFailed`)),p&&(o(p),c(String(p.threshold)),u(String(p.stickyLimit)))}finally{let e=A.current===l;e&&(A.current=null),e&&E.current&&D.current===r&&k.current===s&&f(!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=C||a===null&&!h&&!y,B=z||d||h||y,V=B||!M&&n<2;return(0,Q.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":z||d,children:[(0,Q.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,Q.jsxs)(`div`,{style:{flex:1},children:[(0,Q.jsx)(`strong`,{children:i(`anthropicPool.title`)}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:y?i(`anthropicPool.saveStateUnknown`):h?i(`anthropicPool.loadFailed`):z?i(`common.loading`):M?Ud(i,P,N,I):i(`anthropicPool.disabledDesc`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${M?`on`:``}`,disabled:V,"aria-pressed":y?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,Q.jsx)(`span`,{className:`toggle-knob`})})]}),(0,Q.jsx)(`p`,{className:`card-sub anthropic-pool-card__notice`,children:i(`anthropicPool.experimentalWarning`)}),n<2&&(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:i(`anthropicPool.needTwoAccounts`)}),(0,Q.jsxs)(`details`,{className:`anthropic-pool-card__details`,children:[(0,Q.jsx)(`summary`,{children:i(`anthropicPool.detailsSummary`)}),(0,Q.jsx)(`p`,{children:i(`anthropicPool.detailsEnabling`)}),(0,Q.jsx)(`p`,{children:i(`anthropicPool.detailsFailover`)}),(0,Q.jsx)(`p`,{children:i(`anthropicPool.detailsActivity`)}),(0,Q.jsxs)(`label`,{className:`anthropic-pool-card__native-messages`,children:[(0,Q.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,Q.jsxs)(`span`,{className:`anthropic-pool-card__native-messages-copy`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`anthropicPool.nativeMessagesLabel`)}),(0,Q.jsx)(`span`,{id:`anthropic-pool-native-messages-help`,className:`card-sub`,children:i(`anthropicPool.nativeMessagesHelp`)})]})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`a`,{href:Vd,target:`_blank`,rel:`noreferrer`,children:i(`anthropicPool.detailsGuide`)})})]}),M&&a&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`anthropicPool.threshold`)}),(0,Q.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:s,disabled:B,"aria-label":i(`anthropicPool.thresholdAria`),onChange:e=>c(e.target.value),onBlur:()=>{let e=Number(s);if(!Number.isInteger(e)||e<0||e>100){c(String(N)),m(i(`anthropicPool.thresholdInvalid`));return}e!==N&&j({enabled:!0,threshold:e,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:L})}}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:i(`anthropicPool.thresholdHelp`)})]}),(0,Q.jsx)(Xu,{strategy:P,stickyDraft:l,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:u,onStickyCommit:e=>{let t=Rl(e??l);if(t===null){u(String(F)),m(i(`accountPool.stickyLimitInvalid`));return}if(t===F){u(String(t));return}j({enabled:!0,threshold:N,strategy:P,stickyLimit:t,quotaWindow:I,nativeMessages:L})}}),(0,Q.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`accountPool.quotaWindow`)}),(0,Q.jsx)(cn,{id:`anthropic-pool-quota-window`,value:I,options:Al.map(e=>({value:e,label:i(Hd[e])})),disabled:B||R,label:i(`accountPool.quotaWindow`),onChange:e=>{let t=Il(e);t!==I&&j({enabled:!0,threshold:N,strategy:P,stickyLimit:F,quotaWindow:t,nativeMessages:L})}}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:i(`accountPool.quotaWindowDesc`)}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:i(R?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),y&&(0,Q.jsxs)(`div`,{role:`alert`,className:`anthropic-pool-card__save-warning`,children:[(0,Q.jsx)(`p`,{children:i(`anthropicPool.saveStateUnknown`)}),h&&(0,Q.jsx)(`p`,{children:i(`anthropicPool.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:C,onClick:()=>{g(!1),w(!0),S(e=>e+1)},children:i(`anthropicPool.reloadSettings`)})]}),_&&(0,Q.jsx)(`div`,{role:`status`,className:`anthropic-pool-card__save-warning`,children:i(`anthropicPool.saveWarning`)}),p&&(0,Q.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:p})]})}function Gd({serverDefault:e=!0}){let t=O(),[n,r]=(0,Z.useState)(pl);return(0,Q.jsxs)(`label`,{className:`open-browser-pref`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!(n??e),onChange:e=>{let t=!e.target.checked;r(t),hl(t)}}),(0,Q.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,Q.jsx)(`span`,{className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}function Kd(e){return e?.status===`ready`?e.coupons:[]}function qd(){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 Jd={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 Yd({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(lt,{width:12}),`0`]});let r=e.status===`ready`?e.coupons.length:null,i=r===null?n(`grokCoupon.badgeErrorAria`):n(`grokCoupon.badgeAria`,{count:String(r)});return(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${r?`badge-amber`:`badge-muted`} badge-clickable`,"data-grok-coupon-badge":r===null?`error`:String(r),onClick:e=>{e.stopPropagation(),t()},"aria-label":i,title:i,children:[(0,Q.jsx)(lt,{width:12}),r===null?(0,Q.jsx)(Ae,{width:11}):r]})}function Xd({coupon:e,index:t,isNext:n,locale:r,t:i}){let a=e.validityEnd?vd(e.validityEnd):null;return(0,Q.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(lt,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:n?i(`grokCoupon.couponNext`):i(`grokCoupon.couponLabel`,{n:String(t+1)})}),n&&(0,Q.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:i(`grokCoupon.couponNextBadge`)})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[e.validityStart&&(0,Q.jsx)(`span`,{children:i(`grokCoupon.validFrom`,{date:gd(e.validityStart,r)})}),a!==null&&(0,Q.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`grokCoupon.expires`,{date:_d(e.validityEnd,r),days:String(a)})})]})]})}function Zd({accountId:e,accountLabel:n,entry:r,controller:i,onClose:a}){let{locale:o,t:s}=t(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),g=i.uncertain[e],[_,v]=(0,Z.useState)(null),y=(0,Z.useRef)(void 0);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,Z.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,Z.useCallback)(e=>{e.preventDefault(),a()},[a]),x=Kd(r),S=x[0],C=()=>{if(g)return;let e=qd();if(!e){v({tone:`warn`,key:`grokCoupon.noOperationId`});return}y.current=e,v(null),d(!0)},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 i.redeem(e,{tokenId:S.tokenId,operationId:t});if(p(!1),n.ok){y.current=void 0,d(!1),v({tone:`ok`,key:n.replayed?`grokCoupon.redeemReplayed`:`grokCoupon.redeemSuccess`});return}if(n.uncertain||n.code===`aborted`){n.operationId&&(y.current=n.operationId),d(!1),v(null),i.refresh(e);return}n.code===`operation_id_owned_by_another_account`&&(y.current=void 0),v({tone:`warn`,key:Jd[n.code]??`grokCoupon.redeemFailed`})},T=async()=>{!g||m||(h(!0),await i.refresh(e),h(!1))},E=g?Kd(r).some(e=>e.tokenId===g.tokenId):!1,D=String(x.length),O=e=>(0,Q.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:s(e.key,{count:D})});return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`grok-coupon-title`,onCancel:b,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ae,{width:22})}),(0,Q.jsx)(`h3`,{id:`grok-coupon-title`,children:s(`grokCoupon.title`)}),(0,Q.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:s(`grokCoupon.unknownOutcome`)}),!m&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(E?`grokCoupon.unresolved`:`grokCoupon.consumedElsewhere`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{T()},disabled:m,children:s(m?`grokCoupon.checking`:`grokCoupon.checkResult`)})]})]}):u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ae,{width:22})}),(0,Q.jsx)(`h3`,{id:`grok-coupon-title`,children:s(`grokCoupon.confirmTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`grokCoupon.confirmDesc`,{count:D})}),S?.validityEnd&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`grokCoupon.confirmWhich`,{date:gd(S.validityEnd,o)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`grokCoupon.irreversible`)}),_&&O(_)]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(!1),disabled:f,children:s(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,onClick:()=>{w()},disabled:f,children:s(f?`grokCoupon.redeeming`:`grokCoupon.redeem`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`grok-coupon-title`,children:[(0,Q.jsx)(lt,{width:16}),` `,s(`grokCoupon.title`)]}),(0,Q.jsx)(`div`,{className:`card-sub`,children:n}),(0,Q.jsxs)(`div`,{style:{margin:`16px 0`},children:[r===void 0||r.status===`loading`?(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`common.loading`)}):r.status===`error`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,role:`alert`,children:s(r.reason===`auth`?`grokCoupon.loadFailedAuth`:`grokCoupon.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{i.refresh(e)},children:s(`grokCoupon.retry`)})]}):x.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:s(`grokCoupon.available`,{count:D})}),(0,Q.jsx)(`div`,{className:`credit-list`,children:x.map((e,t)=>(0,Q.jsx)(Xd,{coupon:e,index:t,isNext:t===0,locale:o,t:s},e.tokenId))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:C,disabled:f,children:s(`grokCoupon.useOne`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:s(`grokCoupon.fifoNote`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:s(`grokCoupon.none`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`grokCoupon.desc`)})]}),_&&O(_)]})]})})]})}var Qd=2e4,$d=6e4,ef=3,tf={},nf=[`five_hour`,`seven_day`,`seven_day_overage_included`],rf=new Set([`unknown_outcome`,`journal_write_failed`,`in_flight`]);function af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function of(e){return e==null?null:typeof e==`string`?e:void 0}function sf(e){if(!af(e))return null;let{id:t,label:n,resetsTotal:r,resetsLeft:i,paused:a,usableNow:o,useRequiresLimit:s}=e,c=of(e.startsAt),l=of(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(af(e.percentUsed))for(let t of nf){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:nf.filter(t=>e.clears.includes(t))}}function cf(e){if(!af(e)||typeof e.eligible!=`boolean`||!Array.isArray(e.grants))return null;let t=[];for(let n of e.grants){let e=sf(n);if(!e)return null;t.push(e)}let n=null,r=e.pendingOperation;return af(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 lf(e){return e.eligible?e.grants.reduce((e,t)=>e+t.resetsLeft,0):0}function uf(e){if(!(!e.eligible||!e.journalAvailable))return e.grants.find(t=>!t.paused&&t.usableNow&&t.resetsLeft>0&&(!t.useRequiresLimit||e.atLimit))}function df(e){return af(e)&&af(e.error)&&typeof e.error.code==`string`&&e.error.code!==``?e.error.code:`failed`}function ff({apiBase:e,provider:t=`anthropic`,accountIds:n,enabled:r}){let i=`${e}\0${t}`,[a,o]=(0,Z.useState)(()=>({namespace:i,entries:{}})),s=(0,Z.useRef)(0),c=(0,Z.useRef)(new Map),l=(0,Z.useRef)({active:0,waiting:[]}),u=n.join(`\0`);(0,Z.useLayoutEffect)(()=>{s.current+=1,c.current.clear();let e=l.current;l.current={active:0,waiting:[]};for(let t of e.waiting.splice(0))t();return()=>{s.current+=1}},[i]);let d=(0,Z.useCallback)((e,t)=>{o(n=>({namespace:i,entries:{...n.namespace===i?n.entries:{},[e]:t}}))},[i]),f=(0,Z.useCallback)(async(n,r)=>{if(s.current!==r)return;let i=(c.current.get(n)??0)+1;c.current.set(n,i);let a=l.current;a.active>=ef&&await new Promise(e=>a.waiting.push(e)),a.active+=1;let o=()=>s.current===r&&c.current.get(n)===i,u=A(Qd);try{if(!o())return;let r=await fetch(`${e}/api/anthropic/reset-grants?accountId=${encodeURIComponent(n)}${t===`anthropic`?``:`&provider=${encodeURIComponent(t)}`}`,{signal:u.signal}),i=r.ok?await r.json().catch(()=>null):null,a=af(i)&&(i.provider===t||t===`anthropic`&&i.provider===void 0)?cf(i):null;if(!o())return;d(n,a?{status:`ready`,snapshot:a}:{status:`error`,reason:r.status===401?`auth`:`upstream`})}catch{if(!o())return;d(n,{status:`error`,reason:`upstream`})}finally{u.clear(),--a.active,a.waiting.shift()?.()}},[e,t,d]);(0,Z.useEffect)(()=>{if(!r||u===``)return;let e=++s.current;return Promise.resolve().then(()=>{for(let t of u.split(`\0`))f(t,e)}),()=>{s.current+=1}},[r,u,f]);let p=(0,Z.useCallback)(async e=>{d(e,{status:`loading`}),await f(e,s.current)},[f,d]),m=(0,Z.useCallback)(async(n,r)=>{let i=s.current,a=A($d);try{let o=await fetch(`${e}/api/anthropic/reset-grants/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t===`anthropic`?{}:{provider:t},accountId:n,grantId:r.grantId,operationId:r.operationId}),signal:a.signal});if(!o.ok){let e=df(await o.json().catch(()=>null));return rf.has(e)?{kind:`unknown`,code:e}:{kind:`refused`,code:e}}let c=await o.json().catch(()=>null);return!af(c)||typeof c.code!=`string`||c.provider!==t&&(t!==`anthropic`||c.provider!==void 0)?{kind:`unknown`,code:`unknown_outcome`}:(i===s.current&&f(n,i),{kind:`settled`,code:c.code,replayed:c.replayed===!0,resetsLeft:typeof c.resetsLeft==`number`?c.resetsLeft:null})}catch{return{kind:`unknown`,code:`aborted`}}finally{a.clear()}},[e,t,f]);return{entries:a.namespace===i?a.entries:tf,refresh:p,spend:m}}function pf(){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 mf={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`},hf={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 gf({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(lt,{width:12}),`0`]});let r=e.status===`ready`?lf(e.snapshot):null,i=e.status===`ready`&&uf(e.snapshot)!==void 0,a=r===null?n(`anthropicGrant.badgeErrorAria`):n(`anthropicGrant.badgeAria`,{count:String(r)});return(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${i?`badge-amber`:`badge-muted`} badge-clickable`,"data-anthropic-grant-badge":r===null?`error`:String(r),onClick:e=>{e.stopPropagation(),t()},"aria-label":a,title:a,children:[(0,Q.jsx)(lt,{width:12}),r===null?(0,Q.jsx)(Ae,{width:11}):r]})}var _f={five_hour:`anthropicGrant.windowFiveHour`,seven_day:`anthropicGrant.windowWeekly`,seven_day_overage_included:`anthropicGrant.windowOverage`};function vf({grant:e,snapshot:t,isNext:n,locale:r,t:i}){let a=e.endsAt?vd(e.endsAt):null,o=e.paused?i(`anthropicGrant.paused`):e.usableNow?e.useRequiresLimit&&!t.atLimit?i(`anthropicGrant.requiresLimit`):null:i(`anthropicGrant.notUsable`);return(0,Q.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,"data-anthropic-grant":e.id,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(lt,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:e.label||e.id}),(0,Q.jsx)(`span`,{className:`badge badge-muted text-micro anthropic-grant-count`,children:i(`anthropicGrant.resetsLeft`,{left:String(e.resetsLeft),total:String(e.resetsTotal)})})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[e.startsAt&&(0,Q.jsx)(`span`,{children:i(`anthropicGrant.validFrom`,{date:gd(e.startsAt,r)})}),e.endsAt&&a!==null&&(0,Q.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`anthropicGrant.expires`,{date:_d(e.endsAt,r),days:String(a)})})]}),e.clears.length>0&&(0,Q.jsx)(`div`,{className:`anthropic-grant-windows`,children:e.clears.map(t=>(0,Q.jsx)(`span`,{className:`anthropic-grant-window`,children:i(_f[t],{percent:String(e.percentUsed[t]??0)})},t))}),o&&(0,Q.jsx)(`div`,{className:`faint text-caption anthropic-grant-note`,children:o})]})}function yf(e){return e.kind===`settled`?e.replayed&&e.code===`reset`?{tone:`ok`,key:`anthropicGrant.replayed`}:{tone:e.code===`reset`?`ok`:`warn`,key:mf[e.code]??`anthropicGrant.failed`,count:e.resetsLeft===null?`?`:String(e.resetsLeft)}:{tone:`warn`,key:hf[e.code]??`anthropicGrant.failed`}}var bf=new Set([`unknown_outcome_expired`,`operation_identity_mismatch`]);function xf({accountId:e,accountLabel:n,entry:r,controller:i,onClose:a}){let{locale:o,t:s}=t(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,Z.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,Z.useCallback)(e=>{e.preventDefault(),a()},[a]),x=r?.status===`ready`?r.snapshot:null,S=x?.pendingOperation,C=g??(S?{grantId:S.grantId,operationId:S.operationId}:null),w=x?uf(x):void 0,T=()=>{if(!w||C)return;let e=pf();if(!e){y({tone:`warn`,key:`anthropicGrant.noOperationId`});return}y(null),d({grantId:w.id,operationId:e})},E=async t=>{if(f)return;let n=C!==null&&C.operationId===t.operationId;p(!0);let r=await i.spend(e,t);if(p(!1),d(null),r.kind===`unknown`||r.kind===`refused`&&n&&!bf.has(r.code)){_(t),y(r.kind===`refused`?yf(r):null);return}_(null),y(yf(r)),r.kind===`refused`&&i.refresh(e)},D=async()=>{m||(h(!0),await i.refresh(e),h(!1))},O=e=>(0,Q.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:s(e.key,{count:e.count??``})}),k=u&&x?x.grants.find(e=>e.id===u.grantId):void 0,A=x?lf(x):0;return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`anthropic-grant-title`,onCancel:b,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:C?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ae,{width:22})}),(0,Q.jsx)(`h3`,{id:`anthropic-grant-title`,children:s(`anthropicGrant.title`)}),(0,Q.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:s(`anthropicGrant.unknownOutcome`)}),v&&O(v)]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{D()},disabled:m||f,children:s(m?`anthropicGrant.checking`:`anthropicGrant.checkResult`)}),(0,Q.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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ae,{width:22})}),(0,Q.jsx)(`h3`,{id:`anthropic-grant-title`,children:s(`anthropicGrant.confirmTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`anthropicGrant.confirmDesc`)}),k&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`anthropicGrant.confirmWhich`,{label:k.label||k.id})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`anthropicGrant.irreversible`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(null),disabled:f,children:s(`common.cancel`)}),(0,Q.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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`anthropic-grant-title`,children:[(0,Q.jsx)(lt,{width:16}),` `,s(`anthropicGrant.title`)]}),(0,Q.jsx)(`div`,{className:`card-sub`,children:n}),(0,Q.jsxs)(`div`,{style:{margin:`16px 0`},children:[r===void 0||r.status===`loading`?(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`common.loading`)}):r.status===`error`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,role:`alert`,children:s(r.reason===`auth`?`anthropicGrant.loadFailedAuth`:`anthropicGrant.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{i.refresh(e)},children:s(`anthropicGrant.retry`)})]}):r.snapshot.eligible?r.snapshot.grants.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:s(`anthropicGrant.available`,{count:String(A)})}),(0,Q.jsx)(`div`,{className:`credit-list`,children:r.snapshot.grants.map(e=>(0,Q.jsx)(vf,{grant:e,snapshot:r.snapshot,isNext:e.id===w?.id,locale:o,t:s},e.id))}),(0,Q.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,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:s(`anthropicGrant.desc`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:s(`anthropicGrant.none`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`anthropicGrant.desc`)})]}):(0,Q.jsx)(`p`,{className:`faint`,children:s(`anthropicGrant.ineligible`)}),v&&O(v)]})]})})]})}var Sf=2e4,Cf=3e4,wf=3,Tf=`ocx.grok-coupon-holds.v1`,Ef=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Df=new Set([`attempt_unresolved`,`attempt_in_progress`,`attempt_reconcile_failed`,`operation_state_changed`,`redeem_failed`,`attempt_mark_failed`,`operation_token_mismatch`]),Of=new Set([`ledger_unavailable`,`capacity`]),kf=new Set([`redeemed`,`auth_failed`,`fetch_resets_failed`,`no_coupons_available`,`coupon_unavailable`,`token_unresolved`]),Af=new Map,jf=new Set,Mf;function Nf(e){if(!e||typeof e!=`object`)return!1;let{tokenId:t,operationId:n}=e;return typeof t==`string`&&t.trim()!==``&&typeof n==`string`&&Ef.test(n)}function Pf(){try{let e=window.sessionStorage.getItem(Tf);if(e!==Mf){Mf=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`)||!Nf(n)||Af.has(e)||(Af=new Map(Af).set(e,{tokenId:n.tokenId,operationId:n.operationId}))}}catch{}return Af}function Ff(e){return jf.add(e),()=>{jf.delete(e)}}function If(){try{let e=JSON.stringify(Object.fromEntries(Af));window.sessionStorage.setItem(Tf,e),Mf=e}catch{}for(let e of jf)e()}function Lf(e,t){Af=new Map(Af).set(e,{...t}),If()}function Rf(e,t){Pf().get(e)?.operationId===t&&(Af=new Map(Af),Af.delete(e),If())}function zf(e,t){return Df.has(e)||Of.has(e)&&!!(t&&typeof t==`object`&&`operationId`in t)}function Bf(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 Vf(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 Hf(e){if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&t.trim()!==``)return t}return null}function Uf(e){if(!e.validityEnd)return 1/0;let t=Date.parse(e.validityEnd);return Number.isNaN(t)?1/0:t}function Wf(e){return e.toSorted((e,t)=>Uf(e)-Uf(t))}function Gf({apiBase:e,accountIds:t,enabled:n}){let[r,i]=(0,Z.useState)({}),a=(0,Z.useSyncExternalStore)(Ff,Pf,Pf),o=(0,Z.useMemo)(()=>{let t=`${e}\u0000`;return Object.fromEntries([...a].filter(([e])=>e.startsWith(t)).map(([e,n])=>[e.slice(t.length),n]))},[e,a]),s=(0,Z.useRef)(0),c=(0,Z.useRef)(new Map),l=(0,Z.useRef)({active:0,waiting:[]}),u=t.join(`\0`),d=(0,Z.useCallback)(async(t,n)=>{let r=(c.current.get(t)??0)+1;c.current.set(t,r);let a=l.current;a.active>=wf&&await new Promise(e=>a.waiting.push(e)),a.active+=1;let o=()=>s.current===n&&c.current.get(t)===r,u=A(Sf);try{let n=await fetch(`${e}/api/grok/reset-coupons?accountId=${encodeURIComponent(t)}`,{signal:u.signal}),r=n.ok?Bf(await n.json().catch(()=>null)):null;if(!o())return;i(e=>({...e,[t]:r?{status:`ready`,coupons:Wf(r)}:{status:`error`,reason:n.status===401?`auth`:`upstream`}}))}catch{if(!o())return;i(e=>({...e,[t]:{status:`error`,reason:`upstream`}}))}finally{u.clear(),--a.active,a.waiting.shift()?.()}},[e]);return(0,Z.useEffect)(()=>{if(!n||u===``)return;let e=++s.current;return Promise.resolve().then(()=>{for(let t of u.split(`\0`))d(t,e)}),()=>{s.current+=1}},[n,u,d]),{entries:r,uncertain:o,refresh:(0,Z.useCallback)(async e=>{i(t=>({...t,[e]:{status:`loading`}})),await d(e,s.current)},[d]),redeem:(0,Z.useCallback)(async(t,n)=>{let r=`${e}\u0000${t}`,i=(e,t=`attempt_unresolved`)=>({ok:!1,code:t,replayed:!1,operationId:e.operationId,uncertain:!0}),a=Pf().get(r);if(a)return i(a);Lf(r,n);let o=()=>Rf(r,n.operationId),c=A(Cf);try{let r=await fetch(`${e}/api/grok/reset-coupons/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t,tokenId:n.tokenId,operationId:n.operationId}),signal:c.signal});if(!r.ok){let e=await r.json().catch(()=>null),t=Vf(e);return zf(t,e)?i(n,t):(o(),{ok:!1,code:t,replayed:!1})}let a=await r.json().catch(()=>null),l=!!(a&&typeof a==`object`&&a.replayed===!0),u=Hf(a);return u===null||!kf.has(u)?i(n,u??`attempt_unresolved`):(o(),await d(t,s.current),{ok:u===`redeemed`,code:u,replayed:l})}catch{return i(n,`aborted`)}finally{c.clear()}},[e,d])}}var Kf=new Set([`builder-id`,`google`,`github`]),qf=new Set([`pending`,`done`,`failed`,`expired`,`cancelled`]);function Jf(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.flowId!=`string`||!t.flowId||!Kf.has(t.method)||!qf.has(t.state)?null:{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}:{}}}function Yf(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();return n!==`device.sso.us-east-1.amazonaws.com`&&n!==`kiro.dev`&&!n.endsWith(`.kiro.dev`)?null:t.href}catch{return null}}function Xf(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 Zf=new Map;function Qf(e,t){let n=JSON.stringify([e,t]),r=Zf.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(()=>{Zf.get(n)===i&&Zf.delete(n)});return Zf.set(n,i),i}async function $f(e,t,n){let r=JSON.stringify([e,t]),i=Zf.get(r);return i?(await i,$f(e,t,n)):n()}var ep=new Map,tp=new Map,np=new Map,rp=(e,t)=>JSON.stringify([e,t]),ip=e=>new Promise(t=>setTimeout(t,e)),ap=65536;function op(e){try{e.body?.cancel().catch(()=>{})}catch{}}function sp(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){op(n);return}if(n.status===404){op(n),c({kind:`missing`});return}if(!n.ok||!n.body){op(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>ap){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=Jf(d);c(f?{kind:`view`,view:f}:{kind:`retry`})}catch{c({kind:`retry`})}})(),{result:s,cancel:l}}async function cp(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 lp(e,t){let n=np.get(e)??new Set;return n.add(t),np.set(e,n),()=>{n.delete(t),n.size===0&&np.delete(e)}}function up(e,t,n){let r=rp(e,t);if(tp.has(r))return tp.get(r);tp.set(r,n);for(let t of np.get(e)??[])t(n);return n}function dp(e,t,n,r=`status`){return n.flowId!==t||r===`cancel`&&n.state!==`failed`?null:n.state===`done`?up(e,t,`added`):n.state===`failed`?up(e,t,`failed`):n.state===`expired`||n.state===`cancelled`?up(e,t,`ended`):null}function fp(e,t,n,r){let i=rp(e,t),a=ep.get(i);if(a)return a;let o=tp.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??sp(e,t,Math.min(45e3,r));n=void 0;let o=await cp(a,r);if(tp.has(i))return tp.get(i);if(o.kind===`missing`)return up(e,t,`ended`);if(o.kind===`view`){let n=dp(e,t,o.view);if(n)return n}let c=s-Date.now();if(c<=0)break;await ip(Math.min(2e3,c))}return n?.cancel(),up(e,t,`ended`)})().finally(()=>{ep.delete(i)});return ep.set(i,c),c}var pp=(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})}),mp=Symbol(`closed`),hp=(e,t)=>new Promise(n=>{if(e.closed){n(mp);return}let r=!1,i=t=>{r||(r=!0,e.closedController.signal.removeEventListener(`abort`,a),n(t))},a=()=>i(mp);e.closedController.signal.addEventListener(`abort`,a,{once:!0}),t.then(t=>i(e.closed?mp:t),()=>i(mp))});function gp(e,t,n=pp){let[r,i]=(0,Z.useState)({phase:`idle`}),a=(0,Z.useRef)(null),o=(0,Z.useRef)(!0),s=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{s.current=t},[t]);let c=(0,Z.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,Z.useCallback)(t=>{let n=t.view;n&&!t.terminal&&fp(e,n.flowId,n.expiresAt,t.inFlight)},[e]),u=(0,Z.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?Jf(await r.json().catch(()=>null)):null;s&&dp(e,t.view.flowId,s,`cancel`)},[e,c,l]);return(0,Z.useEffect)(()=>(o.current=!0,()=>{o.current=!1,u()}),[u]),{state:r,start:(0,Z.useCallback)(async t=>{if(a.current)return;let r={closed:!1,closedController:new AbortController};a.current=r,i({phase:`starting`});let u;try{u=await $f(e,`kiro`,()=>fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,method:t})}))}catch{!r.closed&&o.current&&i({phase:`failed`,error:`network`}),a.current===r&&(a.current=null);return}let d=u.ok?Jf(await u.json().catch(()=>null)):null;if(!d||d.method!==t){!r.closed&&o.current&&i({phase:`failed`,error:u.ok?`invalid`:`start`}),a.current===r&&(a.current=null);return}if(r.view=d,r.closed){let t=c(d);l(r);let n=await t,i=n?.ok?Jf(await n.json().catch(()=>null)):null;i&&dp(e,d.flowId,i,`cancel`);return}if(d.state!==`pending`){d.state===`done`?s.current?.(`kiro`,`added`):d.state===`failed`&&s.current?.(`kiro`,`failed`),o.current&&i({phase:d.state,view:d}),r.terminal=d.state===`done`?`added`:d.state===`failed`?`failed`:`ended`,a.current=null;return}for(i({phase:`pending`,view:d});!r.closed&&!r.terminal;){let t=new AbortController;if(r.waitController=t,await n(2e3,t.signal),r.waitController=void 0,r.closed||r.terminal)break;if(r.view?.expiresAt&&Date.now()>=r.view.expiresAt){r.terminal=`ended`,o.current&&i({phase:`expired`,view:r.view});break}let a=d.flowId,c=sp(e,a);r.inFlight=c;let l=await hp(r,c.result);if(l===mp)break;if(r.inFlight=void 0,l.kind===`missing`){r.terminal=`ended`,s.current?.(`kiro`,`ended`),i({phase:`ended`,view:r.view});break}let u=l.kind===`view`?l.view:null;if(!(!u||u.flowId!==a)){if(r.view=u,u.state===`pending`){i({phase:`pending`,view:u});continue}r.terminal=u.state===`done`?`added`:u.state===`failed`?`failed`:`ended`,(u.state===`done`||u.state===`failed`)&&s.current?.(`kiro`,r.terminal),i({phase:u.state,view:u});break}}a.current===r&&(a.current=null)},[e,c,l,n]),close:u,reset:(0,Z.useCallback)(()=>{a.current||i({phase:`idle`})},[])}}function _p({disabled:e,onCli:t,onMethod:n}){let r=O();return(0,Q.jsxs)(`div`,{className:`kiro-login-choices`,role:`group`,"aria-label":r(`kiroLogin.chooseMethod`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:t,children:r(`kiroLogin.cli`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`builder-id`),children:r(`kiroLogin.builderId`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`google`),children:r(`kiroLogin.google`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>n(`github`),children:r(`kiroLogin.github`)})]})}function vp({apiBase:e,triggerRef:t,addAccount:n,busy:r,onCli:i,onClose:a,onSettled:o,pollDelay:s}){let c=O(),l=(0,Z.useId)(),u=rr(!0,t),d=gp(e,o,s),f=sl(),{state:p}=d,m=p.view,h=m?.verificationUriComplete??m?.verificationUri,g=Yf(h),_=()=>{d.close(),a()};return(0,Q.jsxs)(`dialog`,{ref:u,className:`kiro-device-dialog`,"aria-modal":`true`,"aria-labelledby":l,onCancel:e=>{e.preventDefault(),_()},children:[(0,Q.jsx)(`h2`,{id:l,children:c(`kiroLogin.title`)}),p.phase===`idle`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:c(n?`kiroLogin.addDescription`:`kiroLogin.loginDescription`)}),(0,Q.jsx)(_p,{disabled:r,onCli:()=>{a(),i(n)},onMethod:e=>{d.start(e)}})]}),p.phase===`starting`&&(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:c(`kiroLogin.starting`)}),m&&(p.phase===`pending`||p.phase===`done`||p.phase===`failed`||p.phase===`expired`||p.phase===`ended`)&&(0,Q.jsxs)(Q.Fragment,{children:[m.userCode&&(0,Q.jsxs)(`div`,{className:`kiro-device-code`,children:[(0,Q.jsx)(`span`,{className:`kiro-device-code-value`,children:m.userCode}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.copy(m.userCode,m.flowId),children:f.outcomeFor(m.flowId)===`copied`?c(`kiroLogin.copied`):f.outcomeFor(m.flowId)===`unavailable`?c(`kiroLogin.copyUnavailable`):c(`kiroLogin.copyCode`)})]}),h&&(g?(0,Q.jsx)(`a`,{href:g,target:`_blank`,rel:`noopener noreferrer`,children:c(`kiroLogin.openVerification`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`kiro-device-destination`,children:h}),(0,Q.jsx)(`p`,{className:`notice-warn`,children:c(`kiroLogin.unexpectedHost`)})]})),m.warning===`duplicate_profile_arn`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:c(`kiroLogin.duplicate`)}),m.warning===`manual_review_required`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:c(`kiroLogin.manualReview`)})]}),(0,Q.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[p.phase===`pending`&&c(`kiroLogin.pending`),p.phase===`done`&&c(`kiroLogin.done`),p.phase===`expired`&&c(`kiroLogin.expired`),p.phase===`ended`&&c(`kiroLogin.ended`),p.phase===`failed`&&c(p.error===`start`?`kiroLogin.startFailed`:`kiroLogin.failed`)]}),(0,Q.jsxs)(`div`,{className:`kiro-device-actions`,children:[(p.phase===`failed`||p.phase===`expired`||p.phase===`ended`)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:d.reset,children:c(`kiroLogin.tryAgain`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:_,children:c(`common.cancel`)})]})]})}var yp=262144,bp=[],xp=[];function Sp(e){return!!e.needsReauth||Gc(e.health?.status)}function Cp({initialState:e,onUpdateProvider:t}){let n=O(),[r,i]=(0,Z.useState)(e),[a,o]=(0,Z.useState)(e),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``);e!==a&&(o(e),i(e));let d=r===`mixed`,f=async()=>{if(!t||s)return;let e=r===!1;c(!0),u(``);try{let r=await t(`xai`,{xaiResponsesOptIn:e});if(!r.ok){u(r.error??n(`prov.updateFail`));return}i(r.xaiResponsesOptInState??e)}catch{u(n(`prov.networkError`))}finally{c(!1)}};return(0,Q.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-optin-label`,children:n(`pws.xaiChatOptIn`)}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[n(`pws.xaiChatOptInDesc`),d&&(0,Q.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,n(`pws.xaiChatOptInMixed`)]})]}),l&&(0,Q.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:l})]}),(0,Q.jsx)(on,{on:r===!1,mixed:d,onClick:()=>{f()},disabled:!t||s,label:n(`pws.xaiChatOptIn`)})]})}var wp=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Tp=new Set([`imported`,`updated`,`failed`,`unsupported`]),Ep={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 Dp(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Op(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function kp(e){if(!Dp(e)||Object.keys(e).some(e=>!wp.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!Op(t)||!Op(n)||!Op(r)||!Op(i)||!Op(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(!Dp(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||!Tp.has(n)||!Ep[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 Ap({item:e,apiBase:t,oauth:n,accounts:r=bp,keys:i=xp,accountLoadState:a=`ready`,switchingAccountId:o=null,pausingAccountId:s=null,busy:c=!1,loginHint:l,authHandlers:u,onCodexActiveNeedsReauthChange:d,codexController:f,onUpdateProvider:p}){let m=O(),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(null),x=t=>{e.name===`kiro`?v({addAccount:t}):u?.onLogin(e.name,t)},[S,C]=(0,Z.useState)(``),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(`idle`),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null),[P,I]=(0,Z.useState)(``),[L,R]=(0,Z.useState)(!1),[z,B]=(0,Z.useState)(``),[V,H]=(0,Z.useState)(!0),U=JSON.stringify([t,e.name,r.find(e=>e.active)?.id,i.find(e=>e.active)?.id]),[W,G]=(0,Z.useState)({identity:U,refreshing:!1,result:null}),ee=W.identity===U&&W.refreshing,K=W.identity===U?W.result:null,q=(0,Z.useRef)(0);(0,Z.useEffect)(()=>(q.current+=1,()=>{q.current+=1}),[U]);let te=u?.onRefreshQuota,ne=Bs({...e,hasApiKey:e.hasApiKey||i.length>0}),J=ne===`oauth-accounts`,Y=ne===`api-keys`,ie=J&&e.name===`xai`&&r.length>0,X=Gf({apiBase:t,accountIds:(0,Z.useMemo)(()=>ie?r.filter(e=>!Sp(e)).map(e=>e.id):[],[ie,r]),enabled:ie}),[ae,oe]=(0,Z.useState)(null),se=Ic(e.name)&&Lc(e.name,e),ce=J&&se&&r.length>0,le=(0,Z.useMemo)(()=>ce?r.filter(e=>!Sp(e)).map(e=>e.id):[],[ce,r]),ue=ff({apiBase:t,provider:Ic(e.name)?e.name:`anthropic`,accountIds:le,enabled:ce}),de=`${t}\0${e.name}`,[fe,pe]=(0,Z.useState)(null),me=fe?.scope===de?fe.account:null,he=e=>{pe(e?{scope:de,account:e}:null)},ge=async()=>{if(!te||ee)return;let t=++q.current;G({identity:U,refreshing:!0,result:null});try{let n=await te(e.name);q.current===t&&G({identity:U,refreshing:!1,result:{ok:n,text:m(n?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}})}catch{q.current===t&&G({identity:U,refreshing:!1,result:{ok:!1,text:m(`codexAuth.quotaRefreshFailed`)}})}};if(ne===`codex-accounts`)return(0,Q.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":m(`pws.availableAccounts`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:m(`pws.availableAccounts`)}),(0,Q.jsx)(`div`,{className:`pwi-auth-body`,children:(0,Q.jsx)(Bd,{apiBase:t,embedded:!0,controller:f,onActiveNeedsReauthChange:d})})]});if(!ne||!u)return null;let _e=l?.provider===e.name?l:null,ve=async()=>{let n=P.trim();if(!(!n||L)){R(!0),B(``);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(()=>({}));H(!1),B(m(`prov.pasteFail`,{error:e.error||r.statusText}));return}I(``),H(!0),B(m(`prov.pasteOk`))}catch{H(!1),B(m(`modal.networkError`))}finally{R(!1)}}},ye=r.length>0||n?.loggedIn===!0,be=r.find(e=>e.active&&e.needsReauth),xe=!!be,Se=J?r:i,Ce=!!te&&!(Se.length>0&&Se.every(e=>e.quotaMode===`unsupported`)),we=async()=>{let t=S.trim();if(t){T(!0);try{await u.onAddApiKey(e.name,t)&&(C(``),g(!1))}finally{T(!1)}}},Te=async n=>{if(!(!n||E)){D(!0),A(`idle`),M(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>yp){A(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{A(`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){A(`failed`);return}let a=kp(await i.json().catch(()=>null));if(!a){A(`failed`);return}M(a),A(`complete`);try{await u.onRetryAccounts?.(e.name)}catch{}}catch{A(`failed`)}finally{N.current&&(N.current.value=``),D(!1)}}};return(0,Q.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":m(J?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-head`,children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:m(J?`pws.availableAccounts`:`pws.apiKeys`)}),(J&&ye||Y)&&Ce&&(0,Q.jsxs)(`div`,{className:`pwi-auth-head-actions`,children:[K&&(0,Q.jsx)(`span`,{role:`status`,className:K.ok?`pws-status-ok`:`pws-status-warn`,children:K.text}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ee||c||!!o,onClick:()=>{ge()},children:[(0,Q.jsx)(re,{width:14,height:14,"aria-hidden":`true`}),` `,m(ee?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,Q.jsx)(Cp,{initialState:e.xaiResponsesOptInState??!0,onUpdateProvider:p}),J&&(0,Q.jsxs)(Q.Fragment,{children:[se&&(0,Q.jsx)(Wd,{apiBase:t,provider:Ic(e.name)?e.name:`anthropic`,accountCount:r.length,onThresholdChange:t=>{u?.onAccountPoolThreshold?.(e.name,t)}},`${t}:${e.name}`),e.name===`google-antigravity`&&(0,Q.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:m(`pws.cockpitImportDescription`)}),(0,Q.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:m(`pws.cockpitImportFileLabel`)}),(0,Q.jsx)(`input`,{ref:N,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:E,onChange:e=>{Te(e.currentTarget.files?.[0])}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:E,onClick:()=>N.current?.click(),children:m(E?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,Q.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[k===`invalid`&&m(`pws.cockpitImportInvalid`),k===`failed`&&m(`pws.cockpitImportFailed`),k===`complete`&&j&&m(`pws.cockpitImportComplete`,{imported:j.importedCount,updated:j.updatedCount,failed:j.failedCount,unsupported:j.unsupportedCount})]})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${xe?`pwi-auth-dot--warn`:ye?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`pwi-auth-status-text`,children:ye?r.length>0?m(`pws.loggedInTitle`):n?.email??m(`pws.loggedInTitle`):n?.error||m(`pws.notLoggedInTitle`)}),(0,Q.jsxs)(`span`,{className:`pwi-auth-actions`,children:[be&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:c,onClick:()=>void u.onReauth(e.name,be.id),children:m(`pws.reauthenticate`)}),ye?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void u.onLogout(e.name),children:m(`prov.logout`)}):(0,Q.jsxs)(`button`,{ref:e.name===`kiro`?y:void 0,type:`button`,className:`btn btn-primary btn-sm`,disabled:c||e.name===`kiro`&&!!_,onClick:()=>x(!1),children:[c?(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,Q.jsx)(at,{style:{width:13,height:13},"aria-hidden":`true`}),m(c?`prov.waitingBrowser`:`prov.login`)]})]})]}),!c&&(0,Q.jsx)(Gd,{}),c&&_e&&(0,Q.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,Q.jsx)(`div`,{className:`pwi-auth-wait-title`,children:m(`prov.waitingBrowser`)}),(0,Q.jsx)(ul,{hint:{url:_e.url,deviceCode:_e.deviceCode,instructions:_e.instructions,browserLaunch:_e.browserLaunch},paste:{value:P,busy:L,message:z,ok:V,onChange:I,onSubmit:()=>{ve()}}}),u.onCancelLogin&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void u.onCancelLogin?.(e.name),children:m(`common.cancel`)})]})]}),a===`loading`&&r.length===0&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),m(`pws.accountsLoading`)]}),a===`error`&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:m(`pws.accountsLoadFailed`)}),u.onRetryAccounts&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void u.onRetryAccounts?.(e.name),children:m(`pws.retryAccounts`)})]}),r.length>0&&(0,Q.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=Vs(r,t,m),i=o===t.id,a=s===t.id,l=t.health?.status,d=Sp(t),f=qc(l),p=zc(t.id),h=Xc(m,t.health),g=Zc(m,e.name,t.id,t.health);return(0,Q.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!t.paused&&!d&&!f&&!o&&!s&&u.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${m(`pws.accountCurrent`)}`:``}`,disabled:!!(t.paused||d||f||o||s),children:[(0,Q.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,Q.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${m(`prov.accountId`)}: ${p}`].filter(Boolean).join(` · `)}),g&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:g}),f&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m(`pws.healthCooldownHint`)}),t.paused&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m(`pws.accountPausedHint`)})]}),h&&(0,Q.jsx)(`span`,{className:Wc(l),children:h}),d&&!h&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:m(`pws.reauth`)}),Xf(t,e.name)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:m(Xf(t,e.name))}),t.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:m(`codexAuth.paused`)}),t.active&&!t.paused&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:m(`prov.accountActive`)}),i&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:m(`pws.accountSwitching`)})]}),typeof t.paused==`boolean`&&u.onPauseAccount&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":`${m(t.paused?`codexAuth.resume`:`codexAuth.pause`)} — ${n}`,title:t.paused?m(`pws.accountPausedHint`):void 0,"aria-busy":a,disabled:c||!!o||!!s,onClick:()=>void u.onPauseAccount(e.name,t,!t.paused),children:m(t.paused?`codexAuth.resume`:`codexAuth.pause`)}),d&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:c||!!o||!!s,onClick:()=>void u.onReauth(e.name,t.id),children:m(`pws.reauthenticate`)}),ie&&!d&&(0,Q.jsx)(Yd,{entry:X.entries[t.id],t:m,onClick:()=>oe(t)}),ce&&!d&&(0,Q.jsx)(gf,{entry:ue.entries[t.id],t:m,onClick:()=>he(t)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void u.onEditAlias(e.name,`oauth`,t.id,t.alias),children:m(`prov.editAlias`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${m(`common.remove`)} — ${n}`,title:`${m(`common.remove`)} — ${n}`,disabled:!!o||!!s,onClick:()=>void u.onRemoveAccount(e.name,t),children:(0,Q.jsx)(F,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-acct-quota`,children:[se&&t.autoSwitchThresholdOverride!==void 0&&t.autoSwitchThreshold!==void 0&&u.onAccountThreshold&&(0,Q.jsx)(Hc,{accountLabel:n,inputId:`anthropic-threshold-${t.id}`,globalThreshold:t.autoSwitchThreshold,override:t.autoSwitchThresholdOverride,hintText:m(`pws.anthropicAccountThresholdHint`),disabled:c||!!o||!!s,onChange:n=>u.onAccountThreshold(e.name,t,n)}),(0,Q.jsx)(Hs,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})]})]},t.id)})}),ae&&(0,Q.jsx)(Zd,{accountId:ae.id,accountLabel:Vs(r,ae,m),entry:X.entries[ae.id],controller:X,onClose:()=>oe(null)}),me&&(0,Q.jsx)(xf,{accountId:me.id,accountLabel:Vs(r,me,m),entry:ue.entries[me.id],controller:ue,onClose:()=>he(null)},`${t}:${e.name}:${me.id}`),a===`ready`&&ye&&r.length===0&&(0,Q.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:m(`pws.noAccounts`)}),ye&&(0,Q.jsxs)(`div`,{className:`pwi-auth-actions`,children:[(0,Q.jsx)(`button`,{ref:e.name===`kiro`?b:void 0,type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x(!0),disabled:c||!!o||e.name===`kiro`&&!!_,children:m(`pws.addAccount`)}),Ce&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ee||c||!!o,onClick:()=>{ge()},children:[(0,Q.jsx)(re,{width:14,height:14,"aria-hidden":`true`}),` `,m(ee?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),e.name===`kiro`&&_&&(0,Q.jsx)(vp,{apiBase:t,triggerRef:_.addAccount?b:y,addAccount:_.addAccount,busy:c,onClose:()=>v(null),onCli:t=>{u.onLogin(e.name,t)},onSettled:u.onNativeLoginSettled}),Y&&(0,Q.jsxs)(Q.Fragment,{children:[i.length>0&&(0,Q.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,Q.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void u.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,Q.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,m(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:m(`prov.accountActive`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void u.onEditAlias(e.name,`api-key`,t.id,t.label),children:m(`prov.editAlias`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${m(`common.remove`)} — ${t.label??t.masked}`,title:`${m(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void u.onRemoveApiKey(e.name,t),children:(0,Q.jsx)(F,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:(0,Q.jsx)(Hs,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})})]},t.id))}),h?(0,Q.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Q.jsx)(`input`,{className:`input`,type:`password`,value:S,onChange:e=>C(e.target.value),placeholder:m(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:w}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void we(),disabled:w||!S.trim(),children:m(w?`pws.saving`:`pws.addKey`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g(!1),C(``)},children:m(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>g(!0),children:m(`pws.addKey`)})]})]})]})}function jp(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 Mp(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 Np(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}function Pp(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 Fp=`https://chatgpt.com/backend-api/codex`;function Ip(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 Lp(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 Rp(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Ip(e.baseUrl)!==Fp?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function zp(e){return e.id===`openai`}function Bp(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Vp(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),Pp(e)&&e.preserveResponsesReasoningContent===!0&&(t.preserveResponsesReasoningContent=!0),t}function Hp(e,t){return zp(e)?Up(e):{name:t.name.trim(),provider:Vp(t)}}function Up(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Wp=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function Gp(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 Wp(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Wp(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Wp(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Up(i))})).ok)throw new Wp(`codexAuth.enableOpenaiFailed`)}function Kp({checked:e,onChange:t}){let n=O();return(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Q.jsx)(`input`,{name:`preserveResponsesReasoningContent`,type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:n(`pws.responsesReasoningReplay`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:n(`pws.responsesReasoningReplayHint`)})]})]})}var qp=[`responses`,`chat`,`messages`],Jp=[`responses`,`chat`,`messages`,`other`],Yp=[`responses`,`chat`,`messages`,`other`,`ir`,`responses-internal`],Xp=[`native`,`translated`,`legacy-bridge`,`blocked`],Zp=[`preserved`,`degraded`,`unknown`],Qp=[`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`],$p=new Set(qp),em=new Set(Jp),tm=new Set(Yp),nm=new Set(Xp),rm=new Set(Zp),im=new Set(Qp);function am(e){return typeof e==`string`&&$p.has(e)}function om(e){return typeof e==`string`&&em.has(e)}function sm(e){return typeof e==`string`&&tm.has(e)}function cm(e){return typeof e==`string`&&nm.has(e)}function lm(e){return typeof e==`string`&&rm.has(e)}function um(e){return typeof e==`string`&&im.has(e)}function dm(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic-messages`:return`messages`;default:return}}function fm(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic`:return`messages`;default:return`other`}}var pm=[`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`],mm=new Set(pm);function hm(e){return typeof e==`string`&&mm.has(e)}var gm={"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`]},_m={pathHops:6,reasonCodes:8,featureEffects:24,candidates:16,attempts:16,identifierLength:200},vm=[`hard-pin`,`operator`,`registry`,`provider-default`];function ym(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var bm=new Set([`passthrough`,`translated`,`degraded`,`unsupported`]);function xm(e,t,n){return Array.isArray(e)&&e.length<=t&&e.every(n)}function Sm(e){return typeof e==`string`&&e.length>0&&e.length<=_m.identifierLength&&!/[\u0000-\u001f\u007f]/.test(e)}function Cm(e){return ym(e)&&hm(e.feature)&&typeof e.disposition==`string`&&bm.has(e.disposition)}function wm(e){return xm(e,_m.pathHops,sm)&&e.length>0}function Tm(e){return xm(e,_m.reasonCodes,um)}function Em(e){return xm(e,_m.featureEffects,hm)}function Dm(e){return ym(e)&&Sm(e.provider)&&Sm(e.model)&&Sm(e.adapter)&&om(e.upstream)&&cm(e.mode)&&(e.mode===`blocked`?Array.isArray(e.requestPath):wm(e.requestPath))&&(e.mode===`blocked`?Array.isArray(e.responsePath):wm(e.responsePath))&&lm(e.fidelity)&&Tm(e.reasonCodes)&&xm(e.featureEffects,_m.featureEffects,Cm)&&Em(e.unknownFeatures)&&typeof e.eligible==`boolean`}function Om(e){return ym(e)&&e.schemaVersion===1&&(e.basis===`preview`||e.basis===`dispatch`)&&typeof e.contractVersion==`string`&&typeof e.policyRevision==`string`&&am(e.inbound)&&Sm(e.requestedModel)&&(e.routeKind===`direct`||e.routeKind===`combo`||e.routeKind===`policy`||e.routeKind===`unknown`)&&cm(e.mode)&&Tm(e.reasonCodes)&&xm(e.candidates,_m.candidates,Dm)&&Em(e.guaranteedFeatures)&&Em(e.partialFeatures)}function km(e){return ym(e)&&typeof e.ordinal==`number`&&Number.isInteger(e.ordinal)&&e.ordinal>0&&om(e.upstream)&&cm(e.mode)&&e.mode!==`blocked`&&wm(e.requestPath)&&(e.responsePath===void 0||wm(e.responsePath))}function Am(e){return!(!ym(e)||e.v!==1||!am(e.inbound)||!cm(e.mode)||e.upstream!==void 0&&!om(e.upstream)||!(e.mode===`blocked`?Array.isArray(e.requestPath)&&e.requestPath.length===0&&Array.isArray(e.responsePath)&&e.responsePath.length===0:wm(e.requestPath)&&wm(e.responsePath))||!Tm(e.reasonCodes)||typeof e.contractVersion!=`string`||e.featureEffects!==void 0&&!xm(e.featureEffects,_m.featureEffects,Cm)||e.attempts!==void 0&&!xm(e.attempts,_m.attempts,km)||e.planMismatch!==void 0&&e.planMismatch!==!0)}function jm(e){if(Am(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 Mm=new Set(vm);function Nm(e){return typeof e==`string`&&Mm.has(e)}function Pm(e){return ym(e)&&Sm(e.model)&&Sm(e.adapter)&&Nm(e.source)}function Fm(e){return ym(e)&&Sm(e.name)&&Sm(e.adapter)&&Nm(e.adapterSource)&&(e.authMode===null||Sm(e.authMode))&&om(e.upstream)&&xm(e.modelOverrides,64,Pm)&&(e.modelOverridesTruncated===void 0||e.modelOverridesTruncated===!0)}var Im=32,Lm=new Map;function Rm(e,t,n){return JSON.stringify([e,t.model,t.inbound,[...new Set(t.features)].sort(),n])}function zm(e,t){for(Lm.delete(e),Lm.set(e,t);Lm.size>Im;){let e=Lm.keys().next().value;if(e===void 0)break;Lm.delete(e)}}function Bm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Vm(e){if(!Bm(e)||e.schemaVersion!==1||typeof e.policyRevision!=`string`||!Array.isArray(e.features)||!e.features.every(hm)||!Bm(e.surfaces))return null;let t={};for(let[n,r]of Object.entries(e.surfaces)){if(!am(n)||!Bm(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 Hm(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=Vm(await n.json());if(!r)throw Error(`invalid protocol info`);return r}async function Um(e,t,n){try{let r=await Hm(e,n);if(!r)return{kind:`unavailable`};let i=Rm(e,t,r.policyRevision),a=Lm.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 Om(s)?(zm(Rm(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 Wm(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=Bm(i)&&Bm(i.error)&&typeof i.error.code==`string`?i.error.code:void 0;return e?{kind:`error`,code:e}:{kind:`error`}}let a=Vm(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 Gm(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!Bm(i)||i.provider===void 0?{kind:`unavailable`}:!Fm(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 Km={native:`logs.protocol.mode.native`,translated:`logs.protocol.mode.translated`,"legacy-bridge":`logs.protocol.mode.legacyBridge`,blocked:`logs.protocol.mode.blocked`},qm={passthrough:`logs.protocol.disposition.passthrough`,translated:`logs.protocol.disposition.translated`,degraded:`logs.protocol.disposition.degraded`,unsupported:`logs.protocol.disposition.unsupported`},Jm={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`},Ym=` → `;function Xm(e,t){return t(Jm[e])}function Zm(e,t){return e.map(e=>Xm(e,t)).join(Ym)}function Qm(e,t){let n=Xm(e.inbound,t);if(e.mode===`blocked`)return n;let r=e.upstream??e.requestPath[e.requestPath.length-1];return r?`${n}${Ym}${Xm(r,t)}`:n}var $m={"hard-pin":`pws.protocol.source.hardPin`,operator:`pws.protocol.source.operator`,registry:`pws.protocol.source.registry`,"provider-default":`pws.protocol.source.providerDefault`};function eh({adapter:e}){let t=O();return(0,Q.jsxs)(`span`,{className:`ppp-wire`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{className:`muted`,children:Xm(fm(e),t)})]})}function th({apiBase:e,providerName:t,savedAdapter:n,draftAdapter:r,refreshKey:i}){let a=O(),o=JSON.stringify([e??``,t,n,i??``]),[s,c]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{if(e===void 0)return;let n=new AbortController;return Gm(e,t,n.signal).then(e=>{n.signal.aborted||c(e.kind===`summary`?{key:o,kind:`summary`,summary:e.summary}:{key:o,kind:e.kind===`unavailable`?`hidden`:`error`})}).catch(()=>{}),()=>n.abort()},[e,t,o]);let l=s?.key===o?s:null;if(e===void 0||!l||l.kind===`hidden`)return null;let u=r&&r!==n?r:null;return(0,Q.jsxs)(`section`,{className:`ppp-card`,"aria-labelledby":`ppp-title`,"data-testid":`provider-protocol-panel`,children:[(0,Q.jsx)(`h3`,{id:`ppp-title`,children:a(`pws.protocol.title`)}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:a(`pws.protocol.note`)}),l.kind===`error`?(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:a(`pws.protocol.loadFailed`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dl`,{className:`ppp-kv`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`pws.protocol.adapterLabel`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(eh,{adapter:l.summary.adapter})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`pws.protocol.source`)}),(0,Q.jsx)(`dd`,{"data-adapter-source":l.summary.adapterSource,children:a($m[l.summary.adapterSource])})]}),l.summary.authMode&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`pws.authMode`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:l.summary.authMode})})]})]}),u&&(0,Q.jsx)(`p`,{className:`ppp-pending`,role:`status`,children:a(`pws.protocol.pending`,{adapter:u})}),(0,Q.jsx)(`h4`,{children:a(`pws.protocol.overrides`)}),l.summary.modelOverrides.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:a(`pws.protocol.noOverrides`)}):(0,Q.jsxs)(`table`,{className:`ppp-overrides`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.model`)}),(0,Q.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.wire`)}),(0,Q.jsx)(`th`,{scope:`col`,children:a(`pws.protocol.col.source`)})]})}),(0,Q.jsx)(`tbody`,{children:l.summary.modelOverrides.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.model})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(eh,{adapter:e.adapter})}),(0,Q.jsx)(`td`,{"data-adapter-source":e.source,children:a($m[e.source])})]},e.model))})]}),l.summary.modelOverridesTruncated&&(0,Q.jsx)(`p`,{className:`muted small`,children:a(`pws.protocol.overridesTruncated`,{count:l.summary.modelOverrides.length})})]})]})}var nh=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],rh=[];function ih(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function ah(e){return e===void 0?``:String(e)}function oh(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function sh(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function ch(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,t])}function lh({item:e,availableModels:t=rh,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=O(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),c=ge(e.name,e),l=c?e.liveModels!==!1:!1,u=ih(e.upstreamHttpVersion),[d,f]=(0,Z.useState)(e.adapter),[p,m]=(0,Z.useState)(e.baseUrl),[h,g]=(0,Z.useState)(e.defaultModel??``),[_,v]=(0,Z.useState)(s),[y,b]=(0,Z.useState)(e.apiKeyTransport??`x-api-key`),[x,S]=(0,Z.useState)(e.note??``),[C,w]=(0,Z.useState)(e.allowPrivateNetwork??!1),[T,E]=(0,Z.useState)(e.preserveResponsesReasoningContent===!0),[D,k]=(0,Z.useState)(l),[j,M]=(0,Z.useState)(u),[N,P]=(0,Z.useState)(!1),[F,I]=(0,Z.useState)(null),[L,z]=(0,Z.useState)(e.codexAccountMode??`pool`),[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(null),[W,G]=(0,Z.useState)(),[ee,K]=(0,Z.useState)(n?`loading`:`idle`),[q,te]=(0,Z.useState)(()=>`custom`),[ne,J]=(0,Z.useState)(e.requestPacing?.enabled===!0),[Y,re]=(0,Z.useState)(()=>ah(e.requestPacing?.requestsPerMinute)),[ie,X]=(0,Z.useState)(()=>ah(e.requestPacing?.minIntervalMs)),[ae,oe]=(0,Z.useState)(()=>ah(e.requestPacing?.maxConcurrentRequests)),[se,ce]=(0,Z.useState)(()=>({...e.requestPacing?.models??{}})),[le,ue]=(0,Z.useState)(``),[de,fe]=(0,Z.useState)(``),[pe,me]=(0,Z.useState)(``),[he,_e]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),v(String(e.authMode??(e.keyOptional?`local`:`key`))),b(e.apiKeyTransport??`x-api-key`),S(e.note??``),w(e.allowPrivateNetwork??!1),E(e.preserveResponsesReasoningContent===!0),k(l),M(u),J(e.requestPacing?.enabled===!0),re(ah(e.requestPacing?.requestsPerMinute)),X(ah(e.requestPacing?.minIntervalMs)),oe(ah(e.requestPacing?.maxConcurrentRequests)),ce({...e.requestPacing?.models??{}}),I(null),U(null),queueMicrotask(()=>te(Mp(W,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,e.preserveResponsesReasoningContent,l,u,e.requestPacing,W]),(0,Z.useEffect)(()=>{z(e.codexAccountMode??`pool`)},[e.codexAccountMode]),(0,Z.useEffect)(()=>{if(!n)return;let t=!1,r=e.name,i=e.baseUrl;return fetch(`${n}/api/provider-presets`).then(e=>gn(e)).then(e=>{if(t)return;if(!e){G(void 0),K(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;G(n),K(`ready`),te(Mp(n,i))}).catch(()=>{t||(G(void 0),K(`error`))}),()=>{t=!0}},[n,e.name]),(0,Z.useEffect)(()=>{if(!n)return;let t=!0,r=!1,i=()=>{if(r)return;r=!0;let i=A(1e4);fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`,{signal:i.signal}).then(e=>gn(e)).then(e=>{t&&e&&ye(e)}).catch(()=>void 0).finally(()=>{i.clear(),r=!1})};i();let a=sa(i,2e3);return()=>{t=!1,a()}},[n,e.name]);let be=(0,Z.useMemo)(()=>({enabled:ne,...oh(Y)===void 0?{}:{requestsPerMinute:oh(Y)},...sh(ie)===void 0?{}:{minIntervalMs:sh(ie)},...sh(ae)===void 0?{}:{maxConcurrentRequests:sh(ae)},...Object.keys(se).length>0?{models:se}:{}}),[ae,ie,ne,se,Y]),xe=!Se(e.name)&&Pp({adapter:d,baseUrl:p,authMode:_}),Ce=xe&&T!==(e.preserveResponsesReasoningContent===!0),we=Ce||d.trim()!==e.adapter||p.trim()!==e.baseUrl||h.trim()!==(e.defaultModel??``)||_!==String(e.authMode??(e.keyOptional?`local`:`key`))||d.trim()===`anthropic`&&_===`key`&&y!==(e.apiKeyTransport??`x-api-key`)||x.trim()!==(e.note??``)||C!==(e.allowPrivateNetwork??!1)||D!==l||d.trim()===`cursor`&&j!==u,Te=ch(be)!==ch(e.requestPacing),Ee=we||Te;(0,Z.useEffect)(()=>(i?.(Ee),()=>i?.(!1)),[Ee,i]);let De=(0,Z.useMemo)(()=>{let n=new Set(t);return h.trim()&&n.add(h.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,h,e.defaultModel]),Oe=(0,Z.useMemo)(()=>{let e=[...nh];return d&&!e.includes(d)&&e.unshift(d),e},[d]),ke=Se(e.name),Ae=ee===`ready`&&!!(W&&W.length>0),je=d.trim()===`anthropic`&&_===`key`,Me=e.name===`openai`?Rp(e):`invalid`,Ne=Me===`ready`||Me===`disabled`,Pe=ke&&ee!==`error`,Fe=async()=>{if(!r)return I({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;if(B)return!1;let t=Ae?Np(W,q,p):p.trim();if(!d.trim()||!t)return I({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;P(!0),I(null);try{if(ae.trim()!==``&&sh(ae)===void 0)return I({ok:!1,text:o(`pws.pacingCapInvalid`)}),!1;if(ne&&!be.requestsPerMinute&&!be.minIntervalMs&&!be.maxConcurrentRequests&&!be.models)return I({ok:!1,text:o(`pws.pacingRuleRequired`)}),!1;let n=Te&&!we,i=n?{requestPacing:be}:{adapter:d.trim(),baseUrl:t,defaultModel:h.trim(),authMode:_,note:x.trim(),allowPrivateNetwork:C,...Te?{requestPacing:be}:{}};n||(c&&D!==(e.liveModels!==!1)&&(i.liveModels=D),Ce&&(i.preserveResponsesReasoningContent=T),d.trim()===`cursor`&&j!==u&&(i.upstreamHttpVersion=j===`http1.1`?`http1.1`:null),je?i.apiKeyTransport=y:e.apiKeyTransport!==void 0&&(i.apiKeyTransport=``));let a=await r(e.name,i);return I(a.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:a.error||o(`prov.saveFailed`)}),a.ok}finally{P(!1)}},Ie=(0,Z.useRef)(Fe);(0,Z.useEffect)(()=>{Ie.current=Fe}),(0,Z.useEffect)(()=>{if(a)return a(()=>Ie.current()),()=>a(null)},[a]);let Le=async e=>{if(!(B||N||e===L)){if(!r){U({ok:!1,text:o(`pws.updatesUnavailable`)});return}V(!0),U(null);try{let t=await r(`openai`,{codexAccountMode:e});t.ok?(z(e),U({ok:!0,text:o(`pws.accountModeSaved`)})):U({ok:!1,text:t.error||o(`pws.accountModeFailed`)})}catch{U({ok:!1,text:o(`pws.accountModeFailed`)})}finally{V(!1)}}},Re=async(e,t)=>{if(await na({message:o(`pws.accountModeConfirm`)})){await Le(e);return}t.value=L},ze=()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),v(s),b(e.apiKeyTransport??`x-api-key`),S(e.note??``),w(e.allowPrivateNetwork??!1),k(l),E(e.preserveResponsesReasoningContent===!0),M(u),I(null),J(e.requestPacing?.enabled===!0),re(ah(e.requestPacing?.requestsPerMinute)),X(ah(e.requestPacing?.minIntervalMs)),oe(ah(e.requestPacing?.maxConcurrentRequests)),ce({...e.requestPacing?.models??{}}),te(Mp(W,e.baseUrl))},Be=(e,t)=>{switch(e){case`token-plan`:return o(`modal.endpoint.tokenPlan`);case`payg`:return o(`modal.endpoint.payAsYouGo`);case`custom`:return o(`modal.endpoint.custom`);default:return t}};return(0,Q.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,Q.jsx)(at,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,Q.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),ke?(0,Q.jsx)(`input`,{className:`input`,value:d,readOnly:!0,disabled:!0}):(0,Q.jsx)(`select`,{className:`input`,value:d,onChange:e=>f(e.target.value),children:Oe.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})]}),(0,Q.jsx)(th,{apiBase:n,providerName:e.name,savedAdapter:e.adapter,draftAdapter:d.trim(),refreshKey:`${e.baseUrl}|${e.authMode??``}`}),Ae?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,Q.jsx)(`select`,{className:`input`,value:q,onChange:e=>{let t=e.target.value;te(t),m(jp(W,t,p))},children:W.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:Be(e.id,e.label)},e.id))})]}),q===`custom`&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,Q.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,Q.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),readOnly:Pe,disabled:Pe})]}),d.trim()===`cursor`&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cursorTransport`)}),(0,Q.jsxs)(`select`,{className:`input`,value:j,onChange:e=>M(e.target.value),children:[(0,Q.jsx)(`option`,{value:`http2`,children:o(`pws.cursorTransportHttp2`)}),(0,Q.jsx)(`option`,{value:`http1.1`,children:o(`pws.cursorTransportHttp1`)})]}),(0,Q.jsx)(`span`,{className:`pwi-settings-hint`,children:o(`pws.cursorTransportDesc`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),De.length>0?(0,Q.jsxs)(`select`,{className:`input`,value:h,onChange:e=>g(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),De.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}):(0,Q.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),ke?(0,Q.jsx)(`input`,{className:`input`,value:R(e,o),readOnly:!0,disabled:!0}):(0,Q.jsxs)(`select`,{className:`input`,value:_,onChange:e=>v(e.target.value),children:[(0,Q.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,Q.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,Q.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,Q.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),Ne&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`codexAuth.accountModeTitle`)}),(0,Q.jsxs)(`select`,{className:`input`,value:L,disabled:B||N,onChange:e=>{let t=e.target.value;t!==L&&Re(t,e.currentTarget)},children:[(0,Q.jsx)(`option`,{value:`pool`,children:o(`codexAuth.accountModePool`)}),(0,Q.jsx)(`option`,{value:`direct`,children:o(`codexAuth.accountModeDirect`)})]}),(0,Q.jsx)(`span`,{className:`pwi-settings-hint`,children:o(L===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),B&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:o(`pws.accountSwitching`)}),H&&(0,Q.jsx)(`span`,{role:H.ok?`status`:`alert`,className:H.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:H.text})]}),je&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,Q.jsxs)(`select`,{className:`input`,value:y,onChange:e=>b(e.target.value),children:[(0,Q.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,Q.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,Q.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:x,onChange:e=>S(e.target.value),rows:2})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),xe&&(0,Q.jsx)(Kp,{checked:T,onChange:E}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:D,disabled:!c,onChange:e=>k(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),(0,Q.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,Q.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`pwi-pacing-title`,children:o(`pws.pacingTitle`)}),(0,Q.jsx)(`p`,{children:o(`pws.pacingDesc`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:ne,onChange:e=>J(e.target.checked)}),` `,o(`pws.pacingEnabled`)]})]}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:Y,onChange:e=>re(e.target.value),placeholder:`38`})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ie,onChange:e=>X(e.target.value),placeholder:`1600`})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingConcurrency`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ae,onChange:e=>oe(e.target.value),placeholder:`8`})]})]}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.pacingSlowerWins`)}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:ve?.queued??0}),` `,o(`pws.pacingQueued`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[ve?.nextSlotInMs??0,` ms`]}),` `,o(`pws.pacingNextSlot`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:ve?.lastModelId??o(`pws.pacingNone`)}),` `,o(`pws.pacingLastModel`)]})]}),(0,Q.jsx)(`h4`,{children:o(`pws.pacingModelOverrides`)}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingModel`)}),(0,Q.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:le,onChange:e=>ue(e.target.value)}),(0,Q.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,Q.jsx)(`option`,{value:e},e))})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:de,onChange:e=>fe(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:pe,onChange:e=>me(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingConcurrency`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:he,onChange:e=>_e(e.target.value)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=le.trim(),t=oh(de),n=sh(pe),r=sh(he);if(he.trim()!==``&&r===void 0){I({ok:!1,text:o(`pws.pacingCapInvalid`)});return}!e||t===void 0&&n===void 0&&r===void 0||(ce(i=>({...i,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n},...r===void 0?{}:{maxConcurrentRequests:r}}})),ue(``),fe(``),me(``),_e(``))},children:o(`pws.pacingAdd`)})]}),Object.entries(se).length>0&&(0,Q.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(se).map(([e,t])=>(0,Q.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{children:[t.requestsPerMinute===void 0?void 0:`${t.requestsPerMinute} ${o(`pws.pacingRpmUnit`)}`,t.minIntervalMs===void 0?void 0:`${t.minIntervalMs} ms`,t.maxConcurrentRequests===void 0?void 0:`${t.maxConcurrentRequests} ${o(`pws.pacingCapUnit`)}`].filter(e=>e!==void 0).join(` · `)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ce(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":o(`pws.pacingRemoveModel`,{model:e}),children:o(`pws.pacingRemove`)})]},e))})]}),Ee&&(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ze,disabled:N,children:o(`pws.discardSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Fe(),disabled:N||B,children:o(N?`pws.saving`:`pws.saveSettings`)})]})]}),F&&(0,Q.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 uh({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=O();return(0,Q.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,Q.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,Q.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function dh({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=O();return(0,Q.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,Q.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,Q.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function fh({item:e,preset:t,usageTotals:n,modelUsage:r,quotaReport:i,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:c,modelRevision:l,modelRowsReady:u,onOpenModels:d,onCreateJevAuto:f,modelsLoading:p,modelsLoadFailed:m,onRetryModels:h,oauthEmail:g,onDeselect:_,apiBase:v,oauth:y,accounts:b,accountLoadState:x,accountsFocusToken:S=0,accountsFocusProvider:C=null,settingsFocusToken:w=0,settingsFocusProvider:T=null,switchingAccountId:E,pausingAccountId:D,keys:k,busyProvider:A,loginHint:j,authHandlers:M,onCodexActiveNeedsReauthChange:N,codexController:P,onUpdateProvider:I,isDefault:L,onRemoveProvider:R,onSetDisabled:z,onSetDefault:B,onRefreshQuota:V}){let U=O(),[W,ee]=(0,Z.useState)(`overview`),[K,q]=(0,Z.useState)(!1),[te,ne]=(0,Z.useState)(null),[J,Y]=(0,Z.useState)(!1),re=(0,Z.useRef)(null),[ie,X]=(0,Z.useState)(0),[ae,oe]=(0,Z.useState)(0),se=(0,Z.useCallback)(e=>{re.current=e},[]),ce=e.disabled===!0,le=(0,Z.useMemo)(()=>G(e),[e]),ue=(0,Z.useMemo)(()=>H(e),[e]),de=(0,Z.useMemo)(()=>Bs(e),[e]),fe=de===`oauth-accounts`?b?.find(e=>e.active):de===`api-keys`?k?.find(e=>e.active):void 0,pe=C===e.name?S:0,he=JSON.stringify([P?.activeId??``,b?.find(e=>e.active)?.id??``,k?.find(e=>e.active)?.id??``,y?.loggedIn===void 0?``:String(y.loggedIn),y?.needsReauth===void 0?``:String(y.needsReauth),g??``]),ge=(0,Z.useMemo)(()=>[{id:`overview`,label:U(`pws.tab.overview`)},{id:`models`,label:U(`pws.tab.models`)},{id:`usage`,label:U(`pws.tab.usage`)},...de?[{id:`accounts`,label:U(de===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:U(`pws.tab.settings`)}],[de,U]),_e=(0,Z.useCallback)(e=>{if(K&&W===`settings`&&e!==`settings`){ne(e);return}ee(e)},[W,K]);pe!==ie&&!(pe&&!de)&&(X(pe),pe&&de&&(K&&W===`settings`?ne(`accounts`):ee(`accounts`)));let ve=T===e.name?w:0;ve!==ae&&(oe(ve),ve&&ee(`settings`));let ye=(0,Z.useCallback)(()=>{if(K&&W===`settings`){ne(`deselect`);return}_()},[K,W,_]),xe=(0,Z.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%ge.length;else if(e.key===`ArrowLeft`)n=(t-1+ge.length)%ge.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=ge.length-1;else return;e.preventDefault(),_e(ge[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[_e,ge]),Se=`pws-tab-${W}`,Ce=`pws-panel-${W}`;return(0,Q.jsxs)(`div`,{className:`pws-detail`,children:[(0,Q.jsx)(`div`,{className:`pws-detail-head`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:ye,children:[(0,Q.jsx)(Ke,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),U(`pws.allProviders`)]})}),(0,Q.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,Q.jsx)(me,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,Q.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,Q.jsxs)(`h2`,{className:`pws-detail-title`,children:[be(e.name,U),ue&&(0,Q.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:U(`modal.badge.local`)}),!ue&&le&&(0,Q.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:U(`modal.badge.free`)})]})}),(0,Q.jsxs)(`div`,{className:`pws-detail-actions`,children:[!L&&!ce&&B&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>B(e.name),children:U(`prov.setDefault`)}),R&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>R(e.name),"aria-label":U(`pws.removeConfirmTitle`),title:U(`pws.removeConfirmTitle`),children:(0,Q.jsx)(F,{style:{width:15,height:15},"aria-hidden":`true`})}),z&&(0,Q.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,Q.jsx)(`span`,{className:`pws-detail-toggle-label`,children:U(`pws.enabledLabel`)}),(0,Q.jsx)(on,{on:!ce,onClick:()=>z(e.name,!ce),disabled:L,label:U(`pws.enabledLabel`)})]})]})]}),(0,Q.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:ge.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":W===e.id,tabIndex:W===e.id?0:-1,className:`pws-detail-tab${W===e.id?` pws-detail-tab--active`:``}`,onClick:()=>_e(e.id),onKeyDown:e=>xe(e,t),children:e.label},e.id))}),(0,Q.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:Ce,"aria-labelledby":Se,tabIndex:0,children:[W===`overview`&&(0,Q.jsx)(sc,{item:e,preset:t,apiBase:v,connectionIdentity:he,usageTotals:n,quotaReport:i,currentQuotaReading:fe,onRefreshQuota:V,oauthEmail:g,oauth:y,onEditSettings:()=>_e(`settings`),onViewUsage:()=>_e(`usage`),onCreateJevAuto:f,onUpdateProvider:I,reauthBusy:A===e.name,onCancelLogin:M?.onCancelLogin?()=>void M.onCancelLogin?.(e.name):void 0,onReauthenticate:e.activeNeedsReauth?()=>{if(e.authMode===`oauth`){let t=b??[],n=t.find(e=>e.active&&e.needsReauth)??t.find(e=>e.needsReauth);M?.onReauth(e.name,n?.id);return}_e(`accounts`)}:void 0}),W===`models`&&(0,Q.jsx)(Nc,{item:e,apiBase:v,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:c,modelRevision:l,modelRowsReady:u,onOpenModels:d,modelsLoading:p,modelsLoadFailed:m,needsReauth:(b??[]).some(e=>e.active&&e.needsReauth)||y?.needsReauth===!0,onRetryModels:h,onOpenAccounts:de?()=>_e(`accounts`):void 0},e.name),W===`usage`&&(0,Q.jsx)(Fc,{item:e,usageTotals:n,quotaReport:i,currentQuotaReading:fe,quotaIdentity:he,modelUsage:r,...V?{onRefreshQuota:V}:{}}),W===`accounts`&&(0,Q.jsx)(Ap,{item:e,apiBase:v,oauth:y,accounts:b,keys:k,accountLoadState:x,switchingAccountId:E,pausingAccountId:D,busy:A===e.name,loginHint:j,authHandlers:M,onUpdateProvider:I,onCodexActiveNeedsReauthChange:N,codexController:P}),W===`settings`&&(0,Q.jsx)(lh,{item:e,apiBase:v,availableModels:a,onUpdateProvider:I,onDirtyChange:q,onRegisterSave:se},e.name)]}),te&&(0,Q.jsx)(dh,{saving:J,onCancel:()=>{J||ne(null)},onDiscard:()=>{if(J)return;let e=te;ne(null),q(!1),e===`deselect`?_():ee(e)},onSave:()=>{(async()=>{if(!J){Y(!0);try{if(!(await re.current?.()??!1))return;let e=te;ne(null),q(!1),e===`deselect`?_():e&&ee(e)}finally{Y(!1)}}})()}})]})}var ph=new Set([`anthropic`,`anthropic2`,`google-antigravity`,`meta-muse`]),mh=new Set([`github-copilot`,`cursor`,`zed`]);function hh(e){let t=e.trim().toLowerCase();return ph.has(t)?`high`:mh.has(t)?`elevated`:null}function gh(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function _h(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function vh(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:gh(t),body:_h(t),conditions:null,saferPath:n===`google-antigravity`?`oauthTos.saferPath`:null,acknowledge:`oauthTos.acknowledge`,continue:`oauthTos.continue`}}function yh(e,t){return t===void 0?e:e.map(e=>({...e,active:e.id===t}))}function bh(e,t){let n=new Map(t.map(e=>[e.id,e]));return Ch(e,t,!1).map(e=>Sh(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?jr(n.get(e.id)?.quotaFailure):void 0}:e)}function xh(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=Ch([t],[e],!0)[0];return{...e,quota:r.quota,quotaPending:r.quotaPending,quotaUnavailable:r.quotaUnavailable,quotaFailure:r.quotaFailure}})}var Sh=e=>e.quotaMode===`probe`||e.quotaMode===`passive`;function Ch(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=Sh(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?jr(e.quotaFailure):void 0}})}function wh(e,t){let n=t&&new Map(t.map(e=>[e.id,e.quotaMode]));return e.map(e=>Sh(e)&&(!n||n.get(e.id)===e.quotaMode)?{...e,quotaUnavailable:!0,quotaPending:!1,quotaFailure:void 0}:e)}function Th(e,t=!1){let n={};for(let[t,r]of Object.entries(e))Kc(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function Eh(e){let{apiBase:t,t:n,config:r,aliveRef:i,notify:a,fetchConfig:o,fetchOauth:s,fetchProviderQuotas:c,codexActiveNeedsReauth:l}=e,[u,d]=(0,Z.useState)({}),[f,p]=(0,Z.useState)({}),[m,h]=(0,Z.useState)({}),g=Object.values(m)[0]??null,_=e=>h(e?{[e.provider]:e}:{}),[v,y]=(0,Z.useState)({}),b=Object.values(v)[0]??null,[x,S]=(0,Z.useState)({}),[C,w]=(0,Z.useState)({}),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(``),k=(0,Z.useRef)({}),j=(0,Z.useRef)({}),M=(0,Z.useRef)({}),N=(0,Z.useRef)(new Map),P=(0,Z.useRef)(new Set),F=(0,Z.useRef)(new Map),I=(0,Z.useRef)(new Map),L=(0,Z.useRef)(!0),R=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{let e=k.current,n=P.current,r=j.current,i=M.current,a=N.current,o=F.current,s=I.current;L.current=!0;let c=R.current!==t;return R.current=t,c&&Promise.resolve().then(()=>{!L.current||R.current!==t||(d({}),y({}),h({}),w({}),p({}))}),()=>{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 n)e.abort();n.clear()}},[t]);let z=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useCallback)(async(e,t)=>{let n=A(2e4),r=()=>n.controller.abort();t?.aborted&&r(),t?.addEventListener(`abort`,r,{once:!0}),P.current.add(n.controller);try{let t=await fetch(e,{signal:n.signal});if(!t.ok)throw Error(String(t.status));let r=await t.json();if(n.signal.aborted)throw Error(`Quota roster deadline exceeded`);return r}finally{n.clear(),t?.removeEventListener(`abort`,r),P.current.delete(n.controller)}},[]),H=(0,Z.useCallback)(async(e,n=!1)=>{if(!i.current||!L.current||R.current!==t)return!1;let r=[...new Set(e)];return p(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}`,a=(k.current[r]??0)+1;k.current[r]=a;let o=(j.current[r]??0)+1;j.current[r]=o;let s=()=>i.current&&L.current&&R.current===t&&k.current[r]===a,c=()=>s()&&j.current[r]===o,l=`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`;try{let a=await V(l);if(!Array.isArray(a.accounts))throw Error(`Invalid account roster`);if(!s())return!1;let o=yh(a.accounts,a.activeAccountId);if(d(t=>c()?{...t,[e]:{activeAccountId:a.activeAccountId??null,accounts:Ch(o,t[e]?.accounts??[],!1)}}:t),p(t=>c()?{...t,[e]:`ready`}:t),!o.some(Sh))return!0;let u=async()=>{let s=(M.current[r]??0)+1;M.current[r]=s;let u=()=>i.current&&L.current&&R.current===t&&M.current[r]===s;try{let t=await V(`${l}"a=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.accounts))throw Error(`Invalid account quota roster`);if(!u())return!1;let r=yh(t.accounts,t.activeAccountId);return d(n=>u()?c()?{...n,[e]:{activeAccountId:t.activeAccountId===void 0?a.activeAccountId??null:t.activeAccountId,accounts:Ch(r,n[e]?.accounts??[],!0)}}:{...n,[e]:{...n[e],accounts:xh(n[e]?.accounts??[],r)}}:n),!r.some(e=>e.quotaUnavailable===!0)}catch{return u()&&d(t=>u()&&t[e]?{...t,[e]:{...t[e],accounts:wh(t[e].accounts,o)}}:t),!1}};return n?await u():(u(),!0)}catch{return c()?(p(t=>c()?{...t,[e]:`error`}:t),d(t=>c()&&t[e]?{...t,[e]:{...t[e],accounts:wh(t[e].accounts)}}:t),!1):!1}}))).every(Boolean)},[i,t,V]),U=(0,Z.useCallback)(async(e,n=!1)=>!i.current||!L.current||R.current!==t?!1:(await Promise.all([...new Set(e)].map(async e=>{let r=`key:${e}`,a=(k.current[r]??0)+1;k.current[r]=a;let o=(j.current[r]??0)+1;j.current[r]=o;let s=()=>i.current&&L.current&&R.current===t&&k.current[r]===a,c=()=>s()&&j.current[r]===o,l=`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,u=()=>(c()&&w(t=>c()?{...t,[e]:wh(t[e]??[])}:t),!1);try{let a=await V(l);if(!Array.isArray(a.keys))throw Error(`Invalid key roster`);if(!s())return!1;let o=yh(a.keys,a.activeId);if(w(t=>c()?{...t,[e]:Ch(o,t[e]??[],!1)}:t),!o.some(Sh))return!0;let u=async()=>{let a=(M.current[r]??0)+1;M.current[r]=a;let s=()=>i.current&&L.current&&R.current===t&&M.current[r]===a;try{let t=await V(`${l}"a=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.keys))throw Error(`Invalid key quota roster`);if(!s())return!1;let r=yh(t.keys,t.activeId);return w(t=>s()?{...t,[e]:c()?Ch(r,t[e]??[],!0):xh(t[e]??[],r)}:t),!r.some(e=>e.quotaUnavailable===!0)}catch{return s()&&w(t=>s()?{...t,[e]:wh(t[e]??[],o)}:t),!1}};return n?await u():(u(),!0)}catch{return u()}}))).every(Boolean),[t,i,V]),W=(0,Z.useCallback)(async(e,n)=>{if(!i.current||!L.current||R.current!==t||n?.aborted)return!1;let a=e?[e]:Object.entries(r?.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(a.map(async({provider:e,kind:r})=>{let a=`${r===`oauth`?`oauth`:`key`}:${e}`;if(N.current.has(a))return!1;let o=(j.current[a]??0)+1;j.current[a]=o;let s=()=>i.current&&L.current&&R.current===t&&!n?.aborted&&j.current[a]===o&&!N.current.has(a);try{if(r===`oauth`){let r=await V(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.accounts)||!s())return!1;let i=yh(r.accounts,r.activeAccountId);d(t=>s()?{...t,[e]:{activeAccountId:r.activeAccountId===void 0?i.find(e=>e.active)?.id??null:r.activeAccountId,accounts:bh(i,t[e]?.accounts??[])}}:t),p(t=>s()?{...t,[e]:`ready`}:t)}else{let r=await V(`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.keys)||!s())return!1;let i=yh(r.keys,r.activeId);w(t=>s()?{...t,[e]:bh(i,t[e]??[])}:t)}return!0}catch{return!1}}))).every(Boolean)},[i,t,r,V]),G=(e,t)=>{let n=`${t===`oauth`?`oauth`:`key`}:${e}`;return k.current[n]=(k.current[n]??0)+1,j.current[n]=(j.current[n]??0)+1,n},ee=async(e,n)=>!i.current||!L.current||R.current!==t?!1:(G(e,`oauth`),d(t=>{let r=t[e];return r?{...t,[e]:{...r,accounts:r.accounts.map(e=>({...e,autoSwitchThreshold:n,effectiveAutoSwitchThreshold:typeof e.autoSwitchThresholdOverride==`number`?e.autoSwitchThresholdOverride:n}))}}:t}),H([e])),K=async(e,r)=>{if(r.active||r.needsReauth||r.paused||I.current.has(e)||F.current.has(e)||N.current.has(`oauth:${e}`))return;let o={provider:e,accountId:r.id};I.current.set(e,o),h(t=>({...t,[e]:o}));let l=G(e,`oauth`),f=Symbol();N.current.set(l,f);let p=()=>i.current&&L.current&&R.current===t&&N.current.get(l)===f,m=Vs(u[e]?.accounts??[r],r,n);try{let i=await fetch(`${t}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:r.id})});if(!p())return;if(!i.ok){a(n(`prov.accountSwitchFail`),!1);return}let o=await i.json().catch(()=>({}));if(!p())return;G(e,`oauth`);let u=o.activeAccountId===void 0?r.id:o.activeAccountId;d(t=>t[e]?{...t,[e]:{...t[e],activeAccountId:u,accounts:yh(t[e].accounts,u)}}:t),N.current.delete(l);let f=await W({provider:e,kind:`oauth`});if(await Promise.all([s(),c(!0)]),!f){a(n(`pws.accountsLoadFailed`),!1);return}a(n(`prov.accountSwitched`,{email:m}),!0)}catch{p()&&a(n(`prov.accountSwitchFail`),!1)}finally{p()&&(G(e,`oauth`),N.current.delete(l),W({provider:e,kind:`oauth`})),I.current.get(e)===o&&(I.current.delete(e),i.current&&h(t=>{let n={...t};return delete n[e],n}))}},q=async(e,r,o)=>{let s=`oauth:${e}`;if(I.current.has(e)||F.current.has(e)||N.current.has(s))return!1;let c=G(e,`oauth`),l=Symbol();N.current.set(c,l);let f=()=>i.current&&L.current&&R.current===t&&N.current.get(c)===l,p=Vs(u[e]?.accounts??[r],r,n);try{let n=A(2e4);P.current.add(n.controller);let i;try{let a=await fetch(`${t}/api/oauth/accounts/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:n.signal,body:JSON.stringify({provider:e,accountId:r.id,threshold:o})});if(!a.ok)throw Error(`account threshold write failed`);if(i=await a.json(),n.signal.aborted)throw Error(`account threshold deadline exceeded`)}finally{n.clear(),P.current.delete(n.controller)}let a=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100;if(!i||i.autoSwitchThresholdOverride!==null&&!a(i.autoSwitchThresholdOverride)||!a(i.autoSwitchThreshold)||!a(i.effectiveAutoSwitchThreshold))throw Error(`invalid threshold response`);return f()?(G(e,`oauth`),d(t=>{let n=t[e];return n?{...t,[e]:{...n,accounts:n.accounts.map(e=>e.id===r.id?{...e,autoSwitchThresholdOverride:i.autoSwitchThresholdOverride,autoSwitchThreshold:i.autoSwitchThreshold,effectiveAutoSwitchThreshold:i.effectiveAutoSwitchThreshold}:e)}}:t}),!0):!1}catch{return f()&&a(n(`accountPool.autoSwitchUpdateFailed`,{email:p}),!1),!1}finally{f()&&(G(e,`oauth`),N.current.delete(c),W({provider:e,kind:`oauth`}))}},te=async(e,r,o)=>{if(I.current.has(e)||F.current.has(e)||N.current.has(`oauth:${e}`))return;let l={provider:e,accountId:r.id};F.current.set(e,l),y(t=>({...t,[e]:{...l,paused:o}}));let f=G(e,`oauth`),p=Symbol();N.current.set(f,p);let m=()=>i.current&&L.current&&R.current===t&&N.current.get(f)===p,h=Vs(u[e]?.accounts??[r],r,n),g;try{let i=await fetch(`${t}/api/oauth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:r.id,paused:o})});if(!m())return;if(!i.ok){a(n(o?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:h}),!1);return}if(g=await i.json().catch(()=>({})),!m())return;G(e,`oauth`);let s=g.activeAccountId===void 0?u[e]?.activeAccountId??null:g.activeAccountId;d(t=>{let n=t[e];if(!n)return t;let i=n.accounts.map(e=>e.id===r.id?{...e,paused:o}:e);return{...t,[e]:{activeAccountId:s,accounts:yh(i,s)}}}),N.current.delete(f)}catch{m()&&a(n(o?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:h}),!1);return}finally{m()&&(G(e,`oauth`),N.current.delete(f),W({provider:e,kind:`oauth`})),F.current.get(e)===l&&(F.current.delete(e),i.current&&y(t=>{let n={...t};return delete n[e],n}))}if(!(!i.current||!L.current||R.current!==t)){a(n(o?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`,{email:h}),!0);try{let t=await W({provider:e,kind:`oauth`});g.activeAccountChanged&&await Promise.all([s(),c(!0)]),t||a(n(`pws.accountsLoadFailed`),!1)}catch{i.current&&L.current&&a(n(`pws.accountsLoadFailed`),!1)}}},ne=async(e,r)=>{if(r.active||N.current.has(`key:${e}`))return;let o=G(e,`api-key`),s=Symbol();N.current.set(o,s);let l=()=>i.current&&L.current&&R.current===t&&N.current.get(o)===s;try{let i=await fetch(`${t}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:r.id})});if(!l())return;if(!i.ok){let e=await i.json().catch(()=>({}));l()&&a(e.error||n(`prov.keySwitchFail`),!1);return}let o=await i.json().catch(()=>({}));if(!l())return;G(e,`api-key`);let s=o.activeId===void 0?r.id:o.activeId;w(t=>t[e]?{...t,[e]:yh(t[e],s)}:t),a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),c(!0)}catch{l()&&a(n(`prov.keySwitchFail`),!1)}finally{l()&&(G(e,`api-key`),N.current.delete(o),W({provider:e,kind:`api-key`}))}},J=async(e,r)=>{await na({message:n(`prov.keyRemoveConfirm`,{key:r.label??r.masked}),confirmLabel:n(`common.remove`),tone:`danger`})&&(await fetch(`${t}/api/providers/keys?name=${encodeURIComponent(e)}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok&&(a(n(`prov.keyRemoved`,{key:r.label??r.masked}),!0),U(Object.keys(C)),o(),c(!0))},Y=async(e,r)=>{let i=r.trim();if(!i)return!1;try{let r=await fetch(`${t}/api/providers/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,key:i})});if(!r.ok){let e=await r.json().catch(()=>({}));return a(e.error||n(`prov.keyAddFail`),!1),!1}return a(n(`prov.keyAdded`,{name:e}),!0),E(null),await Promise.all([U(Object.keys(C).includes(e)?Object.keys(C):[...Object.keys(C),e]),o(),c(!0)]),!0}catch{return a(n(`prov.keyAddFail`),!1),!1}},re=async e=>{await Y(e,D)&&O(``)},ie=async(e,r,i,o)=>{let s=await ra({message:n(`prov.aliasPrompt`),initialValue:o??``,maxLength:80,validate:e=>nl(e,n)});if(s===null)return;let c=s.trim(),l=await fetch(r===`oauth`?`${t}/api/oauth/accounts/alias`:`${t}/api/providers/keys/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r===`oauth`?{provider:e,accountId:i,alias:c}:{name:e,id:i,alias:c})});if(!l.ok){let e=await l.json().catch(()=>({}));a(e.error||n(`prov.aliasSaveFailed`),!1);return}r===`oauth`?await H([e]):await U(Object.keys(C).includes(e)?Object.keys(C):[...Object.keys(C),e]),a(n(`prov.aliasSaved`),!0)},X=async(e,r)=>{let i=Vs(u[e]?.accounts??[r],r,n);if(await na({message:n(`prov.accountRemoveConfirm`,{email:i}),confirmLabel:n(`common.remove`),tone:`danger`}))try{if(!(await fetch(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok){a(n(`prov.accountRemoveFail`,{email:i}),!1);return}a(n(`prov.accountRemoved`,{email:i}),!0),await H([e]),await Promise.all([s(),c(!0)])}catch{a(n(`prov.accountRemoveFail`,{email:i}),!1)}},ae=(0,Z.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[r]);(0,Z.useEffect)(()=>{if(ae.length===0)return;let e=`${t}:${ae.join(`,`)}`;z.current!==e&&(z.current=e,Promise.resolve().then(()=>{H(ae)}))},[t,H,ae]);let oe=(0,Z.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[r]);return(0,Z.useEffect)(()=>{if(oe.length===0)return;let e=`${t}:${oe.join(`,`)}`;B.current!==e&&(B.current=e,Promise.resolve().then(()=>{U(oe)}))},[t,U,oe]),{accountSets:u,accountLoadStates:f,switchingAccount:g,pausingAccount:b,switchingAccounts:m,pausingAccounts:v,openAccounts:x,keyPools:C,addingKeyFor:T,newKeyValue:D,setAccountSets:d,setAccountLoadStates:p,setSwitchingAccount:_,setOpenAccounts:S,setKeyPools:w,setAddingKeyFor:E,setNewKeyValue:O,fetchAccountSets:H,fetchKeyPools:U,refreshAccountRosters:W,switchAccount:K,pauseAccount:te,setAccountPoolThreshold:ee,setAccountThreshold:q,switchApiKey:ne,removeApiKey:J,addApiKeyValue:Y,addApiKey:re,editCredentialAlias:ie,removeAccount:X,oauthCardProviders:ae,keyCardProviders:oe,activeAccountNeedsReauth:(0,Z.useMemo)(()=>Th(u,l),[u,l])}}var Dh=new Set([`hasApiKey`,`hasHeaders`,`xaiResponsesOptInState`,`initialModelSelection`]);function Oh(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))Dh.has(e)||(n[e]=structuredClone(r));return[e,n]}))}}function kh(e){let{apiBase:t,config:n,notify:r,fetchConfig:i,fetchProviderQuotas:a,onSaved:o,t:s}=e,[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(!1),b=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{n&&!b.current&&d(JSON.stringify(Oh(n),null,2))},[n]);let x=(0,Z.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,Z.useCallback)(()=>{let e=n?JSON.stringify(Oh(n),null,2):u;h(e),d(e),y(!1),p(!0),b.current=!0},[n,u]),C=(0,Z.useCallback)(()=>{y(!1),p(!1),b.current=!1;let e=n?JSON.stringify(Oh(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,Z.useCallback)(()=>{if(f&&u!==m){y(!0);return}C()},[C,u,m,f]),restoreJsonEditor:(0,Z.useCallback)(()=>{d(m)},[m]),jsonIsDirty:f&&u!==m,setJsonLeaveOpen:y}}var Ah=186e4;function jh(e,t,n){return e?Math.max(n,Math.ceil(Ah/t)):n}var Mh={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`},Nh=e=>Mh[e]??e;function Ph({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,Z.useRef)(null);g.current===null&&(g.current=new Map);let _=(0,Z.useRef)(new Map),v=(0,Z.useCallback)(e=>{let t=(g.current.get(e)??0)+1;return g.current.set(e,t),t},[]),y=(0,Z.useCallback)(t=>Qf(e,t),[e]),b=(0,Z.useCallback)(async e=>{let t=Object.keys(r);await f(new Set(t).has(e)?t:[...t,e])},[r,f]),x=(0,Z.useCallback)(()=>{u(),p(!0),m()},[u,p,m]),S=(0,Z.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:Nh(e),cmd:`ocx sync`}),!0):l(r===`ended`?t(`kiroLogin.ended`):t(`prov.loginError`,{provider:Nh(e),error:t(`kiroLogin.failed`)}),!1),x())}},[n,h,b,l,t,x]);return(0,Z.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,Z.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:Nh(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 $f(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,...ml(),...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:Nh(u)}),!1);return}let o=await a.json();if(!n.current||g.current.get(u)!==p)return;let f=gl(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<jh(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 gn(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:Nh(u)}):t(`prov.loginError`,{provider:Nh(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:Nh(u),error:t(`prov.reauthAccountMissing`)}),!1),s(null),v=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:Nh(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:Nh(u)}),!1):l(t(`prov.loginOk`,{provider:Nh(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:Nh(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:Nh(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:Nh(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:Nh(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:Nh(n)}),!1)}},onNativeLoginSettled:S}}async function Fh(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function Ih(e){let t=e.dependentShadowIntercept;return!t||typeof t.model!=`string`||t.enabled!==!0?null:{model:t.model,enabled:!0}}function Lh(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 Rh({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,refreshCodexAccount:u}){let d=(0,Z.useCallback)(async e=>{a(e)},[a]),f=(0,Z.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=Ih(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(Lh(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,Z.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 Fh(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}let a=Ih(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,Z.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 Fh(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,Z.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(Lh(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 zh({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){let c=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>()=>{c.current+=1},[e]),{fetchConfig:(0,Z.useCallback)(async()=>{let r=++c.current;try{let t=await hn(await fetch(`${e}/api/config`));if(r!==c.current)return`superseded`;if(!t)throw Error(`config response missing`);return n(t??null),s&&t&&Va(s,t),`applied`}catch{return r===c.current?(a(t(`prov.loadConfigFail`),!1),`failed`):`superseded`}},[e,s,a,n,t]),fetchOauth:(0,Z.useCallback)(async()=>{try{let t=(await hn(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 gn(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,Z.useCallback)(async(e=!1)=>{o(e)},[o])}}function Bh({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=O(),a=(0,Z.useId)(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),m=hh(e);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let h=(0,Z.useCallback)(e=>{e.preventDefault(),n()},[n]);if(!m)return null;let g=vh(e,m);return(0,Q.jsxs)(`dialog`,{ref:c,"aria-labelledby":a,"aria-describedby":g.conditions?`${o} ${s}`:o,className:`modal-overlay`,onCancel:h,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,Q.jsx)(`h3`,{id:a,children:i(g.title,{provider:t})}),(0,Q.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(Ae,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g.body,{provider:t})})]}),g.conditions&&(0,Q.jsx)(`p`,{id:s,className:`modal-desc`,style:{marginTop:12},children:i(g.conditions)}),g.saferPath&&(0,Q.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(g.saferPath)}),(0,Q.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,Q.jsx)(`span`,{className:`text-label`,children:i(g.acknowledge)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!u||f,onClick:()=>{!u||l.current||(l.current=!0,p(!0),r())},children:i(g.continue)})]})]})]})}function Vh(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}function Hh({row:e,status:t,busyProvider:n,loginHint:r,paste:i,onLogin:a,onCancelLogin:o,onLogout:s,onManage:c}){let l=O(),u=n===e.id,d=!!t?.loggedIn,f=d?t?.email??e.statusLabel??l(`modal.accountLoggedIn`):t?.error??e.statusLabel??l(`modal.accountLoggedOut`),p=Vh(e,n,r);return(0,Q.jsxs)(`div`,{className:`list-row provider-catalog-account-row${p?` provider-catalog-account-row--waiting`:``}`,children:[(0,Q.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,Q.jsx)(me,{name:e.id,cls:`provider-icon provider-icon-sm`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:e.label}),(0,Q.jsx)(`div`,{className:`sub`,children:f})]}),(0,Q.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,Q.jsxs)(Q.Fragment,{children:[d&&(0,Q.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:l(`modal.accountManage`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:d?`btn btn-ghost`:`btn btn-primary`,disabled:u,onClick:()=>{u||a(e.id)},children:l(u?`codexAuth.enablingOpenai`:d?`modal.accountAdd`:`modal.accountLogin`)})]}):d?(0,Q.jsxs)(Q.Fragment,{children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>c(e.id),children:l(`modal.accountManage`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:u,onClick:()=>{u||a(e.id,!0)},children:l(u?`prov.waitingBrowser`:`modal.accountAdd`)}),u&&o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:l(`common.cancel`)}),s&&!u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>s(e.id),children:l(`modal.accountLogout`)})]}):u?o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:l(`common.cancel`)}):a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>a(e.id),children:l(`modal.accountLogin`)})})]}),p&&r&&(0,Q.jsx)(ul,{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 Uh=[`accounts`,`free`,`local`,`paid`],Wh={accounts:`modal.tab.accounts`,free:`modal.tab.free`,local:`modal.tab.local`,paid:`modal.tab.paid`},Gh={},Kh=[],qh={};function Jh({presets:e,usageRank:t=Gh,presetsLoading:n=!1,initialTier:r=`free`,query:i,onQueryChange:a,onSelectPreset:o,onSelectCustom:s,onShowNote:c,accountRows:l=Kh,accountStatus:u=qh,busyProvider:d=null,loginHint:f=null,paste:p,onLogin:m,onCancelLogin:h,onLogout:g,onManage:_}){let v=O(),[y,b]=(0,Z.useState)(r),x=(0,Z.useId)(),S=e=>`${x}-${e}`,C=(0,Z.useRef)(null),w=i.trim().length>0;(0,Z.useEffect)(()=>{C.current&&(C.current.scrollTop=0)},[y,w]);let T=(0,Z.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),E=(0,Z.useMemo)(()=>{let e=Object.keys(t).length>0;return T.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)})},[T,t]),D=(0,Z.useMemo)(()=>Js(nc(E)),[E]),k=D[y],A=(0,Z.useMemo)(()=>w?$s(l,i,d):l,[l,i,w,d]),j=(0,Z.useMemo)(()=>{let e=Uh.filter(e=>e!==`accounts`);return w?e.map(e=>({tier:e,rows:Qs(ec(D[e].filter(e=>Zs(e,i)),A),i)})):y===`accounts`?[]:[{tier:y,rows:k}]},[w,y,k,D,i,A]),M=(0,Z.useMemo)(()=>({...Object.fromEntries(j.map(e=>[e.tier,e.rows.length])),accounts:A.length}),[j,A]),N=Uh.reduce((e,t)=>e+(M[t]??0),0),P=Uh.filter(e=>(M[e]??0)>0),F=w?N:y===`accounts`?A.length:j[0]?.rows.length??0,I=e=>{let t=C.current,n=t?.querySelector(`[data-catalog-group="${e}"]`);!t||!n||(t.scrollTop=n.offsetTop-t.offsetTop,d||n.focus({preventScroll:!0}))},L=e=>{if(e.key!==`ArrowDown`)return;let t=C.current?.querySelector(`button:not(:disabled), a[href]`);t&&(e.preventDefault(),t.focus())},R=(e,t)=>(0,Q.jsxs)(`h4`,{id:S(e),"data-catalog-group":e,className:`provider-catalog-group-head`,tabIndex:-1,children:[(0,Q.jsx)(`span`,{children:v(Wh[e])}),(0,Q.jsx)(`span`,{className:`provider-catalog-group-count`,children:t})]}),z=e=>{let t=Je(e),n=t?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:v(`modal.badge.subscriptionCli`)}):e.codexAccountMode===`direct`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:v(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:v(`modal.badge.pool`)}):e.auth===`oauth`?(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:v(`modal.badge.oauth`)}):e.auth===`forward`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:v(`modal.badge.codexLogin`)}):e.auth===`local`?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:v(`modal.badge.local`)}):e.keyOptional?null:(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:v(`modal.badge.apiKey`)}),r=(e.freeTier||e.keyOptional)&&e.auth===`key`&&!t?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:v(`modal.badge.free`)}):null,i=e.sponsor?(0,Q.jsx)(`span`,{className:`badge badge-accent provider-catalog-sponsor`,title:e.sponsorUrl,children:v(`modal.badge.sponsor`)}):null;return(0,Q.jsxs)(Q.Fragment,{children:[i,r,n]})};return(0,Q.jsxs)(`div`,{className:`provider-catalog`,children:[(0,Q.jsx)(`input`,{className:`input provider-catalog-search`,type:`search`,value:i,onChange:e=>a(e.target.value),onKeyDown:L,placeholder:v(`modal.search`),"aria-label":v(`modal.search`)}),w?(0,Q.jsx)(`div`,{className:`provider-catalog-tabs provider-catalog-tabs--chips`,children:Uh.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`provider-catalog-tab provider-catalog-chip`,disabled:(M[e]??0)===0,...(M[e]??0)>0?{"aria-controls":S(e)}:{},onClick:()=>I(e),children:[v(Wh[e]),(0,Q.jsx)(`span`,{className:`provider-catalog-chip-count`,children:M[e]??0})]},e))}):(0,Q.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:Uh.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":y===e,"aria-controls":x,className:`provider-catalog-tab${y===e?` active`:``}`,onClick:()=>b(e),children:v(Wh[e])},e))}),!w&&y===`accounts`&&(0,Q.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:v(`modal.accountsHint`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:w?N===0?v(`modal.noMatch`):v(`modal.searchResults`,{count:N,tiers:P.map(e=>v(Wh[e])).join(`, `)}):``}),(0,Q.jsxs)(`div`,{className:`provider-catalog-rows`,id:x,ref:C,children:[n&&F===0&&(0,Q.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:v(`modal.catalogLoading`)}),(w||y===`accounts`)&&A.length>0&&(0,Q.jsxs)(Z.Fragment,{children:[w&&R(`accounts`,A.length),A.map(e=>(0,Q.jsx)(Hh,{row:e,status:u[e.id],busyProvider:d,loginHint:f,...p?{paste:p}:{},...m?{onLogin:m}:{},...h?{onCancelLogin:h}:{},...g?{onLogout:g}:{},..._?{onManage:_}:{}},e.id))]},`accounts`),j.map(e=>e.rows.length===0?null:(0,Q.jsxs)(Z.Fragment,{children:[w&&R(e.tier,e.rows.length),e.rows.map(e=>(0,Q.jsxs)(`div`,{className:`provider-catalog-row-wrap`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>o(e),children:[(0,Q.jsx)(me,{name:e.id,adapter:e.adapter,cls:`provider-icon provider-icon-sm`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:e.label}),(0,Q.jsxs)(`div`,{className:`sub`,children:[(0,Q.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,Q.jsx)(`div`,{className:`provider-catalog-badges`,children:z(e)})]}),c&&Ys(e.note)&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn provider-catalog-note-more`,onClick:()=>c(e),children:v(`modal.noteMore`)})]},e.id))]},e.tier)),!n&&F===0&&(0,Q.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:v(`modal.noMatch`)})]}),(0,Q.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,Q.jsx)(`div`,{style:{flex:1}}),!w&&y!==`accounts`&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:s,children:v(`modal.notListed`)})]})]})}function Yh({providerId:e,label:t,adapter:n,note:r,onClose:i}){let a=O(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=c.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[]);let l=(0,Z.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Q.jsxs)(`dialog`,{ref:c,"aria-labelledby":o,"aria-describedby":s,className:`modal-overlay`,onCancel:l,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:i}),(0,Q.jsxs)(`div`,{className:`modal-card provider-note-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:o,className:`provider-note-title`,children:[(0,Q.jsx)(me,{name:e,adapter:n,cls:`provider-icon provider-icon-sm`}),t]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":a(`common.close`),onClick:i,children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsxs)(`div`,{id:s,className:`provider-note-body`,children:[(0,Q.jsx)(`code`,{className:`chip`,children:n}),(0,Q.jsx)(`p`,{className:`modal-desc provider-note-text`,children:r})]}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:a(`common.close`)})})]})]})}function Xh({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,oauthDeviceCode:o,oauthInstructions:s,oauthBrowserLaunch:c,manualCode:l,manualCodeBusy:u,manualCodeMsg:d,manualCodeOk:f,onRequestLogin:p,onCancelLogin:m,onUseApiKeyInstead:h,onManualCodeChange:g,onSubmitManualCode:_,onBack:v}){let y=O();return(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,Q.jsx)(`div`,{className:`muted text-control`,children:e.note??y(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>p(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,Q.jsx)(at,{}),n?y(`modal.waitingBrowser`):y(`modal.logInWith`,{label:e.label})]}),!n&&(0,Q.jsx)(Gd,{})]}):(0,Q.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:y(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,Q.jsx)(ul,{hint:{url:a,deviceCode:o,instructions:s,browserLaunch:c},paste:{value:l,busy:u,disabled:!e.oauthProvider,message:d,ok:f,onChange:g,onSubmit:()=>{e.oauthProvider&&_(e.oauthProvider)}}}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:h,children:y(`modal.useApiKeyInstead`)}),(0,Q.jsx)(`div`,{style:{flex:1}}),n&&e.oauthProvider&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>m(e.oauthProvider),children:y(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,children:y(`modal.back`)})]})]})}function Zh({label:e,children:t}){return(0,Q.jsxs)(`label`,{style:{display:`block`},children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),t]})}var Qh=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`];function $h(e){return e&&!Qh.includes(e)?[e,...Qh]:Qh}function eg({preset:e,form:t,endpointChoice:n,error:r,saving:i,dup:a,isCustom:o,isLocal:s,isReservedForward:c,presetDescription:l,onFormChange:u,onEndpointChoiceChange:d,onSubmit:f,onUseOauthLogin:p,onBack:m}){let h=O(),g=Je(t);return(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,Q.jsxs)(`details`,{className:`setup-guide`,children:[(0,Q.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,Q.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,Q.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,Q.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,Q.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,Q.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,Q.jsx)(Zh,{label:h(`modal.providerName`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Zh,{label:h(`modal.adapter`),children:(0,Q.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>u({...t,adapter:e.target.value}),children:$h(t.adapter).map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Zh,{label:h(`modal.endpoint`),children:(0,Q.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:jp(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.id===`token-plan`?h(`modal.endpoint.tokenPlan`):e.id===`payg`?h(`modal.endpoint.payAsYouGo`):e.id===`custom`?h(`modal.endpoint.custom`):e.label},e.id))})}),n===`custom`&&(0,Q.jsx)(Zh,{label:h(`modal.baseUrl`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,Q.jsx)(Zh,{label:h(`modal.baseUrl`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,Q.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,Q.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,Q.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),o&&Pp(t)&&(0,Q.jsx)(Kp,{checked:t.preserveResponsesReasoningContent===!0,onChange:e=>u({...t,preserveResponsesReasoningContent:e})}),t.authMode===`forward`?(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,Q.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):g?(0,Q.jsxs)(`div`,{role:`note`,"data-subscription-cli-warning":``,className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,Q.jsx)(`strong`,{children:h(`modal.subscriptionCliTitle`)}),(0,Q.jsx)(`div`,{style:{marginTop:4},children:(0,Q.jsx)(T,{k:`modal.subscriptionCliWarning`,cmd:`claude -p`,vars:{apiProvider:te}})})]}):e.keyOptional?(0,Q.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,Q.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,Q.jsxs)(Q.Fragment,{children:[e.dashboardUrl&&(0,Q.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,Q.jsx)(tt,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,Q.jsx)(Ve,{style:{width:13,height:13}})]}),(0,Q.jsx)(Zh,{label:h(`modal.apiKey`),children:(0,Q.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>u({...t,apiKey:e.target.value}),placeholder:h(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,Q.jsx)(Zh,{label:h(`modal.apiKeyTransport`),children:(0,Q.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,Q.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,Q.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,Q.jsx)(Zh,{label:h(`modal.defaultModel`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,Q.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,Q.jsx)(`div`,{style:{flex:1}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var tg=2e3;function ng({apiBase:e,t,aliveRef:n,onAdded:r}){let i=(0,Z.useRef)(new Map),a=(0,Z.useRef)(new Map),o=(0,Z.useCallback)(e=>{let t=(i.current.get(e)??0)+1;return i.current.set(e,t),t},[]),s=(0,Z.useCallback)(t=>Qf(e,t),[e]);return(0,Z.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,Z.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,Z.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 $f(e,c,()=>{if(!(!n.current||!v()))return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:c,...ml()})})});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,gl(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<jh(l,tg,100);i++){if(await new Promise(e=>setTimeout(e,tg)),!n.current||!v())return;let i=await fetch(`${e}/api/oauth/status?provider=${c}`).catch(()=>null),o=i?await gn(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,Z.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 rg(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 ig(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 ag({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:c,accountLoginHint:l=null,onAccountLogin:u,onAccountCancelLogin:d,onAccountLogout:f,onAccountManage:p,onOpen:m}){let h=O(),g=(0,Z.useMemo)(()=>[{id:`custom`,label:h(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[h]),[_,v]=(0,Z.useReducer)(ig,a,e=>rg(e,h(`modal.customProvider`))),y=(0,Z.useRef)(!0),b=(0,Z.useRef)(null),x=(0,Z.useRef)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(``),E=Vt(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),D=Vt(`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=Vt(hr(e),[e],async t=>await mr(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4}),A=E.data??[],j=D.data??g,M=D.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:G,manualCode:ee,manualCodeBusy:K,manualCodeMsg:q,manualCodeOk:te,endpointChoice:ne,oauthTosPending:J}=_;(0,Z.useEffect)(()=>{y.current=!0,b.current=document.activeElement,m?.();let e=x.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()=>{y.current=!1,b.current?.focus()}},[]),(0,Z.useEffect)(()=>{let e=e=>{let t=!J&&!S;if(!(e.key!==`Escape`||!t)){if(w){T(``);return}n()}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,J,S,w]);let Y=e=>{let t=Bp(e);return t?h(t):e.note},re=e=>{let t=Mp(e.baseUrlChoices,e.baseUrl);v({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?jp(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},ie=async()=>{if(!F)return;let t=P?zp(P):!1,n=P?.baseUrlChoices?.length?Np(P.baseUrlChoices,ne,F.baseUrl):F.baseUrl.trim();if(!t&&!F.name.trim()){v({type:`set-error`,error:h(`modal.nameRequired`)});return}if(!t&&!n){v({type:`set-error`,error:h(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){v({type:`set-error`,error:h(`modal.baseUrlPlaceholderError`)});return}let i={...F,baseUrl:n},a;try{a=Hp(P??{id:`custom`},i)}catch{v({type:`set-error`,error:h(`modal.invalidPreset`)});return}v({type:`set-saving`,saving:!0}),v({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(()=>({}));v({type:`set-error`,error:e.error||h(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{v({type:`set-error`,error:h(`modal.networkError`)})}finally{v({type:`set-saving`,saving:!1})}},{cancelLoginOAuth:X,loginOAuth:ae,submitManualCode:oe}=ng({apiBase:e,t:h,aliveRef:y,onAdded:r}),se={setOauthBusy:e=>v({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>v({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>v({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t,n,r,i)=>v({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r,browserLaunch:i}),setManualCode:e=>v({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>v({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>v({type:`set-manual-code-msg`,msg:q,ok:e})},ce=F?t.includes(F.name.trim())&&F.name.trim()!==``:!1,le=e=>{if(!R){if(hh(e)){v({type:`set-oauth-tos-pending`,providerId:e});return}ae(e,se)}},ue=e=>{oe(e,ee,K,{setManualCodeBusy:e=>v({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>v({type:`set-manual-code`,code:e}),setManualCodeOk:e=>v({type:`set-manual-code-msg`,msg:q,ok:e}),setManualCodeMsg:e=>v({type:`set-manual-code-msg`,msg:e})})},de=P?.id===`custom`,fe=F?.authMode===`local`,pe=P?zp(P):!1;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":h(`modal.add`),className:`modal-overlay`,children:(0,Q.jsxs)(`div`,{ref:x,className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:P?h(`modal.addNamed`,{label:P.label}):h(`modal.add`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":h(`common.close`),onClick:n,children:(0,Q.jsx)(ve,{})})]}),!P&&(0,Q.jsx)(gr,{data:k.data}),P?F&&(P.auth===`oauth`&&F.authMode===`oauth`?(0,Q.jsx)(Xh,{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?G:void 0,manualCode:ee,manualCodeBusy:K,manualCodeMsg:q,manualCodeOk:te,onRequestLogin:le,onCancelLogin:e=>{X(e,se,P.label)},onUseApiKeyInstead:()=>{R&&P.oauthProvider&&X(P.oauthProvider,se,P.label),v({type:`use-api-key-instead`,form:{...F,authMode:`key`}})},onManualCodeChange:e=>v({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{ue(e)},onBack:()=>{R&&P.oauthProvider&&X(P.oauthProvider,se,P.label),v({type:`back`})}}):(0,Q.jsx)(eg,{preset:P,form:F,endpointChoice:ne,error:L,saving:I,dup:ce,isCustom:de,isLocal:fe,isReservedForward:pe,presetDescription:Y,onFormChange:e=>v({type:`set-form`,form:e}),onEndpointChoiceChange:e=>v({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{ie()},onUseOauthLogin:()=>v({type:`use-oauth-login`,form:{...F,authMode:`oauth`}}),onBack:()=>v({type:`back`})})):(0,Q.jsx)(Jh,{presets:j,usageRank:N,presetsLoading:M,initialTier:i,query:w,onQueryChange:T,onSelectPreset:e=>re(e),onSelectCustom:()=>re(g[0]),onShowNote:e=>C(e),accountRows:o,accountStatus:s,busyProvider:c,onLogin:u,onCancelLogin:d,onLogout:f,onManage:p,loginHint:l,paste:{value:ee,busy:K,message:q,ok:te,onChange:e=>v({type:`set-manual-code`,code:e}),onSubmit:e=>{ue(e)}}})]})}),J&&(0,Q.jsx)(Bh,{providerId:J,providerLabel:P?.label??J,onCancel:()=>v({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=J;e&&(v({type:`set-oauth-tos-pending`,providerId:null}),ae(e,se))}},J),S?.note&&(0,Q.jsx)(Yh,{providerId:S.id,label:S.label,adapter:S.adapter,note:S.note,onClose:()=>C(null)},S.id)]})}function og({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,Q.jsxs)(Q.Fragment,{children:[r&&(0,Q.jsx)(Rd,{...r}),n&&(0,Q.jsx)(ag,{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,Q.jsx)(xl,{apiBase:e,onClose:S,onAdded:C}),l&&(0,Q.jsx)(uh,{providerName:l,defaultProviderName:u,onCancel:w,onConfirm:T}),f&&E&&D&&O&&(0,Q.jsx)(dh,{saving:p??!1,onCancel:E,onDiscard:D,onSave:O}),m&&(0,Q.jsx)(Bh,{providerId:m.provider,providerLabel:Nh(m.provider),onCancel:k,onContinue:A},`${m.provider}:${m.addAccount?`add`:`login`}`)]})}function sg(e,t,n){return[...Lp(e.providers).map(e=>({id:e,label:be(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:Nh(e),kind:`oauth`}))]}function cg(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);return n}function lg(e,t){let[n,r]=(0,Z.useState)({apiBase:e,notice:null});n.apiBase!==e&&r({apiBase:e,notice:null});let i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{i.current=null},[e]);let a=(0,Z.useCallback)((t,n,a=!1)=>{let o=typeof t==`string`?[t]:t,s={provider:o.join(`, `),providers:o,apiBase:e,initialRegistration:n&&o.length===1,catalogRefreshPending:a};i.current=s,r({apiBase:e,notice:{context:s,loading:!0,failed:!1}})},[e]),o=(0,Z.useCallback)(()=>{i.current=null,r(e=>({...e,notice:null}))},[]),s=(0,Z.useCallback)(n=>{let a=i.current;!a||a.apiBase!==e||t().then(async e=>{e===`superseded`&&i.current===a&&(e=await t()),i.current===a&&r(t=>t.apiBase===a.apiBase?{...t,notice:{context:a,loading:!1,failed:!n||e!==`applied`}}:t)}).catch(()=>{i.current===a&&r(e=>e.apiBase===a.apiBase?{...e,notice:{context:a,loading:!1,failed:!0}}:e)})},[e,t]);return{notice:n.apiBase===e?n.notice:null,open:a,close:o,modelsSettled:s}}var ug=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`advisor`,`logs`,`usage`,`storage`,`remote`,`remote-workspace`,`codex-set`,`integrations`,`claude`]);function dg(e){let t=Gt(Wt(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`:ug.has(n)?n:`dashboard`}function fg(e){let t=Wt(e);return Sg(t).replaceTo??t}var pg=[`dashboard/providers`,`dashboard/models`],mg=[`models/combos`,`models/routing`,`models/compatibility`],hg=`models/combos/jev-auto`;function gg(e){let t=e?.trim();return t&&t!==`jev`?`${hg}?${new URLSearchParams({decisionProvider:t})}`:hg}function _g(e){let{path:t,query:n}=Gt(Wt(e));if(t!==`models/combos/jev-auto`)return;let r=new URLSearchParams(n).get(`decisionProvider`)?.trim();return r&&r!==`jev`?r:null}var vg=[`integrations/keys`,`integrations/codex`,`integrations/claude`,`integrations/claude/desktop`,`integrations/grok`,`integrations/cursor`,`integrations/opencode`,`integrations/pi`,`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`],yg=[`providers`,`models/compatibility`,hg],bg=`providers?provider=anthropic&tab=accounts`;function xg(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`&&(mg.includes(e)||e===`models/combos/jev-auto`)||t===`dashboard`&&(e===`dashboard/update`||pg.includes(e))||t===`integrations`&&vg.includes(e)}function Sg(e){let{path:t,query:n}=Gt(e);if(n||t!==e){let e=Sg(t);return e.replaceTo===null&&yg.includes(t)?e:{page:e.page,replaceTo:e.replaceTo??t}}let r=dg(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:bg}:e===`claude/settings`?{page:`claude`,replaceTo:`claude/code`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:xg(e,r)?{page:r,replaceTo:null}:{page:r,replaceTo:r}}var Cg=`models/compatibility`,wg=`providers`,Tg=200,Eg={inbound:``,upstream:``};function Dg(e){return e!==void 0&&am(e)?e:``}function Og(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?`${Cg}?${n}`:Cg}function kg(e,t){let n=Gt(fg(e));return n.path===t?new URLSearchParams(n.query):null}function Ag(e=window.location.hash){let t=kg(e,Cg);if(!t)return null;let n=t.get(`inbound`),r=t.get(`upstream`);return{inbound:am(n)?n:``,upstream:am(r)?r:``}}function jg(e){return`${wg}?${new URLSearchParams({provider:e}).toString()}`}function Mg(e){return`${wg}?${new URLSearchParams({provider:e,tab:`accounts`}).toString()}`}function Ng(e=window.location.hash){return kg(e,`providers`)?.get(`tab`)===`accounts`?`accounts`:`settings`}function Pg(e=window.location.hash){let t=kg(e,`providers`)?.get(`provider`)?.trim()??``;return t&&t.length<=Tg?t:null}function Fg(e){qt(Og(e))}function Ig(e){qt(jg(e))}function Lg(e,t=window){let n=Mg(e);if(Wt(t.location.hash)===n){t.dispatchEvent(new t.Event(`hashchange`));return}qt(n,t)}function Rg(e,t,n,r){let[i,a]=(0,Z.useState)(()=>({name:Pg(),tab:Ng(),seq:0})),[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(t);if((0,Z.useEffect)(()=>{let e=()=>a(e=>({name:Pg(),tab:Ng(),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,Z.useEffect)(()=>{let e=c.current;if(c.current=t,e===t)return;let n=Pg();!n||o?.seq!==i.seq||i.name!==n||(t===null?e===n:t!==n)&&Kt(wg)},[o,i,t]),o?.tab===`settings`?{token:o.seq+1,provider:o.provider}:{token:0,provider:null}}function zg(e){let[t,n]=(0,Z.useState)({epoch:0,force:!1}),r=(0,Z.useRef)(0),i=(0,Z.useRef)(!0),a=(0,Z.useRef)(new Map),o=(0,Z.useCallback)(()=>{for(let e of a.current.values())e.resolve(!1);a.current.clear()},[]);(0,Z.useEffect)(()=>(i.current=!0,()=>{i.current=!1,o()}),[e,o]);let s=(0,Z.useCallback)((e=!1)=>{o();let t=++r.current;return i.current&&n({epoch:t,force:e}),t},[o]),c=(0,Z.useCallback)((e,t,n)=>{let r=a.current.get(e);!r||!i.current||(r[t]=n,r.accounts!==void 0&&r.report!==void 0&&(a.current.delete(e),r.resolve(r.accounts&&r.report)))},[]);return{quotaRefresh:t,invalidateProviderQuotas:s,settleQuotaRefresh:(0,Z.useCallback)((e,t)=>c(t,`report`,e),[c]),beginQuotaRefresh:(0,Z.useCallback)(e=>{if(!i.current)return Promise.resolve(!1);let t=s(!0),n=new Promise(n=>{a.current.set(t,{resolve:n,accounts:!e||void 0})});return e&&Promise.resolve().then(e).then(e=>c(t,`accounts`,e),()=>c(t,`accounts`,!1)),n},[c,s])}}function Bg(e,t,n){let r=(0,Z.useRef)(n);(0,Z.useLayoutEffect)(()=>{r.current=n});let i=(0,Z.useRef)(()=>{});return(0,Z.useEffect)(()=>{if(!t)return;let n=!1,a=null,o=250,s=null,c=()=>{a!==null&&window.clearTimeout(a),a=null},l=e=>{e.controller.abort(),e.reader?.cancel().catch(()=>{})},u=()=>{if(n||s)return;c();let t={controller:new AbortController,lastActivity:Date.now()};s=t,(async()=>{try{let i=await fetch(`${e}/api/accounts/events`,{signal:t.controller.signal,credentials:`same-origin`,headers:{Accept:`text/event-stream`}});if(!i.ok||!i.headers.get(`content-type`)?.includes(`text/event-stream`)||!i.body)throw Error(`Account selection stream unavailable`);if(n||t.controller.signal.aborted){await i.body.cancel();return}let a=i.body.getReader();t.reader=a,t.openedAt=Date.now();let o=new TextDecoder,s=new Map,c=new Map,l=!1,u=!1,d=()=>{u||(u=!0,Promise.resolve().then(async()=>{if(u=!1,n||t.controller.signal.aborted)return;let e=l?[void 0]:[...c.values()];l=!1,c.clear(),await Promise.all(e.map(e=>r.current(e)))}).catch(()=>{}))},f=``,p=``,m=[],h=0,g=()=>{let e;try{e=JSON.parse(m.join(`
|
|
4
|
+
`))}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(`
|
|
5
|
+
`))!==-1;){let e=f.slice(0,n).replace(/\r$/,``);if(f=f.slice(n+1),h+=e.length,h>16384)throw Error(`Account selection event too large`);e?e.startsWith(`event:`)?p=e.slice(6).replace(/^ /,``):e.startsWith(`data:`)&&m.push(e.slice(5).replace(/^ /,``)):(g(),p=``,m=[],h=0)}if(f.length+h>16384)throw Error(`Account selection event too large`)}}catch{}finally{if(l(t),s===t&&(s=null,!n)){t.openedAt!==void 0&&Date.now()-t.openedAt>=1e4&&(o=250);let e=o;o=Math.min(o*2,5e3),a=window.setTimeout(()=>{a=null,u()},e)}}})()};return i.current=()=>{s&&Date.now()-s.lastActivity>6e4&&(l(s),s=null),u()},u(),()=>{n=!0,i.current=()=>{},c(),s&&l(s)}},[e,t]),(0,Z.useCallback)(()=>i.current(),[])}function Vg({apiBase:e}){let t=O(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,Z.useState)(()=>La(n)),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(`err`),[p,m]=(0,Z.useState)(0),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)({}),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(!1),[M,P]=(0,Z.useState)(0),[F,I]=(0,Z.useState)(null),[L,R]=(0,Z.useState)({token:0,provider:null}),z=(0,Z.useRef)(!0),B=(0,Z.useRef)(null),V=(0,Z.useRef)(!1),H=(0,Z.useCallback)((e,t=!0,n)=>{c(e),u(t),f(n??(t?`ok`:`err`)),m(e=>e+1)},[]),U=(0,Z.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),W=(0,Z.useCallback)(e=>{if(e.validationPending||e.catalogRefreshPending){c(t(e.validationPending?`pws.healthLabel.validationPending`:`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}H(t(`codexAuth.accountAdded`),!0)},[H,t]);(0,Z.useEffect)(()=>(z.current=!0,()=>{z.current=!1}),[]),(0,Z.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(U,4500);return()=>window.clearTimeout(e)},[s,l,p,U]);let G=(0,Z.useCallback)(e=>{o(!1),E(null),w(e),R(t=>({token:t.token+1,provider:e}))},[]),ee=Rg(r?Object.keys(r.providers):null,C,w,G),K=Vt(`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});Vt(hr(e),[e],async t=>await mr(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4});let{quotaRefresh:q,invalidateProviderQuotas:te,settleQuotaRefresh:ne,beginQuotaRefresh:J}=zg(e),{fetchConfig:Y,fetchOauth:re,fetchProviderQuotas:ie}=zh({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:v,notify:H,invalidateProviderQuotas:te,configCacheKey:n}),X=(0,Z.useCallback)(async()=>{await Y()},[Y]),ae=lg(e,Y),oe=ae.open,se=(0,Z.useCallback)(e=>{G(e),oe(e,!1)},[G,oe]),ce=au(e),le=ce.activeNeedsReauth,ue=(0,Z.useMemo)(()=>{let e=ce.accounts;if(e.length===0&&ce.loadState===`loading`)return _;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{..._,openai:{loggedIn:i,...a?{email:a}:{},...le?{needsReauth:!0}:{}}}},[_,ce.accounts,ce.loadState,le]),{accountSets:de,setAccountSets:fe,accountLoadStates:pe,switchingAccounts:me,pausingAccounts:he,keyPools:ge,fetchAccountSets:ve,fetchKeyPools:ye,refreshAccountRosters:be,oauthCardProviders:xe,keyCardProviders:Se,switchAccount:Ce,pauseAccount:we,setAccountPoolThreshold:Te,setAccountThreshold:Ee,switchApiKey:De,removeApiKey:Oe,addApiKeyValue:ke,editCredentialAlias:Ae,removeAccount:je,activeAccountNeedsReauth:Me}=Eh({apiBase:e,t,config:r,oauthStatus:ue,aliveRef:z,notify:H,fetchConfig:X,fetchOauth:re,fetchProviderQuotas:ie,codexActiveNeedsReauth:le}),Ne=(0,Z.useCallback)(e=>e&&!(e.kind===`oauth`?xe:Se).includes(e.provider)?Promise.resolve(!0):be(e),[be,xe,Se]),Pe=Bg(e,r!==null,Ne),Fe=JSON.stringify([e,xe.toSorted(),Se.toSorted()]),Ie=(0,Z.useRef)(null);Vt(`provider-rosters:${Fe}`,[Fe],async e=>Ie.current===Fe?(Pe(),be(void 0,e)):(Ie.current=Fe,!0),{enabled:r!==null,pollMs:3e4});let{draft:Le,setDraft:Re,jsonEditorOpen:ze,jsonSaving:Be,jsonLeaveOpen:Ve,saveConfig:He,openJsonEditor:Ue,discardJsonEditor:We,requestCloseJsonEditor:Ge,restoreJsonEditor:Ke,jsonIsDirty:qe,setJsonLeaveOpen:Je}=kh({apiBase:e,config:r,notify:H,fetchConfig:X,fetchProviderQuotas:ie,onSaved:e=>{e.length&&ae.open(e,!0),P(e=>e+1)},t}),Ye=(0,Z.useCallback)(e=>{let t=r?.providers[e],n=t?.authMode,i=t&&_e(e,t)?()=>ce.load(!0,{validatePending:!0}):n===`oauth`?()=>ve([e],!0):n===`forward`||n===`local`?void 0:()=>ye([e],!0);return J(i)},[r,ce,ve,ye,J]),Xe=(0,Z.useCallback)(()=>J(),[J]);(0,Z.useEffect)(()=>{B.current!==e&&(B.current=e,Promise.resolve().then(()=>{X(),re()}))},[e,X,re]);let Ze=()=>P(e=>e+1),{cancelLoginOAuth:Qe,loginOAuth:$e,logoutOAuth:et,onNativeLoginSettled:tt}=Ph({apiBase:e,t,aliveRef:z,accountSets:de,setAccountSets:fe,setBusy:b,setStatus:c,setLoginInfo:S,setOauthStatus:v,notify:H,fetchConfig:X,fetchOauth:re,fetchAccountSets:ve,fetchProviderQuotas:ie,bumpModelsRefresh:Ze,onLoginSettled:se}),nt=(0,Z.useRef)(tt);(0,Z.useEffect)(()=>{nt.current=tt},[tt]),(0,Z.useEffect)(()=>lp(e,e=>{nt.current(`kiro`,e).catch(()=>{})}),[e]);let{removeProvider:rt,confirmRemoveProvider:it,setProviderDisabled:at,setDefaultProvider:ot,updateProvider:st}=Rh({apiBase:e,t,removeBusyRef:V,workspaceSelected:C,setWorkspaceSelected:w,setRemoveConfirmName:k,notify:H,fetchConfig:X,fetchOauth:re,fetchProviderQuotas:ie,refreshCodexAccount:()=>ce.load(!0)}),ct=(e,t=!1,n)=>{if(y!==e){if(hh(e)){I({provider:e,addAccount:t,...n?{accountId:n}:{}});return}$e(e,t,n)}};if(!r)return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,Q.jsx)(sn,{tone:d,onDismiss:U,dismissLabel:t(`common.close`),children:s}):(0,Q.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,Q.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`providers-workspace-main`,children:(0,Q.jsxs)(`p`,{className:`muted`,children:[(0,Q.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let lt=sg(r,h,t),ut=cg(r,ue),dt=e=>r.providers[e]?.authMode===`forward`,ft=async(n,i=!1)=>{if(n===`openai`){if(y===`openai`)return;let n=r.providers.openai,i=Rp(n);if(i===`invalid`){H(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){b(`openai`);try{await Gp(e,i),await X()}catch(e){e instanceof Wp?H(t(e.i18nKey),!1):H(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{z.current&&b(e=>e===`openai`?null:e)}}j(!0);return}if(dt(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&ct(n,i)},pt=e=>{G(e)},mt={onLogin:ct,onNativeLoginSettled:tt,onCancelLogin:Qe,onLogout:et,onReauth:(e,t)=>ct(e,!0,t),onSwitchAccount:Ce,onPauseAccount:we,onAccountPoolThreshold:Te,onAccountThreshold:Ee,onRemoveAccount:je,onRetryAccounts:async e=>{await ve([e])},onAddApiKey:ke,onSwitchApiKey:De,onRemoveApiKey:Oe,onEditAlias:Ae,onRefreshQuota:Ye};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:t(`nav.providers`)}),(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,Q.jsx)(N,{}),t(`prov.add`)]})})]}),s&&(0,Q.jsx)(sn,{tone:d,onDismiss:U,dismissLabel:t(`common.close`),children:s}),(0,Q.jsx)(Rs,{onRemoveProvider:rt,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:C,onSelect:w,onAddProvider:e=>{E(e??null),o(!0)},onEditConfig:Ue,jsonEditor:{open:ze,draft:Le,isDirty:qe,onDraftChange:Re,onSave:()=>He(),onClose:Ge,onRestore:Ke},jsonSaving:Be,modelsRefreshToken:M,onModelsSettled:ae.modelsSettled,activeAccountNeedsReauth:Me,quotaRefreshEpoch:q.epoch,quotaForceRefresh:q.force,onQuotaRefreshSettled:ne,onRefreshAllQuotas:Xe,detail:(t,n)=>{let i=ut[t.name]??_[t.name];return(0,Q.jsx)(fh,{item:t,preset:Ws(t,K.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:()=>qt(`models`),onCreateJevAuto:Lr(t)?()=>qt(gg(t.name)):void 0,modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:i?.email,onDeselect:()=>w(null),apiBase:e,oauth:i,accounts:de[t.name]?.accounts??[],keys:ge[t.name]??[],accountLoadState:pe[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:L.token,accountsFocusProvider:L.provider,settingsFocusToken:ee.token,settingsFocusProvider:ee.provider,switchingAccountId:me[t.name]?.accountId??null,pausingAccountId:he[t.name]?.accountId??null,busyProvider:y,loginHint:x,authHandlers:mt,onRefreshQuota:()=>Ye(t.name),isDefault:t.name===r.defaultProvider,onRemoveProvider:rt,onSetDisabled:at,onSetDefault:e=>{ot(e)},onUpdateProvider:st,codexController:ce},t.name)}}),(0,Q.jsx)(og,{apiBase:e,config:r,adding:a,modelsNotice:ae.notice?{provider:ae.notice.context.provider,initialRegistration:ae.notice.context.initialRegistration,catalogRefreshPending:ae.notice.context.catalogRefreshPending,loading:ae.notice.loading,failed:ae.notice.failed,providerKnown:ae.notice.context.providers.every(e=>!!r.providers[e]),selection:ae.notice.context.providers.length===1?r.providers[ae.notice.context.provider]?.initialModelSelection:ae.notice.context.providers.some(e=>r.providers[e]?.initialModelSelection?.status===`pending`)?{status:`pending`}:void 0,onClose:ae.close,onOpenModels:()=>{ae.close(),qt(`models`)},onRetry:()=>{let e=ae.notice.context;ae.open(e.providers,e.initialRegistration,e.catalogRefreshPending),Ze()}}:null,addIntent:T,busy:y,addModalAccountRows:lt,accountLoginStatus:ut,accountLoginHint:x,removeConfirmName:D,removeDefaultProvider:D===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==D&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Ve,jsonSaving:Be,oauthTosPending:F,onCloseAdd:()=>{y&&Qe(y),o(!1),E(null)},onAdded:e=>{o(!1),E(null),U(),ae.open(e,!r.providers[e]),X(),re(),ie(!0),Ze()},onAccountLogin:ft,onAccountCancelLogin:e=>{Qe(e)},onAccountLogout:e=>{et(e)},onAccountManage:pt,onOpenAdd:re,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),W(e),e.validationPending||ae.open(`openai`,!r.providers.openai,e.catalogRefreshPending),X(),re(),ie(!0),Ze()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{it(D)},onCancelJsonLeave:()=>{Be||Je(!1)},onDiscardJson:We,onSaveJson:()=>{He()},onCancelOauthTos:()=>I(null),onContinueOauthTos:()=>{let e=F;e&&(I(null),$e(e.provider,e.addAccount,e.accountId))}})]})}function Hg(e){let{t:n}=t();return e.state===`stale`?(0,Q.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`codex-stale-banner-text`,children:n(`models.staleBanner`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:e.controller.restarting,onClick:()=>{e.controller.restart()},children:e.controller.restarting?n(`dash.codexRestarting`):n(`dash.codexRestart`)})]}):null}function Ug(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim().length>0)}function Wg(e){return e===null||e===`alphabetical`||e===`provider`||e===`most-used`}function Gg(e){if(typeof e!=`object`||!e)return!1;let t=e;return Ug(t.pickerOrder)&&Wg(t.pickerOrderMode)}function Kg(e){if(!Gg(e))return!1;let t=e;return Ug(t.pickerAvailable)&&(!(`chosen`in t)||Array.isArray(t.chosen)&&t.chosen.every(e=>typeof e==`string`))}function qg(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 Jg(e){let t=e.indexOf(`/`);return t<0?[``,e]:[e.slice(0,t),e.slice(t+1)]}var Yg=(e,t)=>e.localeCompare(t,`en`);function Xg(e,t){let[n,r]=Jg(e),[i,a]=Jg(t);return Yg(n,i)||Yg(r,a)}function Zg(e,t,n=[],r=[]){if(e==="default")return null;let i=[...new Set(t)];if(e===`alphabetical`)return i.sort((e,t)=>Yg(Jg(e)[1],Jg(t)[1])||Xg(e,t));if(e===`provider`)return i.sort(Xg);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)||Xg(e,t))}function Qg(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=Zg(n,e);if(r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n]))return n}return`custom`}function $g(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 e_(e,t,n){return JSON.stringify([e,t,n.pickerAvailable,n.chosen??null,n.pickerOrder,n.pickerOrderMode])}function t_(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 n_(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(!t_(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=$g(e.pickerOrder,n,t);return{fixed:o,order:[...new Set([...o,...s,...n])]}}function r_(e,t,n,r){let i=[...e];return t===n||r.includes(t)||r.includes(n)||!i.includes(t)||!i.includes(n)?i:(i.splice(i.indexOf(t),1),i.splice(i.indexOf(n),0,t),i)}function i_(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 a_=`application/x-ocx-picker-order`,o_=0;function s_(){let e=++o_;if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return`${e}:${crypto.randomUUID()}`}catch{}return`picker-${Date.now().toString(36)}-${e}`}function c_({apiBase:e,active:t,identities:n,onAccepted:r,onBusyChange:i}){let a=O(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),S=(0,Z.useRef)({generation:0,flight:null,drag:null}),[C,w]=(0,Z.useState)({apiBase:e,active:t,onBusyChange:i}),T=JSON.stringify(n.map(({provider:e,id:t,namespaced:n})=>[e,t,n])),E=(0,Z.useRef)(T);(0,Z.useLayoutEffect)(()=>{E.current=T},[T]);let D=o!==null&&o.identities!==T,k=!t||u||!o||f!==null||D,j=o!==null&&JSON.stringify(c)!==JSON.stringify(o.order),M=(0,Z.useCallback)(()=>{S.current.drag=null,y(null),x(null)},[]);(C.apiBase!==e||C.active!==t||C.onBusyChange!==i)&&(w({apiBase:e,active:t,onBusyChange:i}),s(null),l([]),p(null),h(!1),d(!1));let[N,P]=(0,Z.useState)({disabled:k,snapshot:o,identitySignature:T});(N.disabled!==k||N.snapshot!==o||N.identitySignature!==T)&&(P({disabled:k,snapshot:o,identitySignature:T}),y(null),x(null)),(0,Z.useLayoutEffect)(()=>{let e=S.current;return e.generation++,()=>{e.generation++,e.flight?.controller.abort(),e.flight?.clear(),e.flight=null,e.drag=null,i(!1)}},[e,t,i]),(0,Z.useLayoutEffect)(()=>{S.current.drag=null},[k,o,T]);let F=async a=>{if(!t||S.current.flight||a&&(k||!j))return;let u=S.current.generation,f=A(15e3);S.current.flight=f,d(!0),i(!0),h(!1),M();let m=()=>S.current.generation===u&&S.current.flight===f,g=()=>m()&&!f.signal.aborted&&E.current===T;try{let t=await fetch(`${e}/api/subagent-models`,{signal:f.signal});if(!g())return;let i=await hn(t);if(!g())return;if(!Kg(i))throw Error(`Invalid picker settings`);let d=e_(e,u,i);if(a&&(!o||d!==o.signature||T!==o.identities)){p(`models.pickerOrder.changed`);return}let m=n_(i,n);if(!m){p(i.pickerOrder.some(e=>!e.includes(`/`))?`models.pickerOrder.nativeLocked`:i.chosen===void 0?`models.pickerOrder.unknownChosen`:`models.pickerOrder.catalogRequired`);return}if(!a){s({...m,signature:d,identities:T}),l(m.order),p(null),_(``);return}let h=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:f.signal,body:JSON.stringify({pickerOrder:c,pickerOrderMode:null})});if(!g())return;let v=await hn(h);if(!g())return;if(!Gg(v)||!(`ok`in v)||v.ok!==!0)throw Error(`Invalid picker receipt`);l(v.pickerOrder),p(`models.pickerOrder.savedReload`),r({pickerOrder:v.pickerOrder,pickerOrderMode:v.pickerOrderMode,catalogRefresh:`catalogRefresh`in v?v.catalogRefresh:void 0})}catch{m()&&E.current===T&&h(!0)}finally{f.clear(),m()&&(S.current.flight=null,d(!1),i(!1))}},I=(0,Z.useEffectEvent)(async()=>{let e=S.current,n=e.generation;await Promise.resolve(),t&&e.generation===n&&F(!1)});(0,Z.useEffect)(()=>{t&&I()},[e,t,i]);let L=(e,t)=>{k||(l(t),_(a(`models.pickerOrder.position`,{model:e,position:t.indexOf(e)+1,total:t.length})),M())},R=new Set(c),z=new Set(o?.fixed),B=e=>!k&&R.has(e)&&!z.has(e),V=(e,t)=>{!S.current.drag||S.current.drag.id===t||!B(S.current.drag.id)||!B(t)||!e.dataTransfer.types.includes(a_)||(e.preventDefault(),e.dataTransfer.dropEffect=`move`,x(t))};return(0,Q.jsxs)(`section`,{className:`picker-order-editor`,"aria-label":a(`models.pickerOrder.custom`),"aria-busy":u,children:[(0,Q.jsx)(`p`,{className:`muted text-label`,children:a(`models.pickerOrder.editorHint`)}),(f||D)&&(0,Q.jsx)(`p`,{role:`alert`,children:a(f??`models.pickerOrder.changed`)}),m&&(0,Q.jsx)(`p`,{role:`alert`,children:a(`models.pickerOrder.requestFailed`)}),o&&c.length===0&&(0,Q.jsx)(`p`,{children:a(`models.pickerOrder.empty`)}),(0,Q.jsx)(`ol`,{className:`picker-order-list`,children:c.map((e,t)=>{let n=z.has(e);return(0,Q.jsxs)(`li`,{className:`picker-order-row${v===e?` cwi-target-row--dragging`:``}${b===e?` cwi-target-row--drop`:``}`,onDragOver:t=>V(t,e),onDragLeave:()=>x(null),onDrop:t=>{let n=S.current.drag;n&&n.id!==e&&n.token===t.dataTransfer.getData(a_)&&B(n.id)&&B(e)&&(t.preventDefault(),L(n.id,r_(c,n.id,e,o?.fixed??[]))),M()},onDragEnd:M,children:[(0,Q.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,disabled:k||n,draggable:!k&&!n,"aria-label":a(`models.pickerOrder.dragModel`,{model:e}),onDragStart:t=>{if(!B(e)){t.preventDefault();return}let n=s_();S.current.drag={id:e,token:n},y(e),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(a_,n)},children:(0,Q.jsx)(Fe,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`code`,{className:`picker-order-name`,children:e}),n&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`models.pickerOrder.featured`)}),(0,Q.jsxs)(`span`,{className:`picker-order-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===0||z.has(c[t-1]),"aria-label":a(`models.pickerOrder.upModel`,{model:e}),onClick:()=>L(e,i_(c,e,-1,o?.fixed??[])),children:(0,Q.jsx)(Ge,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===c.length-1||z.has(c[t+1]),"aria-label":a(`models.pickerOrder.downModel`,{model:e}),onClick:()=>L(e,i_(c,e,1,o?.fixed??[])),children:(0,Q.jsx)(Qe,{width:14,height:14,"aria-hidden":`true`})})]})]},e)})}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:g}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k||!j,onClick:()=>void F(!0),children:a(u?`models.pickerOrder.applying`:`models.pickerOrder.saveDraft`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t||u,onClick:()=>void F(!1),children:a(`models.pickerOrder.reloadDraft`)})]})]})}function l_({apiBase:e,onSaved:t}){let n=O(),[r,i]=(0,Z.useState)(!0),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!0),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(m.current)return;let t=++h.current,n=A(15e3);try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let a=await r.json();if(m.current||t!==h.current)return;if(typeof a.fastRows!=`boolean`)throw Error(`shape`);p.current=a.fastRows,i(a.fastRows),o(!0),u(!1)}catch{!m.current&&t===h.current&&u(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=sa(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async()=>{if(m.current||!a)return;let r=p.current,s=!r;p.current=s,i(s),m.current=!0,c(!0),f(null),h.current+=1;let l=A(15e3);try{let r=await hn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({fastRows:s}),signal:l.signal}))??{};if(r.ok!==!0||typeof r.fastRows!=`boolean`)throw Error(`unconfirmed`);p.current=r.fastRows,i(r.fastRows),o(!0),u(!1),f(r.catalogRefreshPending===!0?{tone:`warn`,message:n(`models.fastRows.refreshHint`)}:{tone:`ok`,message:n(r.fastRows?`models.fastRows.enabled`:`models.fastRows.disabled`)}),t?.()}catch{let a=A(15e3);try{let t=await fetch(`${e}/api/settings`,{signal:a.signal});if(!t.ok)throw Error(`reconcile`);let r=await t.json();if(typeof r.fastRows!=`boolean`)throw Error(`shape`);p.current=r.fastRows,i(r.fastRows),o(!0),u(!1),f(r.fastRows===s?{tone:`warn`,message:n(`models.fastRows.refreshHint`)}:{tone:`err`,message:n(`models.fastRows.updateFailed`)})}catch{p.current=r,i(r),f({tone:`err`,message:n(`models.fastRows.updateFailed`)})}finally{a.clear(),t?.()}}finally{l.clear(),m.current=!1,c(!1)}},[e,a,t,n]),v=l&&!a;return(0,Q.jsxs)(`div`,{className:`card card-row fast-rows-card`,"aria-busy":s||!a&&!v||void 0,children:[(0,Q.jsxs)(`div`,{className:`fast-rows-copy`,children:[(0,Q.jsx)(`strong`,{children:n(`models.fastRows.title`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:v?`status`:void 0,children:n(v?`models.fastRows.loadFailed`:a?`models.fastRows.desc`:`common.loading`)}),a&&l&&(0,Q.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:n(`models.fastRows.loadFailed`)})]}),(0,Q.jsxs)(`div`,{className:`fast-rows-controls`,children:[l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},disabled:s,children:n(`common.retry`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{_()},disabled:s,"aria-pressed":r,"aria-label":n(`models.fastRows.title`),title:n(`models.fastRows.title`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)(`div`,{className:`fast-rows-feedback is-${d.tone}`,role:d.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:d.message})]})}function u_({showOrderEditor:e,onSaved:t,...n}){return(0,Q.jsxs)(Q.Fragment,{children:[e&&(0,Q.jsx)(c_,{...n},n.apiBase),(0,Q.jsx)(l_,{apiBase:n.apiBase,onSaved:t})]})}var d_={operator:`models.displayNameSourceOperator`,provider:`models.displayNameSourceProvider`,fallback:`models.displayNameSourceFallback`};function f_({model:e,saving:t,requestError:n,currentNamePending:r=!1,mutationOutcomeUnknown:i=!1,onRetry:a,onEdit:o,onSave:s,onReset:c,onClose:l}){let u=O(),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(t),h=(0,Z.useId)(),g=(0,Z.useId)(),_=(0,Z.useId)(),[v,y]=(0,Z.useState)(e),[b,x]=(0,Z.useState)(e.displayNameOverride??``),[S,C]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=d.current;return e&&!e.open&&e.showModal(),f.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Z.useEffect)(()=>{let e=m.current&&!t&&!!n;m.current=t,e&&(i?p.current?.focus():f.current?.focus())},[n,t,i]),v!==e&&(y(e),x(e.displayNameOverride??``),C(null));let w=S?u(S):null,T=w??n,E=e.displayNameSource?d_[e.displayNameSource]:`models.displayNameSourceFallback`,D=()=>{t||l()};return(0,Q.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":h,onCancel:e=>{e.preventDefault(),D()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,disabled:t,onClick:D}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),t)return;if(a){a();return}if(i)return;let n=mc(b);C(n),n||s(b.trim())},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:h,children:u(`models.displayNameTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:D,children:u(`common.close`)})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameModelId`)}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-current`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameCurrent`)}),(0,Q.jsx)(`strong`,{children:r?u(`models.displayNameCurrentUnavailable`):e.displayName??e.namespaced}),!r&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:u(E)})]}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${h}-input`,children:u(`models.displayNameField`)}),(0,Q.jsx)(`input`,{ref:f,id:`${h}-input`,className:`input`,value:b,maxLength:129,placeholder:u(`models.displayNamePlaceholder`),"aria-describedby":`${g}${T?` ${_}`:``}`,"aria-invalid":w?!0:void 0,disabled:t||i,onChange:e=>{t||i||(o?.(),x(e.target.value),C(null))}}),(0,Q.jsx)(`p`,{id:g,className:`muted small`,children:u(`models.displayNameHelp`,{model:e.namespaced})}),T&&(0,Q.jsx)(`p`,{id:_,className:`model-display-name-error`,role:`alert`,children:T}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||i||!e.displayNameOverride,onClick:()=>{!t&&!i&&c()},children:u(`models.displayNameReset`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:t,onClick:D,children:u(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:p,type:`submit`,className:`btn btn-primary btn-sm`,disabled:t||i&&!a,children:u(t?`common.saving`:a?`common.retry`:`common.save`)})]})]})]})}var p_=[`input`,`output`,`cacheRead`,`cacheWrite`],m_={input:`pricing.override.input`,output:`pricing.override.output`,cacheRead:`pricing.override.cacheRead`,cacheWrite:`pricing.override.cacheWrite`},h_=1e6,g_=6e4,__={input:``,output:``,cacheRead:``,cacheWrite:``};function v_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function y_(e){return v_(e)&&p_.every(t=>typeof e[t]==`number`&&Number.isFinite(e[t])&&e[t]>=0&&e[t]<=h_)}function b_({model:e,apiBase:t,onRefresh:n,onClose:r}){let i=O(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)(`loading`),[p,m]=(0,Z.useState)(__),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(!1),x=`${t}/api/providers/${encodeURIComponent(e.provider)}/model-costs`,S=d===`saving`||d===`refreshing`,C=d!==`ready`,w=(0,Z.useCallback)((t=!1)=>{if(l.current)return;let n=A(g_);l.current=n,fetch(x,{signal:n.signal,cache:`no-store`}).then(async r=>{let i=await hn(r);if(n.signal.throwIfAborted(),!v_(i)||i.provider!==e.provider||!v_(i.modelCosts))throw Error(`invalid model-costs response`);let a=Object.hasOwn(i.modelCosts,e.id)?i.modelCosts[e.id]:void 0;if(a!==void 0&&!y_(a))throw Error(`invalid model cost`);l.current===n&&(m(a===void 0?__:{input:String(a.input),output:String(a.output),cacheRead:String(a.cacheRead),cacheWrite:String(a.cacheWrite)}),g(a!==void 0),b(t),f(`ready`))}).catch(()=>{l.current===n&&(f(t?`unknown`:`loadFailed`),v(t?`pricing.override.recoveryFailed`:`pricing.override.loadFailed`))}).finally(()=>{n.clear(),l.current===n&&(l.current=null)})},[x,e.id,e.provider]);(0,Z.useEffect)(()=>{let e=o.current;return e&&!e.open&&e.showModal(),w(),()=>{l.current?.controller.abort(),l.current?.clear(),l.current=null,e?.open&&e.close()}},[w]),(0,Z.useEffect)(()=>{d===`ready`?s.current?.focus():(d===`unknown`||d===`loadFailed`||d===`refreshFailed`)&&c.current?.focus()},[d]);let T=async t=>{if(l.current||(t===void 0?d!==`refreshFailed`:d!==`ready`))return;let i=A(g_);l.current=i,f(t===void 0?`refreshing`:`saving`),u.current=!0,v(null);let a=t===void 0;try{if(t!==void 0){let n=await hn(await fetch(x,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e.id,cost:t}),signal:i.signal}));i.signal.throwIfAborted();let r=v_(n)?n.cost:void 0;if(!v_(n)||n.ok!==!0||n.provider!==e.provider||n.modelId!==e.id||(t===null?r!==null:!y_(r)||!p_.every(e=>r[e]===t[e])))throw Error(`invalid model-costs receipt`);if(l.current!==i)return;a=!0,f(`refreshing`)}if(!await n(i.signal))throw Error(`catalog refresh failed`);i.signal.throwIfAborted(),l.current===i&&r()}catch{if(l.current!==i)return;f(a?`refreshFailed`:`unknown`),v(a?`pricing.override.refreshFailed`:`pricing.override.outcomeUnknown`)}finally{i.clear(),l.current===i&&(l.current=null,u.current=!1)}},E=()=>{u.current||r()};return(0,Q.jsxs)(`dialog`,{ref:o,className:`modal-overlay`,"aria-labelledby":`${a}-title`,onCancel:e=>{e.preventDefault(),E()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`pricing.override.close`),disabled:S,onClick:E}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,noValidate:!0,"aria-busy":d===`loading`||S,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),l.current)return;if(d===`unknown`||d===`loadFailed`){f(`loading`),v(null),w(d===`unknown`);return}if(d===`refreshFailed`){T(void 0);return}if(C)return;let t={input:Number(p.input),output:Number(p.output),cacheRead:Number(p.cacheRead),cacheWrite:Number(p.cacheWrite)};if([...e.currentTarget.querySelectorAll(`input`)].some(e=>e.validity.badInput)||!p.input.trim()||!p.output.trim()||!y_(t)){v(`pricing.override.invalid`),s.current?.focus();return}T(t)},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`${a}-title`,children:i(`pricing.override.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S,onClick:E,children:i(`pricing.override.close`)})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:i(`pricing.override.modelId`)}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsx)(`p`,{id:`${a}-help`,className:`muted small`,children:i(`pricing.override.help`)}),d===`loading`&&(0,Q.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.loading`)}),p_.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-${e}`,children:i(m_[e])}),(0,Q.jsx)(`input`,{ref:e===`input`?s:void 0,id:`${a}-${e}`,className:`input`,type:`number`,min:0,max:h_,step:`any`,inputMode:`decimal`,value:p[e],disabled:C,required:e===`input`||e===`output`,"aria-describedby":`${a}-help${_?` ${a}-error`:``}`,"aria-invalid":_===`pricing.override.invalid`||void 0,onChange:t=>{if(C||l.current)return;let n=t.target.value;m(t=>({...t,cacheRead:t.cacheRead||`0`,cacheWrite:t.cacheWrite||`0`,[e]:n})),v(null)}})]},e)),y&&(0,Q.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.recovered`)}),_&&(0,Q.jsx)(`p`,{id:`${a}-error`,className:`model-display-name-error`,role:`alert`,children:i(_)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:C||!h,onClick:()=>void T(null),children:i(`pricing.override.reset`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:S,onClick:E,children:i(`pricing.override.cancel`)}),(0,Q.jsx)(`button`,{ref:c,type:`submit`,className:`btn btn-primary btn-sm`,disabled:d===`loading`||S,children:i(S?`pricing.override.saving`:d===`unknown`||d===`loadFailed`?`pricing.override.reload`:d===`refreshFailed`?`pricing.override.refresh`:`pricing.override.save`)})]})]})]})}var x_=[`text`,`image`,`audio`],S_=[`100000`,`128000`,`200000`,`256000`,`352000`,`500000`,`1000000`],C_=6e4;function w_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T_(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 E_(e){return e.toSorted().join(`,`)}function D_(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 O_({row:e,apiBase:t,onRefresh:n,onFeedback:r,onClose:i}){let a=O(),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u]=(0,Z.useState)(()=>T_(e)),[d,f]=(0,Z.useState)(`ready`),[p,m]=(0,Z.useState)(()=>u.contextWindow),[h,g]=(0,Z.useState)(()=>u.contextWindow!==``&&!S_.includes(u.contextWindow)),[_,v]=(0,Z.useState)(()=>[...u.modalities]),[y,b]=(0,Z.useState)(()=>u.reasoning),[x,S]=(0,Z.useState)(()=>[...u.ladder]),[C,w]=(0,Z.useState)(()=>u.defaultEffort),[T,E]=(0,Z.useState)(null),D=d===`saving`||d===`restoring`,k=d===`unknown`||d===`saved-stale`;(0,Z.useEffect)(()=>{let e=s.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&typeof t.focus==`function`&&t.focus()}},[]),(0,Z.useEffect)(()=>{k&&c.current?.focus()},[k]);let j=async()=>{let t=A(C_);l.current=t;try{if(!await n(t.signal)||(t.signal.throwIfAborted(),l.current!==t))return;r(!0,a(`models.settingsReloaded`,{model:e.namespaced})),i()}catch{}finally{t.clear(),l.current===t&&(l.current=null)}},M=t=>{if(b(t),!t||x.length>0)return;let n=Array.isArray(e.reasoningEfforts)?e.reasoningEfforts:void 0;S(n&&n.length>0?[...n]:[...hc])},N=(e,t)=>{S(n=>t?[...n,e]:n.filter(t=>t!==e)),!t&&C===e&&w(``)},P=()=>{D||i()},F=async(o,s)=>{let c=A(C_);l.current=c,f(s?`restoring`:`saving`),E(null);let u=!1,d=!1;try{let f=await fetch(t+`/api/model-settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:e.provider,modelId:e.id,...o}),signal:c.signal});if(f.status>=400&&f.status<500)throw d=!0,Error(`model settings rejected`);let p=await hn(f);if(c.signal.throwIfAborted(),!w_(p)||p.ok!==!0||p.provider!==e.provider||p.modelId!==e.id||typeof p.changed!=`boolean`||typeof p.hasOverrides!=`boolean`||typeof p.saved!=`boolean`||p.saved!==p.changed||!w_(p.catalogRefresh)||![`committed`,`skipped`,`failed`].includes(String(p.catalogRefresh.status)))throw Error(`invalid model-settings receipt`);if(l.current!==c)return;if(u=!0,!p.changed){r(!0,a(s&&!p.hasOverrides?`models.settingsNothingToRestore`:`models.settingsNoChange`,{model:e.namespaced})),i();return}let m=p.catalogRefresh,h=m.status===`failed`||m.status===`skipped`&&m.retryable===!0;if(!await n(c.signal))throw Error(`catalog refresh failed`);if(c.signal.throwIfAborted(),l.current!==c)return;h?r(!1,a(`models.settingsSavedCodexStale`,{model:e.namespaced})):s?r(!0,a(`models.settingsRestored`,{model:e.namespaced})):r(!0,a(`models.settingsSaved`,{model:e.namespaced})),i()}catch{if(l.current!==c)return;if(d){f(`ready`),E(`models.settingsRejected`);return}f(u?`saved-stale`:`unknown`),E(u?`models.settingsRefreshFailed`:`models.settingsSaveFailed`)}finally{c.clear(),l.current===c&&(l.current=null)}},I=()=>{if(d!==`ready`)return;let e=D_(p);if(e===void 0){E(`models.contextInvalid`);return}let t=u,n={};p.trim()!==t.contextWindow&&(n.contextWindow=e),E_(_)!==E_(t.modalities)&&(n.inputModalities=_.length>0?[..._]:null);let r=y?E_(x):``;(y!==t.reasoning||r!==E_(t.ladder))&&(n.reasoningEfforts=y?[...x]:null);let a=y&&x.includes(C)?C:``;if(a!==t.defaultEffort&&(n.defaultReasoningEffort=a||null),Object.keys(n).length===0){i();return}F(n,!1)},L=async()=>{d===`ready`&&await na({message:a(`models.settingsRestoreConfirm`,{model:e.namespaced}),confirmLabel:a(`models.settingsRestore`),tone:`danger`})&&F({contextWindow:null,inputModalities:null,reasoningEfforts:null,defaultReasoningEffort:null},!0)},R=Array.isArray(e.inputModalities)?e.inputModalities.join(`, `):``,z=Array.isArray(e.inputModalities)?e.inputModalities.filter(e=>x_.includes(e)):[];return(0,Q.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":o+`-title`,onCancel:e=>{e.preventDefault(),P()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,disabled:D,onClick:P}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,noValidate:!0,"aria-busy":D,onClick:e=>e.stopPropagation(),onSubmit:e=>{e.preventDefault(),I()},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:o+`-title`,children:a(`models.settingsTitle`,{model:e.namespaced})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:P,children:a(`common.close`)})]}),T&&(0,Q.jsx)($,{tone:d===`saved-stale`?`warn`:`err`,children:a(T)}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[a(`models.customFieldModelId`),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[a(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(cn,{value:h?bc:p,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:bc,label:a(`models.custom`)}],onChange:e=>{if(e===`custom`){g(!0);return}g(!1),m(e)},disabled:D,label:a(`models.customFieldContext`),portal:!1}),h&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:p,onChange:e=>m(e.target.value),disabled:D,placeholder:a(`models.customPlaceholder`),"aria-label":a(`models.customFieldContext`)})]}),e.contextWindowDeclared===void 0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`models.settingsContextInherit`,{value:e.contextWindow?String(e.contextWindow):a(`models.settingsContextUnknown`)})})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[a(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:x_.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:_.includes(e),onChange:t=>{let n=t.target.checked;v(t=>{if(!n)return t.filter(t=>t!==e);let r=t.length>0?t:z;return[...new Set([...r,e])]})},disabled:D}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))}),_.length===0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`models.settingsModalitiesInherit`,{modalities:R||a(`models.settingsModalitiesUnknown`)})})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[a(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:y,onChange:e=>M(e.target.checked),disabled:D}),(0,Q.jsx)(`span`,{className:`text-control`,children:a(`models.customFieldReasoningOverride`)})]})}),y&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:hc.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:x.includes(e),onChange:t=>N(e,t.target.checked),disabled:D}),(0,Q.jsx)(`span`,{className:`text-control`,children:a(`models.reasoningEffort.`+e)})]},e))})]}),y&&(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[a(`models.settingsDefaultEffort`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsx)(cn,{value:C,options:[{value:``,label:`—`},...x.map(e=>({value:e,label:a(`models.reasoningEffort.`+e)}))],onChange:w,disabled:D,label:a(`models.settingsDefaultEffort`),portal:!1})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[k&&(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn btn-ghost`,onClick:()=>void j(),children:a(`models.settingsReload`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,title:a(`models.settingsRestoreHint`),disabled:D||k,onClick:()=>void L(),children:a(`models.settingsRestore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:P,disabled:D,children:a(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:D||k,children:a(D?`models.customSaving`:`models.customApply`)})]})]})]})}var k_=[`fresh`,`stale`,`not_running`,`unknown`],A_=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function j_(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function M_(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&k_.includes(t.stateBefore)&&typeof t.code==`string`&&A_.includes(t.code)&&j_(t.requested)&&j_(t.stopped)&&j_(t.surviving)&&j_(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`||!j_(n.stopped)||!j_(n.surviving)||n.relaunch!==`started`&&n.relaunch!==`skipped`||n.reason!==void 0&&typeof n.reason!=`string`||n.relaunch===`started`&&n.surviving.length>0)return!1}return!0}function N_(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&k_.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var P_={state:null,runningCount:0};async function F_(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 P_;let i=await r.json().catch(()=>null);return N_(i)?{state:i.state,runningCount:i.runningCount}:P_}catch{return P_}}var I_=3e4;function L_(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function R_(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=I_,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:L_(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:L_(e)?s():o()}}return M_(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function z_(e){return e===`stopped`||e===`nothing_running`}function B_(e,n){let{t:r}=t(),[i,a]=(0,Z.useState)(!1),o=(0,Z.useRef)(!0),s=(0,Z.useRef)(n.onSettled),c=(0,Z.useRef)(n.report),l=(0,Z.useRef)(e),u=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{s.current=n.onSettled,c.current=n.report},[n.onSettled,n.report]),(0,Z.useEffect)(()=>(l.current=e,()=>{u.current?.abort(),u.current=null}),[e]),(0,Z.useEffect)(()=>(o.current=!0,()=>{o.current=!1,u.current?.abort(),u.current=null}),[]),{restarting:i,restart:(0,Z.useCallback)(async()=>{let t=new AbortController;u.current?.abort(),u.current=t;let n=await na({message:r(`dash.codexRestartConfirm`),confirmLabel:r(`dash.codexRestart`),tone:`danger`,signal:t.signal});if(u.current===t&&(u.current=null),!n||!o.current||l.current!==e)return null;a(!0);let i=await R_(e,{formatFailure:e=>r(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>r(`dash.codexRestartUnreachable`),formatTimeout:()=>r(`dash.codexRestartTimeout`),formatMalformed:()=>r(`dash.codexRestartMalformed`)});if(o.current&&a(!1),!i.ok)return c.current(i.message,`err`),null;let d=i.result;return d.code===`stopped`?c.current(r(`dash.codexRestartDone`,{count:String(d.stopped.length)}),`ok`):d.code===`nothing_running`?c.current(r(`dash.codexRestartNothing`),`ok`):d.code===`enumeration_unavailable`?c.current(r(`dash.codexRestartUnknown`),`warn`):c.current(r(`dash.codexRestartPartial`,{count:String(d.surviving.length)}),`warn`),o.current&&z_(d.code)&&s.current?.(d.code),d.code},[e,r])}}async function V_(e,t,{apiBase:n,t:r,reloadAliases:i,publishFeedback:a}){let o=await ra({message:r(`models.aliasPrompt`),initialValue:t});if(o!==null){if(!(await fetch(`${n}/api/providers/${encodeURIComponent(e)}/alias`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:o.trim()||null})})).ok){a(!1,r(`models.aliasConflict`));return}await i(),a(!0,r(`models.aliasSaved`))}}async function H_(e,t,n,{apiBase:r,t:i,reloadAliases:a,publishFeedback:o}){let s=await ra({message:i(`models.modelAliasPrompt`),initialValue:n});if(s===null)return;let c=s.trim()?{set:{[t]:s.trim()}}:{remove:[t]};if(!(await fetch(`${r}/api/providers/${encodeURIComponent(e)}/model-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(c)})).ok){o(!1,i(`models.aliasConflict`));return}await a(),o(!0,i(`models.aliasSaved`))}var U_={"gpt-5.6-sol":J,"gpt-5.6-terra":qe,"gpt-5.6-luna":he,"gpt-daybreak-blue-latest":J,"daybreak-blue-latest":J,"daybreak-red-latest":at},W_={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function G_(e){return e.slice(e.lastIndexOf(`/`)+1)}function K_(e){return U_[e]??U_[G_(e)]??null}function q_(e){let t=K_(e);return t?(0,Z.createElement)(`span`,{className:`model-label`},(0,Z.createElement)(t,{style:W_,"aria-hidden":!0}),e):e}function J_(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Y_=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),X_=new Set([`unparseable`,`not-regular-file`,`foreign-edit`,`unowned-key`,`blocked-container`,`unresolvable-path`]);function Z_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q_(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function $_(e){if(!Z_(e)||e.clientId!==`aside`||!Q_(e.profileId)||typeof e.current!=`boolean`||typeof e.enabled!=`boolean`||!Y_.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&&!X_.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 ev(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Z_(n)||!Q_(n.profileId)||typeof n.ok!=`boolean`||n.state!==void 0&&!Y_.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 tv=[`qoder`,`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`];function nv(e){return e.clientId===`kilo`&&!!e.lastOpId&&(e.reason===`candidate-conflict`||e.state===`unsafe`&&!!e.candidateFailurePath&&e.candidateFailurePath!==e.configPath)}var rv=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`superseded_store`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),iv=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),av=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),ov=[`apply`,`overwrite`,`disable`,`restore`],sv=[`add`,`replace`,`remove`,`snapshot`,`ownership`,`journal`],cv=[`none`,`unowned`,`foreign-edit`,`drift`],lv=new Set([`version`,`clientId`,`operation`,`state`,`foreignEdit`,`changes`,`fingerprint`,`canApply`,`willChange`,`refusalReason`,`supersededReason`,`missingStoreDocument`,`profileId`]),uv=new Set([`owned-config-file`,`unestablished-schema`,`missing-store`]),dv=/^[\x20-\x7e]{1,64}$/,fv=new Set([`kind`,`path`]),pv=new Set([`$snapshot`,`$ownership`,`$journal`]),mv=new Set([`provider.opencodex`,`providers.opencodex`,`models.providers.opencodex`,`models.*`,`modelConfigs.customModels.*`,`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`]),hv=256;function gv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _v(e,t){return Object.keys(e).every(e=>t.has(e))}function vv(e){return pv.has(e)||mv.has(e)}function yv(){return new Sv(502,{code:`invalid_integration_preview_response`})}function bv(e){if(!gv(e)||!_v(e,lv)||e.version!==1||!tv.includes(e.clientId)||!ov.includes(e.operation)||!av.has(String(e.state))||!cv.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>hv||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&&!rv.has(String(e.refusalReason))||e.supersededReason!==void 0&&(e.refusalReason!==`superseded_store`||typeof e.supersededReason!=`string`||!uv.has(e.supersededReason))||e.missingStoreDocument!==void 0&&(e.supersededReason!==`missing-store`||typeof e.missingStoreDocument!=`string`||!dv.test(e.missingStoreDocument)))throw yv();let t=[],n=-1,r=``,i=new Map;for(let a of e.changes){if(!gv(a)||!_v(a,fv)||!sv.includes(a.kind)||typeof a.path!=`string`||!vv(a.path))throw yv();let e=sv.indexOf(a.kind);if(e<n||e===n&&a.path<=r)throw yv();let o=a.kind,s=i.get(o)??new Set;if(s.has(a.path))throw yv();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 yv();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 xv(e){return!gv(e)||!rv.has(String(e.reason))?!1:typeof e.error==`string`&&iv.has(String(e.code))&&tv.includes(e.clientId)&&av.has(String(e.state))&&typeof e.message==`string`}var Sv=class extends Error{refusal;status;body;stalePlan;constructor(e,t){let n=xv(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 Cv(e){return e instanceof Sv&&e.status===404&&e.body.code===`integration_operation_not_found`}async function wv(e){let t;try{t=await e.json()}catch{return{}}return gv(t)?t.code===`integration_preview_stale`?{code:t.code,plan:bv(t.plan)}:t:{}}async function Tv(e){if(!e.ok)throw new Sv(e.status,await wv(e));let t=await gn(e);if(t==null)throw new Sv(e.status,{});return t}function Ev(e){return e instanceof Sv&&e.body.code===`integration_preview_unavailable`}function Dv(e){return{operation:e.operation,planFingerprint:e.fingerprint}}function Ov(e){if(!Number.isSafeInteger(e)||e<0)throw new Sv(400,{code:`invalid_aside_profile`});return`/api/client-integrations/aside/profiles/${e}`}function kv(e,t){if(t!==void 0){if(e!==`aside`)throw new Sv(400,{code:`invalid_aside_profile`});return Ov(t)}return e===`aside`?`/api/client-integrations/aside/profiles`:`/api/client-integrations/${encodeURIComponent(e)}`}async function Av(e,t){return Tv(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function jv(e,t,n,r){let i=await Tv(await fetch(`${e}${kv(t,r)}`,{signal:n}));if(r!==void 0){let e=$_(i);if(!e||e.profileId!==r)throw new Sv(502,{code:`invalid_aside_profile_response`});return e}return i}async function Mv(e,t,n,r){if(r!==void 0&&t!==`aside`)throw new Sv(400,{code:`invalid_aside_profile`});let i=t===`aside`?`${kv(t,r)}/journal`:`/api/client-integrations/journal${t?`?client=${encodeURIComponent(t)}`:``}`,a=await Tv(await fetch(`${e}${i}`,{signal:n}));if(r!==void 0&&(!Array.isArray(a.operations)||a.operations.some(e=>e.clientId!==`aside`||e.profileId!==r)))throw new Sv(502,{code:`invalid_aside_profile_response`});return a}async function Nv(e,t,n,r,i,a){let o=i===void 0?`/api/client-integrations/preview`:`${Ov(i)}/preview`,s={...i===void 0?{clientId:t}:{},operation:n,...t===`droid`&&a!==void 0?{droidReasoningDefaults:a}:{}},c=bv(await Tv(await fetch(`${e}${o}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s),signal:r})));if(c.clientId!==t||c.operation!==n||c.profileId!==i)throw yv();return c}async function Pv(e,t,n=!1,r,i){let a=i===void 0?`/api/client-integrations/restore/preview`:`${Ov(i)}/preview`,o=i===void 0?{opId:t,confirmDrift:n}:{operation:`restore`,opId:t,confirmDrift:n},s=bv(await Tv(await fetch(`${e}${a}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o),signal:r})));if(s.operation!==`restore`||s.profileId!==i)throw yv();return s}async function Fv(e,t,n){let{enabled:r,signal:i,overwriteConflict:a,profileId:o,binding:s,droidReasoningDefaults:c}=n,l=r?a?`overwrite`:`apply`:`disable`,u;try{u=await Tv(await fetch(`${e}${kv(t,o)}`,{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 Sv&&e.stalePlan&&(e.stalePlan.clientId!==t||e.stalePlan.operation!==l||e.stalePlan.profileId!==o)?yv():e}let d=u.results===void 0?void 0:ev(u.results);if(t===`aside`&&u.results!==void 0&&(!d||u.ok!==d.every(e=>e.ok)))throw new Sv(502,{code:`invalid_aside_profile_response`});if(u.ok!==!0)throw new Sv(207,{code:t===`aside`?`aside_profile_partial`:`integration_mutation_failed`,message:u.message,results:d??void 0});if(o!==void 0&&u.profileId!==o)throw new Sv(502,{code:`invalid_aside_profile_response`});return{...u,...d?{results:d}:{}}}async function Iv(e,t){let{opId:n,confirmDrift:r=!1,signal:i,profileId:a,binding:o}=t,s;try{s=await Tv(await fetch(`${e}${a===void 0?`/api/client-integrations/restore`:`${Ov(a)}/restore`}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:n,confirmDrift:r,...o}),signal:i}))}catch(e){throw e instanceof Sv&&e.stalePlan&&(e.stalePlan.operation!==`restore`||e.stalePlan.profileId!==a)?yv():e}if(a!==void 0&&s.profileId!==a)throw new Sv(502,{code:`invalid_aside_profile_response`});return s}async function Lv(e,t,n,r){let i=await Tv(await fetch(`${e}${r===void 0?`/api/client-integrations/journal`:`${Ov(r)}/journal`}?opId=${encodeURIComponent(t)}`,{method:`DELETE`,signal:n}));if(r!==void 0&&i.profileId!==r)throw new Sv(502,{code:`invalid_aside_profile_response`});return i}async function Rv(e){try{let t=await e;return t.ok?await gn(t)??null:null}catch{return null}}async function zv(e,t){let n=await Rv(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 Bv(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await gn(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function Vv(e,t){let n=await Rv(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 Hv(e,t){let n=await Rv(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 Uv(e,t){let n=await Rv(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var Wv=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),Gv=new Set([`native_integration_refused`,`native_integration_failed`]),Kv=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function qv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jv(e){return qv(e)?typeof e.error==`string`&&Gv.has(String(e.code))&&Wv.has(String(e.clientId))&&Kv.has(String(e.reason))&&typeof e.message==`string`:!1}var Yv=class extends Error{refusal;status;body;constructor(e,t){let n=Jv(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 Xv(e){try{let t=await e;return t.ok?await gn(t)??null:null}catch{return null}}async function Zv(e){try{let t=await e.json();return qv(t)?t:{}}catch{return{}}}async function Qv(e){if(!e.ok)throw new Yv(e.status,await Zv(e));let t=await gn(e);if(t==null)throw new Yv(e.status,{});return t}function $v(e,t){return Xv(fetch(`${e}/api/native-integrations`,{signal:t}))}async function ey(e,t,n,r){return Qv(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var ty={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 ny(e){return e instanceof Sv?e.refusal:null}function ry(e){return e instanceof Yv?e.refusal:null}function iy(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var ay=new Set([`non_loopback`]);function oy(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 sy(e,t,n,r){let i=ry(t);if(i)return oy(e,i,r);let a=ny(t);if(!a){if(t instanceof Sv&&`results`in t.body&&t.body.results?.length){let n=t.body.results.filter(e=>!e.ok).map(t=>{let n=cy(e,t);return`${e(`integrations.aside.profile`,{id:String(t.profileId)})}: ${n}`});return[e(`integrations.aside.partial`),...n].join(`
|
|
6
|
+
`)}let r=ty[t instanceof Sv?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}return ly(e,a)}function cy(e,t){return ly(e,{clientId:`aside`,message:t.message??t.reason,reason:t.refusalReason??t.reason,snapshotPath:t.snapshotPath,residual:t.residual})}function ly(e,t){let n=ay.has(t.reason??``)?e(iy(t.reason),{client:t.clientId}):t.message||e(iy(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(iy(t.reason))} ${n}`:n}var uy=(e,t,n)=>JSON.stringify([e,t,n]),dy=new Map;function fy(e,t){let[n,r]=(0,Z.useState)({apiBase:e,overrides:dy,pending:!1});n.apiBase!==e&&r({apiBase:e,overrides:dy,pending:!1});let i=n.apiBase===e?n.overrides:dy,a=n.apiBase===e&&n.pending,o=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{o.current=t});let s=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e={active:!0,running:!1,queue:[],readVersion:0,bounded:null};return s.current=e,o.current.onBusy(!1),()=>{e.active=!1,e.queue.length=0,e.bounded?.controller.abort(),e.bounded?.clear()}},[e]);let c=async t=>{let n=null;for(;t.active;){for(;t.active&&t.queue.length>0;){let r=t.queue.shift(),i=A(6e4);t.bounded=i;try{let a=await Ts(e,r.scope,r.provider,r.targets,r.enabled,fetch,i.signal);if(t.active){if(!a.ok)n=`models.saveFailed`;else{let e=await a.json().catch(()=>void 0);t.active&&o.current.onResponse(e)}}}catch{if(!t.active)return;n=`models.networkError`}finally{i.clear(),t.bounded=null}}if(!t.active)return;let i=t.readVersion,a=!1,s=A(6e4);t.bounded=s;try{a=await o.current.refresh(s.signal)}catch{}finally{s.clear(),t.bounded=null}if(!t.active)return;if(!(t.queue.length||i!==t.readVersion)){t.running=!1,r({apiBase:e,overrides:dy,pending:!1}),o.current.onBusy(!1),o.current.onSettled(n??(a?null:`models.networkError`));return}}};return{pending:a,overrides:i,enqueue:(t,n,i,a)=>{let l=s.current;l?.active&&(l.queue.push({scope:t,provider:n,targets:i,enabled:a}),l.readVersion++,o.current.onQueued(),r(t=>{let r=new Map(t.apiBase===e?t.overrides:dy);for(let e of i)r.set(uy(n,e.id,e.native===!0),a);return{apiBase:e,overrides:r,pending:!0}}),l.running||(l.running=!0,o.current.onBusy(!0),c(l)))},isRunning:()=>s.current?.running===!0,visible:(e,t,n,r)=>i.get(uy(e,t,n))??r}}function py({className:e,style:t}){return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function my({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,Q.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,Q.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,Q.jsx)(py,{})},t))]})}function hy({children:e,busy:t=!0,live:n=!0,className:r}){return(0,Q.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,Q.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:e})]})}var gy=class extends Z.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:Error(String(e))}}reload=()=>{this.setState({error:null})};render(){return this.state.error?(0,Q.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,Q.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,Q.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,Q.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}};function _y(e,t){return e.length!==0&&e.every(e=>{let n=e.provider.trim(),r=e.model.trim();return!n||!r?!1:!!t.find(e=>e.provider===n&&e.id===r)?.inputModalities?.includes(`image`)})}function vy(e,t,n,r){if(t===`invalidDecisionTimeout`)return e(`cws.err.invalidDecisionTimeout`,{min:Mr,max:Nr});if(t===`invalidDecisionProvider`){let t=Pi(n.decisionProvider,r)??`missing`;return e(`cws.err.invalidDecisionProvider`,{name:n.decisionProvider??``,reason:e(Jr[t])})}return e(`cws.err.${t}`)}function yy(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function by(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function xy(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 Sy(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||xy(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))}function Cy({value:e,onChange:t,disabled:n}){let r=O();return(0,Q.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:Ur.map(i=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(Wr[i])},i))})}function wy({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=O(),o=i??Hr,s=t!==null&&!o.includes(t);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`select`,{id:e,className:`input`,value:t??``,disabled:r,"aria-label":a(`cws.field.defaultEffort`),onChange:e=>n(e.target.value===``?null:e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,Q.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}),s?(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function Ty({targets:e,models:t,imageInput:n,reasoningEffortMode:r,disabled:i,onChange:a}){let o=O(),s=_y(e,t),c=s&&n!==`disabled`;return(0,Q.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":o(`cws.capabilities`),children:[(0,Q.jsx)(`span`,{className:`field-label`,children:o(`cws.capabilities`)}),(0,Q.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`cwi-capability-label`,children:o(`cws.capability.imageInput`)}),(0,Q.jsx)(`p`,{className:`muted cwi-capability-hint`,children:o(s?`cws.capability.imageInputHint`:`cws.capability.imageInputUnavailable`)})]}),(0,Q.jsx)(on,{on:c,onClick:()=>{s&&a({imageInput:n===`auto`?`disabled`:`auto`})},disabled:i||!s,label:o(`cws.capability.imageInput`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`cwi-capability-label`,children:o(`cws.capability.adaptiveEffort`)}),(0,Q.jsx)(`p`,{className:`muted cwi-capability-hint`,children:o(`cws.capability.adaptiveEffortHint`)})]}),(0,Q.jsx)(on,{on:r===`adaptive`,onClick:()=>{a({reasoningEffortMode:r===`adaptive`?`strict`:`adaptive`})},disabled:i,label:o(`cws.capability.adaptiveEffort`)})]})]})}function Ey({targets:e,strategy:t,providers:n,models:r,capabilityModels:i=r,providerQuotaStates:a,onChange:o}){let s=O(),c=yy(n),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=t===`jev`?e.findIndex(e=>{let t=n.find(t=>t.name===e.provider.trim());return!!e.provider.trim()&&!!e.model.trim()&&t!==void 0&&t.disabled!==!0&&t.adapter!==`jev-decision`&&a[e.provider.trim()]!==`exhausted`}):-1,m=(t,n)=>{o(e.map((e,r)=>r===t?{...e,...n}:e))},h=(t,n)=>{o(e.map((e,r)=>{if(r!==t)return e;let{reasoningEfforts:i,modelProfile:a,...o}=e;return{...o,...n}}))},g=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[i]=r.splice(t,1);r.splice(n,0,i),o(r)};return(0,Q.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((_,v)=>{let y=n.find(e=>e.name===_.provider),b=y&&!c.some(e=>e.name===_.provider)?[...c,y]:c,x=Sy(r,_.provider,n),S=_.model&&!x.includes(_.model)?[_.model,...x]:x,C=!_.provider,w=l===v,T=d===v&&l!==null&&l!==v,E=a[_.provider.trim()]??`unknown`,D=i.find(e=>e.provider===_.provider&&e.id===_.model)?.reasoningEfforts,O=D===void 0?void 0:new Set(D),k=O===void 0?void 0:Hr.filter(e=>O.has(e)),A=new Set(k??[]),j=k===void 0?[]:_.reasoningEfforts===void 0?k:_.reasoningEfforts.filter(e=>A.has(e)),M=new Set(j);return(0,Q.jsxs)(`div`,{className:`cwi-target-entry`,children:[(0,Q.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`||t===`jev`?`cwi-target-row--failover`:``,w?`cwi-target-row--dragging`:``,T?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{l!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,d!==v&&f(v))},onDrop:e=>{e.preventDefault(),l!==null&&g(l,v),u(null),f(null)},onDragEnd:()=>{u(null),f(null)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":s(`cws.target.drag`),title:s(`cws.target.drag`),onDragStart:e=>{u(v),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(v))},children:(0,Q.jsx)(Fe,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===0,"aria-label":s(`cws.target.moveUp`),onClick:()=>g(v,v-1),children:(0,Q.jsx)(Ge,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===e.length-1,"aria-label":s(`cws.target.moveDown`),onClick:()=>g(v,v+1),children:(0,Q.jsx)(Qe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Q.jsxs)(`select`,{className:`input`,value:_.provider,"aria-label":s(`cws.target.provider`),onChange:e=>{let t=e.target.value,i=Sy(r,t,n)[0]??``;h(v,{provider:t,model:i})},children:[(0,Q.jsx)(`option`,{value:``,children:s(`cws.target.pickProvider`)}),b.map(e=>(0,Q.jsx)(`option`,{value:e.name,children:e.disabled?s(`cws.target.disabled`,{name:be(e.name,s)}):be(e.name,s)},e.name))]}),(0,Q.jsxs)(`select`,{className:`input`,value:_.model,disabled:C,"aria-label":s(`cws.target.model`),onChange:e=>h(v,{provider:_.provider,model:e.target.value}),children:[(0,Q.jsx)(`option`,{value:``,children:C?s(`cws.target.pickProviderFirst`):S.length===0?s(`cws.target.noModels`):s(`cws.target.pickModel`)}),S.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}),(t===`round-robin`||t===`random`)&&(0,Q.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:_.weight??1,"aria-label":s(`cws.target.weight`),onChange:e=>{let t=by(e.target.value,1,1e4);t!==void 0&&m(v,{weight:t})}}),(0,Q.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${E}`,"aria-label":s(`cws.quota.${E}`),children:s(`cws.quota.${E}`)}),(0,Q.jsx)(`div`,{className:`cwi-target-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>o(e.filter((e,t)=>t!==v)),"aria-label":s(`common.remove`),children:(0,Q.jsx)(F,{width:14,height:14})})})]}),t===`jev`&&(0,Q.jsxs)(`div`,{className:`cwi-jev-target-meta`,children:[v===p&&(0,Q.jsx)(`span`,{className:`chip`,children:s(`cws.jev.failOpen`)}),k===void 0?(0,Q.jsx)(`span`,{className:`muted`,children:s(`cws.jev.effortsUnknown`)}):k.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:s(`cws.jev.effortsNone`)}):(0,Q.jsxs)(`fieldset`,{className:`cwi-jev-efforts`,children:[(0,Q.jsx)(`legend`,{children:s(`cws.jev.allowedEfforts`)}),k.map(e=>{let t=M.has(e);return(0,Q.jsxs)(`label`,{className:`cwi-jev-effort`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,"data-jev-effort":!0,value:e,checked:t,disabled:t&&j.length===1,onChange:t=>{let n=new Set(j);t.target.checked?n.add(e):n.delete(e),m(v,{reasoningEfforts:k.filter(e=>n.has(e))})}}),(0,Q.jsx)(`span`,{children:e})]},e)})]}),(0,Q.jsxs)(`label`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:s(`cws.jev.modelProfile`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:3,maxLength:512,value:_.modelProfile??``,placeholder:s(`cws.jev.modelProfilePlaceholder`),onChange:e=>m(v,{modelProfile:e.target.value})}),(0,Q.jsx)(`span`,{className:`muted`,children:s(`cws.jev.modelProfileHint`)})]})]})]},_.clientKey??`${_.provider}:${_.model}`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>o([...e,Qr()]),children:[(0,Q.jsx)(N,{width:14,height:14}),` `,s(`cws.target.add`)]})]})}var Dy=[`typesafe`,`systemone`,`model`],Oy={typesafe:`cws.jev.method.typesafe`,systemone:`cws.jev.method.systemone`,model:`cws.jev.method.model`};function ky({idPrefix:e,apiBase:t,combo:n,combos:r,providers:i,models:a,decisionProvider:o,decisionModel:s,decisionTimeoutMs:c,disabled:l,onChange:u}){let d=O(),f=zr({decisionProvider:o,decisionModel:s}),p=(0,Z.useMemo)(()=>Fi(i,o).filter(e=>e.id!==null),[i,o]),m=p.find(e=>e.id===o?.trim()),{id:h,alias:g,model:_}=n,v=(0,Z.useMemo)(()=>Vr(a,i,r,{id:h,alias:g,model:_}),[a,i,r,h,g,_]),[y,b]=(0,Z.useState)(null),x=(0,Z.useRef)(null),S=`${f}\0${o??``}\0${s??``}\0${c??``}`,C=y?.key===S?y.result:null,w=e+`-decision-model-options`;(0,Z.useEffect)(()=>()=>{x.current?.abort(),x.current=null},[S]);let T=e=>{e!==f&&u(e===`typesafe`?{decisionProvider:null,decisionModel:null}:e===`systemone`?{decisionProvider:p.find(e=>!e.issue)?.id??p[0]?.id??``,decisionModel:null}:{decisionProvider:null,decisionModel:v[0]??``})},E=f===`typesafe`||f===`systemone`&&!!m&&!m.issue||f===`model`&&!!s?.trim(),D=async()=>{x.current?.abort();let e=new AbortController;x.current=e;let r=S,i=e=>b({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()}:{},...f===`systemone`&&o?{decisionProvider:o.trim()}:{},...f===`model`&&s?{decisionModel:s.trim()}:{},...c===null?{}:{decisionTimeoutMs:c}})});if(!r.ok){let t=await r.json().catch(()=>null);if(e.signal.aborted)return;i({state:`error`,message:t&&typeof t.error==`string`?t.error:String(r.status)});return}let a=await r.json().catch(()=>null);if(e.signal.aborted)return;if(!a||typeof a.gate!=`string`){i({state:`error`,message:String(r.status)});return}i({state:`done`,ok:a.ok===!0,backend:typeof a.backend==`string`?a.backend:`unknown`,gate:a.gate,latencyMs:typeof a.latencyMs==`number`?Math.round(a.latencyMs):0})}catch(t){if(e.signal.aborted)return;i({state:`error`,message:t instanceof Error?t.message:String(t)})}finally{x.current===e&&(x.current=null)}};return(0,Q.jsxs)(`fieldset`,{className:`cwi-field cwi-jev-decision`,"aria-describedby":`${e}-decision-method-hint`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:d(`cws.jev.decisionMethod`)}),(0,Q.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":d(`cws.jev.decisionMethod`),children:Dy.map(t=>(0,Q.jsx)(`button`,{type:`button`,id:`${e}-decision-method-${t}`,className:`btn btn-sm ${f===t?`btn-primary`:`btn-ghost`}`,"aria-pressed":f===t,disabled:l,onClick:()=>T(t),children:d(Oy[t])},t))}),(0,Q.jsxs)(`p`,{id:`${e}-decision-method-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[f===`typesafe`&&d(`cws.jev.decisionServiceDefaultHint`),f===`systemone`&&p.length===0&&d(`cws.jev.method.systemoneEmpty`)]}),f===`systemone`&&p.length>0&&(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-provider`,children:d(`cws.jev.decisionService`)}),(0,Q.jsxs)(`select`,{id:`${e}-decision-provider`,className:`input`,value:o?.trim()??``,disabled:l,"aria-describedby":m?.issue?`${e}-decision-provider-hint ${e}-decision-provider-issue`:`${e}-decision-provider-hint`,"aria-invalid":m?.issue?!0:void 0,onChange:e=>u({decisionProvider:e.target.value,decisionModel:null}),children:[!m&&(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`—`}),p.map(e=>(0,Q.jsx)(`option`,{value:e.id,disabled:e.issue!==void 0&&e.id!==m?.id,children:e.issue?`${e.id} (${d(Jr[e.issue])})`:e.id},e.id))]}),(0,Q.jsxs)(`p`,{id:`${e}-decision-provider-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[d(`cws.jev.decisionServiceHint`),m?.baseUrl&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`code`,{children:m.baseUrl})]})]}),m?.issue&&(0,Q.jsx)(`p`,{id:`${e}-decision-provider-issue`,className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:d(`cws.err.invalidDecisionProvider`,{name:m.id??``,reason:d(Jr[m.issue])})})]}),f===`model`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-model`,children:d(`cws.jev.decisionModel`)}),(0,Q.jsx)(`input`,{id:`${e}-decision-model`,className:`input mono`,list:w,value:s??``,maxLength:512,spellCheck:!1,autoComplete:`off`,placeholder:`ollama/qwen3:4b`,disabled:l,"aria-describedby":`${e}-decision-model-hint`,onChange:e=>u({decisionModel:e.target.value,decisionProvider:null})}),(0,Q.jsx)(`datalist`,{id:w,children:v.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),(0,Q.jsx)(`p`,{id:`${e}-decision-model-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:d(`cws.jev.decisionModelHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-timeout`,children:d(`cws.jev.decisionTimeout`)}),(0,Q.jsx)(`input`,{id:`${e}-decision-timeout`,className:`input mono`,type:`number`,inputMode:`numeric`,min:Mr,max:Nr,step:1,placeholder:String(Pr),value:c??``,disabled:l,"aria-describedby":`${e}-decision-timeout-hint`,onChange:e=>{if(e.target.value===``){u({decisionTimeoutMs:null});return}let t=Number(e.target.value);Number.isFinite(t)&&u({decisionTimeoutMs:t})}}),(0,Q.jsx)(`p`,{id:`${e}-decision-timeout-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:d(`cws.jev.decisionTimeoutHint`,{default:Pr,min:Mr,max:Nr})})]}),(0,Q.jsxs)(`div`,{className:`cwi-jev-decision-test`,style:{display:`flex`,gap:8,alignItems:`center`,flexWrap:`wrap`,marginTop:8},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:l||!E||C?.state===`running`,onClick:()=>{D()},children:C?.state===`running`?d(`cws.jev.testing`):d(`cws.jev.test`)}),(0,Q.jsxs)(`span`,{className:`muted`,role:`status`,"aria-live":`polite`,style:{fontSize:12,overflowWrap:`anywhere`},children:[C===null&&d(`cws.jev.testHint`),C?.state===`done`&&(C.ok?d(`cws.jev.testOk`,{ms:C.latencyMs,backend:d(Rr[C.backend]??`cws.jev.backend.unknown`)}):d(`cws.jev.testFailOpen`,{gate:C.gate,ms:C.latencyMs})),C?.state===`error`&&d(`cws.jev.testError`,{error:C.message})]})]})]})}var Ay=[];function jy({apiBase:e,combos:t=Ay,existingIds:n,existingAliases:r,providerMap:i,providerQuotaStates:a,providers:o,models:s,capabilityModels:c=s,initialDraft:l,onClose:u,onSubmit:d}){let f=O(),p=(0,Z.useRef)(null),[m,h]=(0,Z.useState)(()=>l?{...l,targets:l.targets.map(e=>({...e}))}:ji()),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(``),b=(0,Z.useMemo)(()=>{let e=new Map;for(let t of c)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[c]),x=(0,Z.useMemo)(()=>Yr(m.targets,b,m.reasoningEffortMode??`strict`),[m.targets,b,m.reasoningEffortMode]),S=Ti(m.targets,a,i)===`exhausted`,C=l?.strategy===`jev`,w=C&&(n.includes(m.id.trim())||!!m.alias?.trim()&&r.includes(m.alias.trim()));(0,Z.useEffect)(()=>{let e=p.current;e&&!e.open&&e.showModal()},[]);let T=(0,Z.useCallback)(()=>{g||u()},[g,u]),E=(0,Z.useCallback)(e=>{e.preventDefault(),T()},[T]),D=async()=>{let e=Ai(m,{existingIds:n,existingAliases:r,combos:t,isCreate:!0,providers:i});if(e){y(vy(f,e,m,i));return}_(!0),y(``);let a=m.id.trim(),o=m.alias?.trim()||null;try{let e=await d({...m,id:a,alias:o,model:oi(a,o)});if(!e.ok){y(e.error||f(`cws.saveFailed`));return}}finally{_(!1)}};return(0,Q.jsxs)(`dialog`,{ref:p,className:`modal-overlay`,"data-combo-preset":C?`jev-auto`:void 0,"aria-labelledby":`cwi-add-title`,onCancel:E,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":f(`common.close`),tabIndex:-1,onClick:T}),(0,Q.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,Q.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:f(`cws.addTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:T,disabled:g,"aria-label":f(`common.close`),children:(0,Q.jsx)(ve,{width:16,height:16})})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:f(C?`cws.jev.setupHint`:`cws.addSubtitle`)}),v&&(0,Q.jsx)($,{tone:`err`,children:v}),w&&(0,Q.jsx)($,{tone:`err`,children:f(`cws.jev.exists`)}),S&&(0,Q.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:f(`cws.quota.allExhausted`)}),(0,Q.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-id`,children:f(`cws.field.id`)}),(0,Q.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:m.id,disabled:g,onChange:e=>h(t=>({...t,id:e.target.value,model:oi(e.target.value,t.alias)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.idInternalHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:f(`cws.field.alias`)}),(0,Q.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:m.alias??``,placeholder:f(`cws.field.aliasPlaceholder`),disabled:g,onChange:e=>h(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:oi(t.id,e.target.value)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.aliasHint`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.idHint`,{model:m.id.trim()?oi(m.id,m.alias):`…`})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,Q.jsx)(Cy,{value:m.strategy,disabled:g,onChange:e=>h(t=>({...t,strategy:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(Gr[m.strategy])})]}),m.strategy===`jev`&&(0,Q.jsx)(ky,{idPrefix:`cwi-new`,apiBase:e,combo:m,combos:t,providers:o,models:s,decisionProvider:m.decisionProvider??null,decisionModel:m.decisionModel??null,decisionTimeoutMs:m.decisionTimeoutMs??null,disabled:g,onChange:e=>h(t=>({...t,...e}))}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:f(`cws.field.defaultEffort`)}),(0,Q.jsx)(wy,{id:`cwi-new-effort`,value:m.defaultEffort,disabled:g,allowedEfforts:x,onChange:e=>h(t=>({...t,defaultEffort:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),m.strategy===`round-robin`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:f(`cws.field.stickyLimit`)}),(0,Q.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:m.stickyLimit,disabled:g,onChange:e=>{let t=by(e.target.value,1,100);t!==void 0&&h(e=>({...e,stickyLimit:t}))}}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.stickyLimitHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,Q.jsx)(Ey,{targets:m.targets,strategy:m.strategy,providers:o,models:s,capabilityModels:c,providerQuotaStates:a,onChange:e=>h(t=>({...t,targets:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(Kr[m.strategy])})]}),(0,Q.jsx)(Ty,{targets:m.targets,models:c,imageInput:m.imageInput??`auto`,reasoningEffortMode:m.reasoningEffortMode??`strict`,disabled:g,onChange:e=>h(t=>({...t,...e}))})]}),(0,Q.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:T,disabled:g,children:f(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{D()},disabled:g||S||w,children:f(g?`common.saving`:`cws.create`)})]})]})]})}function My(e){return e===null?`—`:`${Math.round(e*100)}%`}function Ny(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 Py({apiBase:e,comboId:n,active:r}){let{t:i,locale:a}=t(),[o,s]=(0,Z.useState)(`30d`),c=(0,Z.useCallback)(async t=>{let r=new URLSearchParams({jev:`1`,comboId:n,range:o}),i=await fetch(`${e}/api/usage?${r}`,{signal:t});if(!i.ok)throw Error(String(i.status));return i.json()},[e,n,o]),l=Ua(`ocx.jev-stats.v1:${e}:${n}:${o}`,[e,n,o],c,{isEmpty:e=>e.summary.decisions===0,enabled:r,pollMs:3e4,pauseWhenHidden:!0,deadlineMs:6e4}),{state:u}=l,d=u.data;return r?(0,Q.jsxs)(`section`,{className:`jev-stats`,"aria-busy":u.refreshing,children:[(0,Q.jsxs)(`div`,{className:`jev-stats-toolbar`,children:[(0,Q.jsx)(`div`,{className:`segmented jev-stats-ranges`,role:`group`,"aria-label":i(`cws.jev.stats.range`),children:[`7d`,`30d`,`all`].map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm ${o===e?`btn-primary`:`btn-ghost`}`,"aria-pressed":o===e,onClick:()=>s(e),children:i(e===`all`?`usage.range.available`:`usage.range.${e}`)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>l.refresh(),children:i(`cws.jev.stats.refresh`)})]}),u.showSkeleton&&(0,Q.jsx)(my,{label:i(`cws.jev.stats.loading`),rows:4}),u.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`cws.jev.stats.loadFailed`)}),d&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(gr,{data:d}),(d.historyTruncated||d.entriesTruncated)&&(0,Q.jsx)($,{tone:`warn`,children:i(`cws.jev.stats.historyIncomplete`)}),d.error&&(0,Q.jsx)($,{tone:`err`,children:i(`cws.jev.stats.loadFailed`)}),d.summary.decisions===0?(0,Q.jsxs)(`div`,{className:`jev-stats-empty`,children:[(0,Q.jsx)(`h3`,{children:i(`cws.jev.stats.emptyTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(`cws.jev.stats.emptyBody`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`jev-stats-cards`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:i(`cws.jev.stats.decisions`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:d.summary.decisions.toLocaleString(a)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:i(`cws.jev.stats.appliedAndFailOpen`,{applied:d.summary.appliedDecisions,failOpen:d.summary.failOpenDecisions})})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:i(`cws.jev.stats.modelTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(d.summary.modelTotalTokens,a)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:i(`cws.jev.stats.measuredAttempts`,{measured:d.summary.measuredModelAttempts,total:d.summary.modelAttempts})})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:i(`cws.jev.stats.decisionTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(d.summary.decisionTotalTokens,a)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:i(`cws.jev.stats.measuredDecisions`,{measured:d.summary.decisionUsageReported,total:d.summary.decisions})})]})]}),(0,Q.jsxs)(`div`,{className:`jev-stats-facts`,children:[(0,Q.jsx)(`span`,{children:i(`cws.jev.stats.successful`,{count:d.summary.successfulRequests})}),(0,Q.jsx)(`span`,{children:i(d.summary.requestsWithModelFallback===1?`cws.jev.stats.fallbackOne`:`cws.jev.stats.fallbackMany`,{count:d.summary.requestsWithModelFallback})}),(0,Q.jsx)(`span`,{children:i(`cws.jev.stats.averageLatency`,{value:Ny(d.summary.averageLatencyMs,a)})}),(0,Q.jsx)(`span`,{children:i(`cws.jev.stats.averageConfidence`,{value:My(d.summary.averageConfidence)})})]}),(0,Q.jsx)(`div`,{className:`jev-stats-gates`,"aria-label":i(`cws.jev.stats.gates`),children:d.gates.map(e=>(0,Q.jsxs)(`span`,{className:`chip`,children:[e.gate,`: `,e.decisions]},e.gate))}),d.backends&&d.backends.length>0&&(0,Q.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`jev-stats-table`,"aria-label":i(`cws.jev.stats.backends`),children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`cws.jev.stats.backend`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.decisions`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.applied`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.latency`)})]})}),(0,Q.jsx)(`tbody`,{children:d.backends.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:i(Rr[e.backend]??`cws.jev.backend.unknown`)}),(0,Q.jsx)(`td`,{className:`num mono`,children:e.decisions.toLocaleString(a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:e.applied.toLocaleString(a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:Ny(e.averageLatencyMs,a)})]},e.backend))})]})}),(0,Q.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`jev-stats-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`cws.jev.stats.model`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.picks`)}),(0,Q.jsx)(`th`,{children:i(`cws.jev.stats.efforts`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.attempts`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.input`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.output`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.reasoning`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.cacheReadWrite`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.total`)})]})}),(0,Q.jsx)(`tbody`,{children:d.models.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:e.overflow?(0,Q.jsx)(`div`,{children:i(`cws.jev.stats.otherModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mono`,children:e.model}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:be(e.provider,i)})]})}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.picks,(0,Q.jsx)(`span`,{className:`jev-stats-cell-note`,children:i(`cws.jev.stats.appliedAndFailOpen`,{applied:e.appliedPicks,failOpen:e.failOpenPicks})})]}),(0,Q.jsx)(`td`,{children:e.efforts.length>0?e.efforts.map(e=>`${e.effort??i(`cws.jev.stats.noEffort`)} × ${e.picks}`).join(`, `):`—`}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.attempts,(0,Q.jsxs)(`span`,{className:`jev-stats-cell-note`,children:[e.measuredAttempts,` `,i(`cws.jev.stats.measuredShort`)]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.inputTokens,a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.outputTokens,a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.reasoningTokens,a)}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[q(e.cacheReadTokens,a),` / `,q(e.cacheWriteTokens,a)]}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,a)})]},e.overflow?`__jev_stats_overflow__`:`${e.provider}\0${e.model}`))})]})}),(0,Q.jsx)(`p`,{className:`muted text-caption jev-stats-footnote`,children:i(`cws.jev.stats.tokenFootnote`)})]})]})]}):null}var Fy={passthrough:`api.plan.disposition.passthrough`,translated:`api.plan.disposition.translated`,degraded:`api.plan.disposition.degraded`,unsupported:`api.plan.disposition.unsupported`},Iy={passthrough:`badge-green`,translated:`badge-accent`,degraded:`badge-amber`,unsupported:`badge-muted`};function Ly({effects:e,unknownFeatures:t}){let n=O();return e.length===0&&t.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:n(`api.plan.noFeatures`)}):(0,Q.jsxs)(`ul`,{className:`protocol-feature-list`,children:[e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e.feature}),(0,Q.jsx)(`span`,{className:`badge ${Iy[e.disposition]}`,children:n(Fy[e.disposition])})]},e.feature)),t.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:n(`api.plan.disposition.unknown`)})]},e))]})}var Ry=[`responses`,`chat`,`messages`],zy={native:`api.plan.mode.native`,translated:`api.plan.mode.translated`,"legacy-bridge":`api.plan.mode.legacyBridge`,blocked:`api.plan.mode.blocked`},By={native:`badge-green`,translated:`badge-accent`,"legacy-bridge":`badge-amber`,blocked:`badge-muted`},Vy={preserved:`api.plan.fidelity.preserved`,degraded:`api.plan.fidelity.degraded`,unknown:`api.plan.fidelity.unknown`},Hy={direct:`api.plan.routeKind.direct`,combo:`api.plan.routeKind.combo`,policy:`api.plan.routeKind.policy`,unknown:`api.plan.routeKind.unknown`},Uy=` → `;function Wy({path:e}){let t=O();return e.length>0?(0,Q.jsx)(`code`,{children:e.join(Uy)}):(0,Q.jsx)(`span`,{className:`muted`,children:t(`api.plan.noPath`)})}function Gy({features:e}){let t=O();return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:t(`api.plan.none`)}):(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:e.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})}function Ky({plan:e}){let t=O();return(0,Q.jsxs)(`div`,{className:`protocol-plan-result`,"aria-live":`polite`,children:[(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.overallMode`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`badge ${By[e.mode]}`,children:t(zy[e.mode])})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.routeKind`)}),(0,Q.jsx)(`dd`,{children:t(Hy[e.routeKind])})]}),e.reasonCodes.length>0&&(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:e.reasonCodes.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.guaranteed`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Gy,{features:e.guaranteedFeatures})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.partial`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Gy,{features:e.partialFeatures})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.policyRevision`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.policyRevision})})]})]}),e.candidates.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:t(`api.plan.noCandidates`)}):(0,Q.jsx)(`ol`,{className:`protocol-plan-candidates`,children:e.candidates.map(n=>(0,Q.jsxs)(`li`,{className:`protocol-plan-candidate`,children:[(0,Q.jsxs)(`div`,{className:`protocol-plan-candidate-head`,children:[(0,Q.jsxs)(`code`,{children:[n.provider,`/`,n.model]}),(0,Q.jsx)(`span`,{className:`badge ${By[n.mode]}`,children:t(zy[n.mode])}),!n.eligible&&n.mode!==`blocked`&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:t(`api.plan.ineligible`)})]}),(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.requestPath`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Wy,{path:n.requestPath})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.responsePath`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Wy,{path:n.responsePath})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.fidelity`)}),(0,Q.jsx)(`dd`,{children:t(Vy[n.fidelity])})]}),n.reasonCodes.length>0&&(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:n.reasonCodes.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})})]})]}),(0,Q.jsx)(Ly,{effects:n.featureEffects,unknownFeatures:n.unknownFeatures}),(0,Q.jsxs)(`div`,{className:`protocol-plan-links`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ig(n.provider),children:t(`protocolLinks.providerSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Fg({inbound:e.inbound,upstream:Dg(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]})]},`${n.provider}/${n.model}`))})]})}function qy({apiBase:e,models:t,protocolLabel:n}){let r=O(),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(`chat`),[c,l]=(0,Z.useState)(()=>new Set),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>v.current?.abort(),[]);let y=i||t[0]?.id||``,b=(0,Z.useMemo)(()=>pm.filter(e=>gm[e].includes(o)),[o]),x=e=>{s(e),l(t=>new Set([...t].filter(t=>gm[t].includes(e))))},S=(e,t)=>{l(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},C=async()=>{if(!y||f)return;v.current?.abort();let t=new AbortController;v.current=t,p(!0),h(!1);try{let n=await Um(e,{model:y,inbound:o,features:[...c]},t.signal);if(t.signal.aborted)return;n.kind===`unavailable`?(_(!0),d(null)):n.kind===`error`?h(!0):d(n.plan)}catch{}finally{v.current===t&&p(!1)}};return(0,Q.jsxs)(`div`,{className:`panel api-panel protocol-plan-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:r(`api.plan.title`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.description`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.modeNote`)}),g?(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.unavailable`)}):t.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`protocol-plan-form`,children:[(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:r(`api.plan.model`)}),(0,Q.jsx)(`select`,{className:`input`,value:y,onChange:e=>a(e.target.value),children:t.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.id},e.id))})]}),(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:r(`api.plan.inbound`)}),(0,Q.jsx)(`select`,{className:`input`,value:o,onChange:e=>x(e.target.value),children:Ry.map(e=>(0,Q.jsx)(`option`,{value:e,children:n(e)},e))})]})]}),(0,Q.jsxs)(`fieldset`,{className:`protocol-plan-features`,children:[(0,Q.jsx)(`legend`,{className:`muted small`,children:r(`api.plan.features`)}),b.map(e=>(0,Q.jsxs)(`label`,{className:`protocol-plan-feature`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:c.has(e),onChange:t=>S(e,t.target.checked)}),(0,Q.jsx)(`code`,{children:e})]},e))]}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:!y||f,onClick:()=>{C()},children:r(f?`api.plan.previewing`:`api.plan.preview`)})}),m&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:r(`api.plan.failed`)}),u&&(0,Q.jsx)(Ky,{plan:u})]})]})}function Jy({apiBase:e,model:t,dirty:n}){let r=O(),[i,a]=(0,Z.useState)(`responses`),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),m=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>m.current?.abort(),[]);let h=(0,Z.useMemo)(()=>pm.filter(e=>gm[e].includes(i)),[i]),g=async()=>{if(c)return;m.current?.abort();let n=new AbortController;m.current=n,l(!0),d(!1);try{let r=await Um(e,{model:t,inbound:i,features:h},n.signal);if(n.signal.aborted)return;r.kind===`unavailable`?p(!0):r.kind===`error`?d(!0):s(r.plan)}catch{}finally{m.current===n&&l(!1)}};return f?null:(0,Q.jsxs)(`section`,{className:`pwi-section combo-protocol-plan`,"aria-labelledby":`cws-plan-title`,children:[(0,Q.jsx)(`h3`,{id:`cws-plan-title`,className:`pwi-section-title`,children:r(`cws.plan.title`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`cws.plan.description`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.modeNote`)}),n&&(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:r(`cws.plan.savedOnly`)}),(0,Q.jsx)(`div`,{className:`protocol-plan-form`,children:(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:r(`api.plan.inbound`)}),(0,Q.jsx)(`select`,{className:`input`,value:i,onChange:e=>{a(e.target.value),s(null)},children:qp.map(e=>(0,Q.jsx)(`option`,{value:e,children:Xm(e,r)},e))})]})}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:c,onClick:()=>{g()},children:r(c?`api.plan.previewing`:`cws.plan.run`)})}),u&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:r(`api.plan.failed`)}),o&&o.inbound===i&&(0,Q.jsx)(Ky,{plan:o})]})}var Yy=[`config`,`about`],Xy=[`config`,`stats`,`about`],Zy=e=>`cws-detail-tab-${e}`,Qy=e=>`cws-detail-panel-${e}`,$y=[];function eb({apiBase:e,baseline:t,combos:n=$y,isCreate:r=!1,otherIds:i,otherAliases:a,providerMap:o,providerQuotaStates:s,providers:c,models:l,capabilityModels:u=l,onBack:d,onSaved:f,onRequestRemove:p,onSave:m,onDirtyChange:h}){let g=O(),[_,v]=(0,Z.useState)(`config`),y=!r&&t.strategy===`jev`?Xy:Yy,b=(0,Z.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%y.length;else if(e.key===`ArrowLeft`)n=(t-1+y.length)%y.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=y.length-1;else return;e.preventDefault(),v(y[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[y]),[x,S]=(0,Z.useState)(t),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(null),[D,k]=(0,Z.useState)(!1),A=!Oi(x,t),j=Ti(x.targets,s,o)===`exhausted`,M=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.targets.map(e=>[e.provider,e.model,e.weight,e.reasoningEfforts,e.modelProfile])]),N=(0,Z.useMemo)(()=>{let e=new Map;for(let t of u)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[u]),P=(0,Z.useMemo)(()=>Yr(x.targets,N,x.reasoningEffortMode??`strict`),[x.targets,N,x.reasoningEffortMode]),I=(0,Z.useCallback)(e=>{let n=e(x);S(n),h(!Oi(n,t))},[x,t,h]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{S(t),E(null),v(`config`),h(!1)},0);return()=>window.clearTimeout(e)},[M]);let L=async()=>{try{await navigator.clipboard.writeText(t.model),k(!0),window.setTimeout(()=>k(!1),1200)}catch{}},R=async()=>{let e=Ai(x,{existingIds:i,existingAliases:a,combos:n,isCreate:r,providers:o});if(e){E({ok:!1,text:vy(g,e,x,o)});return}w(!0);let s=x.id.trim(),c=x.alias?.trim()||null,l=x.displayName?.trim()||null,u={...x,id:s,alias:c,displayName:l,model:oi(s,c),...x.strategy===`jev`?{}:{decisionProvider:null,decisionModel:null,decisionTimeoutMs:null}},d=!r&&s!==t.id?t.id:void 0;try{let e=await m(u,r,d);if(!e.ok){E({ok:!1,text:e.error||g(`cws.saveFailed`)});return}E({ok:!0,text:r?g(`cws.created`,{model:u.model}):g(`cws.saved`)}),f(u)}finally{w(!1)}},z=r?x.id.trim()?oi(x.id,x.alias):g(`cws.addTitle`):t.model;return(0,Q.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[d&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:d,"aria-label":g(`cws.backToAll`),children:[(0,Q.jsx)(Ke,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),g(`cws.allCombos`)]}),(0,Q.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:z}),!r&&(0,Q.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{L()},title:g(`cws.copyModel`),children:g(D?`cws.copied`:`cws.copyModel`)}),(0,Q.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!r&&p&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:[(0,Q.jsx)(F,{width:14,height:14}),` `,g(`common.remove`)]}),(0,Q.jsx)(`button`,{id:r?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!r&&!A||C||j,onClick:()=>{R()},children:g(C?`common.saving`:r?`cws.create`:`common.save`)})]})]}),T&&(0,Q.jsx)($,{tone:T.ok?`ok`:`err`,children:T.text}),j&&(0,Q.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:g(`cws.quota.allExhausted`)}),(0,Q.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":g(`cws.tabsLabel`),children:y.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:Zy(e),"aria-selected":_===e,"aria-controls":Qy(e),tabIndex:_===e?0:-1,className:`btn btn-sm ${_===e?`btn-primary`:`btn-ghost`}`,onClick:()=>v(e),onKeyDown:e=>b(e,t),children:g(e===`config`?`cws.tab.config`:e===`stats`?`cws.jev.stats.tab`:`cws.tab.about`)},e))}),(0,Q.jsxs)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Qy(`config`),"aria-labelledby":Zy(`config`),hidden:_!==`config`,children:[(0,Q.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:g(`cws.field.id`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:x.id,disabled:C,onChange:e=>I(t=>({...t,id:e.target.value,model:oi(e.target.value,t.alias)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:r?g(`cws.field.idInternalHint`):g(`cws.field.idHintEdit`,{model:oi(x.id,x.alias)})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:g(`cws.field.alias`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:x.alias??``,placeholder:ai(x.id.trim()||`…`),disabled:C,onChange:e=>I(t=>si(t,e.target.value))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g(`cws.field.aliasHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,Q.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:x.nativeAlias,disabled:C,onChange:e=>I(t=>({...t,nativeAlias:e.target.checked}))}),` `,g(`cws.field.nativeAlias`)]}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g(`cws.field.nativeAliasHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:g(`cws.field.displayName`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:x.displayName??``,maxLength:128,disabled:C,onChange:e=>I(t=>({...t,displayName:e.target.value||null}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g(`cws.field.displayNameHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:g(`cws.strategy`)}),(0,Q.jsx)(Cy,{value:x.strategy,disabled:C,onChange:e=>I(t=>({...t,strategy:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g(Gr[x.strategy])})]}),x.strategy===`jev`&&(0,Q.jsx)(ky,{idPrefix:`cwi-edit`,apiBase:e,combo:x,combos:n,providers:c,models:l,decisionProvider:x.decisionProvider??null,decisionModel:x.decisionModel??null,decisionTimeoutMs:x.decisionTimeoutMs??null,disabled:C,onChange:e=>I(t=>({...t,...e}))}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-effort`,children:g(`cws.field.defaultEffort`)}),(0,Q.jsx)(wy,{id:`cwi-effort`,value:x.defaultEffort,disabled:C,allowedEfforts:P,onChange:e=>I(t=>({...t,defaultEffort:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g(`cws.field.defaultEffortHint`)})]}),x.strategy===`round-robin`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-sticky`,children:g(`cws.field.stickyLimit`)}),(0,Q.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:x.stickyLimit,disabled:C,onChange:e=>{let t=by(e.target.value,1,100);t!==void 0&&I(e=>({...e,stickyLimit:t}))}})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:g(`cws.targets`)}),(0,Q.jsx)(Ey,{targets:x.targets,strategy:x.strategy,providers:c,models:l,capabilityModels:u,providerQuotaStates:s,onChange:e=>I(t=>({...t,targets:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g(Kr[x.strategy])})]}),(0,Q.jsx)(Ty,{targets:x.targets,models:u,imageInput:x.imageInput??`auto`,reasoningEffortMode:x.reasoningEffortMode??`strict`,disabled:C,onChange:e=>I(t=>({...t,...e}))})]}),!r&&e!==void 0&&(0,Q.jsx)(Jy,{apiBase:e,model:t.model,dirty:A})]}),!r&&t.strategy===`jev`&&(0,Q.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Qy(`stats`),"aria-labelledby":Zy(`stats`),hidden:_!==`stats`,children:(0,Q.jsx)(Py,{apiBase:e??``,comboId:t.id,active:_===`stats`})}),(0,Q.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Qy(`about`),"aria-labelledby":Zy(`about`),hidden:_!==`about`,tabIndex:0,children:(0,Q.jsxs)(`section`,{className:`pwi-section`,children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:g(`cws.aboutTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:g(`cws.aboutBody`)})]})})]})}function tb({model:e,onCancel:t,onConfirm:n}){let r=O(),i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,Z.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,Q.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,Q.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,Q.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,Q.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function nb({onKeep:e,onDiscard:t}){let n=O(),r=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]);let i=(0,Z.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,Q.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,Q.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,Q.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,Q.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function rb(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 ib({combos:e,cataloguedComboIds:t,providerMap:n,providerQuotaStates:r,providers:i,onSelect:a,onAdd:o}){let s=O(),c=_i(e),l=Ei(e,{cataloguedComboIds:t,providers:n,providerQuotaStates:r}),u=e.flatMap(e=>{let t=Ii(e,i);return t?[{item:e,decision:t}]:[]});return(0,Q.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,Q.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:s(`cws.overviewTitle`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:o,children:[(0,Q.jsx)(N,{width:14,height:14}),` `,s(`cws.add`)]})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:s(`cws.overviewBlurb`)}),(0,Q.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:e.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.total`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:c.failover.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.failover`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:c.roundRobin.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.roundRobin`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:c.other.length}),(0,Q.jsx)(`span`,{children:s(`cws.count.other`)})]})]}),(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.howTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.howTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:0},children:s(`cws.howBody`)})]}),u.length>0&&(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.jev.decisionServicesTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.jev.decisionServicesTitle`)}),(0,Q.jsx)(`div`,{className:`cwi-attention-list`,children:u.map(({item:e,decision:t})=>(0,Q.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,style:{flexWrap:`wrap`},"data-decision-provider":t.model?void 0:t.provider??`jev`,"data-decision-model":t.model??void 0,onClick:()=>a(e.id),children:[(0,Q.jsx)(`code`,{className:`chip`,children:e.model}),t.model?(0,Q.jsxs)(`span`,{children:[s(`cws.jev.method.model`),`: `,(0,Q.jsx)(`code`,{children:t.model})]}):(0,Q.jsx)(`span`,{children:t.provider??s(`cws.jev.decisionServiceDefault`)}),t.baseUrl&&(0,Q.jsx)(`code`,{className:`muted`,style:{overflowWrap:`anywhere`},children:t.baseUrl}),(0,Q.jsx)(`span`,{className:`muted`,children:t.timeoutMs===null?s(`cws.jev.decisionTimeoutDefaultShort`):s(`cws.jev.decisionTimeoutShort`,{ms:t.timeoutMs})}),(0,Q.jsx)(Ke,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},e.id))})]}),l.length>0&&(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":s(`cws.attentionTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:s(`cws.attentionTitle`)}),(0,Q.jsx)(`div`,{className:`cwi-attention-list`,children:l.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>a(e.id),children:[(0,Q.jsx)(Ae,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`code`,{className:`chip`,children:e.model}),(0,Q.jsx)(`span`,{className:`muted`,children:rb(e.reason,s)}),(0,Q.jsx)(Ke,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function ab({apiBase:e,combos:t,providerQuotaStates:n,providers:r,models:i,capabilityModels:a=i,cataloguedComboIds:o,loading:s,onRefresh:c,onSave:l,onRemove:u,onAdd:d,adding:f,addIntent:p,addDecisionProvider:m,onCloseAdd:h,onCreated:g}){let _=O(),v=(0,Z.useMemo)(()=>Object.fromEntries(r.map(e=>[e.name,{disabled:e.disabled,adapter:e.adapter,baseUrl:e.baseUrl,defaultModel:e.defaultModel,models:e.models}])),[r]),[y,b]=(0,Z.useState)(``),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(void 0),[T,E]=(0,Z.useState)(null),[D,k]=(0,Z.useState)(null),A=(0,Z.useMemo)(()=>ji(),[]),j=(0,Z.useMemo)(()=>t.some(e=>e.id===`jev-auto`||e.alias===`jev-auto`),[t]),M=(0,Z.useMemo)(()=>new Set(r.filter(e=>!e.disabled&&!e.hiddenFromPicker&&e.adapter!==`jev-decision`).map(e=>e.name)),[r]),P=(0,Z.useMemo)(()=>{if(p!==`jev-auto`)return;let e=r.length===0||Pi(m,v)===null;return Ni(i,M,e?m:null)},[m,p,M,i,v,r.length]),F=(0,Z.useMemo)(()=>vi(t,y),[t,y]),I=(0,Z.useMemo)(()=>_i(F),[F]),L=(0,Z.useMemo)(()=>t.flatMap(e=>e.alias?[e.alias]:[]),[t]),R=x&&t.some(e=>e.id===x)?x:null,z=t.find(e=>e.id===R)??null,B=z&&D?.id===z.id?D:z,[V,H]=(0,Z.useState)(!1),W=[],G=[];if(B)for(let e of t)e.id!==B.id&&(W.push(e.id),e.alias&&G.push(e.alias));let ee=(0,Z.useCallback)(e=>{if(e!==R){if(!V){S(e),k(null);return}w(e)}},[R,V]),K=()=>{C!==void 0&&(S(C),k(null),H(!1),w(void 0))},q=()=>w(void 0),te=C!==void 0&&V,ne=!s&&t.length===0&&!f;return(0,Q.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,Q.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":_(`cws.railAria`),children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`combos-workspace-rail-title`,children:_(`nav.combos`)}),(0,Q.jsx)(`div`,{className:`combos-workspace-rail-count`,children:t.length})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(ne){document.getElementById(`cwi-edit-id`)?.focus();return}d()},"aria-label":_(`cws.add`),children:[(0,Q.jsx)(N,{width:14,height:14}),` `,_(`cws.add`)]})]}),(0,Q.jsxs)(`div`,{className:`cwi-jev-quick-action`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(`jev-auto`),disabled:j,title:_(j?`cws.jev.exists`:`cws.jev.setupHint`),children:[(0,Q.jsx)(U,{width:14,height:14}),` `,_(`cws.jev.create`)]}),j&&(0,Q.jsx)(`span`,{className:`muted`,children:_(`cws.jev.exists`)})]}),t.length>0&&(0,Q.jsx)(`div`,{className:`cwi-search-row`,children:(0,Q.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,Q.jsx)(X,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{className:`input cwi-search-input`,value:y,onChange:e=>b(e.target.value),placeholder:_(`cws.searchPlaceholder`),"aria-label":_(`cws.searchPlaceholder`)})]})}),(0,Q.jsx)(`div`,{className:`combos-workspace-rail-list`,children:F.length===0&&t.length>0?(0,Q.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:_(`cws.noSearchResults`)}):(0,Q.jsx)(Q.Fragment,{children:[[`failover`,I.failover,`cws.group.failover`],[`round-robin`,I.roundRobin,`cws.group.roundRobin`],[`other`,I.other,`cws.group.other`]].map(([e,t,n])=>t.length>0?(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,Q.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),_(n),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${R===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>ee(e.id),"aria-current":R===e.id?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(U,{width:16,height:16})}),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?_(`cws.targetCountOne`):_(`cws.targetCount`,{count:e.targets.length})}),(0,Q.jsx)(Ke,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,Q.jsx)(`div`,{className:`combos-workspace-main`,children:B?(0,Q.jsx)(eb,{apiBase:e,baseline:B,combos:t.filter(e=>e.id!==B.id),otherIds:W,otherAliases:G,providerMap:v,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,onBack:()=>ee(null),onSaved:e=>{H(!1),e.id===B.id?k(e):(S(e.id),k(null)),c()},onRequestRemove:()=>E(B.id),onSave:l,onDirtyChange:H},B.id):ne?(0,Q.jsx)(eb,{apiBase:e,baseline:A,isCreate:!0,otherIds:[],otherAliases:[],providerMap:v,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,onSaved:e=>{H(!1),S(e.id),k(e),g(e.id)},onSave:l,onDirtyChange:H},`first-combo`):(0,Q.jsx)(ib,{combos:t,cataloguedComboIds:o,providerMap:v,providerQuotaStates:n,providers:r,onSelect:e=>ee(e),onAdd:d})}),f&&(0,Q.jsx)(jy,{apiBase:e,combos:t,existingIds:t.map(e=>e.id),existingAliases:L,providerMap:v,providerQuotaStates:n,providers:r,models:i,capabilityModels:a,initialDraft:P,onClose:h,onSubmit:async e=>{let t=await l(e,!0);return t.ok&&(h(),g(e.id),S(e.id),k(null)),t}},`${p??`blank`}:${P?.decisionProvider??``}`),T&&(0,Q.jsx)(tb,{model:t.find(e=>e.id===T)?.model??ai(T),onCancel:()=>E(null),onConfirm:()=>{(async()=>{let e=await u(T);E(null),e.ok&&(R===T&&(S(null),k(null)),c())})()}}),te&&(0,Q.jsx)(nb,{onKeep:q,onDiscard:K})]})}function ob(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function sb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function cb(e){return za(e)?.data??null}function lb(e){return za(e)?.cachedAt??null}function ub({apiBase:e,active:t=!0,onCountChange:n}){let r=O(),i=`ocx.combos.workspace.v1:${e}`,a=(0,Z.useMemo)(()=>cb(i),[i]),[o,s]=(0,Z.useState)(a??null),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(()=>_g(window.location.hash)===void 0?null:`jev-auto`),[m,h]=(0,Z.useState)(()=>_g(window.location.hash)??null),g=(0,Z.useCallback)(()=>{p(null),h(null),_g(window.location.hash)!==void 0&&Kt(`models/combos`)},[]),_=(e,t)=>{l(e),d(t)};(0,Z.useEffect)(()=>{if(!c||!u)return;let e=window.setTimeout(()=>{l(``),d(!1)},5e3);return()=>window.clearTimeout(e)},[c,u]);let v=(0,Z.useCallback)(async t=>{let[n,r,a]=await Promise.all([fetch(`${e}/api/combos`,{signal:t}),fetch(`${e}/api/config`,{signal:t}),fetch(`${e}/api/models`,{signal:t})]);if(!n.ok||!r.ok||!a.ok)throw Error(`combo workspace load failed`);let o=await n.json(),c=await r.json(),l=await a.json(),u=Array.isArray(l)?l:Array.isArray(l?.models)?l.models:[],d=gi(o),f=c.providers??{},p=P(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;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=Array.isArray(t.inputModalities)?t.inputModalities.flatMap(e=>{let t=typeof e==`string`?e.trim():``;return t?[t]:[]}):void 0,o={provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{},...a&&a.length>0?{inputModalities:a}:{}};g.push(o),t.disabled!==!0&&h.push(o)}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 v={combos:d,providers:m,models:h,capabilityModels:g,cataloguedComboIds:[..._]};return Ba(i,v),s(v),v},[e,i]),y=Ua(i,[e],v,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:lb(i),staleAfterMs:6e4,enabled:t}),{state:b}=y,[x,S]=(0,Z.useState)(()=>Date.now()),C=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`combo quota load failed`);let r=await n.json();return t?.aborted||S(Date.now()),r&&typeof r==`object`&&!Array.isArray(r)?r:{}},[e]),w=Ua(`ocx.combos.provider-quotas.v1:${e}`,[e],C,{isEmpty:()=>!1,pollMs:6e4,pauseWhenHidden:!0,enabled:t}),T=t&&w.lastAttemptOk?w.data?.reports:void 0,E=wi(T,x),D=Ci(T,x);(0,Z.useEffect)(()=>{if(!t)return;let e=()=>S(Date.now()),n=window.setTimeout(e,D===void 0?0:Math.max(0,D-Date.now())),r=dt(()=>{ut()||e()});return()=>{window.clearTimeout(n),r()}},[t,e,w.data,w.lastAttemptOk,D]);let k=b.data??o??void 0,A=k?.combos??[];(0,Z.useEffect)(()=>{k&&n?.(A.length)},[A.length,k,n]);let j=k?.providers??[],M=k?.models??[],N=k?.capabilityModels??M,F=new Set(k?.cataloguedComboIds??[]),I=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(ki(t,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=ob(o);if(!a.ok||s||!sb(o)){let e=s||r(`cws.saveFailed`);return _(e,!1),{ok:!1,error:e}}return y.refresh(),_(i?r(`cws.renamed`,{from:ai(i),to:t.model}):n?r(`cws.created`,{model:t.model}):r(`cws.saved`),!0),{ok:!0}}catch{let e=r(`cws.saveFailed`);return _(e,!1),{ok:!1,error:e}}},L=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=ob(i);if(!n.ok||a||!sb(i)){let e=a||r(`cws.removeFailed`);return _(e,!1),{ok:!1,error:e}}return y.refresh(),_(r(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=r(`cws.removeFailed`);return _(e,!1),{ok:!1,error:e}}};if(b.showSkeleton&&!k)return(0,Q.jsx)(my,{label:r(`cws.loading`),rows:5});if(b.kind===`failed-cold`&&!k){let e=b.error instanceof Error?b.error.message:r(`cws.loadFailed`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>y.refresh(),children:r(`common.retry`)})]})}return(0,Q.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,Q.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Q.jsx)($,{tone:u?`ok`:`err`,children:c})}),b.showError&&(0,Q.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Q.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,Q.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":b.refreshing,children:[(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:b.refreshing?r(`common.loading`):``}),(0,Q.jsx)(ab,{apiBase:e,combos:A,providerQuotaStates:E,providers:j,models:M,capabilityModels:N,cataloguedComboIds:F,loading:!1,onRefresh:()=>{y.refresh(),w.refresh()},onSave:I,onRemove:L,onAdd:(e=`blank`)=>p(e),adding:f!==null,addIntent:f??void 0,addDecisionProvider:m,onCloseAdd:g,onCreated:()=>y.refresh()})]})]})}var db=0;function fb(){return db+=1,`candidate-${db}`}function pb(e,t){return{provider:e,model:t,key:fb()}}function mb(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 hb(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:mb(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 gb={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},_b={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function vb(e){return e===!0?`true`:e===!1?`false`:``}function yb(e){return e===void 0?``:String(e)}function bb(e=``,t=``){return{id:``,alias:``,candidates:[pb(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...gb},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{..._b},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function xb(e){let t=hb(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:fb()})),require:{minContextWindow:yb(e.require.minContextWindow),minQuotaHeadroom:yb(e.require.minQuotaHeadroom),tools:vb(e.require.tools),imageInput:vb(e.require.imageInput),structuredOutput:vb(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:vb(e.require.localOnly),remoteAllowed:vb(e.require.remoteAllowed),encryptedCodexTasks:vb(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:yb(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:yb(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function Sb(e){let t=e.trim();return t?Number(t):void 0}function Cb(e){if(e===`true`)return!0;if(e===`false`)return!1}function wb(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Tb(e,t,n){let r=wb({minContextWindow:Sb(e.require.minContextWindow),minQuotaHeadroom:Sb(e.require.minQuotaHeadroom),tools:Cb(e.require.tools),imageInput:Cb(e.require.imageInput),structuredOutput:Cb(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:Cb(e.require.localOnly),remoteAllowed:Cb(e.require.remoteAllowed),encryptedCodexTasks:Cb(e.require.encryptedCodexTasks)}),i=Sb(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?wb({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:Sb(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=wb({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 Eb(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 Db(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Ob(e,t){return e.filter(e=>e.provider===t)}var kb={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`}},Ab=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],jb=[`reasoningEffort`,`serviceTier`],Mb={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},Nb=Object.keys(Mb),Pb=[`latency`,`health`,`cost`,`quota`],Fb=[`capability`,`health`,`quota`,`cost`],Ib=[`allow`,`penalize`,`exclude`],Lb=[`allow`,`exclude`];function Rb(e){return`${e.evidenceLayer}:${e.suiteId}`}function zb(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Bb(e){let t=new Set,n=[];for(let r of e){if(!zb(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=Rb(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 Vb(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function Hb(e,t){return e===void 0?t:`${Math.round(e)}ms`}function Ub(e,t){return e==null?t:`${Math.round(e*100)}%`}function Wb(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 Gb(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 Kb(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>zb(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&zb(e.require)&&zb(e.optimize)&&zb(e.limits)&&zb(e.unknownEvidence):!1).map(e=>{let t=hb(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function qb(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 Jb(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 Yb({apiBase:e,active:n=!0,onCountChange:r}){let{locale:i,t:a}=t(),o=kb[i],s=a(`routing.unavailable`),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)({}),[g,_]=(0,Z.useState)([]),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(``),[A,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(``),[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)([]),[W,G]=(0,Z.useState)(!1),ee=(0,Z.useRef)(null),K=(0,Z.useRef)(0),q=(0,Z.useRef)(null),te=(0,Z.useRef)(!0),ne=(0,Z.useCallback)(()=>{te.current=!1,q.current?.abort(),K.current++},[]),J=(0,Z.useRef)(0),Y=(0,Z.useCallback)((e,t)=>{T({message:e,ok:t})},[]);(0,Z.useEffect)(()=>{if(!w?.ok)return;let e=window.setTimeout(()=>T(null),5e3);return()=>window.clearTimeout(e)},[w]);let re=(0,Z.useCallback)(()=>{J.current+=1,L(null),z(``),V(!1)},[]),ie=(0,Z.useCallback)(e=>{ee.current=e,x(e),C(e?xb(e):null),T(null),re()},[re]),X=(0,Z.useCallback)(async t=>{if(!te.current)return;q.current?.abort();let n=new AbortController;q.current=n;let{signal:r}=n,i=++K.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!==K.current)return;let y=Kb(u),b=ee.current,S=Jb(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()]));ee.current=S,l(y),x(S),C(S?xb(S):null),d(f),p(T),h(E),_(qb(g)),v&&Array.isArray(v.scenarios)?(U(Bb(v.scenarios)),G(!1)):(U([]),G(!0)),(!b||!S||b.id!==S.id||b.revision!==S.revision)&&re()}catch(e){if(i!==K.current||r.aborted)return;y(e instanceof Error?e.message:String(e))}finally{q.current===n&&(q.current=null)}},[e,re]);(0,Z.useEffect)(()=>{if(!n){ne();return}te.current=!0;let e=window.setTimeout(()=>void X(),0);return()=>{window.clearTimeout(e),ne()}},[n,ne,X]),(0,Z.useEffect)(()=>{r?.(c.length)},[r,c.length]);let ae=f[0]??``,oe=m[ae]??Ob(g,ae)[0]?.id??``,se=()=>{ee.current=null,x(null),C(bb(ae,oe)),T(null),re()},ce=()=>{if(b){C(xb(b)),T(null);return}ie(c[0]??null)},le=async()=>{if(!(!S||E)){D(!0),T(null);try{let t=Tb(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 gn(n);if(!n.ok){let e=await n.json().catch(()=>null);Y(Eb(e)??a(`routing.loadFailed`),!1);return}if(!Db(r)){Y(Eb(r)??a(`routing.loadFailed`),!1);return}await X(t.id),Y(a(`common.ok`),!0)}catch(e){Y(e instanceof Error?e.message:a(`routing.loadFailed`),!1)}finally{D(!1)}}},ue=async()=>{if(!(!b||E)&&await na({message:a(`routing.removeConfirm`,{id:b.id}),confirmLabel:a(`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 gn(t);if(!t.ok){let e=await t.json().catch(()=>null);Y(Eb(e)??a(`routing.loadFailed`),!1);return}if(!Db(n)){Y(Eb(n)??a(`routing.loadFailed`),!1);return}ee.current=null,await X(),Y(a(`common.ok`),!0)}catch(e){Y(e instanceof Error?e.message:a(`routing.loadFailed`),!1)}finally{D(!1)}}},de=(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]??Ob(g,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},fe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,pb(ae,oe)]})},pe=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},me=async()=>{if(!b)return;let t=++J.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 i=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!==J.current)return;if(!i.ok){let e=await i.json().catch(()=>null);if(t!==J.current)return;z(Eb(e)??a(`routing.dryRunError`,{status:i.status}));return}let o=await i.json();if(t!==J.current)return;L(o)}catch(e){if(t!==J.current)return;z(e instanceof Error?e.message:String(e))}finally{t===J.current&&V(!1)}},he=S?.candidates.map(e=>Ob(g,e.provider))??[];return(0,Q.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,Q.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:se,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,a(`routing.createProfile`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void X(),children:a(`common.retry`)})]}),v?(0,Q.jsxs)($,{tone:`err`,children:[a(`routing.loadFailed`),`: `,v]}):null,w?(0,Q.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,c.length>0?(0,Q.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:c.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>ie(e),"aria-pressed":b?.id===e.id,children:(0,Q.jsxs)(`div`,{className:`card-badges`,children:[(0,Q.jsx)(`strong`,{children:e.id}),(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,Q.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),le()},children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`h3`,{children:[a(`routing.detail`),`: `,b?.model??(0,Q.jsx)(`code`,{children:`policy/…`})]}),b?(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.revision`),`: `,b.revision]}):null]}),(0,Q.jsxs)(`div`,{className:`model-grid`,children:[(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`id`}),(0,Q.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`alias`}),(0,Q.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.candidates`)}),(0,Q.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,Q.jsxs)(`div`,{className:`model-card`,children:[(0,Q.jsxs)(`div`,{className:`model-grid`,children:[(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`provider`}),(0,Q.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>de(t,`provider`,e.target.value),children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:a(`routing.none`)}),n.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`model`}),(0,Q.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>de(t,`model`,e.target.value)}),(0,Q.jsx)(`datalist`,{id:r,children:he[t]?.map(e=>(0,Q.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S.candidates.length===1,onClick:()=>pe(t),"aria-label":a(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:a(`common.remove`)})]},e.key)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:fe,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,a(`routing.candidate`)]})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.require`)}),(0,Q.jsxs)(`div`,{className:`model-grid`,children:[Nb.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:Mb[e].min,max:Mb[e].max,step:Mb[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),jb.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Ab.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,Q.jsx)(`option`,{value:``,children:a(`routing.none`)}),(0,Q.jsx)(`option`,{value:`true`,children:a(`routing.yes`)}),(0,Q.jsx)(`option`,{value:`false`,children:a(`routing.no`)})]})]},e))]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.optimize`)}),(0,Q.jsx)(`div`,{className:`model-grid`,children:Pb.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,required:!0,value:S.optimize[e],onChange:t=>C(n=>n&&{...n,optimize:{...n.optimize,[e]:t.target.value}})})]},e))})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.limits`)}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,value:S.limits.maxEstimatedCostUsd,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,maxEstimatedCostUsd:e.target.value}})})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`onUnknownCost`}),(0,Q.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Lb.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.unknownEvidence`)}),(0,Q.jsx)(`div`,{className:`model-grid`,children:Fb.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Ib.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.compatibility.title`)}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:S.compatibility.enabled,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),a(`routing.compatibility.enabled`)]}),S.compatibility.enabled?(0,Q.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,Q.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[a(`routing.compatibility.requiredSuites`),W?(0,Q.jsx)(`div`,{style:{marginTop:6},children:(0,Q.jsx)($,{tone:`warn`,children:a(`routing.compatibility.catalogUnavailable`)})}):null,H.length>0?(0,Q.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:H.map(e=>(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Vb(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,Q.jsxs)(`span`,{children:[e.suiteId,` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[`(`,a(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[a(`routing.compatibility.minStatus`),(0,Q.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,Q.jsx)(`option`,{value:``,children:a(`routing.none`)}),(0,Q.jsx)(`option`,{value:`PROBED`,children:a(`lab.verdict.PROBED`)}),(0,Q.jsx)(`option`,{value:`VERIFIED`,children:a(`lab.verdict.VERIFIED`)})]})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[o.maxEvidenceAgeMs,(0,Q.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,Q.jsxs)(`label`,{className:`field-label`,children:[o.unknownEvidence,(0,Q.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Ib.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[o.degradedEvidence,(0,Q.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Ib.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:a(E?`common.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:ce,children:a(`common.cancel`)}),b?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void ue(),children:a(`common.remove`)}):null]})]}):null,b&&(0,Q.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Q.jsx)(`h3`,{children:a(`routing.dryRun`)}),(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[a(`routing.dryRunContext`),(0,Q.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),re()}})]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),re()}}),a(`routing.dryRunTools`)]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),re()}}),a(`routing.dryRunImage`)]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),re()}}),a(`routing.dryRunStructured`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||B,onClick:()=>void me(),children:a(`routing.dryRunRun`)}),R?(0,Q.jsx)($,{tone:`err`,children:R}):null,I?(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`routing.candidate`)}),(0,Q.jsx)(`th`,{children:a(`routing.eligible`)}),(0,Q.jsx)(`th`,{children:a(`routing.exclusions`)}),(0,Q.jsx)(`th`,{children:a(`routing.costCap`)}),(0,Q.jsx)(`th`,{children:a(`routing.score`)})]})}),(0,Q.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${a(`routing.selected`)})`:``]}),(0,Q.jsx)(`td`,{children:e.eligible?a(`routing.yes`):a(`routing.no`)}),(0,Q.jsx)(`td`,{children:e.exclusions.map(e=>Gb(e.code,a)).join(`, `)||a(`routing.none`)}),(0,Q.jsx)(`td`,{children:Wb(e.cost?.capOutcome,a,s)}),(0,Q.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):s})]},`${e.provider}/${e.model}`))})]}):null]}),c.length>0&&(0,Q.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Q.jsx)(`h3`,{children:a(`routing.analytics`)}),u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`card-badges`,children:[(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsTotal`),`: `,u.totalRequests]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsSuccessRate`),`: `,Ub(u.successRate,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsFallbackRate`),`: `,Ub(u.fallbackRate,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsP50`),`: `,Hb(u.durationMs.p50,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsP95`),`: `,Hb(u.durationMs.p95,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsP99`),`: `,Hb(u.durationMs.p99,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsCooldown`),`: `,u.cooldownTriggeringFailures]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsConfidence`),`: `,u.confidence??s]}),u.historyTruncated?(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:a(`routing.analyticsTruncated`)}):null]}),(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`routing.candidate`)}),(0,Q.jsx)(`th`,{children:a(`routing.analyticsRequests`)}),(0,Q.jsx)(`th`,{children:a(`routing.analyticsSuccessRate`)}),(0,Q.jsx)(`th`,{children:a(`routing.analyticsP50`)})]})}),(0,Q.jsx)(`tbody`,{children:u.breakdown.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,Q.jsx)(`td`,{children:e.requests}),(0,Q.jsx)(`td`,{children:Ub(e.successRate,s)}),(0,Q.jsx)(`td`,{children:Hb(e.p50DurationMs,s)})]},`${e.provider}/${e.model}`))})]})]}):(0,Q.jsx)(`p`,{className:`muted`,children:a(`routing.analyticsEmpty`)})]})]})}var Xb=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],Zb=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],Qb=[`present`,`corrupt`,`purged_unavailable`];function $b(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ex(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function tx(e){return e===null||typeof e==`string`}function nx(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function rx(e){if(!$b(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(!nx(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function ix(e){return!$b(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!Xb.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`||!Zb.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!ex(e.scenarioManifestDigests)||!tx(e.claimSourceDigest)||!ex(e.contributingEventIds)||!ex(e.contradictingEventIds)||!ex(e.notes)?null:e}function ax(e){return!$b(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(ix).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function ox(e){return!$b(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>$b(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function sx(e){return!$b(e)||!$b(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function cx(e){return!$b(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!Xb.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`||!tx(e.exclusionReason)?null:e}function lx(e){return!$b(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(cx).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function ux(e){if(!$b(e)||!$b(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`||!tx(t.exclusionReason)?null:t}function dx(e){if(!$b(e)||!$b(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!Qb.includes(t.status)||!tx(t.artifactClass)||!tx(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!tx(t.lastError)?null:t}function fx(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 px(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function mx(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:px()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function hx(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function gx(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function _x(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 vx(e){if(!e)return{};let t=typeof e.inboundProtocol==`string`?dm(e.inboundProtocol):void 0,n=typeof e.upstreamProtocol==`string`?dm(e.upstreamProtocol):void 0;return{...t?{inbound:t}:{},...n?{upstream:n}:{}}}function yx(e){return e.inbound!==``||e.upstream!==``}function bx(e,t){return!yx(t)||!(!e||t.inbound&&e.inbound!==t.inbound||t.upstream&&e.upstream!==t.upstream)}function xx(e,t,n){return yx(n)?e.filter(e=>bx(t.get(e.subjectId),n)):e}function Sx(e,t){return yx(e)?t.some(e=>Xb.some(t=>e.byLayer[t].length>0))?`evidence`:`unverified`:`any`}function Cx(){let e=O();return t=>t?Xm(t,e):e(`compatProtocol.anyProtocol`)}function wx({value:e,onChange:t}){let n=O(),r=Cx(),i=[{value:``,label:n(`lab.filter.all`)},...qp.map(e=>({value:e,label:r(e)}))];return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-inbound`,children:n(`compatProtocol.filter.inbound`)}),(0,Q.jsx)(cn,{id:`lab-filter-inbound`,value:e.inbound,options:i,onChange:n=>t({...e,inbound:n}),label:n(`compatProtocol.filter.inbound`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-upstream`,children:n(`compatProtocol.filter.upstream`)}),(0,Q.jsx)(cn,{id:`lab-filter-upstream`,value:e.upstream,options:i,onChange:n=>t({...e,upstream:n}),label:n(`compatProtocol.filter.upstream`),portal:!1})]})]})}function Tx({filter:e,evidence:t,resolution:n}){let r=O(),i=Cx();if(!yx(e))return null;let a=r(`compatProtocol.pair`,{inbound:i(e.inbound),upstream:i(e.upstream)});return(0,Q.jsxs)(`div`,{className:`lab-protocol-status`,"data-pair-evidence":n.loading?`loading`:t,children:[n.loading?(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:r(`compatProtocol.loading`)}):t===`unverified`?(0,Q.jsx)(`p`,{className:`lab-protocol-unverified`,role:`status`,children:r(`compatProtocol.unverified`,{pair:a})}):null,n.unresolved>0&&!n.loading&&(0,Q.jsx)(`p`,{className:`muted small`,children:r(`compatProtocol.unresolved`,{count:n.unresolved})}),(0,Q.jsx)(`p`,{className:`muted small`,children:r(`compatProtocol.axisNote`)})]})}var Ex=50,Dx=200,Ox=6,kx=200;async function Ax(e,t,n){return hn(await fetch(`${e}${t}`,{signal:n}))}function jx(e,t){let n=new URLSearchParams({limit:String(Ex)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Mx=class extends Error{};function Nx(){return new Mx}function Px(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw Nx()}function Fx(e){if(!$b(e)||!Array.isArray(e.verdicts))throw Nx();let t=ax(e);if(t.verdicts.length!==e.verdicts.length)throw Nx();return Px(e,t.hasMore,t.nextCursor),t}function Ix(e){if(!$b(e)||!Array.isArray(e.subjects))throw Nx();let t=ox(e);if(t.subjects.length!==e.subjects.length)throw Nx();return Px(e,t.hasMore,t.nextCursor),t}function Lx(e){if(!$b(e)||!Array.isArray(e.observations))throw Nx();let t=lx(e);if(t.observations.length!==e.observations.length)throw Nx();return Px(e,t.hasMore,t.nextCursor),t}async function Rx(e,t){let n=rx(await Ax(e,`/api/lab/status`,t));if(!n)throw Nx();return n}async function zx(e,t,n,r){return Fx(await Ax(e,`/api/lab/verdicts?${jx({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Bx(e,t,n){return Ix(await Ax(e,`/api/lab/subjects?${jx({},t)}`,n))}async function Vx(e){let t=[],n=new Set,r;for(let i=0;i<Dx;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 Mx;n.add(a),r=a}return{rows:t,truncated:!0}}async function Hx(e,t){return Vx(async n=>{let r=await Bx(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function Ux(e,t,n){let r=sx(await Ax(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw Nx();return r}async function Wx(e,t,n,r){return Lx(await Ax(e,`/api/lab/observations?${jx({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Gx(e,t,n){return Vx(async r=>{let i=await Wx(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Kx(e,t,n){let r=ux(await Ax(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw Nx();return r}async function qx(e,t,n){let r=dx(await Ax(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw Nx();return r}function Jx(e){if(!$b(e)||e.verificationStatus!==`not_verification`||!$b(e.summary))throw Nx();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 Nx();return{verificationStatus:`not_verification`,summary:t}}async function Yx(e,t,n){return Jx(await Ax(e,`/api/lab/production-signals?${jx({subjectId:t})}`,n))}function Xx(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function Zx(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function Qx(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function $x(e){if(!$b(e)||!Xx(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(!$b(n)||!Xx(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!Zx(n.bundleId)||!Zx(n.publisherKeyId)||!Qx(n.activeRecordCount)||!Qx(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 eS(e,t){let n=$x(await Ax(e,`/api/lab/public/community`,t));if(!n)throw Nx();return n}async function tS(e,t,n){let[r,i]=await Promise.all([Rx(e,n),eS(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([zx(e,t,void 0,n),Hx(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function nS(e,t,n,r){return zx(e,t,n,r)}async function rS(e,t,n,r){let i=e.slice(0,kx),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 iS(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=_x(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([Ux(e,t.subjectId,n),Gx(e,a,n),rS(r,Ox,n,t=>Kx(e,t,n)),rS(i,Ox,n,t=>qx(e,t,n)),Yx(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 aS=6,oS=2e3,sS=`
|
|
7
|
+
`,cS=new Map;function lS(e,t){return JSON.stringify([e,t])}function uS(e,t){for(cS.set(e,t);cS.size>oS;){let e=cS.keys().next().value;if(e===void 0)break;cS.delete(e)}}var dS={pairs:new Map,loading:!1,unresolved:0};function fS(e,t,n){let[,r]=(0,Z.useState)(0),i=n?t.slice(0,200):[],a=i.filter(t=>!cS.has(lS(e,t))).join(sS);if((0,Z.useEffect)(()=>{if(!a)return;let t=new AbortController,n=a.split(sS);return Promise.all(Array.from({length:Math.min(aS,n.length)},async()=>{for(let r=n.shift();r!==void 0;r=n.shift())try{let n=await Ux(e,r,t.signal);uS(lS(e,r),vx(n))}catch{if(t.signal.aborted)return;uS(lS(e,r),null)}})).then(()=>{t.signal.aborted||r(e=>e+1)}),()=>t.abort()},[e,a]),!n)return dS;let o=new Map,s=Math.max(0,t.length-200);for(let t of i){let n=cS.get(lS(e,t));n?o.set(t,n):n===null&&(s+=1)}return{pairs:o,loading:a.length>0,unresolved:s}}var pS={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},mS={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},hS={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`},gS={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function _S(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 vS({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,Q.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]}):(0,Q.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]})}function yS({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:`-`}):(0,Q.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,Q.jsx)(vS,{verdict:e.verdict,caption:e.suiteId,label:t(hS[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function bS({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:gx(r.builtAtMs,n)}),(0,Q.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,Q.jsxs)(`div`,{className:`lab-status-card`,children:[(0,Q.jsx)(`span`,{className:`label`,children:e.label}),(0,Q.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function xS({community:e,locale:t}){if(!e||e.evidence.length===0)return null;let n=e.evidence.reduce((e,t)=>e+t.activeRecordCount,0),r=e.evidence.reduce((e,t)=>e+t.revokedRecordCount,0);return(0,Q.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:i(t,`community.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(t,`community.notLocalVerdict`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(t,`community.bundles`)}),(0,Q.jsx)(`dd`,{children:e.evidence.length})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(t,`community.activeRecords`)}),(0,Q.jsx)(`dd`,{children:n})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(t,`community.revokedRecords`)}),(0,Q.jsx)(`dd`,{children:r})]})]})]})}function SS({verdict:e,detail:t,loading:n,error:r,t:a,locale:o,onClose:s}){let c=new Set([...e.contributingEventIds,...e.contradictingEventIds]).size;return(0,Q.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":a(`lab.detailTitle`),children:[(0,Q.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,Q.jsx)(`h3`,{children:hx(e.subjectId)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:a(`lab.detailClose`)})]}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.col.layer`)}),(0,Q.jsx)(`dd`,{children:a(pS[e.evidenceLayer])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.col.suite`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.col.verdict`)}),(0,Q.jsx)(`dd`,{children:a(hS[e.verdict])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.col.asOf`)}),(0,Q.jsx)(`dd`,{children:gx(e.asOf,o)})]})]}),n&&(0,Q.jsx)(hy,{busy:!0,children:a(`common.loading`)}),r&&(0,Q.jsx)($,{tone:`err`,children:r}),t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:a(`lab.detailSubject`)}),(0,Q.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,Q.jsx)(`h4`,{children:a(`lab.production.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:a(`lab.production.notVerification`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.production.attempts`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.production.successes`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.production.routeErrors`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:a(`lab.production.lastObserved`)}),(0,Q.jsx)(`dd`,{children:gx(t.production.summary.lastObservedProductionAttempt,o)})]})]})]}),t.observations.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:a(`lab.detailObservations`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,Q.jsx)(`span`,{children:e.outcome}),(0,Q.jsx)(`span`,{className:`muted`,children:gx(e.completedAt,o)})]},e.eventId))})]}),(t.events.length>0||c>0)&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsxs)(`h4`,{children:[a(`lab.detailEvents`),t.events.length<c?` (${t.events.length}/${c})`:``]}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,Q.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:a(`lab.detailArtifacts`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,title:e.digest,children:hx(e.digest)}),(0,Q.jsx)(`span`,{children:e.artifactClass??`-`}),(0,Q.jsx)(`span`,{children:i(o,gS[e.status])})]},e.digest))})]})]})]})}function CS({apiBase:e,active:n=!0,onCountChange:r}){let{t:a,locale:o}=t(),[s,c]=(0,Z.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[l,u]=(0,Z.useState)(()=>Ag()??Eg),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(null),T=(0,Z.useRef)(null),E=(0,Z.useRef)(null),D=(0,Z.useRef)(null),O=(0,Z.useMemo)(()=>fx(s),[s]),k=JSON.stringify(O),A=(0,Z.useCallback)(t=>tS(e,O,t),[e,O]),j=Ua(`lab-matrix:${e}:${k}`,[e,k],A,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:n,pauseWhenHidden:!0}),M=(0,Z.useCallback)(()=>{T.current?.abort(),T.current=null,f(null),m(null),g(!1)},[]),N=(0,Z.useCallback)(()=>{D.current=null,E.current?.abort(),E.current=null,v(null),b(null),w(null),S(!1)},[]);(0,Z.useEffect)(()=>{T.current?.abort()},[j.data]),(0,Z.useEffect)(()=>()=>{T.current?.abort(),E.current?.abort()},[]);let P=(0,Z.useCallback)(e=>{N(),M(),c(e)},[N,M]),F=(0,Z.useCallback)(e=>{N(),u(e),n&&Kt(Og(e))},[n,N]);(0,Z.useEffect)(()=>{let e=()=>{let e=Ag();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,Z.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,Z.useEffect)(()=>{r?.(R)},[r,R]);let z=(0,Z.useMemo)(()=>j.data?[...j.data.verdicts,...I?.verdicts??[]]:[],[j.data,I]),B=(0,Z.useMemo)(()=>j.data?mx(z,j.data.subjects):[],[z,j.data]),V=yx(l),H=fS(e,(0,Z.useMemo)(()=>B.map(e=>e.subjectId),[B]),n&&V),U=(0,Z.useMemo)(()=>xx(B,H.pairs,l),[l,H.pairs,B]),W=(0,Z.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]),G=Sx(l,U),ee=(0,Z.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 i=k;m(null),g(!0);try{let a=await nS(e,O,t,r.signal);if(r.signal.aborted)return;f(e=>{let t=e?.baseData===n&&e.queryKey===i?e.verdicts:[];return{baseData:n,queryKey:i,verdicts:[...t,...a.verdicts],nextCursor:a.nextCursor,hasMore:a.hasMore}})}catch(e){r.signal.aborted||m({baseData:n,queryKey:i,message:_S(e,a(`lab.loadFailed`))})}finally{T.current===r&&(T.current=null,g(!1))}},[e,h,O,k,j.data,a,I]),K=(0,Z.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 iS(e,t,r.signal);!r.signal.aborted&&D.current===t.projectionKey&&b(n)}catch(e){!r.signal.aborted&&D.current===t.projectionKey&&w(_S(e,a(`lab.detailLoadFailed`)))}finally{E.current===r&&(E.current=null,!r.signal.aborted&&D.current===t.projectionKey&&S(!1))}},[n,e,a]),q=j.refresh,te=(0,Z.useCallback)(()=>{N(),M(),q({forceLoading:!0})},[N,q,M]),ne=n?_:null,J=I?I.hasMore:j.data?.hasMore??!1,Y=[{value:``,label:a(`lab.filter.all`)},...Xb.map(e=>({value:e,label:a(pS[e])}))],ie=[{value:``,label:a(`lab.filter.all`)},...Zb.map(e=>({value:e,label:a(hS[e])}))],X=[{value:``,label:a(`lab.filter.all`)},...(j.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${hx(e.subjectId)} · ${e.subjectKind}`}))];if(j.state.showSkeleton)return(0,Q.jsx)(my,{label:a(`lab.loading`),rows:5});let ae=j.state.showError?_S(j.error,a(`lab.loadFailed`)):null,oe=j.data?.status,se=oe&&!oe.projectionAvailable,ce=oe?.projectionIncompatible===!0;return(0,Q.jsxs)(`div`,{className:`lab-page`,children:[(0,Q.jsx)(`div`,{className:`lab-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:te,disabled:j.refreshing,children:[(0,Q.jsx)(re,{}),a(`lab.refresh`)]})}),j.refreshing&&!j.state.showSkeleton&&(0,Q.jsx)(hy,{busy:!0,live:!ae,children:a(`common.loading`)}),ae&&(0,Q.jsx)($,{tone:`err`,children:ae}),ce&&(0,Q.jsx)($,{tone:`err`,children:a(`lab.projectionIncompatible`)}),se&&!ce&&(0,Q.jsx)(ln,{title:a(`lab.projectionUnavailable`)}),se&&!ce&&(0,Q.jsx)(Tx,{filter:l,evidence:`unverified`,resolution:{loading:!1,unresolved:0}}),j.data&&(0,Q.jsx)(xS,{community:j.data.community,locale:o}),j.data&&oe?.projectionAvailable&&!ce&&(0,Q.jsxs)(`div`,{className:`lab-layout`,children:[(0,Q.jsxs)(`div`,{className:`lab-main`,children:[(0,Q.jsx)(bS,{data:j.data,t:a,locale:o}),(0,Q.jsxs)(`div`,{className:`lab-filters`,children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:a(`lab.filter.layer`)}),(0,Q.jsx)(cn,{id:`lab-filter-layer`,value:s.layer,options:Y,onChange:e=>P(t=>({...t,layer:e})),label:a(`lab.filter.layer`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:a(`lab.filter.verdict`)}),(0,Q.jsx)(cn,{id:`lab-filter-verdict`,value:s.verdict,options:ie,onChange:e=>P(t=>({...t,verdict:e})),label:a(`lab.filter.verdict`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:a(`lab.filter.subject`)}),(0,Q.jsx)(cn,{id:`lab-filter-subject`,value:s.subjectQuery,options:X,onChange:e=>P(t=>({...t,subjectQuery:e})),label:a(`lab.filter.subject`),portal:!1})]}),(0,Q.jsx)(wx,{value:l,onChange:F})]}),(0,Q.jsx)(Tx,{filter:l,evidence:G,resolution:H}),U.length===0?(0,Q.jsx)(ln,{title:a(`lab.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:a(`lab.matrixTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-matrix`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:a(`lab.subjectKind`)}),Xb.map(e=>(0,Q.jsx)(`th`,{children:a(mS[e])},e))]})}),(0,Q.jsx)(`tbody`,{children:U.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`subject`,title:e.subjectId,children:hx(e.subjectId)}),(0,Q.jsx)(`td`,{className:`kind`,children:e.subjectKind||i(o,`subjectKindUnknown`)}),Xb.map(t=>(0,Q.jsx)(`td`,{children:(0,Q.jsx)(yS,{rows:e.byLayer[t],t:a,selectedKey:ne?.projectionKey??null,onSelect:e=>{K(e)}})},t))]},e.subjectId))})]})})]}),(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:a(`lab.verdictsTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:a(`lab.col.layer`)}),(0,Q.jsx)(`th`,{children:a(`lab.col.suite`)}),(0,Q.jsx)(`th`,{children:a(`lab.col.verdict`)}),(0,Q.jsx)(`th`,{children:a(`lab.col.asOf`)})]})}),(0,Q.jsx)(`tbody`,{children:W.map(e=>{let t=ne?.projectionKey===e.projectionKey;return(0,Q.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":i(o,`selectVerdict`,{subject:hx(e.subjectId)}),onClick:()=>{K(e)},children:hx(e.subjectId)})}),(0,Q.jsx)(`td`,{children:a(pS[e.evidenceLayer])}),(0,Q.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(vS,{verdict:e.verdict,caption:e.suiteId,label:a(hS[e.verdict])})}),(0,Q.jsx)(`td`,{children:gx(e.asOf,o)})]},e.projectionKey)})})]})})]}),L&&(0,Q.jsx)($,{tone:`err`,children:L}),J&&(0,Q.jsx)(`div`,{className:`lab-load-more`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:h,onClick:()=>{ee()},children:a(h?`common.loading`:`lab.loadMore`)})})]})]}),ne&&(0,Q.jsx)(SS,{verdict:ne,detail:y,loading:x,error:C,t:a,locale:o,onClose:N})]})]})}var wS=[`catalog`,`combos`,`routing`,`compatibility`];function TS(e){return e===`catalog`?`models`:`models/${e}`}function ES(e=window.location.hash){let t=Gt(Wt(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 DS(e){qt(TS(e))}function OS(e){return`models-tab-${e}`}function kS(e){return`models-panel-${e}`}var AS={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function jS({tab:e,onSelect:t,meta:n}){let r=O(),i=(0,Z.useRef)(null);i.current===null&&(i.current=new Map);let a=e=>{t(e),window.requestAnimationFrame(()=>{i.current.get(e)?.focus({preventScroll:!0})})},o=t=>{let n=wS.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+wS.length)%wS.length:t.key===`ArrowRight`?r=(n+1)%wS.length:t.key===`Home`?r=0:t.key===`End`&&(r=wS.length-1),r!==null&&(t.preventDefault(),a(wS[r]))};return(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:wS.map(t=>{let s=t===e,c=n?.[t];return(0,Q.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:OS(t),"aria-selected":s,"aria-controls":kS(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(AS[t]),c?(0,Q.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function MS({summary:e,apiBase:t,onSaved:n}){let r=O(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),c=e?.fastOptIn?.enabled;if(o&&c!==o.from&&s(null),!e?.fastOptIn)return null;let l=e.fastOptIn.enabled,u=o&&o.from===l?o.value:l,d=async o=>{if(!(i||o===u)){a(!0);try{await hn(await fetch(`${t}/api/providers?name=${encodeURIComponent(e.name)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({fastEnabled:o})}),r(`models.fastSaveFailed`)),s({value:o,from:l}),n(!0,r(o?`models.fastEnabled`:`models.fastDisabled`))}catch(e){n(!1,e instanceof Error?e.message:r(`models.fastSaveFailed`))}finally{a(!1)}}};return(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:r(`models.fastProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":r(`models.fastProvider`),children:[!1,!0].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e,className:`btn btn-sm${u===e?` btn-primary`:` btn-ghost`}`,disabled:i,onClick:()=>void d(e),children:r(e?`models.newPolicy_on`:`models.newPolicy_off`)},String(e)))}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`models.fastProviderHint`)})]})}function NS(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){if(e.disabled===!0){n.delete(e.name);continue}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 PS({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=O(),i=e&&t?.status===`failed`?t:void 0;return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(we,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[i&&n&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${lc(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>qt(`providers`),children:r(`models.openProviderSettings`)})]})]})}function FS(){let e=O();return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(we,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[`${e(`models.discoveryFailedDependency`,{control:e(`pws.liveModels`)})} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>qt(`providers`),children:e(`models.openProviderSettings`)})]})]})}function IS(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 LS({connected:e,catalogSyncedAt:n}){let{locale:r,t:i}=t(),a=IS(n,r),o=e?[{id:`saved`,chip:i(`models.delivery.chip.savedHub`),title:i(`models.delivery.savedHub.title`),body:i(`models.delivery.savedHub.body`)},{id:`synced`,chip:a?i(`models.delivery.chip.synced`,{time:a}):i(`models.delivery.chip.syncedUnknown`),title:i(`models.delivery.synced.title`),body:a?i(`models.delivery.synced.bodyAt`,{time:a}):i(`models.delivery.synced.bodyUnknown`)}]:[{id:`saved`,chip:i(`models.delivery.chip.saved`),title:i(`models.delivery.saved.title`),body:i(`models.delivery.saved.body`)}];return o.push({id:`loaded`,chip:i(`models.delivery.chip.loaded`),title:i(`models.delivery.loaded.title`),body:i(`models.delivery.loaded.body`)}),(0,Q.jsxs)(`details`,{className:`models-delivery`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`models-delivery-title`,children:i(`models.delivery.title`)}),(0,Q.jsx)(`span`,{className:`models-delivery-flow`,children:o.map(e=>e.chip).join(` → `)})]}),(0,Q.jsx)(`ol`,{className:`models-delivery-steps`,children:o.map(e=>(0,Q.jsxs)(`li`,{"data-step":e.id,children:[(0,Q.jsx)(`strong`,{children:e.title}),(0,Q.jsx)(`p`,{children:e.body})]},e.id))}),(0,Q.jsx)(`p`,{className:`models-delivery-hint`,children:i(`models.delivery.hint`)})]})}var RS=`ocx.models.settingsOpen.v1`;function zS(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function BS(e){try{return zS(e)?.getItem(RS)===`1`}catch{return!1}}function VS(e,t){try{zS(t)?.setItem(RS,e?`1`:`0`)}catch{}}var HS={default:`models.pickerOrder.default`,alphabetical:`models.pickerOrder.alphabetical`,provider:`models.pickerOrder.provider`,"most-used":`models.pickerOrder.mostUsed`,custom:`models.pickerOrder.custom`};function US(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}`)}),t.multiAgentMode===`v2`&&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}),r.push({id:`window`,label:e(`models.contextCapLabel`),value:t.windowOn?wc(t.windowValue):n});let i=HS[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 WS({title:e,attentionLabel:t,summary:n,warn:r,children:i,storage:a}){let[o,s]=(0,Z.useState)(()=>BS(a)),[c,l]=(0,Z.useState)(!1),u=o||r&&!c;return(0,Q.jsxs)(`details`,{className:`models-settings`,open:u,onToggle:e=>{let t=e.currentTarget.open;t!==u&&(s(t),!t&&r&&l(!0),VS(t,a))},children:[(0,Q.jsxs)(`summary`,{className:`models-settings-summary`,children:[(0,Q.jsx)(`span`,{className:`models-settings-title`,children:e}),r&&(0,Q.jsx)(`span`,{className:`models-settings-warn`,role:`img`,"aria-label":t,title:t}),(0,Q.jsx)(`span`,{className:`models-settings-state`,children:n.map(e=>(0,Q.jsxs)(`span`,{className:`models-settings-kv`,"data-item":e.id,children:[(0,Q.jsx)(`span`,{className:`models-settings-k`,children:e.label}),e.value&&(0,Q.jsx)(`span`,{className:`models-settings-v`,children:e.value})]},e.id))})]}),(0,Q.jsx)(`div`,{className:`models-settings-body`,children:i})]})}function GS({count:e,label:t}){return e===0?null:(0,Q.jsx)(`span`,{className:`models-chip mono text-caption models-custom-summary`,children:t})}function KS({text:e}){return(0,Q.jsx)(un,{content:e,side:`top`,maxWidth:360,children:(0,Q.jsxs)(`span`,{className:`models-info-hint`,children:[(0,Q.jsx)(we,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})})}var qS={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function JS(e){let t=e.replace(/[_,\s]/g,``);if(!t)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}function YS({apiBase:e,restartEpoch:t=0,connected:n=!1,catalogSyncedAt:r,reportRestart:i}){let[a,o]=(0,Z.useState)(null),s=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(s.current=!0,()=>{s.current=!1}),[]);let c=(0,Z.useRef)(null),l=(0,Z.useRef)(0),u=(0,Z.useRef)(e),d=(0,Z.useCallback)(()=>{l.current++,c.current?.controller.abort(),c.current?.clear(),c.current=null},[]),f=(0,Z.useCallback)(async()=>{if(!s.current||u.current!==e)return;d();let t=l.current,n=A(15e3);c.current=n;try{let r=await F_(e,{signal:n.signal});if(n.signal.aborted||!s.current||u.current!==e||t!==l.current||c.current!==n)return;o(r.state)}finally{n.clear(),c.current===n&&(c.current=null)}},[e,d]),{restarting:p,restart:m}=B_(e,{onSettled:()=>{f()},report:i});(0,Z.useEffect)(()=>(u.current=e,o(null),f(),d),[e,d,f,t]);let[h,g]=(0,Z.useState)(ES),[_,v]=(0,Z.useState)(()=>new Set([ES()])),y=(0,Z.useCallback)(e=>{g(e),v(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,Z.useEffect)(()=>{let e=()=>y(ES());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[y]);let b=(0,Z.useCallback)(e=>{DS(e),y(e)},[y]),x=h===`catalog`,[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),k=O(),j=`ocx.models.catalog.v1:${e}`,M=(0,Z.useMemo)(()=>La(j),[j]),[N,P]=(0,Z.useState)(()=>M?.models??[]),[F,I]=(0,Z.useState)(()=>M?.providers??[]),[L,R]=(0,Z.useState)(()=>new Set(M?.disabled??[])),[z,B]=(0,Z.useState)(()=>M?.selectedModels??null),[V,H]=(0,Z.useState)({}),[U,W]=(0,Z.useState)({}),[G,ee]=(0,Z.useState)({}),[K,q]=(0,Z.useState)(()=>M?.contextCaps??{}),[te,ne]=(0,Z.useState)(()=>M?.contextCapValues??{}),[J,Y]=(0,Z.useState)(()=>M?.contextCapValue??35e4),ie=`${j}:picker-order`,X=(0,Z.useMemo)(()=>{let e=La(ie);return Kg(e)?e:void 0},[ie]),[ae,se]=(0,Z.useState)(null),[ce,ue]=(0,Z.useState)(!1),de=(0,Z.useRef)(null),fe=(0,Z.useRef)(0),pe=Ua(ie,[e],(0,Z.useCallback)(async t=>{let n=await hn(await fetch(`${e}/api/subagent-models`,{signal:t}));if(!Kg(n))throw Error(`picker settings payload missing`);if(t.aborted)throw Error(`picker settings request aborted`);return Va(ie,n),n},[e,ie]),{isEmpty:()=>!1,enabled:x,deadlineMs:15e3,initialData:X}),me=pe.state.data,he=ae??Qg(me?.pickerAvailable??[],me?.pickerOrder??[],me?.pickerOrderMode);(0,Z.useLayoutEffect)(()=>(fe.current++,se(null),ue(!1),()=>{fe.current++,de.current?.controller.abort(),de.current?.clear(),de.current=null}),[e,x]),(0,Z.useLayoutEffect)(()=>{x&&ae===null&&he===`custom`&&se(`custom`)},[x,ae,he]);let[ge,_e]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(!1),[xe,Se]=(0,Z.useState)({}),[Ce,Ee]=(0,Z.useState)({}),De=Dc(),[Oe,ke]=(0,Z.useState)(()=>De??new Set),je=(0,Z.useRef)(De===null),[Me,Ne]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)([]),[Le,Re]=(0,Z.useState)(!1),[ze,Be]=(0,Z.useState)(0),Ve=(0,Z.useCallback)((e,t)=>{Re(e),Ne(t),Be(e=>e+1)},[]);(0,Z.useEffect)(()=>{if(!Me)return;let e=setTimeout(()=>Ne(``),Le?6e3:8e3);return()=>clearTimeout(e)},[Me,Le,ze]);let[He,Ue]=(0,Z.useState)(!1),We=(0,Z.useRef)(!1),Ge=(0,Z.useRef)(!1),qe=(0,Z.useRef)(0),Je=(0,Z.useRef)(!1),Ye=fy(e,{onQueued:()=>{++qe.current,Ne(``)},onBusy:e=>{++qe.current,Je.current=!1,Ge.current=e,We.current=e,Ue(e)},onResponse:e=>{let t=vs(e);t!==void 0&&Fe(t)},refresh:e=>gr(!0,e),onSettled:e=>{Re(!e),Ne(k(e??`models.applied`))}}),Xe=(e,t,n,r,i)=>Ye.visible(t,n,r,ws(e,t,n,r,i)),[Ze,Qe]=(0,Z.useState)(null),[$e,et]=(0,Z.useState)({}),[tt,nt]=(0,Z.useState)(null),[rt,it]=(0,Z.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[at,ot]=(0,Z.useState)(!1),[st,ct]=(0,Z.useState)(null),[lt,ut]=(0,Z.useState)(!0),[dt,ft]=(0,Z.useState)(!1),[pt,mt]=(0,Z.useState)(``),ht=(0,Z.useRef)(!1),[gt,_t]=(0,Z.useState)(``),[vt,yt]=(0,Z.useState)(!1),[bt,xt]=(0,Z.useState)(!1),[St,Ct]=(0,Z.useState)(null),[wt,Tt]=(0,Z.useState)(!1),[Et,Dt]=(0,Z.useState)(null),[Ot,kt]=(0,Z.useState)(null),At=(0,Z.useRef)(null),[jt,Mt]=(0,Z.useState)(null),[Nt,Pt]=(0,Z.useState)(!1),[Ft,It]=(0,Z.useState)(null),[Lt,Rt]=(0,Z.useState)(null),[zt,Bt]=(0,Z.useState)(!1),Vt=(0,Z.useRef)(null),Ht=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>()=>{Vt.current?.controller.abort(),Vt.current?.clear(),Vt.current=null},[]);let Wt=(0,Z.useRef)(null),Gt=(0,Z.useCallback)(async t=>{let n=await gn(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&it(n)},[e]);(0,Z.useEffect)(()=>{let e=new AbortController;return Gt(e.signal),()=>e.abort()},[Gt]);let Kt={apiBase:e,t:k,reloadAliases:Gt,publishFeedback:Ve},qt=e=>V_(e,rt.providers[e]??``,Kt),Jt=(e,t)=>H_(e,t,rt.models[e]?.[t]?.alias??``,Kt),Yt=async(t,n)=>{(await fetch(`${e}/api/default-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:t,...n?{provider:n}:{}})})).ok&&await Gt()},[Xt,Zt]=(0,Z.useState)(`add`),[Qt,$t]=(0,Z.useState)(``),[en,tn]=(0,Z.useState)(``),[nn,rn]=(0,Z.useState)(``),[an,sn]=(0,Z.useState)(``),[dn,fn]=(0,Z.useState)(``),[pn,mn]=(0,Z.useState)(!1),[_n,vn]=(0,Z.useState)([`text`]),[xn,Sn]=(0,Z.useState)(!1),[Cn,wn]=(0,Z.useState)([]),Tn=(0,Z.useRef)(!1),[En,Dn]=(0,Z.useState)(!1),[On,kn]=(0,Z.useState)(``),[An,jn]=(0,Z.useState)(null),[Mn,Nn]=(0,Z.useState)([]),[Pn,Fn]=(0,Z.useState)(``),[In,Ln]=(0,Z.useState)(``),[Rn,zn]=(0,Z.useState)({}),[Bn,Vn]=(0,Z.useState)({contextWindow:null,modelContextWindows:{}}),[Hn,Un]=(0,Z.useState)(new Set),[Wn,Gn]=(0,Z.useState)(!1),[Kn,qn]=(0,Z.useState)(!1),[Jn,Yn]=(0,Z.useState)(``),[Zn,Qn]=(0,Z.useState)(null),$n=(0,Z.useRef)(null),[er,tr]=(0,Z.useState)(null),[nr,rr]=(0,Z.useState)(!1),[ir,or]=(0,Z.useState)(null);(0,Z.useEffect)(()=>()=>{$n.current&&clearTimeout($n.current)},[]);let cr=(0,Z.useMemo)(()=>Ec(N,L,z??{},k),[N,L,z,k]),lr=(0,Z.useMemo)(()=>{let e=new Set(cr.map(e=>e.value));return Xn(N.filter(t=>e.has(t.namespaced)),er?.model,er?.sourceModels)},[N,er?.model,er?.sourceModels,cr]),ur=(0,Z.useCallback)(async()=>{let t=A(15e3);try{let n=await gn(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&tr(n)}catch{}finally{t.clear()}},[e]),dr=(0,Z.useCallback)(async()=>{if(ht.current)return;let t=A(15e3);try{let n=await fetch(`${e}/api/v2`,{signal:t.signal});if(!(n.headers.get(`content-type`)??``).includes(`application/json`)){Qe(null);return}let r=await gn(n);if(!r||typeof r.enabled!=`boolean`){Qe(null);return}Qe({enabled:r.enabled,agentsMaxThreadsConflict:r.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof r.maxConcurrentThreadsPerSession==`number`?r.maxConcurrentThreadsPerSession:null,multiAgentMode:r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?r.multiAgentMode:`default`,keepNativeChatGptOnV1:r.keepNativeChatGptOnV1===!0})}catch{Qe(null)}finally{t.clear(),ut(!1)}},[e]),fr=(0,Z.useCallback)(async t=>{let n=qe.current,[r,i,a,o]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),Ss(e,fetch,t)]),[s,c,l]=await Promise.all([hn(r),hn(i),hn(a)]);if(s===void 0||c===void 0||l===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let u=Tc(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===qe.current&&Va(j,p),p},[e,j]),pr=(0,Z.useCallback)(e=>{let t=NS(e.models,e.providers);or(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),Y(e.contextCapValue),q(e.contextCaps),ne(e.contextCapValues??e.contextCaps)},[]),mr=Ua(j,[e],async e=>{let t=qe.current,n=await fr(e);if(e.aborted)throw Error(`models request aborted`);return!Ge.current&&t===qe.current&&pr(n),n},{isEmpty:()=>!1,pollMs:1e4,initialData:M??void 0,enabled:x,deadlineMs:6e4}),hr=mr.state,gr=(0,Z.useCallback)(async(e=!1,t)=>{if(Je.current&&!e)return!1;Je.current=!0;let n=++qe.current;try{let e=await fr(t??new AbortController().signal);return Es(n,qe.current)?(pr(e),Ut(j,e),pe.refresh(),!0):!1}catch{return!1}finally{Es(n,qe.current)&&(Je.current=!1)}},[pr,j,fr,pe.refresh]),_r=(0,Z.useCallback)(()=>{let e=Wt.current;Dt(null),It(null),Rt(null),Bt(!1),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)},[]),vr=(0,Z.useCallback)(()=>{Ht.current||_r()},[_r]),yr=(0,Z.useCallback)(async t=>{let n=Et;if(!n||Ht.current)return;let r=A(6e4);Vt.current=r,Ht.current=!0,Pt(!0),It(null);let i=Lt?.confirmed===!0&&(t===void 0||t===Lt.value),a=t===void 0,o=t===void 0;try{if(t!==void 0){let s=await fetch(`${e}/api/providers/${encodeURIComponent(n.provider)}/model-display-names`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:n.id,displayName:t}),signal:r.signal}),c=s.ok?await hn(s,k(`models.displayNameSaveFailed`)):await s.json();if(r.signal.throwIfAborted(),!c||typeof c!=`object`||Array.isArray(c)||!s.ok&&c.saved!==!0&&typeof c.error!=`string`)throw Error(k(`models.displayNameSaveFailed`));a=!0;let l=s.ok||c.saved===!0;if(i||=l,l){let e=c.displayNameOverride===null?void 0:c.displayNameOverride??t??void 0,r={displayName:c.displayName??e,displayNameOverride:e,displayNameSource:c.displayNameSource??(e?`operator`:void 0)};P(e=>e.map(e=>e.namespaced===n.namespaced?{...e,...r}:e)),Dt({...n,...r}),Bt(r.displayName===void 0)}if(!s.ok)throw Error(c.error||k(`models.displayNameSaveFailed`));o=!0}if(!await gr(!0,r.signal))throw Error(k(`models.loadFail`));r.signal.throwIfAborted(),Ve(!0,k(i?t===null||t===void 0&&Lt?.value===null?`models.displayNameResetDone`:`models.displayNameSaved`:`models.displayNameReloaded`)),_r()}catch(e){if(Vt.current!==r)return;let n=!a||r.signal.aborted;n&&!i&&Bt(!0),Rt(i||n||o?{value:o||n?void 0:t,confirmed:i}:null),It(i?k(`models.displayNameSavedRefreshFailed`):n||o?k(`models.displayNameOutcomeUnknown`):e instanceof Error&&e.message?e.message:k(`models.displayNameSaveFailed`))}finally{r.clear(),Vt.current===r&&(Vt.current=null,Ht.current=!1,Pt(!1))}},[e,Et,Lt,_r,gr,Ve,k]);(0,Z.useEffect)(()=>{if(!x)return;let e=window.setTimeout(()=>{ur(),dr(),Hr(),Ur()},0),t=sa(()=>{ht.current||dr()},1e4);return()=>{window.clearTimeout(e),t()}},[x,ur,dr]);let br=(0,Z.useMemo)(()=>NS(N,F),[N,F]),xr=N.length>0||hr.data!==void 0,Sr=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;jn(e.provider),Nn(t),Fn(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));Ln(r),zn(i),Vn({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Un(new Set),Gn(!1),Yn(``)},Cr=e=>{Fn(e)},wr=async()=>{if(!An)return;let t=JS(In);if(!br.find(e=>e.provider===An)){Yn(k(`models.contextSaveFailed`));return}if(Wn&&t===void 0){Yn(k(`models.contextInvalid`));return}let n=Object.create(null);for(let e of Hn){let t=JS(J_(Rn,e)??``);if(t===void 0){Yn(k(`models.contextInvalid`));return}t!==(J_(Bn.modelContextWindows,e)??null)&&(n[e]=t)}let r=Wn&&t!==Bn.contextWindow;if(!r&&Object.keys(n).length===0){jn(null),Ve(!0,k(`models.contextUnchanged`));return}qn(!0),Yn(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await hn(await fetch(`${e}/api/providers?name=${encodeURIComponent(An)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),k(`models.contextSaveFailed`))}catch(e){Yn(e instanceof Error?e.message:k(`models.contextSaveFailed`));return}finally{qn(!1)}jn(null),Ve(!0,k(`models.contextSaved`)),await gr(!0)};(0,Z.useEffect)(()=>{if(!je.current||br.length===0)return;je.current=!1;let e=new Set(br.map(e=>e.provider));ke(e),Oc(e)},[br]);let Tr=(0,Z.useMemo)(()=>z?N.filter(e=>Xe(z,e.provider,e.id,e.native===!0,L.has(e.namespaced))).length:0,[L,N,z,Ye.overrides]),Er=(0,Z.useMemo)(()=>({catalog:xr?k(`models.active`,{active:Tr,total:N.length}):void 0,combos:S===null?void 0:String(S),routing:w===null?void 0:String(w),compatibility:E===null?void 0:String(E)}),[xr,S,E,Tr,N.length,w,k]),Dr=async(e,t,n,r)=>{We.current&&!Ye.isRunning()||Ye.enqueue(e,t,n,r)},Or=async t=>{Ue(!0),We.current=!0,Ne(``);let n=K[t]===void 0;try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,enabled:n})});try{let e=await hn(r,k(`models.capSaveFailed`));q(e?.caps??{}),ne(e?.values??e?.caps??{}),Re(!0),Ne(k(`models.capApplied`)),await gr(!0)}catch(e){Re(!1),Ne(e instanceof Error?e.message:k(`models.capSaveFailed`))}}catch{Re(!1),Ne(k(`models.networkError`))}finally{Ue(!1),We.current=!1}},kr=e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Oc(n),n})},Ar=e=>{ke(()=>{let t=e?new Set(br.map(e=>e.provider)):new Set;return Oc(t),t})},jr=async t=>{Ue(!0),We.current=!0,Ne(``);try{let n=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await hn(n,k(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&Y(e.value),q(e?.caps??{}),ne(e?.values??e?.caps??{}),Re(!0),Ne(k(`models.capApplied`)),await gr(!0)}catch(e){Re(!1),Ne(e instanceof Error?e.message:k(`models.capSaveFailed`))}}catch{Re(!1),Ne(k(`models.networkError`))}finally{Ue(!1),We.current=!1}},Mr=(0,Z.useMemo)(()=>{let e=br.filter(e=>!e.native);return e.length>0&&e.every(e=>K[e.provider]===J)&&Object.keys(K).every(e=>K[e]===J)},[br,K,J]),Nr=e=>{!Number.isSafeInteger(e)||e<=0||jr(Mr?{value:e,setAll:!0}:{value:e})},Pr=(e,t)=>{if(t===`custom`){Se(t=>({...t,[e]:!0})),Ee(t=>({...t,[e]:String(K[e]??te[e]??J)}));return}Se(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==K[e]&&jr({provider:e,enabled:!0,value:n})},Fr=e=>{let t=Number((Ce[e]??``).replace(/[_,\s]/g,``));if(!Number.isSafeInteger(t)||t<=0){Ve(!1,k(`models.capSaveFailed`));return}Se(t=>({...t,[e]:!1})),jr({provider:e,enabled:!0,value:t})},Ir=e=>{if(e===`custom`){ye(!0),_e(String(J));return}ye(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==J&&Nr(t)},Lr=()=>{let e=Number(ge.replace(/[_,\s]/g,``));if(!Number.isSafeInteger(e)||e<=0){Ve(!1,k(`models.capSaveFailed`));return}ye(!1),Nr(e)},Rr=()=>{jr({setAll:!Mr})},zr=async t=>{if(!(!er||nr)){rr(!0),tr({...er,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{rr(!1)}}},Br=async t=>{if(!(!Ze||ht.current)){ft(!0),ht.current=!0,mt(``),Ne(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await hn(n,k(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Re(!1),Ne(k(`models.saveFailed`));return}Qe({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}),Re(!0),Ne(k(`models.v2Applied`)),mt((e.warnings??[]).join(` `))}catch(e){Re(!1),Ne(e instanceof Error?e.message:k(`models.saveFailed`))}}catch{Re(!1),Ne(k(`models.networkError`))}finally{ft(!1),ht.current=!1}}},Vr=async e=>{if(!(!Ze||Ze.multiAgentMode===e)){if(e===`v1`){await Br({multiAgentMode:`v1`});return}Ct(e)}},Hr=async()=>{try{let t=A(15e3),n=await gn(await fetch(`${e}/api/model-presets`,{signal:t.signal}));et(n?.providers??{})}catch{et({})}},Ur=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);nt(await gn(t)??null)}catch{nt(null)}},Wr=async(t,n)=>{await gn(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([Ur(),gr()])},Gr=async(t,n,r)=>{if(!(r&&!await na({message:k(`models.presetConfirmReplace`,{count:String(r.presetCount)}),tone:`danger`}))&&!Ge.current){Ge.current=!0,ct(t),Ue(!0),We.current=!0;try{let r=A(3e4),i=await hn(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}),k(`models.saveFailed`));if(!i)throw Error(k(`models.saveFailed`));if(i.fallback===`preset-empty`)Ve(!1,k(`models.presetEmpty`,{provider:t}));else{let e=vs(i);e!==void 0&&Fe(e),Ve(!0,n===`all`?k(`models.presetClearedToast`,{provider:t}):k(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)}))}await Promise.all([Hr(),gr()])}catch(e){Ve(!1,e instanceof Error?e.message:String(e))}finally{ct(null),Ue(!1),We.current=!1,Ge.current=!1}}},Kr=async e=>{!Ze||Ze.keepNativeChatGptOnV1===e||await Br({keepNativeChatGptOnV1:e})},qr=async t=>{if(!(!Ze||ht.current)){if(!Number.isInteger(t)||t<1){Ve(!1,k(`models.v2ThreadsInvalid`));return}if(Ze.maxConcurrentThreadsPerSession!==t){ft(!0),ht.current=!0,mt(``),Ne(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:t})});try{let e=await hn(n,k(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Re(!1),Ne(k(`models.saveFailed`));return}Qe({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}),Re(!0),Ne(k(`models.v2ThreadsApplied`)),yt(!1)}catch(e){Re(!1),Ne(e instanceof Error?e.message:k(`models.saveFailed`))}}catch{Re(!1),Ne(k(`models.networkError`))}finally{ft(!1),ht.current=!1}}}},Jr=e=>{if(e===`custom`){yt(!0),_t(String(Ze?.maxConcurrentThreadsPerSession??``));return}yt(!1),qr(Number(e))},Yr=(e,t)=>{$n.current&&clearTimeout($n.current),$n.current=setTimeout(()=>{Qn({namespaced:e,rect:t.getBoundingClientRect()})},300)},Xr=(e,t)=>{$n.current&&clearTimeout($n.current),Qn({namespaced:e,rect:t.getBoundingClientRect()})},Zr=()=>{$n.current&&clearTimeout($n.current),$n.current=setTimeout(()=>Qn(null),120)},Qr=()=>{$n.current&&clearTimeout($n.current)},$r=async(t,n,r,i,a,o)=>{Dn(!0),kn(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,modelId:n,displayName:r,contextWindow:i,inputModalities:a,reasoningEfforts:o})});try{await hn(s,k(`models.customSaveFailed`)),Tt(!1),Ve(!0,k(`models.customAdded`)),await gr(!0)}catch(e){kn(e instanceof Error?e.message:k(`models.customSaveFailed`))}}catch{kn(k(`models.networkError`))}finally{Dn(!1)}},ei=async(t,n)=>{Dn(!0),kn(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await hn(r,k(`models.customSaveFailed`)),Tt(!1),Ve(!0,k(`models.customUpdated`)),await gr(!0)}catch(e){kn(e instanceof Error?e.message:k(`models.customSaveFailed`))}}catch{kn(k(`models.networkError`))}finally{Dn(!1)}},ti=async(t,n)=>{if(await na({message:k(`models.customDeleteConfirm`,{name:n}),confirmLabel:k(`common.delete`),tone:`danger`}))try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(Ve(!0,k(`models.customDeleted`)),await gr(!0)):Ve(!1,k(`models.customSaveFailed`))}catch{Ve(!1,k(`models.networkError`))}},ni=hr.data??M,ri=hr.kind===`failed-cold`?hr.error instanceof Error?hr.error.message:k(`models.loadFail`):null,ii=hr.showSkeleton&&!ni,ai=z??{},oi=t=>{let{provider:n,rows:r,nativeProviderGroup:i,liveModels:a,discovery:o}=t,s=Oe.has(n),c=e=>Xe(ai,n,e.id,e.native===!0,L.has(e.namespaced)),l=U[n]===!0,u=uc(r),d=fc(l,r),f=dc(r,d),p=f.filter(c).length,m=tt?.recentArrivals[n]??[],h=new Set(m.map(e=>e.id)),g=K[n]!==void 0,_=K[n]??te[n]??J,v=t.nativeProviderGroup?vc:gc,y=t.nativeProviderGroup?yc:_c,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=G[n]??60,T=C.slice(0,w),E=S.length-T.length,D=f.length>0,O=r.some(e=>e.initialSelectionPending),A=!D||f.every(c),j=!D||f.every(e=>!c(e)),M=e=>{!D||O||Dr(`provider`,n,f.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,Q.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,Q.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>kr(n),"aria-expanded":!s,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,Q.jsx)(Ke,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:le(n)}),rt.providers[n]&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:rt.providers[n]}),i&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.nativeGroupLabel`)}),b&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:lc(k,b),children:k(`models.discoveryFailedBadge`)}),(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:k(`models.active`,{active:p,total:f.length})}),m.length>0&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:k(`models.newCount`,{count:m.length})})]}),(0,Q.jsxs)(`div`,{className:`row models-provider-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm models-alias-edit`,"aria-label":k(`models.editProviderAlias`),title:k(`models.editProviderAlias`),onClick:()=>void qt(n),children:(0,Q.jsx)(oe,{style:{width:14,height:14}})}),(0,Q.jsx)(on,{on:rt.defaults.providers[n]??rt.defaults.global,onClick:()=>void Yt(!(rt.defaults.providers[n]??rt.defaults.global),n),label:k(`models.useDefaultAliases`),showLabel:!0}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),Zt(`add`),$t(n),tn(``),rn(``),sn(``),fn(``),mn(!1),vn([`text`]),Sn(!1),wn([]),Tn.current=!1,kn(``),Tt(!0)},"aria-haspopup":`dialog`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,k(`models.customAdd`)]}),(()=>{let e=$e[n];if(!e)return null;let t=He||st!==null,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.mode===r,className:`btn btn-sm${e.mode===r?` btn-primary`:` btn-ghost`}`,style:{background:e.mode===r?void 0:`transparent`,color:e.mode===r?void 0:`var(--muted)`},disabled:He||t||O,onClick:t=>{t.stopPropagation(),Gr(n,r,r===`preset`&&e.mode===`custom`?e:void 0)},children:k(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:k(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:k(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:k(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})(),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:He&&!Ye.pending||A||O,onClick:()=>M(!0),children:k(`models.allOn`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:He&&!Ye.pending||j||O,onClick:()=>M(!1),children:k(`models.allOff`)}),(0,Q.jsxs)(`div`,{className:`models-cap-cluster`,children:[(0,Q.jsx)(on,{on:g,onClick:()=>Or(n),disabled:He,label:k(`models.contextCapLabel`),showLabel:!0}),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(cn,{value:xe[n]?bc:String(_),options:[...!y.has(_)&&!xe[n]?[{value:String(_),label:wc(_)}]:[],...v.map(e=>({value:String(e),label:wc(e)})),{value:bc,label:k(`models.custom`)}],onChange:e=>Pr(n,e),disabled:He||!g,label:k(`models.capValue`,{value:wc(_)}),title:k(`models.contextCapLabel`)}),g&&xe[n]&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:k(`models.customPlaceholder`),value:Ce[n]??``,onChange:e=>Ee(t=>({...t,[n]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&Fr(n)},disabled:He,"aria-label":k(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>Fr(n),disabled:He,className:`btn btn-ghost btn-sm`,children:k(`models.customApply`)})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Sr(t),"aria-haspopup":`dialog`,children:k(`models.contextSettings`)})]})]})]}),!s&&(0,Q.jsxs)(`div`,{className:`models-provider-body`,children:[i&&(0,Q.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:k(`models.nativeHint`)}),!i&&tt&&(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:k(`models.newPolicyProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(tt.providers[n]??`inherit`)===e,className:`btn btn-sm${(tt.providers[n]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void Wr(e,n),children:k(`models.newPolicy_${e}`)},e))})]}),!i&&(0,Q.jsx)(MS,{summary:F.find(e=>e.name===n),apiBase:e,onSaved:(e,t)=>{Ve(e,t),e&&gr(!0)}}),r.length===0&&(0,Q.jsx)(PS,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>0&&b&&(0,Q.jsx)(FS,{}),u&&(0,Q.jsx)(`div`,{className:`row models-provider-hint`,children:(0,Q.jsx)(on,{on:l,onClick:()=>W(e=>({...e,[n]:!l})),label:k(`models.freeOnly`),showLabel:!0})}),d&&f.length===0&&r.length>0&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:k(`models.noFreeMatch`)}),r.length>30&&(0,Q.jsx)(`input`,{className:`input`,placeholder:k(`models.search`),value:V[n]??``,onChange:e=>H(t=>({...t,[n]:e.target.value})),"aria-label":k(`models.search`)}),T.map(e=>{let t=!c(e);return(0,Q.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Yr(e.namespaced,t.currentTarget),onMouseLeave:Zr,onFocus:t=>Xr(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||Qn(null)},children:[(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsx)(on,{on:!t,onClick:()=>void Dr(`models`,n,[{id:e.id,native:e.native===!0}],t),disabled:He&&!Ye.pending||e.initialSelectionPending,label:e.native?e.id:e.namespaced}),e.initialSelectionPending&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,children:k(`models.initialSelectionPending`)}),e.quotaInactiveReason===`no_credit`&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,title:k(`models.inactiveNoCreditHint`),children:k(`models.inactiveNoCredit`)}),rt.models[n]?.[e.id]&&(0,Q.jsx)(`strong`,{className:`mono text-control`,children:rt.models[n][e.id].alias}),(0,Q.jsxs)(`span`,{className:`models-model-identity`,children:[(0,Q.jsx)(`code`,{className:`mono text-control`,style:{color:t?`var(--faint)`:`var(--text)`,textDecoration:t?`line-through`:`none`},children:e.native?q_(e.id):e.namespaced}),!e.native&&e.displayName?.trim()&&e.displayName.trim()!==e.namespaced&&(0,Q.jsx)(`span`,{className:`models-model-friendly text-caption`,children:e.displayName.trim()})]}),rt.models[n]?.[e.id]?.source===`builtin`&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:k(`models.aliasAuto`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":k(`models.editModelAlias`),title:k(`models.editModelAlias`),onClick:()=>void Jt(n,e.id),children:(0,Q.jsx)(oe,{style:{width:13,height:13}})}),!e.native&&!e.custom&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`models.displayNameActionLabel`,{model:e.namespaced}),onClick:t=>{Wt.current=t.currentTarget,It(null),Rt(null),Bt(!1),Dt(e)},children:k(`models.displayNameAction`)}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.customBadge`)}),!e.native&&e.provider!==`combo`&&(0,Q.jsxs)(Q.Fragment,{children:[e.manualPricing===!0&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:k(`pricing.override.badge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`pricing.override.actionLabel`,{model:e.namespaced}),onClick:t=>{At.current=t.currentTarget,kt(e)},children:k(`pricing.override.action`)})]}),!e.native&&!e.custom&&e.provider!==`combo`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`models.settingsTitle`,{model:e.namespaced}),onClick:()=>Mt(e),children:k(`models.customEdit`)}),!e.custom&&h.has(e.id)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:k(`models.newBadge`)}),e.contextCapped&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.contextCappedValue`,{value:wc(e.contextCap??J)})})]}),Zn?.namespaced===e.namespaced&&(()=>{let n=Zn.rect,r=n.bottom+4,i=r+360>window.innerHeight;return(0,Q.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:n.left+24,...i?{bottom:window.innerHeight-n.top+4}:{top:r}},onMouseEnter:Qr,onMouseLeave:Zr,children:[(0,Q.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,Q.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:k(`models.customBadge`)}),(0,Q.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipProvider`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:be(e.provider,k)}),(e.contextWindow||e.contextCap)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipContext`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:wc(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipModalities`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipStatus`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:k(t?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,Q.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{Zt(`edit`),$t(e.provider),tn(e.customId),rn(e.id),sn(e.displayName??``),fn(e.contextWindow?String(e.contextWindow):``),mn(!1),vn(e.inputModalities??[`text`]),Sn(Array.isArray(e.reasoningEfforts)),wn(e.reasoningEfforts??[]),Tn.current=Array.isArray(e.reasoningEfforts),kn(``),Tt(!0),Qn(null)},children:k(`models.customEdit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{ti(e.customId,e.displayName??e.id).finally(()=>Qn(null))},children:k(`models.customDelete`)})]})]})})()]},e.namespaced)}),E>0&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>ee(e=>({...e,[n]:w+60})),className:`btn btn-ghost btn-sm models-show-more`,children:k(`models.showMore`,{n:E})})]})]},n)},si=ir?br.filter(e=>e.provider===ir):br,ci=(e,t=!1)=>{let n={pickerOrder:e.pickerOrder,pickerOrderMode:e.pickerOrderMode,pickerAvailable:[]};Ut(ie,n),Va(ie,n),t&&se(`custom`),pe.refresh();let r=e.catalogRefresh,i=typeof r==`object`&&!!r&&`status`in r&&r.status===`committed`&&`degraded`in r&&r.degraded===!1;Ve(i,k(i?`models.pickerOrder.saved`:`models.pickerOrder.pending`)),f()},li=async()=>{if(de.current||!me||pe.state.showError||he===`custom`)return;let t=fe.current,n=he,r=me.pickerAvailable,i=A(15e3);de.current=i,ue(!0);let a=()=>fe.current===t&&de.current===i,o=()=>a()&&!i.signal.aborted;try{let t=[];if(n===`most-used`){let n=await fetch(`${e}/api/usage?range=all&surface=all`,{signal:i.signal});if(!o())return;let r=await hn(n,k(`models.pickerOrder.usageFailed`));if(!o())return;if(r?.usageIncomplete===!0)throw Error(k(`models.pickerOrder.usageIncomplete`));if(!qg(r?.models))throw Error(k(`models.pickerOrder.usageFailed`));t=r.models}if(!o())return;let a=Zg(n,r,t,N),s=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:i.signal,body:JSON.stringify({pickerOrder:a,pickerOrderMode:n==="default"?null:n})});if(!o())return;let c=await hn(s,k(`models.saveFailed`));if(!Gg(c)||!(`ok`in c)||c.ok!==!0)throw Error(k(`models.saveFailed`));if(!o())return;ci({pickerOrder:c.pickerOrder,pickerOrderMode:c.pickerOrderMode,catalogRefresh:`catalogRefresh`in c?c.catalogRefresh:void 0}),se(null)}catch(e){a()&&Ve(!1,e instanceof Error?e.message:k(`models.networkError`))}finally{i.clear(),a()&&(de.current=null,ue(!1))}},ui=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`models-control-top-row`,children:[tt&&(0,Q.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,children:[(0,Q.jsx)(`span`,{className:`models-shadow-label`,children:k(`models.newPolicyGlobal`)}),(0,Q.jsx)(on,{on:tt.policy===`off`,onClick:()=>void Wr(tt.policy===`off`?`on`:`off`),label:k(`models.newPolicyGlobal`)})]}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(on,{on:rt.defaults.global,onClick:()=>void Yt(!rt.defaults.global),label:k(`models.useDefaultAliasesGlobal`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ot(e=>!e),children:k(`models.aliases`)})]}),(0,Q.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!er||void 0,children:[(0,Q.jsxs)(`span`,{className:`models-shadow-label`,children:[k(`models.shadowCallIntercept`),` `,(0,Q.jsx)(un,{content:k(`models.shadowCallInterceptHint`,{models:yn(er?.sourceModels)}),side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":k(`models.shadowCallInterceptHint`,{models:yn(er?.sourceModels)}),children:`ⓘ`})})]}),(0,Q.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:k(`models.shadowCallOriginal`,{models:bn(er?.sourceModels)})}),(0,Q.jsx)(on,{on:er?.enabled??!1,onClick:()=>void zr({enabled:!er?.enabled}),disabled:!er||nr,label:k(`models.shadowCallIntercept`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(cn,{value:er?.model??``,options:lr,onChange:e=>{tr(t=>t&&{...t,model:e}),zr({model:e})},disabled:!er||nr||!er.enabled,label:k(`models.shadowCallIntercept`)})})]}),(lt||Ze)&&(0,Q.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.v2Label`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Ze?.multiAgentMode??`default`)===e,className:`btn btn-sm${(Ze?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(Ze?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(Ze?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!Ze||dt,onClick:()=>void Vr(e),children:k(`models.v2Mode_${e}`)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!Ze,onClick:()=>xt(!0),"aria-label":k(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,Q.jsx)(we,{width:14,height:14,"aria-hidden":`true`})})]}),Ze&&Ze.multiAgentMode===`v2`&&(0,Q.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,Q.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,Q.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:k(`models.keepNativeOnV1`)}),(0,Q.jsx)(on,{on:Ze.keepNativeChatGptOnV1===!0,onClick:()=>void Kr(!Ze.keepNativeChatGptOnV1),disabled:dt,label:k(`models.keepNativeOnV1`)}),(0,Q.jsx)(un,{content:k(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,Q.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":k(`models.keepNativeOnV1Hint`),children:(0,Q.jsx)(we,{width:13,height:13,"aria-hidden":`true`})})})]})}),St&&(0,Q.jsx)(sr,{reason:`selection`,mode:St,docsUrl:ar(Ze?.multiAgentSurfaceAdvisory)?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:dt,onContinue:()=>{let e=St;Ct(null),Br({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{Ct(null),Ze?.multiAgentMode!==`v1`&&Br({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>Ct(null)})]}),Ze&&(Ze.enabled||Ze.agentsMaxThreadsConflict||pt)&&(0,Q.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[Ze.enabled&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.v2ThreadsLabel`)}),(0,Q.jsx)(cn,{value:vt?`custom`:Ze.maxConcurrentThreadsPerSession!==null&&Ze.maxConcurrentThreadsPerSession!==void 0?Sc.has(Ze.maxConcurrentThreadsPerSession)?String(Ze.maxConcurrentThreadsPerSession):`custom`:``,options:[...Ze.maxConcurrentThreadsPerSession===null||Ze.maxConcurrentThreadsPerSession===void 0?[{value:``,label:k(`models.v2ThreadsDefault`)}]:[],...Ze.maxConcurrentThreadsPerSession!==null&&Ze.maxConcurrentThreadsPerSession!==void 0&&!Sc.has(Ze.maxConcurrentThreadsPerSession)&&!vt?[{value:`custom`,label:String(Ze.maxConcurrentThreadsPerSession)}]:[],...xc.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:k(`models.custom`)}],onChange:e=>Jr(e),disabled:dt,label:k(`models.v2ThreadsLabel`)}),vt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:gt,onChange:e=>_t(e.target.value),onKeyDown:e=>{e.key===`Enter`&&qr(Number(gt.replace(/[_,\s]/g,``)))},disabled:dt,"aria-label":k(`models.v2ThreadsLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:dt,onClick:()=>{qr(Number(gt.replace(/[_,\s]/g,``)))},children:k(`models.v2ThreadsApply`)})]})]}),Ze.enabled&&Ze.agentsMaxThreadsConflict&&(0,Q.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:k(`models.v2Conflict`)}),pt&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:pt})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.contextCapLabel`)}),(0,Q.jsx)(cn,{value:ve?bc:String(J),options:[...!_c.has(J)&&!ve?[{value:String(J),label:wc(J)}]:[],...gc.map(e=>({value:String(e),label:wc(e)})),{value:bc,label:k(`models.custom`)}],onChange:e=>Ir(e),disabled:He,label:k(`models.contextCapLabel`)}),ve&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:k(`models.customPlaceholder`),value:ge,onChange:e=>_e(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Lr()},disabled:He,"aria-label":k(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:Lr,disabled:He,className:`btn btn-ghost btn-sm`,children:k(`models.customApply`)})]}),(0,Q.jsx)(on,{on:Mr,onClick:Rr,disabled:He,label:k(`models.setAll`)}),(0,Q.jsx)(KS,{text:k(`models.setAllHint`,{value:wc(J)})})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,"aria-busy":ce||pe.state.refreshing,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.pickerOrder.label`)}),(0,Q.jsx)(cn,{value:he,options:[{value:`default`,label:k(`models.pickerOrder.default`)},{value:`alphabetical`,label:k(`models.pickerOrder.alphabetical`)},{value:`provider`,label:k(`models.pickerOrder.provider`)},{value:`most-used`,label:k(`models.pickerOrder.mostUsed`)},{value:`custom`,label:k(`models.pickerOrder.custom`)}],onChange:e=>se(e),disabled:ce||!me||pe.state.showError,label:k(`models.pickerOrder.label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void li(),disabled:ce||!me||pe.state.showError||he===`custom`||he!=="default"&&me.pickerAvailable.length===0,children:k(ce?`models.pickerOrder.applying`:`models.pickerOrder.apply`)}),pe.state.showError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{role:`alert`,children:k(`models.pickerOrder.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pe.refresh(),children:k(`models.pickerOrder.retry`)})]}),(0,Q.jsx)(KS,{text:k(`models.pickerOrder.hint`)})]}),(0,Q.jsx)(u_,{showOrderEditor:he===`custom`,apiBase:e,active:x,identities:N,onBusyChange:ue,onAccepted:e=>ci(e,!0),onSaved:()=>mr.refresh()}),at&&(0,Q.jsxs)(`div`,{className:`card models-aliases-card`,"aria-label":k(`models.aliasesTable`),children:[(0,Q.jsx)(`div`,{className:`row group-head`,children:(0,Q.jsx)(`strong`,{children:k(`models.aliases`)})}),Object.entries(rt.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,Q.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?k(`models.aliasAuto`):k(`models.aliasUser`)}),n.stale&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:k(`models.aliasStale`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":k(`models.editModelAlias`),onClick:()=>void Jt(e,t),children:(0,Q.jsx)(oe,{style:{width:13,height:13}})})]},`${e}/${t}`)))]})]}),di=N.filter(e=>e.custom).length,fi=(0,Q.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Ar(!0),disabled:He,children:[(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`}),` `,k(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Ar(!1),disabled:He,children:[(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,k(`models.expandAll`)]}),(0,Q.jsx)(KS,{text:k(`models.orderHint`)}),(0,Q.jsx)(GS,{count:di,label:k(`models.customSummary`,{count:di})})]}),pi=(0,Q.jsx)(Q.Fragment,{children:br.length===0&&(0,Q.jsx)(ln,{icon:(0,Q.jsx)(Ie,{}),title:k(`models.noRouted`),children:k(`models.noRoutedHint`)})}),mi=(0,Q.jsxs)(Q.Fragment,{children:[bt&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.v2Label`),onClick:()=>xt(!1),onKeyDown:e=>{e.key===`Escape`&&xt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(`models.v2Label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>xt(!1),"aria-label":k(`common.close`),children:`×`})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:k(`models.v2Help`)}),(0,Q.jsx)(`div`,{className:`models-help-link`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:k(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>xt(!1),children:k(`common.ok`)})})]})}),An&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.contextSettings`),onClick:()=>{Kn||jn(null)},onKeyDown:e=>{e.key===`Escape`&&!Kn&&jn(null)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(`models.contextSettingsTitle`,{provider:be(An,k)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>jn(null),disabled:Kn,"aria-label":k(`common.close`),children:`×`})]}),Jn&&(0,Q.jsx)($,{tone:`err`,children:Jn}),(0,Q.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:k(`models.contextHint`)}),(0,Q.jsxs)(`div`,{className:`models-context-fields`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.contextDefault`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:In,onChange:e=>{Ln(e.target.value),Gn(!0)},disabled:Kn,placeholder:k(`models.contextAutomatic`),autoFocus:!0})]}),Mn.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.contextModel`),(0,Q.jsx)(cn,{value:Pn,options:Mn.map(e=>({value:e,label:e})),onChange:Cr,disabled:Kn,label:k(`models.contextModel`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.contextModelOverride`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:J_(Rn,Pn)??``,onChange:e=>{zn(t=>({...t,[Pn]:e.target.value})),Un(e=>new Set(e).add(Pn))},disabled:Kn,placeholder:k(`models.contextAutomatic`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>jn(null),disabled:Kn,children:k(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void wr(),disabled:Kn,children:k(Kn?`models.customSaving`:`models.customApply`)})]})]})}),wt&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.customAdd`),onClick:()=>{En||Tt(!1)},onKeyDown:e=>{e.key===`Escape`&&!En&&Tt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(Xt===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:be(Qt,k)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Tt(!1),disabled:En,"aria-label":k(`common.close`),children:`×`})]}),On&&(0,Q.jsx)($,{tone:`err`,children:On}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldModelId`),(0,Q.jsx)(`input`,{className:`input`,value:nn,onChange:e=>rn(e.target.value),disabled:En,placeholder:k(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldDisplayName`),(0,Q.jsx)(`input`,{className:`input`,value:an,onChange:e=>sn(e.target.value),disabled:En,placeholder:k(`models.customFieldDisplayNamePlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(cn,{value:pn?`custom`:dn,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:k(`models.custom`)}],onChange:e=>{if(e===`custom`){mn(!0);return}mn(!1),fn(e)},disabled:En,label:k(`models.customFieldContext`)}),pn&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:dn,onChange:e=>fn(e.target.value),disabled:En,placeholder:k(`models.customPlaceholder`),"aria-label":k(`models.customFieldContext`)})]})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:_n.includes(e),onChange:t=>{vn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:En}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:xn,onChange:e=>{if(Sn(e.target.checked),e.target.checked&&!Tn.current){Tn.current=!0;let e=N.find(e=>e.provider===Qt&&e.id===nn),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;wn(t??[...hc])}},disabled:En}),(0,Q.jsx)(`span`,{className:`text-control`,children:k(`models.customFieldReasoningOverride`)})]})}),xn&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:hc.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Cn.includes(e),onChange:t=>{wn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:En}),(0,Q.jsx)(`span`,{className:`text-control`,children:k(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Tt(!1),disabled:En,children:k(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:En||!nn.trim(),onClick:()=>{let e=nn.trim(),t=an.trim(),n=JS(dn);if(n===void 0){kn(k(`models.contextInvalid`));return}if(Xt===`add`){let r=xn?Cn:void 0;$r(Qt,e,t||void 0,n??void 0,_n.length>0?_n:void 0,r)}else ei(en,{modelId:e,displayName:t,contextWindow:n,inputModalities:_n,reasoningEfforts:xn?Cn:null})},children:k(En?`models.customSaving`:Xt===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),hi=(0,Q.jsxs)(`div`,{className:`models-workspace-shell`,children:[Me&&(0,Q.jsxs)(`div`,{className:`action-toast notice ${Le?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[Le?(0,Q.jsx)(Te,{}):(0,Q.jsx)(Ae,{}),(0,Q.jsx)(`span`,{children:Me})]}),hr.showError&&(0,Q.jsx)($,{tone:`err`,children:k(`models.loadFail`)}),Pe.length>0&&(0,Q.jsx)(`div`,{className:`models-integration-warning`,children:(0,Q.jsxs)($,{tone:`warn`,children:[k(`models.integrationRefreshWarning`),(0,Q.jsx)(`ul`,{children:Pe.map(e=>(0,Q.jsxs)(`li`,{children:[e.client,e.profileId===void 0?``:`:${e.profileId}`,`: `,ly(k,{clientId:e.client,message:e.reason===`integration_mutation_busy`?k(`integrations.error.busy`):e.reason,reason:e.refusalReason,snapshotPath:e.snapshotPath,residual:e.residual})]},`${e.client}:${e.profileId??`all`}`))})]})}),(0,Q.jsx)(WS,{title:k(`models.settingsPanel.title`),attentionLabel:k(`models.settingsPanel.attention`),warn:!!(Ze?.enabled&&Ze.agentsMaxThreadsConflict)||pt!==``||pe.state.showError,summary:US(k,{multiAgentMode:Ze?.multiAgentMode,v2Threads:Ze?.maxConcurrentThreadsPerSession,keepNativeOnV1:Ze?.keepNativeChatGptOnV1===!0,shadowEnabled:er?.enabled===!0,shadowModel:er?.model,windowOn:Mr,windowValue:J,newModelsOff:tt?.policy===`off`,aliasesOn:rt.defaults.global,pickerMode:Qg(me?.pickerAvailable??[],me?.pickerOrder??[],me?.pickerOrderMode)}),children:ui}),(0,Q.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":Ye.pending||hr.refreshing||void 0,children:[(0,Q.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":k(`nav.models`),children:[(0,Q.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-title`,children:k(`models.workspace.providers`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-count`,children:br.length})]}),(0,Q.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${ir===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>or(null),"aria-current":ir===null?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:k(`models.workspace.allProviders`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:k(`models.active`,{active:Tr,total:N.length})})]}),br.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>Xe(ai,t,e.id,e.native===!0,L.has(e.namespaced))).length;return(0,Q.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${ir===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>or(t),"aria-current":ir===t?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:be(t,k)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:k(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,Q.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":k(`models.workspace.mainAria`),children:[fi,(0,Q.jsx)(`div`,{className:`models-provider-list`,children:si.map(e=>oi(e))}),br.length===0&&pi]})]}),mi]});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:k(`nav.models`)}),(0,Q.jsx)(`div`,{className:`page-head-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{m()},disabled:p,"aria-label":k(p?`dash.codexRestarting`:`dash.codexRestart`),title:k(p?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Q.jsx)(re,{})})})]}),(0,Q.jsx)(Hg,{state:a,controller:{restarting:p,restart:m}}),(0,Q.jsx)(jS,{tab:h,onSelect:b,meta:Er}),(0,Q.jsx)(`p`,{className:`page-sub`,children:k(qS[h])}),h===`catalog`&&(0,Q.jsx)(LS,{connected:n,catalogSyncedAt:r}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:kS(`catalog`),"aria-labelledby":OS(`catalog`),hidden:h!==`catalog`,children:(0,Q.jsx)(gy,{pageName:k(`models.tab.catalog`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:ii?(0,Q.jsx)(my,{label:k(`models.loading`),rows:5}):ri===null?hi:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:ri}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>mr.refresh(),children:k(`common.retry`)})]})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:kS(`combos`),"aria-labelledby":OS(`combos`),hidden:h!==`combos`,children:_.has(`combos`)&&(0,Q.jsx)(gy,{pageName:k(`models.tab.combos`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(ub,{apiBase:e,active:h===`combos`,onCountChange:C})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:kS(`routing`),"aria-labelledby":OS(`routing`),hidden:h!==`routing`,children:_.has(`routing`)&&(0,Q.jsx)(gy,{pageName:k(`models.tab.routing`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(Yb,{apiBase:e,active:h===`routing`,onCountChange:T})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:kS(`compatibility`),"aria-labelledby":OS(`compatibility`),hidden:h!==`compatibility`,children:_.has(`compatibility`)&&(0,Q.jsx)(gy,{pageName:k(`models.tab.compatibility`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(CS,{apiBase:e,active:h===`compatibility`,onCountChange:D})})}),Et&&(0,Q.jsx)(f_,{model:Et,saving:Nt,requestError:Ft,currentNamePending:zt,mutationOutcomeUnknown:Lt?.confirmed===!1,onRetry:Lt?()=>void yr(Lt.value):void 0,onEdit:()=>Rt(null),onSave:e=>void yr(e),onReset:()=>void yr(null),onClose:vr}),Ot&&(0,Q.jsx)(b_,{model:Ot,apiBase:e,onRefresh:e=>gr(!0,e),onClose:()=>{let e=At.current;kt(null),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)}},`${e}/${Ot.namespaced}`),jt&&(0,Q.jsx)(O_,{row:jt,apiBase:e,onRefresh:e=>gr(!0,e),onFeedback:Ve,onClose:()=>Mt(null)},`${e}/${jt.namespaced}`)]})}var XS=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],ZS={display:`flex`,alignItems:`center`,gap:`0.75rem`,margin:`0.6rem 0`},QS={minWidth:`11rem`};function $S({apiBase:e,initial:t}){let n=O(),[r,i]=(0,Z.useState)(t),[a,o]=(0,Z.useState)(t),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(``),p=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]);let m=(0,Z.useCallback)(async()=>{p.current!==null&&(clearTimeout(p.current),p.current=null),u(!1),c(!0),f(``);let t=a;try{let n=await fetch(`${e}/api/advisor/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t.enabled,model:t.model,effort:t.effort,policy:t.policy,timeoutMs:t.timeoutMs,contextSharingConsent:t.contextSharingConsent})});if(!n.ok){let e=await n.json().catch(()=>null);f(e?.error?.message??String(n.status));return}let r=await n.json();i(r.settings),o(e=>JSON.stringify(e)===JSON.stringify(t)?r.settings:e),u(!0),p.current=setTimeout(()=>{p.current=null,u(!1)},2500)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},[e,a]),h=(0,Z.useCallback)(e=>{f(``),o(t=>({...t,...e}))},[]),g=JSON.stringify(a)!==JSON.stringify(r),_=a.enabled&&a.model.trim()===``,v=a.enabled&&a.model.trim()!==``&&a.contextSharingConsent!==`v1`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{marginTop:`0.75rem`},children:[(0,Q.jsxs)(`div`,{style:ZS,children:[(0,Q.jsx)(`span`,{style:QS,children:n(`advisor.enabled`)}),(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.enabled,disabled:s,"aria-label":n(`advisor.enabled`),onChange:e=>h({enabled:e.target.checked})}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})]}),(0,Q.jsxs)(`div`,{style:ZS,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-model`,style:QS,children:n(`advisor.model`)}),(0,Q.jsx)(`input`,{id:`advisor-model`,type:`text`,value:a.model,disabled:s,placeholder:n(`advisor.modelPlaceholder`),onChange:e=>h({model:e.target.value})})]}),(0,Q.jsxs)(`div`,{style:ZS,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-effort`,style:QS,children:n(`advisor.effort`)}),(0,Q.jsx)(`select`,{id:`advisor-effort`,value:a.effort,disabled:s,onChange:e=>h({effort:e.target.value}),children:XS.map(e=>(0,Q.jsx)(`option`,{value:e,children:n(`models.reasoningEffort.${e}`)},e))})]}),(0,Q.jsxs)(`div`,{style:ZS,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-policy`,style:QS,children:n(`advisor.policy`)}),(0,Q.jsxs)(`select`,{id:`advisor-policy`,value:a.policy,disabled:s,onChange:e=>h({policy:e.target.value===`preflight`?`preflight`:`manual`}),children:[(0,Q.jsx)(`option`,{value:`manual`,children:n(`advisor.policy.manual`)}),(0,Q.jsx)(`option`,{value:`preflight`,children:n(`advisor.policy.preflight`)})]})]}),(0,Q.jsx)(`div`,{style:{margin:`0.8rem 0`},children:(0,Q.jsxs)(`label`,{style:{display:`flex`,alignItems:`flex-start`,gap:`0.6rem`},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.contextSharingConsent===`v1`,disabled:s,"aria-label":n(`advisor.consent.label`),onChange:e=>h({contextSharingConsent:e.target.checked?`v1`:null})}),(0,Q.jsx)(`span`,{children:n(`advisor.consent.label`)})]})}),(0,Q.jsxs)(`div`,{style:ZS,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-timeout`,style:QS,children:n(`advisor.timeout`)}),(0,Q.jsx)(`input`,{id:`advisor-timeout`,type:`number`,min:1e3,max:6e5,value:a.timeoutMs,disabled:s,onChange:e=>{let t=e.target.value.trim();if(t===``)return;let n=Number(t);Number.isFinite(n)&&h({timeoutMs:n})}})]})]}),_&&(0,Q.jsx)($,{tone:`warn`,children:n(`advisor.warning.noModel`)}),v&&(0,Q.jsx)($,{tone:`warn`,children:n(`advisor.consent.required`)}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),l&&(0,Q.jsx)($,{tone:`ok`,children:n(`advisor.saved`)}),(0,Q.jsx)(`div`,{style:{marginTop:`0.75rem`},children:(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:!g||s,onClick:()=>void m(),children:n(s?`common.loading`:`advisor.save`)})})]})}function eC({apiBase:e}){let t=O(),n=Ua(`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:r}=n,i=(0,Q.jsx)(`h2`,{children:t(`nav.advisor`)});return(0,Q.jsxs)(`section`,{className:`panel`,children:[i,(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.description`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.costNote`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.privacyNote`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.disclosure`)}),r.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:t(`common.loading`)}),r.showError&&!r.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n.refresh(),children:t(`common.retry`)})]}),r.data!==void 0&&(0,Q.jsx)($S,{apiBase:e,initial:r.data.settings},n.hasSucceeded?`ready`:`cold`)]})}function tC(e,t){let n=new Set(t);return[...new Set([...e.filter(e=>n.has(e)),...t])]}function nC({apiBase:e,roster:t}){let n=O(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(0),[h,g]=(0,Z.useState)(null),_=s||h?.retry!==p||h.t!==n,v=(0,Z.useRef)(!1),y=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{y.current=!0,v.current=!0;let t=new AbortController,r=!1;return(async()=>{try{let a=await hn(await fetch(`${e}/api/subagent-models`,{signal:t.signal}),n(`sub.loadFail`));if(r)return;let s={force:a?.force??null,forceAvailable:a?.forceAvailable??[],forceStatus:a?.forceStatus??null};i(s),o(s.force??``),u(``)}catch{r||u(n(`sub.loadFail`))}finally{r||(v.current=!1,g({retry:p,t:n}))}})(),()=>{r=!0,y.current=!1,t.abort()}},[e,p,n]);async function b(t){if(!(!r||_||v.current)){v.current=!0,c(!0),u(``),f(!1);try{let r=await hn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({force:t})}),n(`sub.saveFailed`));if(!y.current)return;i(e=>e&&{...e,force:r?.force??null,forceStatus:null}),o(r?.force??a),f(!0),m(e=>e+1)}catch{y.current&&u(n(`sub.saveFailed`))}finally{v.current=!1,y.current&&c(!1)}}}let x=tC(t,r?.forceAvailable??[]),S=r?.force??a,C=x.includes(S),w=r?.forceStatus;return(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h3`,{children:n(`sub.forceTitle`)}),(0,Q.jsx)(on,{on:!!r?.force,disabled:!r||_||!r.force&&!C,label:n(`sub.forceTitle`),onClick:()=>{b(r?.force?null:a)}}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[n(`sub.forceModel`),(0,Q.jsxs)(`select`,{className:`input`,value:S,disabled:!r||_,onChange:e=>{let t=e.target.value;r?.force?b(t):o(t)},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:n(`sub.forceChoose`)}),S&&!C&&(0,Q.jsx)(`option`,{value:S,disabled:!0,children:S}),x.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsx)(`p`,{className:`muted`,children:n(`sub.forceHelp`)}),(0,Q.jsx)(`p`,{className:`muted`,children:n(`sub.forceScope`)}),r?.force&&(!C||w?.targetValid===!1)&&(0,Q.jsx)($,{tone:`warn`,children:n(`sub.forceInvalid`)}),r?.force&&w?.support===`unsupported`&&(0,Q.jsx)($,{tone:`warn`,children:n(`sub.forceOld`)}),r?.force&&(!w||w.support===`unknown`)&&(0,Q.jsx)($,{tone:`warn`,children:n(`sub.forceUnknown`)}),r?.force&&w?.settingsOverride&&(0,Q.jsx)($,{tone:`warn`,children:n(`sub.forceOverride`)}),r?.force&&w?.settingsReadable===!1&&(0,Q.jsx)($,{tone:`warn`,children:n(`sub.forceSettingsUnknown`)}),d&&(0,Q.jsx)($,{tone:`ok`,children:n(`sub.forceSaved`)}),l&&(0,Q.jsxs)($,{tone:`err`,children:[l,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:_,onClick:()=>m(e=>e+1),children:n(`common.retry`)})]})]})}var rC=`section`;function iC(e,t){return[e,rC,t].join(`-`)}function aC(e){return[e,rC,``].join(`-`)}var oC=1200;function sC({scope:e,items:t,ariaLabel:n,mobileReadingLine:r}){let[i,a]=(0,Z.useState)(()=>r&&window.matchMedia(`(max-width: 760px)`).matches?r:72);(0,Z.useEffect)(()=>{if(!r)return;let e=window.matchMedia(`(max-width: 760px)`),t=()=>a(e.matches?r:72);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let[o,s]=(0,Z.useState)(t[0]?.id??``),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useCallback)(()=>{c.current=null,l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=(0,Z.useCallback)(()=>{u();let n=null,r=1/0;for(let a of t){let t=document.getElementById(iC(e,a.id));if(!t)continue;let o=Math.abs(t.getBoundingClientRect().top-i);o<r&&(r=o,n=a.id)}n&&s(n)},[u,t,e,i]);(0,Z.useEffect)(()=>()=>u(),[u]),(0,Z.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(iC(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(iC(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(aC(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(iC(e,t));n&&(c.current=t,l.current!==null&&clearTimeout(l.current),l.current=setTimeout(d,oC),s(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,Q.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===t.id,"aria-controls":iC(e,t.id),tabIndex:o===t.id?0:-1,className:`page-tab${o===t.id?` page-tab--active`:``}`,onClick:()=>f(t.id),children:[t.label,t.meta?(0,Q.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}var cC=1500,lC={fast:`integrations.lazycodexRoles.auto.tierFast`,standard:`integrations.lazycodexRoles.auto.tierStandard`,frontier:`integrations.lazycodexRoles.auto.tierFrontier`},uC={glance:`integrations.lazycodexRoles.auto.effortGlance`,measured:`integrations.lazycodexRoles.auto.effortMeasured`,thorough:`integrations.lazycodexRoles.auto.effortThorough`,exhaustive:`integrations.lazycodexRoles.auto.effortExhaustive`};function dC({apiBase:e,model:t,effort:n,available:r,saving:i,onAccept:a}){let o=O(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),h=e=>{let t=r.find(t=>t.namespaced===e);return t?xe(`${t.provider}/${t.model}`,o):e},g=async()=>{u(!0),f(null);try{let t=await fetch(`${e}/api/injection-model/suggest`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({work:s.trim()})});m(await hn(t,o(`sub.suggest.failed`))??null)}catch(e){m(null),f(e instanceof Error&&e.message?e.message:o(`sub.suggest.failed`))}finally{u(!1)}},_=p?.proposal,v=!!_?.proposedModel&&_.proposedModel===t&&(_.proposedEffort??``)===n,y=l?o(`sub.suggest.running`):p?o(`sub.suggest.title`):``;return(0,Q.jsxs)(`div`,{className:`swi-suggest`,children:[(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:y}),(0,Q.jsx)(`label`,{className:`swi-suggest-label`,htmlFor:`swi-suggest-work`,children:o(`sub.suggest.label`)}),(0,Q.jsxs)(`div`,{className:`swi-suggest-input`,children:[(0,Q.jsx)(`textarea`,{id:`swi-suggest-work`,className:`input`,rows:2,maxLength:cC,value:s,placeholder:o(`sub.suggest.placeholder`),onChange:e=>c(e.target.value),disabled:l}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:l||i||s.trim()===``,onClick:()=>void g(),children:o(l?`sub.suggest.running`:`sub.suggest.submit`)})]}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),p&&_&&(0,Q.jsxs)(`section`,{className:`swi-suggest-result`,"aria-label":o(`sub.suggest.title`),children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-head`,children:[_.tier&&_.effortIntent&&(0,Q.jsx)(`span`,{className:`font-semibold`,children:o(`integrations.lazycodexRoles.auto.tierEffort`,{tier:o(lC[_.tier]),effort:o(uC[_.effortIntent])})}),(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.sizedWith`,{model:p.sizingModel})})]}),p.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:o(`integrations.lazycodexRoles.auto.sizingFailed`,{error:p.sizingError})}),_.status===`unsized`?(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.unsized`,{reason:_.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-change`,children:[(0,Q.jsxs)(`span`,{children:[_.model?h(_.model):o(`dash.injectionNone`),_.effort?` · ${_.effort}`:``]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),_.proposedModel?(0,Q.jsxs)(`strong`,{children:[h(_.proposedModel),_.proposedEffort?` · ${_.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`muted`,children:o(`integrations.lazycodexRoles.auto.unassigned`,{reason:_.reason??``})})]}),_.rationale&&(0,Q.jsx)(`p`,{children:_.rationale}),_.moveUpIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.moveUp`,{text:_.moveUpIf})}),_.moveDownIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:o(`integrations.lazycodexRoles.auto.moveDown`,{text:_.moveDownIf})})]}),(0,Q.jsxs)(`div`,{className:`swi-suggest-actions`,children:[v?(0,Q.jsx)(`span`,{className:`swi-suggest-done`,children:o(`integrations.lazycodexRoles.auto.alreadySet`)}):_.status===`proposed`&&_.proposedModel&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:i,onClick:()=>a({model:_.proposedModel,effort:_.proposedEffort??null}),children:o(`sub.suggest.accept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:i,onClick:()=>m(null),children:o(`integrations.lazycodexRoles.auto.discard`)})]})]})]})}function fC({apiBase:e,model:t,effort:n,efforts:r,available:i,guidanceEnabled:a,syncCodexDefaults:o,saving:s,onSave:c,ultraMode:l,ultraSaving:u,onUltraModeSave:d,ultraLoadFailed:f,onUltraModeRetry:p,fallback:m,fallbackPollMs:h,fallbackBusy:g,availableModels:_,onFallbackChange:v,onFallbackPollMsChange:y,onFallbackSave:b}){let x=O(),S=(l.hintText??``).trim().length>0,C=i.some(e=>e.namespaced===t&&(e.provider!==`openai`||e.namespaced!==e.model)),w=l.enabled||l.multiAgentMode!==`v1`&&!(l.multiAgentMode===`v2`&&l.keepNativeChatGptOnV1),T=!f&&l.loaded===!0&&C&&w,E=new Set(_),D=new Set(m),[k,A]=(0,Z.useState)(()=>({pollMs:h,text:String(h)}));Object.is(k.pollMs,h)||A({pollMs:h,text:Number.isFinite(h)?String(h):``});let j=(0,Z.useRef)(null),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(()=>({models:m,rows:m.map((e,t)=>({model:e,id:t})),nextId:m.length})),I=P.rows;if(P.models!==m){let e=[...P.rows],t=P.nextId;I=m.map(n=>{let r=e.findIndex(e=>e.model===n);return r>=0?e.splice(r,1)[0]:{model:n,id:t++}}),F({models:m,rows:I,nextId:t})}let L=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e=L.current;if(!e)return;L.current=null;let t=j.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)`)??j.current?.querySelector(`button[role="combobox"]`))?.focus()},[m]);let R=Number.isInteger(h)&&h>=5e3&&h<=6e5,z=(e,t)=>{let n=[...m],r=e+t;if(g||r<0||r>=n.length)return;[n[e],n[r]]=[n[r],n[e]];let i=[...I];[i[e],i[r]]=[i[r],i[e]],F({...P,models:n,rows:i}),L.current={row:r,action:t===-1?`up`:`down`},v(n)};return(0,Q.jsxs)(`div`,{className:`swi-delegation`,children:[f&&(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`sub.ultraMode`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.ultraModeLoadFail`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:x(`common.retry`)})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row swi-delegation-model-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`sub.delegation.model`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.delegation.modelHint`)})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,Q.jsx)(cn,{value:t,options:[{value:``,label:x(`dash.injectionNone`)},...i.map(e=>({value:e.namespaced,label:xe(`${e.provider}/${e.model}`,x)}))],onChange:e=>c({model:e||null,effort:n||null}),disabled:s,label:x(`dash.injectionLabel`),align:`right`}),t&&r.length>0&&(0,Q.jsx)(cn,{value:n,options:[{value:``,label:x(`dash.injectionEffortNone`)},...r.map(e=>({value:e,label:e}))],onChange:e=>c({model:t||null,effort:e||null}),disabled:s,label:x(`dash.injectionEffortLabel`),align:`right`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-expanded":M,onClick:()=>N(e=>!e),children:x(`sub.suggest.button`)})]})]}),M&&(0,Q.jsx)(`div`,{className:`swi-delegation-row`,children:(0,Q.jsx)(dC,{apiBase:e,model:t,effort:n,available:i,saving:s,onAccept:c})}),T&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-v2-compatibility`,role:`note`,children:(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`sub.v2Compatibility.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:x(`sub.v2Compatibility.risk`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:x(`sub.v2Compatibility.recoveryUnknown`)}),(0,Q.jsx)(`a`,{href:`https://github.com/lidge-jun/opencodex/issues/92`,target:`_blank`,rel:`noreferrer`,children:x(`sub.v2Compatibility.details`)})]})}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row swi-fallback-editor`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`sub.fallbackLabel`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.fallbackHint`)})]}),(0,Q.jsxs)(`div`,{className:`swi-fallback-controls`,ref:j,children:[m.map((e,t)=>(0,Q.jsxs)(`div`,{className:`swi-fallback-row`,children:[(0,Q.jsxs)(`span`,{className:`swi-fallback-model`,children:[t+1,`. `,e,!E.has(e)&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:x(`sub.fallbackUnavailable`)})]}),(0,Q.jsxs)(`span`,{className:`swi-fallback-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`up`,onClick:()=>z(t,-1),disabled:g||t===0,"aria-label":x(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(Ge,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`down`,onClick:()=>z(t,1),disabled:g||t===m.length-1,"aria-label":x(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(Qe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`remove`,onClick:()=>{let e=m.filter((e,n)=>n!==t);F({...P,models:e,rows:I.filter((e,n)=>n!==t)}),L.current={row:Math.max(0,Math.min(t,m.length-2)),action:`remove`},v(e)},disabled:g,"aria-label":x(`sub.removeAria`,{m:e}),children:(0,Q.jsx)(ve,{})})]})]},I[t].id)),(0,Q.jsx)(cn,{value:``,label:x(`sub.fallbackAdd`),options:[{value:``,label:x(`sub.fallbackAdd`)},..._.filter(e=>!D.has(e)).map(e=>({value:e,label:e}))],onChange:e=>{e&&!D.has(e)&&v([...m,e])},disabled:g}),(0,Q.jsxs)(`label`,{className:`setting-hint`,children:[x(`sub.fallbackPoll`),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:5e3,max:6e5,step:1e3,value:k.text,onChange:e=>{let t=e.currentTarget.value,n=Number(t),r=t.trim()!==``&&Number.isFinite(n)?n:NaN;A({pollMs:r,text:t}),y(r)},disabled:g,"aria-invalid":!R}),` ms`]}),!R&&(0,Q.jsx)(`div`,{className:`setting-hint`,role:`alert`,children:x(`sub.fallbackPollInvalid`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:b,disabled:g||!R,children:x(`common.save`)})]})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`dash.syncCodexSubagentDefaults`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${o?`on`:``}`,onClick:()=>c({syncCodexSubagentDefaults:!o}),disabled:s||!t,"aria-label":x(`dash.syncCodexSubagentDefaults`),"aria-pressed":o,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),(0,Q.jsxs)(`details`,{className:`swi-advanced`,children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,children:x(`sub.advanced`)}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[x(`models.v2Label`),(0,Q.jsxs)(un,{content:x(`models.v2Help`),side:`top`,maxWidth:380,children:[(0,Q.jsx)(we,{width:13,height:13,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:x(`models.v2Label`)})]})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:x(`models.v2DocsLink`)})})]}),(0,Q.jsx)(`div`,{className:`swi-delegation-controls`,children:(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":x(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l.multiAgentMode===e,className:`btn btn-sm${l.multiAgentMode===e?` btn-primary`:` btn-ghost`}`,style:{background:l.multiAgentMode===e?void 0:`transparent`,color:l.multiAgentMode===e?void 0:`var(--muted)`},disabled:u||f,onClick:()=>{l.multiAgentMode!==e&&d({multiAgentMode:e})},children:x(`models.v2Mode_${e}`)},e))})})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`dash.multiAgentGuidance`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`dash.multiAgentGuidanceHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>c({multiAgentGuidanceEnabled:!a}),disabled:s,"aria-label":x(`dash.multiAgentGuidance`),"aria-pressed":a,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:x(`sub.ultraMode`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.ultraModeHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${S?`on`:``}`,onClick:()=>{S?d({multiAgentModeHintText:null}):l.recommendation&&d({multiAgentModeHintText:l.recommendation.text})},disabled:s||u||!S&&(!l.multiAgentV2Enabled||!l.recommendation),"aria-label":x(`sub.ultraMode`),"aria-pressed":S,children:(0,Q.jsx)(`span`,{className:`knob`})}),!l.multiAgentV2Enabled&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.ultraModeV2Required`)})]}),S&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,Q.jsx)(pC,{initialHint:l.hintText??``,disabled:s||u,onSave:d,preset:l.recommendation?.text??null,labels:{text:x(`sub.ultraModeText`),preset:x(`sub.ultraModePreset`),save:x(`common.save`)}},l.hintText)})]})]})}function pC({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,Z.useState)(e);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`textarea`,{className:`input swi-ultra-mode-textarea`,value:a,onChange:e=>o(e.target.value),disabled:t,rows:4,"aria-label":i.text}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{r!==null&&o(r)},disabled:t||r===null,children:i.preset}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{a.trim().length!==0&&n({multiAgentModeHintText:a})},disabled:t||a.trim().length===0,children:i.save})]})}function mC({available:e,fallbackAvailable:t,chosen:n,onToggle:r,onMove:i,fallback:a,fallbackPollMs:o,fallbackBusy:s,onFallbackChange:c,onFallbackPollMsChange:l,onFallbackSave:u,delegation:d}){let f=O(),[p,m]=(0,Z.useState)(``),h=(0,Z.useMemo)(()=>new Set(n),[n]),g=n.length>=5,_=(0,Z.useMemo)(()=>{let t=p.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,p]),v=(0,Z.useMemo)(()=>[{id:`featured`,label:f(`sub.featured`),meta:`${n.length}/5`},{id:`models`,label:f(`sub.models`),meta:String(_.length)},{id:`settings`,label:f(`sub.settings`)}],[f,n.length,_.length]);return(0,Q.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,Q.jsx)(sC,{scope:`subagents`,items:v,ariaLabel:f(`sub.sections`)}),(0,Q.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,Q.jsxs)(`section`,{id:iC(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":f(`sub.featured`),children:[(0,Q.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:f(`sub.featured`)}),(0,Q.jsxs)(`span`,{className:`swi-featured-count`,children:[n.length,`/`,5]}),(0,Q.jsxs)(un,{content:(0,Q.jsx)(T,{k:`sub.orderHint`,cmd:`spawn_agent`}),side:`bottom`,maxWidth:380,children:[(0,Q.jsx)(we,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:f(`sub.orderHintAria`)})]})]}),n.length===0?(0,Q.jsx)(`div`,{className:`swi-featured-empty`,children:f(`sub.noneSelected`)}):(0,Q.jsx)(`div`,{className:`swi-featured-list`,children:n.map((e,t)=>(0,Q.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,Q.jsx)(`span`,{className:`swi-featured-pos`,children:t+1}),(0,Q.jsx)(`span`,{className:`swi-featured-name`,children:q_(e)}),(0,Q.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(t,-1),disabled:t===0,"aria-label":f(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(Ge,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(t,1),disabled:t===n.length-1,"aria-label":f(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(Qe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>r(e),"aria-label":f(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,Q.jsx)(ve,{})})]})]},e))})]}),(0,Q.jsxs)(`section`,{id:iC(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":f(`sub.models`),children:[(0,Q.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:f(`sub.models`)}),(0,Q.jsx)(`span`,{className:`swi-featured-count`,children:_.length})]}),(0,Q.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,Q.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,Q.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),placeholder:f(`sub.search`),"aria-label":f(`sub.search`)})}),(0,Q.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:_.length===0?(0,Q.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:f(`sub.noModels`)}):_.map(e=>{let t=h.has(e),i=t?n.indexOf(e)+1:null,a=!t&&g;return(0,Q.jsxs)(`div`,{className:`subagents-workspace-rail-row${t?` subagents-workspace-rail-row--selected`:``}`,children:[(0,Q.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,Q.jsx)(`span`,{className:`swi-rail-priority`,children:i??``}),(0,Q.jsx)(Ye,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:q_(e)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${t?` subagents-workspace-rail-toggle--on`:``}${a?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{a||r(e)},disabled:a,"aria-pressed":t,"aria-label":f(t?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:t?f(`sub.workspace.removeFromFeatured`,{m:e}):g?f(`sub.workspace.featuredFull`):f(`sub.workspace.addToFeatured`,{m:e}),children:t?(0,Q.jsx)(Te,{style:{width:14,height:14}}):(0,Q.jsx)(N,{style:{width:14,height:14}})})]},e)})})]})]}),(0,Q.jsxs)(`section`,{id:iC(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":f(`sub.settings`),children:[(0,Q.jsx)(`div`,{className:`swi-featured-head`,children:(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:f(`sub.settings`)})}),(0,Q.jsx)(fC,{apiBase:d.apiBase,model:d.model,effort:d.effort,efforts:d.efforts,available:d.available,guidanceEnabled:d.guidanceEnabled,syncCodexDefaults:d.syncCodexDefaults,saving:d.saving,onSave:d.onSave,ultraMode:d.ultraMode,ultraSaving:d.ultraSaving,onUltraModeSave:d.onUltraModeSave,ultraLoadFailed:d.ultraLoadFailed,onUltraModeRetry:d.onUltraModeRetry,fallback:a,fallbackPollMs:o,fallbackBusy:s,availableModels:t??e,onFallbackChange:c,onFallbackPollMsChange:l,onFallbackSave:u})]})]})]})}function hC(e){let[t,n]=(0,Z.useState)(!1),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(!0),[h,g]=(0,Z.useState)(!1),_=(0,Z.useCallback)(e=>{let t=po(e);m(t.multiAgentGuidanceEnabled),g(t.syncCodexSubagentDefaults),o(t.injectionModel),c(t.injectionEffort),Array.isArray(e.efforts)&&u(e.efforts),Array.isArray(e.available)&&f(e.available)},[]);return(0,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await Tn(await fetch(`${e}/api/injection-model`));if(t)return;_(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,_]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,Z.useCallback)(async t=>{if(!r){i(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await fetch(`${e}/api/injection-model`);_(await Tn(n))}catch{}finally{i(!1)}}},[e,_,r])}}var gC={enabled:!1,hintText:null,recommendation:null,multiAgentV2Enabled:!1,multiAgentMode:`default`};function _C(e){return La(e)}function vC({apiBase:e}){let t=O(),n=`ocx.subagents.v1:${e}`,r=_C(n),[i,a]=(0,Z.useState)(()=>r?.chosen??[]),[o,s]=(0,Z.useState)(()=>r?.fallback??[]),[c,l]=(0,Z.useState)(()=>r?.pollMs??6e4),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(()=>Array.isArray(r?.fallback)&&Number.isInteger(r?.pollMs)),[m,h]=(0,Z.useState)(()=>r?.fallbackAvailable),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(!0),b=(0,Z.useRef)(null),x=(0,Z.useRef)({fallback:r?.fallback,pollMs:r?.pollMs,fallbackAvailable:r?.fallbackAvailable}),S=(0,Z.useRef)(0),C=(0,Z.useRef)(0),w=(0,Z.useRef)(!1),T=(0,Z.useRef)(r),[E,D]=(0,Z.useState)(``),[k,A]=(0,Z.useState)(!1),j=(0,Z.useRef)(!1),M=(0,Z.useRef)(null),N=(0,Z.useRef)(i),P=(0,Z.useCallback)(e=>{N.current=e,a(e)},[]),F=hC(e),[I,L]=(0,Z.useState)(null),R=I?.apiBase===e,z=R?I.mode:gC,[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(null),[W,G]=(0,Z.useState)(!1),ee=(0,Z.useRef)(0),K=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{K.current=e,ee.current++},[e]);let q=(0,Z.useCallback)(async n=>{if(K.current!==e)return!1;let r=++ee.current,i=await hn(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));if(!i||n?.aborted||r!==ee.current||K.current!==e)return!1;G(!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 L({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,Z.useEffect)(()=>{let e=new AbortController;return(async()=>{await q(e.signal)})().catch(()=>{e.signal.aborted||(A(!1),G(!0),D(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[q,t]);let te=async n=>{if(B||!R||K.current!==e)return;let r=e;V(!0),D(``);try{if(await hn(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),K.current!==r||!await q())return;A(!0),D(t(`sub.ultraModeSaved`))}catch(e){if(K.current!==r)return;A(!1),D(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{V(!1)}},ne=(0,Z.useCallback)(async()=>{try{if(!await q())return;A(!1),D(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{A(!1),G(!0),D(t(`sub.ultraModeLoadFail`))}},[q,t]),J=(0,Z.useCallback)(async()=>{b.current?.abort();let r=new AbortController;b.current=r;let{signal:i}=r,a=S.current;try{let r=await hn(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!==S.current||w.current)return;let o={fallback:r.models,pollMs:r.pollMs,fallbackAvailable:r.available};x.current=o,s(o.fallback),l(o.pollMs),h(o.fallbackAvailable),p(!0),_(``),T.current&&(T.current={...T.current,...o},Va(n,T.current))}catch(e){if(i.aborted||a!==S.current||w.current)return;p(!1),_(e instanceof Error&&!(e instanceof SyntaxError)?e.message:t(`sub.loadFail`))}finally{i.aborted||y(!1)}},[e,n,t]);(0,Z.useEffect)(()=>((async()=>{await J()})(),()=>{b.current?.abort()}),[J]);let Y=(0,Z.useCallback)(async r=>{let i=C.current,a=await hn(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===C.current&&!j.current,l={...x.current,available:o,chosen:c?(a.chosen??[]).filter(e=>s.has(e)):T.current?.chosen??[]};if(r?.aborted)throw r.reason;return T.current=l,c&&P(l.chosen),Va(n,l),l},[e,n,P,t]),re=Ua(n,[e],Y,{isEmpty:()=>!1,initialData:r??void 0}),{state:ie}=re,X=re.refresh,ae=ie.data??r,oe=ae?.available??[],se=async r=>{if(M.current=r,j.current)return;j.current=!0,D(``);let i=null,a=r;for(;M.current;){let r=M.current;M.current=null;try{a=(await hn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:r})}),t(`sub.saveFailed`)))?.applied??r,T.current={...T.current,available:oe,chosen:a},Va(n,T.current),i=null}catch(e){i=e}}if(C.current+=1,j.current=!1,i){P(T.current?.chosen??[]),A(!1),D(i instanceof Error&&i.message?i.message:t(`sub.networkError`));return}P(a),A(!0),D(t(`sub.saved`,{n:a.length,cmd:`ocx sync`}))},ce=e=>{C.current+=1,P(e),se(e)},le=e=>{let t=N.current;!t.includes(e)&&t.length>=5||ce(t.includes(e)?t.filter(t=>t!==e):[...t,e])},ue=(e,t)=>{let n=e+t,r=[...N.current];n<0||n>=r.length||([r[e],r[n]]=[r[n],r[e]],ce(r))},de=async()=>{if(!f||w.current||!Number.isInteger(c)||c<5e3||c>6e5)return;w.current=!0,S.current+=1;let r=e;d(!0),D(``);try{let i=await hn(await fetch(`${e}/api/subagent-model-fallback`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:o,pollMs:c})}),t(`sub.fallbackSaveFailed`));if(K.current!==r)return;if(!i||!Array.isArray(i.models)||typeof i.pollMs!=`number`)throw Error(t(`sub.fallbackSaveFailed`));S.current+=1,s(i.models),l(i.pollMs),x.current={...x.current,fallback:i.models,pollMs:i.pollMs};let a={available:oe,chosen:T.current?.chosen??[],...x.current};T.current=a,Va(n,a),A(!0),D(t(`sub.fallbackSaved`))}catch(e){A(!1),D(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{w.current=!1,d(!1)}};if(ie.showSkeleton&&!ae)return(0,Q.jsx)(my,{label:t(`sub.loading`),rows:4});if(ie.kind===`failed-cold`){let e=ie.error instanceof Error?ie.error.message:t(`sub.loadFail`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>X(),children:t(`common.retry`)})]})}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:t(`nav.subagents`)})}),E&&(0,Q.jsx)($,{tone:k?`ok`:`err`,children:E}),ie.showError&&(0,Q.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),g&&(0,Q.jsxs)($,{tone:`err`,children:[t(`sub.fallbackLabel`),`: `,t(`sub.loadFail`),g!==t(`sub.loadFail`)&&(0,Q.jsxs)(Q.Fragment,{children:[` `,g]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v,onClick:()=>{y(!0),J()},children:t(`common.retry`)})]}),(0,Q.jsx)(nC,{apiBase:e,roster:i},e),(0,Q.jsx)(mC,{available:oe,fallbackAvailable:m??[],chosen:i,onToggle:le,onMove:ue,fallback:o,fallbackPollMs:c,fallbackBusy:u||!f,onFallbackChange:e=>{S.current+=1,s(e)},onFallbackPollMsChange:e=>{S.current+=1,l(e)},onFallbackSave:()=>{de()},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:z,ultraSaving:B||!R,onUltraModeSave:t=>{if(t.multiAgentMode==="default"||t.multiAgentMode===`v2`){U({mode:t.multiAgentMode,apiBase:e});return}te(t)},ultraLoadFailed:W,onUltraModeRetry:()=>{ne()}}}),H&&H.apiBase===e&&(0,Q.jsx)(sr,{reason:`selection`,mode:H.mode,docsUrl:`https://opencodex.me/guides/subagent-v1-default/`,busy:B,onContinue:()=>{let e=H.mode;U(null),te({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{U(null),z.multiAgentMode!==`v1`&&te({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>U(null)})]})}function yC(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 bC(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):i}return o.updateDeps=e=>{r=e},o}function xC(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var SC=(e,t)=>Math.abs(e-t)<1.01,CC=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},wC,TC=()=>{if(wC!==void 0)return wC;if(typeof navigator>`u`)return wC=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return wC=!0;let e=navigator.maxTouchPoints;return wC=navigator.platform===`MacIntel`&&e!==void 0&&e>0},EC=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},DC=e=>e,OC=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},kC=(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(EC(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(EC(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},AC={passive:!0},jC=typeof window>`u`||`onscrollend`in window,MC=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&jC,o=0,s=a?null:CC(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,AC),a&&r.addEventListener(`scrollend`,u,AC),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},NC=(e,t)=>MC(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),PC=(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`]},FC=(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})},IC=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.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};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:DC,rangeExtractor:OC,onChange:()=>{},measureElement:PC,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=bC(()=>(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,!(!TC()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,AC),e.addEventListener(`touchend`,n,AC),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&&(TC()&&(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=bC(()=>[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=bC(()=>[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=yC(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=bC(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=zC(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=bC(()=>{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=bC(()=>[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 xC(t[LC(0,t.length-1,r?e=>n[e*2]:e=>xC(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`}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e});return}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:TC()&&(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(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}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&&SC(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()}},LC=(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 RC(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 zC(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=RC(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=LC(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 BC=typeof document<`u`?Z.useLayoutEffect:Z.useEffect;function VC({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=Z.useReducer(e=>e+1,0)[1],a=Z.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;let o=e=>{let t=a.current;if(!t.enabled||!t.container)return;let n=e.getTotalSize();if(n!==t.lastSize){t.lastSize=n;let r=e.options.horizontal?`width`:`height`;t.container.style[r]=`${n}px`}},s=e=>{let t=a.current;if(!t.enabled||!t.container)return;o(e);let n=!!e.options.horizontal,r=t.mode===`transform`,i=n?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let a of c){let o=a.start-s,c=e.elementsCache.get(a.key);c&&t.lastPositions.get(c)!==o&&(t.lastPositions.set(c,o),r?c.style.transform=n?`translate3d(${o}px, 0, 0)`:`translate3d(0, ${o}px, 0)`:c.style[i]=`${o}px`)}},c={...r,onChange:(t,n)=>{var o;let c=a.current,l=!0;if(c.enabled){s(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,Jt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=Z.useState(()=>{let e=new IC(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),BC(()=>l._didMount(),[]),BC(()=>(o(l),l._willUpdate())),BC(()=>{s(l)}),l}function HC(e){return VC({observeElementRect:kC,observeElementOffset:NC,scrollToFn:FC,...e})}var UC=32;function WC(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function GC(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}var KC=`codex://threads/`,qC=512;function JC(e){let t=e.trim();if(t.length>qC||t.length<=16||!t.toLowerCase().startsWith(KC))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 YC(e){let t=e.trim(),n=JC(t);return n===t?[n]:[n,t]}async function XC(e){let t=YC(e).filter(e=>e!==``&&!GC(e)&&e.length<=4096);return(await Promise.all(t.map(e=>crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))).map(e=>WC(e).slice(0,UC))}function ZC(e,t,n){if(!e)return!1;let r=YC(t);return r.some(Boolean)?r.includes(e)?!0:n!==void 0&&n.includes(e):!1}var QC={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.`}}},$C={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 ew(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 tw(e,t){if(e<400)return null;let n=ew(t);return(QC[Math.trunc(e)]??(e<500?$C.client:$C.server))[n]}var nw=[`provider`,`usage`,`injection`];function rw(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function iw(e){return new Date(e).toLocaleTimeString()}function aw(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function ow(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function sw({entries:e}){let{t:n}=t();return(0,Q.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:n(`debug.claudeInbound.title`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`debug.claudeInbound.sub`)}),e.length===0?(0,Q.jsx)(`div`,{className:`muted text-control`,children:n(`debug.claudeInbound.empty`)}):(0,Q.jsx)(`div`,{style:{overflowX:`auto`},children:(0,Q.jsxs)(`table`,{className:`table text-label`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`debug.claudeInbound.time`)}),(0,Q.jsx)(`th`,{children:n(`debug.claudeInbound.endpoint`)}),(0,Q.jsx)(`th`,{children:n(`debug.claudeInbound.model`)}),(0,Q.jsx)(`th`,{children:`thinking`}),(0,Q.jsx)(`th`,{children:`effort`}),(0,Q.jsx)(`th`,{children:`beta`}),(0,Q.jsx)(`th`,{children:`metadata`}),(0,Q.jsx)(`th`,{children:`system`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted mono`,children:iw(e.at)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,Q.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,Q.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,Q.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:n(`debug.claudeInbound.none`)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:n(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function cw({debug:e,stream:n,streamEnabled:r,entries:i,scrollContainerRef:a,lineVirtualizer:o}){let{t:s}=t();return e?r?i.length===0?(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:s(`debug.noLinesTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:s(`debug.noLines.${n}`)})]}):(0,Q.jsx)(`div`,{ref:a,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,Q.jsx)(`div`,{style:{position:`relative`,height:o.getTotalSize(),width:`100%`},children:o.getVirtualItems().map(e=>(0,Q.jsx)(`div`,{ref:o.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${rw(i[e.index].at)}${i[e.index].line}`},e.key))})}):(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:s(`debug.emptyTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:s(`debug.empty`)})]}):null}function lw({debug:e,debugBusy:n,stream:r,onSetFlag:i,onReset:a,onStreamChange:o}){let{t:s}=t();return(0,Q.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Q.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(t=>{let r=ow(e,t);return(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,Q.jsx)(on,{on:r,disabled:n,label:s(`debug.${t}`),onClick:()=>i(t,!r)}),(0,Q.jsx)(`span`,{className:`text-control`,children:s(`debug.${t}`)})]},t)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:a,children:s(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${r===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`provider`),children:s(`debug.streamProvider`)}),e.usage&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${r===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`usage`),children:s(`debug.streamUsage`)}),e.injection&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${r===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`injection`),children:s(`debug.streamInjection`)})]})]})}function uw({embedded:e,refreshing:n,streamEnabled:r,follow:i,onRefresh:a,onFollowChange:o}){let{t:s}=t();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,Q.jsx)(`h2`,{children:s(`debug.title`)}),(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n||!r,onClick:a,children:[(0,Q.jsx)(re,{}),` `,s(`debug.refresh`)]}),(0,Q.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>o(e.target.checked)}),s(`debug.follow`)]})]})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:s(`debug.subtitle`)})]})}function dw(e){return`debug-settings:${e}`}function fw({apiBase:e,embedded:n,active:r=!0}){let{t:i}=t(),a=`ocx.debug.settings.v1:${e}`,o=La(a),s=dw(e),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(`provider`),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)(!0),[g,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(0),y=(0,Z.useRef)(0),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=Ua(s,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Va(a,r),r},{pollMs:2e3,enabled:r,isEmpty:()=>!1,initialData:o??void 0}),T=w.state,E=w.data??o??null,D=Vt(`debug-claude-inbound:${e}`,[e,E?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:r&&!!E?.claude}).data??[],O=HC({count:f.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>f[e].seq}),k=(0,Z.useCallback)(e=>aw(E,e),[E]);(0,Z.useEffect)(()=>{if(!E||k(u))return;let e=nw.find(k);if(!e)return;let t=window.setTimeout(()=>d(e),0);return()=>window.clearTimeout(t)},[E,u,k]);let j=k(u),M=u===`provider`?`${e}/api/debug/logs`:u===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,N=(0,Z.useCallback)(async(e,t)=>{let n=++b.current;if(!j){n===b.current&&(p([]),v.current=0);return}_(!0);try{let r=new URLSearchParams({limit:`500`});!e&&v.current>0&&r.set(`after`,String(v.current));let i=await fetch(`${M}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==b.current)return;let a=await i.json();if(t?.aborted||n!==b.current||a.length===0)return;p(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===b.current&&_(!1)}},[M,j]);(0,Z.useEffect)(()=>{if(!r)return;let t=`${e}:${u}:${j}`,n=C.current!==t;if(C.current=t,!n&&f.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{n&&p([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),b.current+=1,i.abort()}},[r,e,u,j]);let P=(0,Z.useRef)(!1),F=(0,Z.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let e=A(1e4);N(!1,e.signal).finally(()=>{e.clear(),P.current=!1})});(0,Z.useEffect)(()=>{if(!(!r||!m||!j))return sa(()=>F(),1e3)},[r,m,j]),(0,Z.useEffect)(()=>{m&&f.length>0&&O.scrollToIndex(f.length-1,{align:`end`})},[f,m,O]);let I=async t=>{let n=++y.current;l(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let i=await r.json();if(n!==y.current)return;Va(a,i),Ut(s,i)}catch{}},i=(x.current??Promise.resolve()).then(r,r);x.current=i.then(()=>void 0,()=>void 0);try{await i}finally{n===y.current&&l(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(uw,{embedded:n,refreshing:g,streamEnabled:j,follow:m,onRefresh:()=>void N(!0),onFollowChange:h}),!E&&T.showError?(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:i(`debug.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:i(`common.retry`)})]}):T.showSkeleton&&!E?(0,Q.jsx)(my,{label:i(`debug.loading`),rows:3}):E?(0,Q.jsx)(lw,{debug:E,debugBusy:c,stream:u,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()},onStreamChange:d}):null,E&&T.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`debug.loadFailed`)}),E?.claude&&(0,Q.jsx)(sw,{entries:D}),(0,Q.jsx)(cw,{debug:!!E,stream:u,streamEnabled:j,entries:f,scrollContainerRef:S,lineVirtualizer:O})]})}function pw(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 mw=[`all`,`native`,`translated`,`legacy-bridge`,`blocked`,`none`],hw={surface:`all`,model:``,provider:``,status:`all`,timeWindow:`all`,interceptedOnly:!1,conversationId:``};function gw(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 _w(e){return Array.isArray(e.attempts)?e.attempts.filter(e=>typeof e==`object`&&!!e):[]}function vw(e){if(typeof e!=`string`)return;let t=e.trim();return t?t.toLowerCase():void 0}function yw(e,t){if(e===`15m`)return t-9e5;if(e===`1h`)return t-36e5;if(e===`24h`)return t-864e5}function bw(e,t,n=Date.now()){let r=t.model.trim().toLowerCase(),i=t.provider.trim().toLowerCase(),a=t.conversationId.trim(),o=yw(t.timeWindow,n),s=t.protocolMode??`all`;return e.filter(e=>{if(!pw(e,t.surface)||t.interceptedOnly&&typeof e.shadowCallRewrittenFrom!=`string`)return!1;if(s!==`all`){let t=jm(e.protocolTrace)?.mode;if(s===`none`?t!==void 0:t!==s)return!1}if(a&&!ZC(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=_w(e);if(r&&![vw(e.model),vw(e.resolvedModel),vw(e.servedModel),...n.map(e=>vw(e.model))].some(e=>e===r)||i&&![vw(e.provider),...n.map(e=>vw(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 xw(e,t){if(typeof t!=`string`)return;let n=t.trim(),r=vw(n);if(!r)return;let i=e.get(r);(i===void 0||n<i)&&e.set(r,n)}function Sw(e){let t=new Map,n=new Map;for(let r of e){for(let e of[r.model,r.resolvedModel,r.servedModel,..._w(r).map(e=>e.model)])xw(t,e);for(let e of[r.provider,..._w(r).map(e=>e.provider)])xw(n,e)}return{models:[...t.values()].sort(),providers:[...n.values()].sort()}}var Cw=[`all`,`claude`,`codex`,`grok`];function ww(e,t,n){let r=Cw.indexOf(t),i=-1;if(e.key===`ArrowRight`||e.key===`ArrowDown`?i=(r+1)%Cw.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?i=(r-1+Cw.length)%Cw.length:e.key===`Home`?i=0:e.key===`End`&&(i=Cw.length-1),i<0)return;e.preventDefault();let a=Cw[i];n(a),document.getElementById(`logs-surface-${a}`)?.focus()}function Tw({filters:e,options:t,hasActiveFilters:n,filteredCount:r,totalCount:i,t:a,onFilterChange:o,onResetFilters:s}){let c=(0,Z.useRef)(null),l=()=>{s(),c.current?.focus({preventScroll:!0})},u=e.maxTokPerSec===15?`slow`:e.minTokPerSec===15&&e.maxTokPerSec===50?`medium`:e.minTokPerSec===50?`fast`:`all`,d=t=>{let n=t===`slow`?{minTokPerSec:void 0,maxTokPerSec:15}:t===`medium`?{minTokPerSec:15,maxTokPerSec:50}:t===`fast`?{minTokPerSec:50,maxTokPerSec:void 0}:{minTokPerSec:void 0,maxTokPerSec:void 0};o({...e,...n})};return(0,Q.jsxs)(`div`,{className:`logs-filter-container`,children:[(0,Q.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.surface.label`)}),(0,Q.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":a(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(t=>(0,Q.jsx)(`button`,{ref:t===`all`?c:void 0,type:`button`,role:`radio`,"aria-checked":e.surface===t,id:`logs-surface-${t}`,tabIndex:e.surface===t?0:-1,className:`btn btn-sm${e.surface===t?` btn-primary`:` btn-ghost`}`,style:{background:e.surface===t?void 0:`transparent`,color:e.surface===t?void 0:`var(--muted)`},onClick:()=>o({...e,surface:t}),onKeyDown:n=>ww(n,t,t=>o({...e,surface:t})),children:a(`logs.filter.surface.${t}`)},t))}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.interceptedOnly,onChange:t=>o({...e,interceptedOnly:t.target.checked})}),a(`logs.filter.interceptedHelpersOnly`)]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.provider.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:e.provider,"aria-label":a(`logs.filter.provider.label`),onChange:t=>o({...e,provider:t.target.value}),children:[(0,Q.jsx)(`option`,{value:``,children:a(`logs.filter.provider.all`)}),t.providers.map(e=>(0,Q.jsx)(`option`,{value:e,children:be(e,a)},e))]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.model.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:e.model,"aria-label":a(`logs.filter.model.label`),onChange:t=>o({...e,model:t.target.value}),children:[(0,Q.jsx)(`option`,{value:``,children:a(`logs.filter.model.all`)}),t.models.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.time.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:e.timeWindow,"aria-label":a(`logs.filter.time.label`),onChange:t=>o({...e,timeWindow:t.target.value}),children:[(0,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.time.all`)}),(0,Q.jsx)(`option`,{value:`15m`,children:a(`logs.filter.time.15m`)}),(0,Q.jsx)(`option`,{value:`1h`,children:a(`logs.filter.time.1h`)}),(0,Q.jsx)(`option`,{value:`24h`,children:a(`logs.filter.time.24h`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.speed.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:u,"aria-label":a(`logs.filter.speed.label`),onChange:e=>d(e.target.value),children:[(0,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.speed.all`)}),(0,Q.jsx)(`option`,{value:`slow`,children:a(`logs.filter.speed.slow`)}),(0,Q.jsx)(`option`,{value:`medium`,children:a(`logs.filter.speed.medium`)}),(0,Q.jsx)(`option`,{value:`fast`,children:a(`logs.filter.speed.fast`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.status.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:e.status,"aria-label":a(`logs.filter.status.label`),onChange:t=>o({...e,status:t.target.value}),children:[(0,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.status.all`)}),(0,Q.jsx)(`option`,{value:`success`,children:a(`logs.filter.status.success`)}),(0,Q.jsx)(`option`,{value:`errors`,children:a(`logs.filter.status.errors`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.protocol.label`),(0,Q.jsx)(`select`,{className:`input select-sm`,value:e.protocolMode??`all`,"aria-label":a(`logs.filter.protocol.label`),onChange:t=>o({...e,protocolMode:t.target.value}),children:mw.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(Ew(e))},e))})]})]}),(0,Q.jsxs)(`div`,{className:`logs-toolbar logs-toolbar-secondary`,children:[(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.conversation.label`),(0,Q.jsx)(`input`,{type:`search`,className:`input mono select-sm`,value:e.conversationId,onChange:t=>o({...e,conversationId:t.target.value}),placeholder:a(`logs.filter.conversation.placeholder`),"aria-label":a(`logs.filter.conversation.label`)})]}),n&&(0,Q.jsxs)(`div`,{className:`logs-filter-status`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.showingCount`,{count:r,total:i})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,Q.jsx)(ve,{}),` `,a(`logs.filter.reset`)]})]})]})]})}function Ew(e){return e===`all`?`logs.filter.protocol.all`:e===`none`?`logs.filter.protocol.none`:Km[e]}function Dw({trace:e,t}){let n=jm(e);if(!n)return null;let r=Qm(n,t),i=t(Km[n.mode]);return(0,Q.jsxs)(`span`,{className:`badge badge-muted protocol-path-badge`,title:t(`logs.protocol.badgeTitle`,{path:r,mode:i}),"data-protocol-mode":n.mode,children:[r,` · `,i]})}function Ow({trace:e,t}){let n=jm(e);return(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-protocol`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-protocol`,className:`log-detail-section-title`,children:t(`logs.detail.protocol.section`)}),n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,"data-protocol-mode":n.mode,children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.inbound`)}),(0,Q.jsx)(`span`,{children:Xm(n.inbound,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.mode`)}),(0,Q.jsx)(`span`,{children:t(Km[n.mode])}),n.upstream&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.upstream`)}),(0,Q.jsx)(`span`,{children:Xm(n.upstream,t)})]}),n.requestPath.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.requestPath`)}),(0,Q.jsx)(`span`,{children:Zm(n.requestPath,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.responsePath`)}),(0,Q.jsx)(`span`,{children:Zm(n.responsePath,t)})]}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.reasons`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:n.reasonCodes.join(`, `)||`–`}),n.featureEffects&&n.featureEffects.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.features`)}),(0,Q.jsx)(`span`,{children:n.featureEffects.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[(0,Q.jsx)(`code`,{children:e.feature}),`: `,t(qm[e.disposition])]},e.feature))})]}),n.attempts&&n.attempts.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.attempts`)}),(0,Q.jsx)(`span`,{children:n.attempts.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[t(`logs.detail.protocol.attempt`,{ordinal:e.ordinal}),`:`,` `,Zm(e.requestPath,t),` · `,t(Km[e.mode])]},e.ordinal))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm protocol-deep-link`,onClick:()=>Fg({inbound:n.inbound,upstream:Dg(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]}):(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:t(`logs.detail.protocol.none`)})]})}function kw(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?{generatedAt:e,receivedAt:t}:void 0}function Aw(e,t,n){return e?e.generatedAt+Math.max(0,t-e.receivedAt):n}function jw(){return fg(window.location.hash)===`logs/debug`?`debug`:`logs`}function Mw(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function Nw(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),Mw(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),Mw(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function Pw(e){return e.servedModel!==void 0&&e.servedModel!==(e.wireModel??e.model)}function Fw(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 Iw(e,t){return[Pw(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}${Fw(e.tierOutcome,t)}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function Lw(e){return e.requestedSpeedLabel||void 0}function Rw(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 zw=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function Bw(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=zw.format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function Vw(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):Bw(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function Hw(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 Uw(e){return e===`cursor`||e.startsWith(`cursor-`)}function Ww(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 Gw(e,t){if(!e.usage)return;let n=Ww(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(Uw(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function Kw(e){return e===void 0||typeof e==`string`}function qw(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!Kw(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!Kw(e.profile.id)||!Kw(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!Kw(e.selected.provider)||!Kw(e.selected.model)||!Kw(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`||!Kw(t.provider)||!Kw(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`||!Kw(e.code))return!1}}return!0}function Jw(e){if(e.routeDecision===void 0||qw(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function Yw(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 Xw(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}var Zw=Object.freeze([`completed`,`failed`,`incomplete`,`aborted`]);Object.freeze(Zw.filter(e=>e!==`aborted`)),Object.freeze([`terminal`,`client_cancel`,`non_stream`,`body_stall`,`body_overflow`]);function Qw(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 $w(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function eT(e){return $w(e?.sends)}function tT(e){return $w(e?.unresolved)}function nT(e){return`ocx.logs.list.v1:${e}`}var rT=[];function iT(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`||!qw(t.routeDecision))return null;return e}function aT(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 oT(e){let t=aT(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function sT(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 cT(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function lT(e){return Pw(e)?(0,Q.jsxs)(Q.Fragment,{children:[q_(e.wireModel??e.model),` → `,q_(e.servedModel)]}):q_(e.servedModel??e.resolvedModel??e.model)}function uT(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 dT=2e3,fT=3e4,pT=4,mT=3,hT={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`},gT={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`},_T={"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`,"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 vT(e){return hT[e]}function yT(e){return gT[e]}function bT(e){return _T[e]??`logs.detail.attempt.recovery.unknown`}function xT(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}var ST={completed:`logs.detail.outcome.completed`,failed:`logs.detail.outcome.failed`,incomplete:`logs.detail.outcome.incomplete`,aborted:`logs.detail.outcome.aborted`},CT={"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`},wT={"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`},TT={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 ET(e){return ST[Qw(e)]}function DT(e,t){let n=e.failureCause===void 0?void 0:CT[e.failureCause],r=e.failureStage===void 0?void 0:wT[e.failureStage],i=e.resendPermission===void 0?void 0:TT[e.resendPermission];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}:{}}}function OT(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function kT(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 AT(e,t,n){let{date:r,time:i}=kT(e,t,n);return`${r} ${i}`}function jT(e){let t=0;for(let n of e){let e=aT(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...Hw(e)}}function MT({apiBase:e}){let{t:n,locale:r}=t(),i=nT(e),a=iT(La(i)),[o,s]=(0,Z.useState)(!0),[c,l]=(0,Z.useState)({error:null,count:0}),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(hw),[m,h]=(0,Z.useState)(()=>Date.now()),g=(0,Z.useRef)({key:i,active:!1,request:0}),_=(0,Z.useRef)({key:i,cursor:null,rows:[]});(0,Z.useLayoutEffect)(()=>{let e={key:i,active:!0,request:0};return g.current=e,_.current={key:i,cursor:null,rows:[]},h(Date.now()),()=>{e.active=!1}},[i]);let v=(0,Z.useCallback)(()=>{let e=g.current;return Aw(e.key===i?e.anchor:void 0,performance.now(),Date.now())},[i]),y=(0,Z.useRef)(null),b=(0,Z.useRef)({key:i,failures:0,nextAttemptAt:0,error:null}),x=k.find(e=>e.code===r)?.htmlLang,[S,C]=(0,Z.useState)();(0,Z.useEffect)(()=>{let t=new AbortController,n=!1;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{n||!e||typeof e.timeZone==`string`&&e.timeZone.trim()&&C(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[w,T]=(0,Z.useState)(jw),[E,D]=(0,Z.useState)(()=>jw()===`debug`);(0,Z.useEffect)(()=>{let e=()=>T(jw());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>{w===`debug`&&D(!0)},[w]);let O=Mw,A=(0,Z.useCallback)(async t=>{let n=g.current;if(t.aborted||!n.active||n.key!==i)throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);let r=++n.request,a=()=>!t.aborted&&n.active&&g.current===n&&n.request===r,o=b.current;if(o.key!==i&&(o={key:i,failures:0,nextAttemptAt:0,error:null},b.current=o),o.failures>0&&Date.now()<o.nextAttemptAt)throw o.error;let s=_.current,c=s.key===i?s.cursor:null,l=`${e}/api/logs?limit=2000${c?`&cursor=${encodeURIComponent(c)}`:``}`;try{let e=await fetch(l,{signal:t});if(!e.ok)throw Error(`${e.status} ${e.statusText}`.trim());let r=await e.json(),o=performance.now(),u=Yw(r),d=u.rows.map(Jw),f=c&&u.cursor&&!u.reset?Xw(s.rows,d):d;if(!a())throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);_.current={key:i,cursor:u.cursor,rows:f};let m=Sw(f);p(e=>{let t=e.model.trim().toLowerCase(),n=e.provider.trim().toLowerCase(),r=t?m.models.find(e=>e.trim().toLowerCase()===t)??``:``,i=n?m.providers.find(e=>e.trim().toLowerCase()===n)??``:``;return e.model===r&&e.provider===i?e:{...e,model:r,provider:i}});let g=kw(u.generatedAt,o);return g&&(n.anchor=g),h(Aw(n.anchor,o,Date.now())),b.current={key:i,failures:0,nextAttemptAt:0,error:null},Va(i,f),f}catch(e){if(!a())throw e;let t=e??Error(`log request failed`),n=o.failures+1,r=dT*2**Math.min(n,pT);throw b.current={key:i,failures:n,nextAttemptAt:Date.now()+r,error:t},t}},[e,i]),j=Ua(i,[e],A,{isEmpty:e=>e.length===0,enabled:w===`logs`,pollMs:o?dT:void 0,initialData:a??void 0}),M=j.state,N=M.data??a??rT,P=j.refresh,F=(0,Z.useCallback)(()=>{b.current={key:i,failures:0,nextAttemptAt:0,error:null},_.current={key:i,cursor:null,rows:[]},P({forceLoading:!0})},[P,i]),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>=mT||!o&&I,R=u?tw(u.status,r):null,z=f.conversationId.trim();(0,Z.useEffect)(()=>{if(f.timeWindow===`all`||w!==`logs`)return;h(v());let e=window.setInterval(()=>h(v()),fT);return()=>window.clearInterval(e)},[f.timeWindow,w,v]),(0,Z.useEffect)(()=>{let e=!1;if(!z){p(e=>e.conversationQueryHash===void 0?e:{...e,conversationQueryHash:void 0});return}return XC(z).then(t=>{e||p(e=>e.conversationQueryHash?.join(` `)===t.join(` `)?e:{...e,conversationQueryHash:t})}),()=>{e=!0}},[z]);let B=(0,Z.useMemo)(()=>Sw(N),[N]),V=gw(f),H=(0,Z.useMemo)(()=>bw(N,f,m),[N,f,m]),U=z?jT(H):null,W=HC({count:H.length,getScrollElement:()=>y.current,estimateSize:()=>92,overscan:15,getItemKey:e=>{let t=H[H.length-1-e];return t.requestId??`${t.timestamp}:${t.model}:${t.provider}`}}),G=W.getVirtualItems(),ee=G.length>0?G[0].start:0,K=G.length>0?W.getTotalSize()-G[G.length-1].end:0;return(0,Q.jsxs)(`div`,{className:`logs-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:n(`nav.logs`)}),w===`logs`&&(0,Q.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),n(`logs.autoRefresh`)]})]}),(0,Q.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`nav.logs`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":w===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:w===`logs`?0:-1,className:`page-tab${w===`logs`?` page-tab--active`:``}`,onClick:()=>O(`logs`),onKeyDown:Nw,children:n(`logs.tabLogs`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":w===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:w===`debug`?0:-1,className:`page-tab${w===`debug`?` page-tab--active`:``}`,onClick:()=>O(`debug`),onKeyDown:Nw,children:n(`logs.tabDebug`)})]}),E&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:w!==`debug`,children:(0,Q.jsx)(fw,{apiBase:e,embedded:!0,active:w===`debug`})}),(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:w!==`logs`,children:[(0,Q.jsx)(Tw,{filters:f,options:B,hasActiveFilters:V,filteredCount:H.length,totalCount:N.length,t:n,onFilterChange:p,onResetFilters:()=>p(hw)}),U&&(0,Q.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,Q.jsxs)($,{tone:`ok`,children:[n(`logs.conversation.totals`,{requests:U.requests,tokens:q(U.totalTokens,x??r),cost:Bw(U.estimatedCostUsd,n,x,U.priorityLowerBound)}),` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[n(`logs.conversation.scope`),U.unpricedRequests+U.unmeteredRequests>0?` ${n(`logs.conversation.excluded`,{unpriced:U.unpricedRequests,unmetered:U.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,Q.jsxs)($,{tone:`err`,children:[M.error instanceof Error?`${n(`logs.loadError`)} ${M.error.message}`:n(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:n(`common.retry`)})]}),L&&N.length>0&&(0,Q.jsxs)($,{tone:`err`,children:[n(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:j.refreshing,children:n(`common.retry`)})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,Q.jsx)(my,{label:n(`common.loading`),rows:6}):H.length===0?(0,Q.jsx)(ln,{title:N.length>0&&V?n(`logs.noMatchingRequests`):n(`logs.noRequests`)}):(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{ref:y,className:`tbl-wrap logs-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,Q.jsxs)(`colgroup`,{children:[(0,Q.jsx)(`col`,{className:`logs-col-time`}),(0,Q.jsx)(`col`,{className:`logs-col-tokens`}),(0,Q.jsx)(`col`,{className:`logs-col-rate`}),(0,Q.jsx)(`col`,{className:`logs-col-cost`}),(0,Q.jsx)(`col`,{className:`logs-col-model`}),(0,Q.jsx)(`col`,{className:`logs-col-effort`}),(0,Q.jsx)(`col`,{className:`logs-col-provider`}),(0,Q.jsx)(`col`,{className:`logs-col-status`}),(0,Q.jsx)(`col`,{className:`logs-col-request`}),(0,Q.jsx)(`col`,{className:`logs-col-duration`})]}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`logs.col.time`)}),(0,Q.jsx)(`th`,{className:`num log-col-tokens`,children:n(`logs.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num log-col-rate`,title:n(`logs.metric.tokPerSecTitle`),children:n(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num log-col-cost`,title:n(`logs.metric.estimatedCostTitle`),children:n(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{className:`log-col-model`,children:n(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:n(`logs.col.effort`)}),(0,Q.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:n(`logs.col.status`)}),(0,Q.jsx)(`th`,{children:n(`logs.col.request`)}),(0,Q.jsx)(`th`,{className:`num log-col-duration`,children:n(`logs.col.duration`)})]})}),(0,Q.jsxs)(`tbody`,{children:[ee>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:ee}})}),G.map(e=>{let t=H[H.length-1-e.index],i=cT(t),a=t.displayMetrics?.decodeTokPerSecond,o=Rw(a?.kind===`value`?a:{}),s=kT(t.timestamp,x,S);return(0,Q.jsxs)(`tr`,{"data-index":e.index,ref:W.measureElement,children:[(0,Q.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,Q.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,Q.jsx)(`span`,{children:s.date}),(0,Q.jsx)(`span`,{children:s.time})]})}),(0,Q.jsx)(`td`,{className:`num mono log-col-tokens`,title:Gw(t,n),children:(()=>{let e=oT(t),{read:i,write:a}=Ww(t);return e===void 0?(0,Q.jsx)(`span`,{className:`muted`,children:n(`logs.tokens.${t.usageStatus??`unreported`}`)}):(0,Q.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,Q.jsxs)(`span`,{children:[t.usageStatus===`estimated`?`~`:``,q(e,r)]}),i!==void 0&&i>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,q(i,r)]}),a!==void 0&&a>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,q(a,r)]}),t.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,Q.jsx)(`span`,{className:`muted text-caption leading-tight`,children:n(Uw(t.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,Q.jsxs)(`td`,{className:`num mono log-col-rate`,children:[uT(t.displayMetrics?.tokPerSecond,x),a?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:n(o.detail),children:[(0,Q.jsx)(`span`,{children:uT(a,x)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:n(o.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono log-col-cost`,children:Vw(t.displayMetrics?.cost,n,x)}),(0,Q.jsx)(`td`,{className:`mono log-col-model`,title:Iw(t,n),children:(0,Q.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,Q.jsx)(`span`,{children:lT(t)}),t.shadowCallRewrittenFrom&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,style:{whiteSpace:`nowrap`},title:n(`logs.badge.interceptedHelperTitle`),children:n(`logs.badge.interceptedHelper`,{model:t.shadowCallRewrittenFrom})}),(t.surface===`claude`||t.surface===`claude-desktop`)&&(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:n(`logs.badge.claude`)}),t.surface===`grok`&&(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:n(`logs.badge.grok`)}),Lw(t)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:Lw(t)}),(0,Q.jsx)(Dw,{trace:t.protocolTrace,t:n})]})}),(0,Q.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:sT(t)}),(0,Q.jsx)(`td`,{className:`muted`,children:be(t.provider,n)}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`span`,{className:`log-status-cell`,children:[(0,Q.jsx)(`span`,{className:`mono font-semibold`,style:{color:OT(t.status)},children:t.status}),(0,Q.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>d(t),"aria-label":`${n(`logs.details`)}: ${t.requestId??t.status}`,children:n(`logs.details`)})]})}),(0,Q.jsx)(`td`,{className:`muted mono`,children:(0,Q.jsx)(`span`,{className:`log-reqid`,title:t.requestId,children:t.requestId??`-`})}),(0,Q.jsxs)(`td`,{className:`num log-col-duration`,children:[t.durationMs,`ms`]})]},e.key)}),K>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:K}})})]})]})})}),u&&(0,Q.jsx)(PT,{detail:u,detailInfo:R,localeCode:r,localeTag:x,serverTimeZone:S,t:n,onClose:()=>d(null),onFilterConversation:e=>{p(t=>({...t,conversationId:e})),d(null)}})]})]})}function NT(e){let t=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function PT({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=NT(!0),[l,u]=(0,Z.useState)(!1),d=Ww(e),f=e.displayMetrics?.cost,p=e.displayMetrics?.decodeTokPerSecond,m=Rw(p?.kind===`value`?p:{}),h=cT(e),g=DT(e,a),_=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,Q.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,Q.jsx)(`span`,{className:`mono`,style:{color:OT(e.status)},children:e.status}),t&&(0,Q.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,Q.jsx)(ve,{})})]}),t&&(0,Q.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,Q.jsx)(`span`,{className:`mono`,children:AT(e.timestamp,r,i)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.outcome.label`)}),(0,Q.jsx)(`span`,{children:a(ET(e))}),g.cause&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.cause.label`)}),(0,Q.jsxs)(`span`,{children:[g.cause,g.stage&&` (${a(`logs.detail.stage.label`)}: ${g.stage})`]})]}),g.resend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.resend.label`)}),(0,Q.jsx)(`span`,{children:g.resend})]}),e.spend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.sends.label`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[eT(e.spend),tT(e.spend)>0&&` (${a(`logs.detail.sends.unresolved`)}: ${tT(e.spend)})`]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void _(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,Q.jsx)(`span`,{className:`mono`,children:lT(e)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,Q.jsx)(`span`,{children:be(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[sT(e),h?` (${h})`:``]})]}),e.errorCode&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,Q.jsx)(`span`,{className:`mono`,children:(e.routeDecision.candidates??[]).map(e=>`${typeof e.provider==`string`&&e.provider.length>0?e.provider:`–`}/${typeof e.model==`string`&&e.model.length>0?e.model:`–`}${e.eligible===!0?` ✓`:e.eligible===!1?` ✗`:` ?`}`).join(` `)||`–`})]}):(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,Q.jsx)(Ow,{trace:e.protocolTrace,t:a}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid log-detail-performance-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.endToEndTokPerSec`)}),(0,Q.jsx)(`span`,{className:`mono`,children:uT(e.displayMetrics?.tokPerSecond,r)}),p?.kind===`value`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,title:a(m.hint),children:a(m.detail)}),(0,Q.jsx)(`span`,{className:`mono`,children:uT(p,r)}),(0,Q.jsx)(`span`,{className:`logs-decode-basis-hint muted text-caption`,children:a(m.hint)})]}),e.firstOutputMs!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(vT(e.displayMetrics.tokPerSecond.reason))}),e.displayMetrics?.decodeTokPerSecond?.kind===`unavailable`&&(0,Q.jsxs)(`p`,{className:`log-detail-notes-line muted`,children:[a(`logs.detail.decodeTokPerSec`),`: `,a(vT(e.displayMetrics.decodeTokPerSecond.reason))]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:Bw(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:Bw(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:Bw(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:Bw(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:Bw(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,Q.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,Q.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(xT(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,Q.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,Q.jsx)(`li`,{children:a(yT(e))},e))})]}):(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,Q.jsx)(`span`,{children:f?.kind===`unavailable`?a(vT(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,Q.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`num`,children:`#`}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,Q.jsx)(`th`,{className:`num`,title:a(`logs.detail.endToEndTokPerSec`),children:a(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,Q.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=e.displayMetrics?.decodeTokPerSecond,i=Rw(n?.kind===`value`?n:{}),o=cT(e),s=t?.kind===`value`?t.estimate.price:void 0,c=DT(e,a).cause??e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(bT(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(vT(t.reason)):a(`logs.detail.attempt.completed`));return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{children:be(e.provider,a)}),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[sT(e),o?` (${o})`:``]})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[s.jawcodeProvider??s.provider,`/`,s.modelId,` · `,a(`logs.detail.source.${s.source}`),` · `,a(xT(s.status))]})]})]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[uT(e.displayMetrics?.tokPerSecond,r),n?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:a(i.detail),children:[(0,Q.jsx)(`span`,{children:uT(n,r)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:a(i.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:Vw(t,a,r)}),(0,Q.jsx)(`td`,{className:`log-detail-break`,children:c})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?q(e.usage.inputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?q(e.usage.outputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:q(d.read,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:q(d.write,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:q(e.usage.reasoningOutputTokens,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,Q.jsx)(`span`,{className:`mono`,children:oT(e)===void 0?`—`:q(oT(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:q(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,Q.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,Q.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,Q.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function FT(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 IT(e,t){if(!e||!t)return{ok:!1,error:`required`};let n=FT(e),r=FT(t);return n===null||r===null?{ok:!1,error:`invalid`}:n>r?{ok:!1,error:`reversed`}:{ok:!0,window:{since:n,until:r+59999}}}var LT=[`requests`,`tokens`,`cost`,`quota`,`none`],RT=[6,24,72,168],zT=[`line`,`stackedBar`],BT=[`total`,`input`,`output`,`cached`],VT=[`sum`,`average`,`max`],HT=[`model`,`modelAccount`],UT={requests:`usage.companion.menuRequests`,tokens:`usage.companion.menuTokens`,cost:`usage.companion.menuCost`,quota:`usage.companion.menuQuota`,none:`usage.companion.menuNone`},WT={6:`usage.companion.window6`,24:`usage.companion.window24`,72:`usage.companion.window72`,168:`usage.companion.window168`},GT={total:`usage.companion.metricTotal`,input:`usage.companion.metricInput`,output:`usage.companion.metricOutput`,cached:`usage.companion.metricCached`},KT=[[`showToday`,`usage.companion.sectionToday`],[`showChart`,`usage.companion.sectionChart`],[`showModels`,`usage.companion.sectionModels`],[`showCost`,`usage.companion.sectionCost`],[`showAccounts`,`usage.companion.sectionAccounts`]],qT={sum:`usage.companion.aggregationSum`,average:`usage.companion.aggregationAverage`,max:`usage.companion.aggregationMax`},JT={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`]},YT={macos:`usage.companion.osMac`,windows:`usage.companion.osWindows`,linux:`usage.companion.osLinux`};function XT(e,t){return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`}).format(e)}function ZT(e){return e instanceof Error&&e.message?e.message:String(e)}function QT({value:e,onChange:t,t:n}){return(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":n(`usage.companion.installOs`),children:Object.keys(YT).map(r=>(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${e===r?` active`:``}`,"aria-pressed":e===r,onClick:()=>t(r),children:n(YT[r])},r))})}function $T({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`div`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":e,children:n.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${e===t?` active`:``}`,"aria-pressed":e===t,onClick:()=>i(e),children:r(e)},String(e)))})]})}function eE({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`label`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),(0,Q.jsx)(`select`,{value:t,onChange:e=>i(e.target.value),children:n.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(e)},e))})]})}function tE(e){let[t,n]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{if(t||!e.current||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(n(!0),r.disconnect())},{rootMargin:`240px`});return r.observe(e.current),()=>r.disconnect()},[e,t]),t}function nE({apiBase:e,providers:n,onSettingsLoaded:r}){let{t:i,locale:a}=t(),o=(0,Z.useRef)(null),s=tE(o),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(`idle`),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),A=(0,Z.useRef)(null),j=(0,Z.useRef)(S),M=(0,Z.useRef)(u),N=(0,Z.useRef)(new Map),[P,F]=(0,Z.useState)(new Map),[I,L]=(0,Z.useState)(()=>{let e=Xa();return e===`unknown`?`macos`:e});(0,Z.useEffect)(()=>{j.current=S},[S]),(0,Z.useEffect)(()=>{M.current=u},[u]);let R=(0,Z.useCallback)(async()=>{_(null);try{let t=await fetch(`${e}/api/companion/settings`);if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());let n=await t.json();l(n),T(Date.now()),d(n.settings),k.current=n.settings,r?.(n.settings.menuBarMetric)}catch(e){_(ZT(e))}},[e,r]);(0,Z.useEffect)(()=>{if(!s||c)return;let e=setTimeout(()=>void R(),0);return()=>clearTimeout(e)},[R,c,s]),(0,Z.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,Z.useMemo)(()=>u?et(u):null,[u]),B=(0,Z.useCallback)(async()=>{if(!z)return;A.current?.abort();let t=new AbortController;A.current=t,x(!0),y(null);try{let n=await fetch(`${e}/api/usage/timeline?${z}`,{signal:t.signal});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let r=await n.json(),i=u?Ce(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(ZT(e))}finally{t.signal.aborted||x(!1)}},[u,e,z]);(0,Z.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,Z.useCallback)(e=>{c?.corrupt||(d(t=>t&&{...t,...e}),C(`saving`),D(null))},[c?.corrupt]);(0,Z.useEffect)(()=>{if(!(c?.corrupt||!u||!k.current||k.current===u||S!==`saving`))return O.current&&clearTimeout(O.current),O.current=setTimeout(async()=>{try{let t=Me(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(ZT(e)),C(`error`)}},300),()=>{O.current&&clearTimeout(O.current)}},[e,m,c?.corrupt,S,u]);let H=(0,Z.useRef)(m);(0,Z.useEffect)(()=>{H.current=m},[m]),(0,Z.useEffect)(()=>()=>{let t=M.current;!t||!k.current||k.current===t||j.current!==`saving`||fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:Me(t,H.current)}),keepalive:!0}).catch(()=>{})},[e]);let U=(0,Z.useCallback)(async()=>{C(`saving`),D(null);try{let t=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({reset:!0})});if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());await R(),C(`saved`)}catch(e){D(ZT(e)),C(`error`)}},[e,R]),W=(0,Z.useCallback)(async()=>{try{let t=location.hash?`/${location.hash}`:`/#/usage`,n=await fetch(`${e}/api/companion/open-in-browser`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:t})});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim())}catch(e){D(ZT(e))}},[e]);if(g)return(0,Q.jsxs)(`section`,{ref:o,className:`usage-companion-panel`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:i(`usage.companion.settingsUnavailable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void R(),children:i(`common.retry`)})]});let G=u;if(!G)return(0,Q.jsx)(`section`,{ref:o,className:`usage-companion-panel`,"aria-busy":`true`,children:(0,Q.jsx)(`div`,{className:`usage-companion-loading`,children:i(`common.loading`)})});let ee=n.map(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t).toSorted(),K=G.models??m,q=new Set(K),te=Ee(m,P),ne=new Set(G.hiddenProviders),J=S===`saved`&&c?.updatedAt?i(`usage.companion.saved`,{time:XT(c.updatedAt,a)}):S===`error`?i(`usage.companion.saveFailed`,{error:E??``}):``;return(0,Q.jsxs)(`section`,{ref:o,className:`usage-companion-panel`,children:[c?.corrupt&&(0,Q.jsxs)(`div`,{className:`usage-companion-save-status is-error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:i(`usage.companion.corrupt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(),disabled:S===`saving`,children:i(`usage.companion.corruptReset`)})]}),(0,Q.jsxs)(`div`,{className:`usage-companion-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:i(`usage.companion.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`usage.companion.description`)})]}),(0,Q.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`https://opencodex.me/guides/macos-menu-bar/`,target:`_blank`,rel:`noreferrer`,children:i(`usage.companion.installGuide`)})]}),(()=>{let e=c?.companion?.lastSeenAt??null,t=e!==null&&w!==null&&w-e<=6e5,n=e===null||w===null?``:zo(e,Bo(i),w),r=Ka(),a=Ga()??`2.86.0`,o=JT[I],s=(0,Q.jsxs)(`ol`,{className:`usage-companion-install-steps`,children:[(0,Q.jsxs)(`li`,{children:[i(o[0]),` `,(0,Q.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`https://github.com/lidge-jun/opencodex/releases/latest`,target:`_blank`,rel:`noreferrer`,children:i(`common.github`)})]}),(0,Q.jsx)(`li`,{children:i(o[1])}),(0,Q.jsx)(`li`,{children:i(o[2])})]}),l=I===`macos`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command`,children:`xattr -d com.apple.quarantine /Applications/OpenCodex.app`}):I===`linux`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command`,children:`chmod +x OpenCodex-*.AppImage`}):null,u=(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.installAnother`)}),(0,Q.jsx)(QT,{value:I,onChange:L,t:i}),s,l]});return r?(0,Q.jsxs)(`div`,{className:`usage-companion-install usage-companion-install--shell`,children:[(0,Q.jsx)(`p`,{children:i(`usage.companion.runningInDesktop`,{version:a})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void W(),children:i(`usage.companion.openInBrowser`)}),u]}):t?(0,Q.jsxs)(`div`,{className:`usage-companion-install usage-companion-install--connected`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-install-status`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-install-dot`,"aria-hidden":`true`}),i(c?.companion?.kind===`desktop`?`usage.companion.connectedDesktop`:`usage.companion.connected`,{age:n})]}),u]}):(0,Q.jsxs)(`details`,{className:`usage-companion-install`,open:!0,children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.installTitle`)}),e!==null&&(0,Q.jsx)(`p`,{className:`usage-companion-install-last-seen muted text-caption`,children:i(`usage.companion.lastSeen`,{age:n})}),e===null&&(0,Q.jsx)(`p`,{className:`usage-companion-install-last-seen muted text-caption`,children:i(`usage.companion.notConnected`)}),(0,Q.jsx)(QT,{value:I,onChange:L,t:i}),s,l]})})(),(0,Q.jsx)(He,{timeline:f,chartStyle:G.chartStyle,hours:G.chartHours,loading:b,error:v,onRetry:()=>void B(),locale:a,t:i}),te.length>0&&(0,Q.jsxs)(`section`,{className:`usage-companion-models`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-models-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.companion.modelsOnChart`)}),(0,Q.jsx)(`span`,{className:`usage-companion-models-count text-caption muted`,children:i(`usage.companion.modelsCount`,{selected:K.length,total:m.length})})]}),G.models!==null&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>V({models:null}),disabled:c?.corrupt,children:i(`usage.companion.modelsShowAll`)})]}),(0,Q.jsx)(`div`,{className:`usage-companion-models-list`,children:te.map(e=>{let t=e.models.filter(e=>q.has(e.id)).length,n=t===e.models.length;return(0,Q.jsxs)(`div`,{className:`usage-companion-model-group`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-model-group-header`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-model-provider`,children:e.provider}),(0,Q.jsx)(`span`,{className:`usage-companion-model-chip mono text-caption`,children:e.models.length}),(0,Q.jsx)(on,{on:n,mixed:t>0&&!n,onClick:()=>V({models:it(G.models,m,e.models.map(e=>e.id),!n)}),disabled:c?.corrupt,label:e.provider,title:e.provider})]}),e.models.map(e=>{let t=q.has(e.id);return(0,Q.jsxs)(`div`,{className:`usage-companion-model-row${t?``:` is-off`}`,children:[(0,Q.jsx)(on,{on:t,onClick:()=>V({models:it(G.models,m,[e.id],!t)}),disabled:c?.corrupt,label:e.id,title:e.id}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.id}),(0,Q.jsx)(`span`,{className:`usage-companion-model-total muted text-caption`,children:P.has(e.id)?ot(e.total):`—`})]},e.id)})]},e.provider)})})]}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-controls`,disabled:c?.corrupt,children:[(0,Q.jsx)($T,{label:i(`usage.companion.menuBarShows`),value:G.menuBarMetric,options:LT,optionLabel:e=>i(UT[e]),onChange:e=>V({menuBarMetric:e})}),(0,Q.jsx)($T,{label:i(`usage.companion.window`),value:G.chartHours,options:RT,optionLabel:e=>i(WT[e]),onChange:e=>V({chartHours:e,bucketMinutes:Pe(e)})}),(0,Q.jsx)($T,{label:i(`usage.companion.style`),value:G.chartStyle,options:zT,optionLabel:e=>i(e===`line`?`usage.companion.styleLine`:`usage.companion.styleStacked`),onChange:e=>V({chartStyle:e})}),(0,Q.jsx)(eE,{label:i(`usage.companion.metric`),value:G.tokenMetric,options:BT,optionLabel:e=>i(GT[e]),onChange:e=>V({tokenMetric:e})}),(0,Q.jsx)(eE,{label:i(`usage.companion.groupBy`),value:G.chartGrouping,options:HT,optionLabel:e=>i(e===`model`?`usage.companion.groupModel`:`usage.companion.groupAccount`),onChange:e=>V({chartGrouping:e})}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-switches`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`usage.companion.popoverSections`)}),KT.map(([e,t])=>(0,Q.jsxs)(`div`,{className:`usage-companion-switch`,children:[(0,Q.jsx)(`span`,{children:i(t)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${G[e]?`on`:``}`,"aria-label":i(t),"aria-pressed":G[e],onClick:()=>V({[e]:!G[e]}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]},e))]}),(0,Q.jsxs)(`details`,{className:`usage-companion-advanced`,children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.advanced`)}),(0,Q.jsxs)(`div`,{className:`usage-companion-advanced-body`,children:[(0,Q.jsx)(eE,{label:i(`usage.companion.aggregation`),value:G.aggregation,options:VT,optionLabel:e=>i(qT[e]),onChange:e=>V({aggregation:e})}),(0,Q.jsxs)(`label`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.companion.menuText`)}),(0,Q.jsx)(`input`,{value:G.menuBarTemplate??``,onChange:e=>V({menuBarTemplate:e.target.value}),maxLength:200}),(0,Q.jsxs)(`span`,{className:`muted text-caption`,children:[i(`usage.companion.placeholders`),` `,(0,Q.jsx)(`code`,{children:`{requests} {totalTokens} {inputTokens} {outputTokens} {costUsd} {quotaPercent}`})]})]}),ee.length>0&&(0,Q.jsxs)(`fieldset`,{className:`usage-companion-check-list`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`usage.companion.hideProviders`)}),ee.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:ne.has(e),onChange:t=>V({hiddenProviders:t.target.checked?[...G.hiddenProviders,e]:G.hiddenProviders.filter(t=>t!==e)})}),` `,(0,Q.jsx)(`span`,{children:e})]},e))]})]})]})]}),(0,Q.jsxs)(`div`,{className:`usage-companion-save-status${S===`error`?` is-error`:``}`,role:S===`error`?`alert`:`status`,children:[J||`\xA0`,S===`error`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{C(`saving`)},children:i(`common.retry`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(),children:i(`usage.companion.reset`)}),(0,Q.jsx)(`p`,{className:`muted text-caption`,children:i(`usage.companion.footer`)})]})}function rE({apiBase:e,providers:t}){let[n,r]=(0,Z.useState)([]);return(0,Z.useEffect)(()=>{if(t.length>0)return;let n=new AbortController;return fetch(`${e}/api/config`,{signal:n.signal}).then(e=>hn(e)).then(e=>{n.signal.aborted||r(Object.keys(e?.providers??{}).map(e=>({provider:e})))}).catch(()=>{}),()=>n.abort()},[e,t.length]),(0,Q.jsx)(nE,{apiBase:e,providers:t.length>0?t:n})}function iE(){return window.location.hash.replace(/^#\/?/,``)===`usage/companion`?`companion`:`report`}function aE(e){window.location.hash=e===`report`?`usage`:`usage/companion`}function oE(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`;aE(t),document.getElementById(`usage-tab-${t}`)?.focus()}}var sE=class extends Error{};function cE(e){return`${Math.round(e*100)}%`}function lE({row:e,locale:t,t:n}){if(e.estimatedCostUsd===void 0&&e.pricedRequests===void 0&&e.unpricedRequests===void 0)return(0,Q.jsx)(`span`,{className:`muted`,children:`—`});let r=e.unpricedRequests??0,i=n(r===1?`usage.cost.excludedOne`:`usage.cost.excluded`,{count:r});return e.estimatedCostUsd===void 0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:`—`}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:hd(e.estimatedCostUsd??0,t)}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]})}function uE(e,t,n){return typeof e==`number`&&Number.isFinite(e)&&e>=0?q(e,t):n}function dE(e,t){return typeof e==`number`&&Number.isFinite(e)?cE(e):t}function fE(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:q(r,t),total:q(e.inputTokens,t)})}function pE(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function mE(e,t){return pE(e.throughputTokensPerSec)?t(`usage.throughput.title`,{samples:e.throughputSamples??0}):t(`usage.throughput.unmeasured`)}function hE(e,t){let n=`${t}/${e}`,r=0;for(let e=0;e<n.length;e++)r=r*31+n.charCodeAt(e)>>>0;return`hsl(${r%360} 55% 55%)`}function gE(e){let t=new Map(e.map(e=>[e.date,e])),n=[],r=new Date;r.setHours(0,0,0,0),r.setDate(r.getDate()-6);for(let e=0;e<7;e++){let e=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,`0`)}-${String(r.getDate()).padStart(2,`0`)}`,i=t.get(e);n.push({date:e,requests:i?.requests??0,measuredRequests:i?.measuredRequests??0,reportedRequests:i?.reportedRequests??0,totalTokens:i?.totalTokens??0,models:i?.models??[]}),r.setDate(r.getDate()+1)}return n}function _E(e,t){return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(new Date(`${e}T12:00:00`))}function vE(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 yE({anchor:e,className:t,children:n}){return(0,Jt.createPortal)((0,Q.jsx)(`div`,{className:`${t} chart-overlay`,role:`tooltip`,style:vE(e),children:n}),document.body)}function bE(e,t,n){return n(`usage.chart.dayDetail`,{date:_E(e.date,t),requests:e.requests,tokens:q(e.totalTokens,t)})}function xE(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 SE(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function CE(e,t=!1){let n=xE(e.map(e=>e.totalTokens)),r=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];if(t){let t=[],i=[],a=[],o,s=-1,c=-4,l=e=>{for(;a.length<e;)a.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:a.length})};for(let u of e){let[e,d,f]=u.date.split(`-`).map(Number),p=new Date(Date.UTC(e,d-1,f)),m=p.getUTCDay(),h=p.getTime()-m*864e5;o!==h&&(a.length>0&&(l(7),t.push(a)),a=[],o=h);let g=p.getUTCMonth();g!==s&&t.length-c>=4&&(i.push({label:r[g],col:t.length}),s=g,c=t.length),l(m),a.push({date:u.date,requests:u.requests,totalTokens:u.totalTokens,level:SE(u.totalTokens,n),dayOfWeek:m})}return a.length>0&&(l(7),t.push(a)),{weeks:t,months:i,buckets:n}}let i=new Map(e.map(e=>[e.date,e])),a=new Date;a.setHours(0,0,0,0);let o=new Date(a);o.setDate(o.getDate()-364),o.setDate(o.getDate()-o.getDay());let s=[],c=[],l=-4,u=-1,d=[],f=new Date(o);for(;f<=a;){let e=`${f.getFullYear()}-${String(f.getMonth()+1).padStart(2,`0`)}-${String(f.getDate()).padStart(2,`0`)}`,t=f.getMonth();f.getDay()===0&&t!==u&&s.length-l>=4&&(c.push({label:r[t],col:s.length}),l=s.length,u=t);let a=i.get(e);d.push({date:e,requests:a?.requests??0,totalTokens:a?.totalTokens??0,level:a?SE(a.totalTokens,n):0,dayOfWeek:f.getDay()}),f.getDay()===6&&(s.push(d),d=[]),f.setDate(f.getDate()+1)}if(d.length>0){for(;d.length<7;)d.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:d.length});s.push(d)}return{weeks:s,months:c,buckets:n}}function wE({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,Q.jsxs)(`div`,{className:`usage-filters`,children:[(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`logs.filter.surface.label`),children:[`all`,`codex`,`claude`,`grok`].map(t=>{let r=i(`logs.filter.surface.${t}`);return(0,Q.jsxs)(`button`,{type:`button`,className:`usage-segmented-btn usage-source-btn${e===t?` active`:``}`,"aria-label":r,"aria-pressed":e===t,onClick:()=>n(t),children:[t===`codex`&&(0,Q.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,Q.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,Q.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(e===`all`?`usage.range.available`:`usage.range.${e}`);return(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${t===e?` active`:``}`,"aria-label":n,"aria-pressed":t===e,onClick:()=>r(e),children:n},e)})})]})}function TE({summary:e,activeDays:t,locale:n,t:r}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(e.totalTokens,n)})]}),(0,Q.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,Q.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,q(e.cacheCreationInputTokens??0,n)]})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:cE(e.coverageRatio)})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:t})]})]}),(0,Q.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,title:mE(e,r),children:[(0,Q.jsx)(`span`,{className:`muted`,children:r(`usage.col.tokPerSec`)}),(0,Q.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:pE(e.throughputTokensPerSec)?e.throughputTokensPerSec.toFixed(1):r(`usage.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:mE(e,r)})]}),e.estimatedCostUsd!==void 0&&(0,Q.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,Q.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:hd(e.estimatedCostUsd,n)}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function EE({weekBars:e,locale:t,t:n}){let[r,i]=(0,Z.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens)),o=e.find(e=>e.date===r?.date),s=(e,t)=>{i({date:e.date,anchor:t.getBoundingClientRect()})};return(0,Q.jsxs)(`div`,{className:`daybars`,role:`group`,"aria-label":n(`usage.section.heatmap`),children:[e.map(e=>{let r=Math.round(e.totalTokens/a*100),o=new Intl.DateTimeFormat(t,{weekday:`short`}).format(new Date(`${e.date}T12:00:00`));return(0,Q.jsxs)(`button`,{type:`button`,className:`daybar`,"aria-label":bE(e,t,n),onFocus:t=>s(e,t.currentTarget),onBlur:()=>i(t=>t?.date===e.date?null:t),onPointerEnter:t=>s(e,t.currentTarget),onPointerDown:t=>s(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&i(t=>t?.date===e.date?null:t)},children:[(0,Q.jsx)(`div`,{className:`daybar-track`,children:(0,Q.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,r/100)))},children:[e.models.map(e=>(0,Q.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:hE(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,Q.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),(0,Q.jsx)(`span`,{className:`daybar-count`,children:q(e.totalTokens,t)}),(0,Q.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)}),r&&o&&(0,Q.jsxs)(yE,{className:`daybar-tip`,anchor:r.anchor,children:[(0,Q.jsx)(`div`,{className:`daybar-tip-date`,children:_E(o.date,t)}),(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{children:n(`usage.heatmap.tooltipRequests`,{requests:o.requests})}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:q(o.totalTokens,t)})})]}),o.models.slice(0,8).map(e=>(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:hE(e.model,e.provider)}}),(0,Q.jsx)(`span`,{className:`daybar-tip-name`,children:q_(e.model)}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:q(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]})]})}function DE({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,Z.useRef)(null),o=(0,Z.useMemo)(()=>t.weeks.flat().filter(e=>e.date),[t]),[s,c]=(0,Z.useState)(()=>o.at(-1)?.date??``),[l,u]=(0,Z.useState)(null),d=(0,Z.useId)(),f=o.some(e=>e.date===s)?s:o.at(-1)?.date??``,p=(e,t)=>{c(e.date),u({date:e.date,anchor:t.getBoundingClientRect()})},m=(e,t)=>{let n=o.findIndex(e=>e.date===t.date),r=e.key===`ArrowUp`?-1:e.key===`ArrowDown`?1:e.key===`ArrowLeft`?-7:e.key===`ArrowRight`?7:0;if(!r||n<0)return;e.preventDefault();let i=o[Math.max(0,Math.min(o.length-1,n+r))];c(i.date);let s=a.current?.querySelector(`[data-date="${i.date}"]`);s&&(s.focus(),u({date:i.date,anchor:s.getBoundingClientRect()}))};return(0,Z.useEffect)(()=>{let e=a.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[t,e]),(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,Q.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,Q.jsx)(EE,{weekBars:n,locale:r,t:i}):(0,Q.jsxs)(`div`,{className:`heatmap`,ref:a,children:[(0,Q.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,Q.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,Q.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,Q.jsxs)(`div`,{className:`heatmap-body`,children:[(0,Q.jsxs)(`div`,{className:`heatmap-days`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`div`,{className:`heatmap-grid`,role:`group`,"aria-labelledby":`usage-heatmap-title`,"aria-describedby":d,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,Q.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>e.date?(0,Q.jsx)(`button`,{type:`button`,className:`heatmap-cell heatmap-cell-${e.level}`,"data-date":e.date,tabIndex:f===e.date?0:-1,"aria-label":bE(e,r,i),onFocus:t=>p(e,t.currentTarget),onBlur:()=>u(t=>t?.date===e.date?null:t),onKeyDown:t=>m(t,e),onPointerEnter:t=>p(e,t.currentTarget),onPointerDown:t=>p(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&u(t=>t?.date===e.date?null:t)}},e.date):(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-0`,"aria-hidden":`true`},`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),(0,Q.jsx)(`span`,{id:d,className:`sr-only`,children:i(`usage.heatmap.keyboardLabel`)}),(0,Q.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:o.find(e=>e.date===f)?bE(o.find(e=>e.date===f),r,i):``}),l&&(()=>{let e=o.find(e=>e.date===l.date);return e?.date?(0,Q.jsxs)(yE,{className:`heatmap-tip`,anchor:l.anchor,children:[(0,Q.jsx)(`div`,{className:`heatmap-tip-date`,children:_E(e.date,r)}),(0,Q.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:q(e.totalTokens,r)})}),(0,Q.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,Q.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,Q.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,Q.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function OE({title:e,titleId:t,children:n}){return(0,Q.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,Q.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function kE({models:e,modelQuery:t,onModelQuery:n,locale:r,t:i,workspace:a=!1}){let o=i(`usage.search.models`),s=i(`usage.section.models`),c=`usage-models-title`,l=`usage-models-list-price-disclaimer`,u=i(`usage.unavailable`),d=(0,Q.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),f=(0,Q.jsxs)(`div`,{className:`tbl-wrap`,children:[(0,Q.jsxs)(`table`,{className:`tbl usage-models-tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:i(`usage.col.share`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":l,children:i(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.inputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.outputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheHits`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheWrites`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheHitRate`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=be(e.provider,i),n=fE(e,r,i),a=mE(e,i);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.model,children:q_(e.model)}),(0,Q.jsx)(`td`,{className:`muted`,title:t,children:t}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`usage-bar`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,r)}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(lE,{row:e,locale:r,t:i})}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.inputTokens,r)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.outputTokens,r)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:a,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:pE(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:u}),pE(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:a})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:uE(e.cacheReadInputTokens??e.cachedInputTokens,r,u)}),(0,Q.jsx)(`td`,{className:`num mono`,children:uE(e.cacheCreationInputTokens,r,u)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:n,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:dE(e.cacheHitRate,u)}),n!==void 0&&(0,Q.jsx)(`span`,{className:`sr-only`,children:n})]})]},`${e.provider}/${e.model}`)})})]}),(0,Q.jsx)(`p`,{id:l,className:`muted text-caption`,children:i(`usage.cost.disclaimer`)})]});return a?(0,Q.jsxs)(OE,{title:s,titleId:c,children:[(0,Q.jsx)(`div`,{className:`usw-section-toolbar`,children:d}),f]}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),d]}),f]})}function AE({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.unavailable`),a=n(`usage.section.providers`),o=`usage-providers-title`,s=`usage-providers-list-price-disclaimer`,c=(0,Q.jsxs)(`div`,{className:`tbl-wrap`,children:[(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":s,children:n(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono`,children:be(e.provider,n)}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,t)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:mE(e,n),children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:pE(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:i}),pE(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:mE(e,n)})]}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(lE,{row:e,locale:t,t:n})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`usage-bar`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]}),(0,Q.jsx)(`p`,{id:s,className:`muted text-caption`,children:n(`usage.cost.disclaimer`)})]});return r?(0,Q.jsx)(OE,{title:a,titleId:o,children:c}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":o,children:[(0,Q.jsx)(`h3`,{id:o,className:`panel-title`,children:a}),c]})}function jE({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,Q.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,Q.jsx)(OE,{title:r,titleId:i,children:a}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,Q.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function ME({data:e,heatmap:t,weekBars:n,activeDays:r,filteredModels:i,modelQuery:a,onModelQuery:o,sortedProviders:s,range:c,locale:l,t:u}){let d=!!e&&e.summary.requests===0,f=[{id:`overview`,label:u(`usage.section.overview`),meta:e?`${e.summary.requests}`:`—`,body:e?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(TE,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,Q.jsx)(DE,{range:c,heatmap:t,weekBars:n,locale:l,t:u})]}):null},{id:`models`,label:u(`usage.section.models`),meta:e?`${e.models.length}`:`—`,body:e?(0,Q.jsx)(kE,{models:i,modelQuery:a,onModelQuery:o,locale:l,t:u,workspace:!0}):null},{id:`providers`,label:u(`usage.section.providers`),meta:e?`${e.providers.length}`:`—`,body:e?(0,Q.jsx)(AE,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?cE(e.summary.coverageRatio):`—`,body:e?(0,Q.jsx)(jE,{summary:e.summary,t:u,workspace:!0}):null}];return(0,Q.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,Q.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,Q.jsx)(sC,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,Q.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,Q.jsx)(ln,{title:u(`usage.empty`)}):f.map(e=>(0,Q.jsx)(`div`,{id:iC(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var NE=new Map;function PE(e,t,n,r,i,a){return`ocx.usage.v2:${e}:${r?`connected`:`standalone`}:${i}:${a??``}:${t}:${n}`}function FE(e,t,n,r,i,a){let o=PE(e,t,n,r,i,a);return NE.get(o)??La(o)}function IE(e,t,n,r,i,a,o){let s=PE(e,t,n,r,i,a);NE.set(s,o),Va(s,o)}function LE({apiBase:e,connected:n=!1,apiKeyId:r}){let{t:i,locale:a}=t(),[o,s]=(0,Z.useState)(iE);(0,Z.useEffect)(()=>{let e=()=>s(iE());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let[c,l]=(0,Z.useState)(`30d`),[u,d]=(0,Z.useState)(`all`),[f,p]=(0,Z.useState)(`machine`),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)({since:``,until:``}),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(!1),w=v?.since,T=v?.until,E=()=>{y(null),_({since:``,until:``}),x(null)},D=e=>{l(e),E()},O=(0,Z.useCallback)(async t=>{let i=new URLSearchParams({range:c,surface:u});n&&f===`machine`&&r&&i.set(`apiKeyId`,r),w!==void 0&&T!==void 0&&(i.set(`since`,String(w)),i.set(`until`,String(T)));let a=await mr(await fetch(`${e}/api/usage?${i}`,{signal:t}));if(w!==void 0&&(a?.customWindow!==!0||a.since!==w||a.until!==T))throw new sE;return w===void 0&&IE(e,c,u,n,f,r,a),a},[e,r,n,c,f,u,w,T]),k=PE(e,c,u,n,f,r),A=v?JSON.stringify([k,w,T]):k,j=v?null:FE(e,c,u,n,f,r),M=Ua(A,[e,r,n,c,f,u,w,T],O,{isEmpty:()=>!1,initialData:j??void 0}),{state:N}=M,P=N.data??j??null,F=(0,Z.useMemo)(()=>CE(P?.days??[],!!v),[P?.days,v]),I=(0,Z.useMemo)(()=>gE(P?.days??[]),[P?.days]),L=(0,Z.useMemo)(()=>(P?.days??[]).filter(e=>e.requests>0).length,[P?.days]),R=(0,Z.useMemo)(()=>{let e=m.trim().toLowerCase(),t=(P?.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)},[P?.models,m]),z=(0,Z.useMemo)(()=>(P?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[P?.providers]);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,Q.jsx)(`h2`,{id:`usage-page-title`,children:i(`usage.title`)}),o===`report`&&(0,Q.jsx)(wE,{surface:u,range:v?null:c,onSurface:d,onRange:D,t:i})]}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`nav.usage`),children:[`report`,`companion`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`usage-tab-${e}`,"aria-selected":o===e,"aria-controls":`usage-panel-${e}`,tabIndex:o===e?0:-1,className:`page-tab${o===e?` page-tab--active`:``}`,onClick:()=>aE(e),onKeyDown:oE,children:i(e===`report`?`usage.workspace.report`:`usage.section.companion`)},e))}),o===`companion`?(0,Q.jsx)(`div`,{role:`tabpanel`,id:`usage-panel-companion`,"aria-labelledby":`usage-tab-companion`,children:(0,Q.jsx)(rE,{apiBase:e,providers:P?.providers??[]})}):(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`usage-panel-report`,"aria-labelledby":`usage-tab-report`,children:[(0,Q.jsx)(`p`,{className:`page-sub`,children:i(`usage.subtitle`)}),(0,Q.jsxs)(`section`,{className:`usage-range`,children:[(0,Q.jsxs)(`div`,{className:`usage-range-bar`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`usage-range-toggle${v?` is-active`:``}`,"aria-expanded":S,"aria-controls":S?`usage-range-panel`:void 0,onClick:()=>{S&&x(null),C(!S)},children:[(0,Q.jsx)(`span`,{children:i(`usage.range.custom`)}),(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`,className:`usage-range-chevron`})]}),v&&(0,Q.jsx)(`p`,{className:`usage-range-applied muted text-control`,role:`status`,children:(()=>{let e=new Intl.DateTimeFormat(a,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,timeZoneName:`short`});return i(`usage.range.applied`,{start:e.format(v.since),end:e.format(v.until)})})()})]}),S&&(0,Q.jsxs)(`form`,{id:`usage-range-panel`,className:`usage-range-panel`,"aria-label":i(`usage.range.custom`),noValidate:!0,onSubmit:e=>{e.preventDefault();let t=IT(g.since,g.until);if(t.ok===!1){x(t.error);return}x(null),y(t.window)},children:[(0,Q.jsxs)(`div`,{className:`usage-range-fields`,children:[(0,Q.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.range.start`)}),(0,Q.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:g.since,"aria-invalid":b!==null,"aria-describedby":b?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;_(e=>({...e,since:t})),x(null)}})]}),(0,Q.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.range.end`)}),(0,Q.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:g.until,"aria-invalid":b!==null,"aria-describedby":b?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;_(e=>({...e,until:t})),x(null)}})]}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary btn-sm usage-range-action`,children:i(`usage.range.apply`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm usage-range-action`,onClick:E,children:i(`usage.range.clear`)})]}),(0,Q.jsx)(`p`,{id:`usage-range-help`,className:`muted text-caption`,children:i(`usage.range.help`)}),b&&(0,Q.jsx)(`p`,{id:`usage-range-error`,role:`alert`,className:`notice notice-err`,children:i(`usage.range.${b}`)})]})]}),n&&(0,Q.jsxs)(`div`,{className:`usage-source-row`,children:[(0,Q.jsx)(`span`,{children:i(`usage.source.connected`)}),(0,Q.jsxs)(`div`,{className:`usage-scope-control`,role:`group`,"aria-label":i(`usage.scope.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${f===`machine`?` btn-primary`:` btn-ghost`}`,"aria-pressed":f===`machine`,onClick:()=>p(`machine`),children:i(`usage.scope.machine`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${f===`hub`?` btn-primary`:` btn-ghost`}`,"aria-pressed":f===`hub`,onClick:()=>p(`hub`),children:i(`usage.scope.hub`)})]})]}),N.showSkeleton&&!P?(0,Q.jsx)(my,{label:i(`usage.loading`),rows:5}):N.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[N.error instanceof sE?`${i(`usage.loadError`)} ${i(`dash.codexRestartMalformed`)}`:N.error instanceof pr?i(`usage.loadError`):n?i(`usage.hubOffline`):N.error instanceof Error?`${i(`usage.loadError`)} ${N.error.message}`:i(`usage.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>M.refresh(),children:i(`common.retry`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[N.showError&&(0,Q.jsx)($,{tone:`err`,children:i(n&&!(N.error instanceof pr)?`usage.hubOffline`:`usage.loadError`)}),(0,Q.jsx)(gr,{data:P}),P?.historyTruncated&&(0,Q.jsx)($,{tone:`warn`,children:(()=>{let e=RE(P.snapshotWindowStart),t=RE(P.snapshotWindowEnd);return e!==null&&t!==null?i(`usage.historyTruncatedWindow`,{start:e,end:t}):i(`usage.historyTruncated`)})()}),(0,Q.jsx)(ME,{data:P,heatmap:F,weekBars:I,activeDays:L,filteredModels:R,modelQuery:m,onModelQuery:h,sortedProviders:z,range:v?null:c,locale:a,t:i})]})]})]})}function RE(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function zE(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 BE={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 VE(e,t){return BE[e][t]}var HE={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 UE(e,t){return HE[e][t]}var WE={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 GE(e,t){return WE[e].schema[t]}function KE(e,t){return WE[e].protection[t]}function qE(e,t){return WE[e].mode[t]}var JE={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 YE(e,t){let n=JE[e.key];return n?t(n):e.label}function XE(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function ZE(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function QE(e,t){switch(t){case`codex_running`:return UE(e,`error.codex_running`);case`process_enumeration_failed`:return UE(e,`error.process_enumeration_failed`);case`busy`:return UE(e,`error.busy`);case`unsupported_schema`:return UE(e,`error.unsupported_schema`);case`trigger_collision`:return VE(e,`error.trigger_collision`);case`unsafe_path`:return UE(e,`error.unsafe_path`);case`database_error`:return UE(e,`error.database_error`);case`auto_vacuum_not_incremental`:return UE(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return UE(e,`error.integrity_check_failed`);case`config_write_failed`:return VE(e,`error.config_write_failed`);default:return UE(e,`error.generic`)}}function $E({report:e,locale:t,t:n,busy:r,error:i,compaction:a,onAction:o}){let s=e.metrics,c=e.capabilities.protection.state===`unsupported`||e.capabilities.reclaim.state===`unsupported`,l=e.protection,u=r||e.capabilities.protection.state!==`supported`,d=l!==void 0&&e.capabilities.reclaim.state===`supported`&&(s?.reclaimableBytes??0)>0,[f,p]=(0,Z.useState)(!1);return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:GE(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:VE(t,`inspectionOnly`)})]}):null]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:zE(e.files.databaseBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`WAL`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:zE(e.files.walBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`SHM`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:zE(e.files.shmBytes,t)})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`TRACE`})}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`freelist`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:zE(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,Q.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`muted`,children:VE(t,`metricsSkippedLarge`).replace(`{threshold}`,zE(e.metricsSkipped.thresholdBytes,t))})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`sqlite_home`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,Q.jsx)(`code`,{children:e.externalSqliteHome?VE(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:VE(t,`protection`)}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:(0,Q.jsx)(`code`,{children:KE(t,l.state)})}),(0,Q.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:qE(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:qE(t,l.observedMode)})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-compat`,disabled:u,"aria-pressed":l.desiredMode===`compat`,onClick:()=>o({action:`protect`,mode:`compat`}),children:VE(t,`compat`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-quiet`,disabled:u,"aria-pressed":l.desiredMode===`quiet`,onClick:()=>o({action:`protect`,mode:`quiet`}),children:VE(t,`quiet`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-unprotect`,disabled:u||l.desiredMode===`off`,onClick:()=>o({action:`unprotect`}),children:VE(t,`disable`)}),l.state===`drifted`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:VE(t,`repair`)}),r&&(0,Q.jsx)(`span`,{className:`muted`,role:`status`,children:UE(t,`applying`)})]}),i&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,Q.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,Q.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:VE(t,`confirmCompact`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:VE(t,`cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:VE(t,`compact`)})})}),a&&(0,Q.jsx)(`div`,{className:`stw-section`,children:(0,Q.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:(0,Q.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,Q.jsx)(`code`,{children:e.target})}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:(0,Q.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function eD({locale:e,t}){return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:VE(e,`inspectionUnavailable`)})]})}function tD({report:e,locale:t,apiBase:n=``,logGuardBusy:r=!1,onLogGuardAction:i}){let a=O(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),g=(0,Z.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),_=g.find(e=>e.key===o)??null,v=c?.generation===e.generatedAt?c.report:e.codexLogs??null,y=f?.generation===e.generatedAt?f.message:null,b=m?.generation===e.generatedAt?m.summary:null,x=r||u,S=(0,Z.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),C=(0,Z.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,Q.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,Q.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":a(`storage.section.buckets`),children:[(0,Q.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-title`,children:a(`storage.section.buckets`)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-count`,children:g.length})]}),(0,Q.jsx)(`div`,{className:`storage-workspace-rail-list`,children:g.length===0?(0,Q.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:a(`storage.empty`)}):g.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${o===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>s(t=>t===e.key?null:e.key),"aria-current":o===e.key?`true`:void 0,children:[(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-name`,children:YE(e,a)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-size`,children:zE(e.bytes,t)})]}),(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,a(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,Q.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":_?YE(_,a):a(`storage.section.largest`),children:_?(0,Q.jsxs)(`div`,{className:`stw-detail`,children:[(0,Q.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>s(null),children:[(0,Q.jsx)(Ke,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),a(`modal.back`)]})}),(0,Q.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,Q.jsx)(`h2`,{className:`stw-detail-title`,children:YE(_,a)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.size`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:zE(_.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.files`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:_.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.oldest`)}),(0,Q.jsx)(`dd`,{children:XE(_.oldest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.newest`)}),(0,Q.jsx)(`dd`,{children:XE(_.newest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:ZE(_,t,a)})]})]}),(_.largest?.length??0)>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),_.largest.map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:zE(e.bytes,t)})]},e.path))]})]})]}):(0,Q.jsxs)(`div`,{className:`stw-overview`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.total`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:zE(e.total.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.files`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.home`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),v?(0,Q.jsx)($E,{report:v,locale:t,t:a,busy:x,error:y,compaction:b,onAction:r=>{if(i){i(r);return}if(u)return;let a=e.generatedAt;(async()=>{d(!0),p(null),r.action===`compact`&&h(null);try{let e=r.action===`protect`?`protect`:r.action,i={method:`POST`,...r.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:r.mode})}:{}},o=await fetch(`${n}/api/storage/codex-logs/${e}`,i);if(!o.ok){let e=await o.json().catch(()=>({}));p({generation:a,message:QE(t,e.error)});return}if(r.action===`compact`){let e=(await o.json().catch(()=>null))?.report;if(e){let n=zE(e.logicalBytesReclaimed??0,t),r=zE(e.physicalDatabaseBytesReclaimed??0,t),i=e.complete?VE(t,`compactComplete`):VE(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;h({generation:a,summary:[`${i}${s}`,`${o.toLocaleString(t)} ${VE(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${n}/api/storage/codex-logs`);if(e.ok){let t=await e.json();l({generation:a,report:t})}}catch{}return}let s=await o.json();l({generation:a,report:s})}catch{p({generation:a,message:UE(t,`error.generic`)})}finally{d(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,Q.jsx)(eD,{locale:t,t:a}):null,S.length>0?(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),S.map(e=>{let n=C.get(e.bucketKey);return(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,Q.jsx)(`span`,{className:`stw-file-bucket`,children:YE(n,a)}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:zE(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,Q.jsxs)(`p`,{className:`stw-hint`,children:[(0,Q.jsx)(Ne,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),a(`storage.workspace.selectBucket`)]})]})})]})}var nD=1024**3,rD=[10,25,50],iD=(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 aD({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,Z.useState)(25),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(!1),x=(0,Z.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,Z.useEffect)(()=>{b.current=f},[f]),(0,Z.useEffect)(()=>{if(!c)return;y.current=document.activeElement,v.current?.focus();let e=e=>{e.key===`Escape`&&!b.current&&x()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),y.current?.focus()}},[c,x]);let S=(e,t,r)=>{switch(e){case`codex_busy`:return n(`storage.cleanup.err.codex_busy`);case`stale_preview`:return n(`storage.cleanup.err.stale_preview`);case`restore_pending_overlap`:return n(`storage.cleanup.err.restore_pending_overlap`);case`referenced_history`:return n(`storage.cleanup.err.referenced_history`);case`invalid_digest`:return n(`storage.cleanup.err.invalid_digest`);case`invalid_mode`:return n(`storage.cleanup.err.invalid_mode`);case`fs_failed`:return r?n(`storage.cleanup.err.fs_failed_trash`,{trashDir:r}):n(`storage.cleanup.err.fs_failed`);case`db_reconcile_failed`:return n(`storage.cleanup.err.db_reconcile_failed`);case`cleanup_failed`:return n(`storage.cleanup.err.cleanup_failed`);default:return t??n(`storage.cleanup.cleanupFailed`)}},C=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),w=async()=>{p(!0),_(null),h(null);try{let t=await fetch(`${e}/api/storage/cleanup/preview`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({percent:i})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(S(e.error,n(`storage.cleanup.previewFailed`)))}let r=await t.json();s(r),l(!0)}catch(e){_(iD(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:zE(a.bytes,t)});h(a.skippedReferencedPaths?.length?`${s} ${n(`storage.cleanup.skippedReferenced`,{count:String(a.skippedReferencedPaths.length)})}`:s),r()}catch(e){_(iD(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,Q.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,Q.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,Q.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,Q.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,Q.jsx)(`div`,{className:`storage-manual-panel__presets`,children:rD.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:C(e)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void w(),children:n(`storage.cleanup.preview`)})]}),m&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&x(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:zE(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,Q.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,Q.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,Q.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,Q.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,Q.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:v,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>x(),children:n(`storage.cleanup.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void T(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function oD({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{g.current=o},[o]);let _=(0,Z.useCallback)(()=>l(null),[]);(0,Z.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&_()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,_]);let v=(0,Z.useCallback)(async t=>{let r=await fetch(`${e}/api/storage/trash`,{signal:t});if(!r.ok)throw Error(n(`storage.trash.listFailed`));let i=await r.json(),o=Array.isArray(i.entries)?i.entries:[];return a?.(o),o},[e,a,n]),y=Ua(`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:zE(a.bytes,t)})),r()}catch(e){p(iD(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},C=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},w=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),y.showError&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:y.error instanceof Error?y.error.message:n(`storage.trash.listFailed`)}),y.refreshing&&!y.showSkeleton&&(0,Q.jsx)(hy,{live:!y.showError,children:n(`storage.trash.loading`)}),y.showSkeleton?(0,Q.jsx)(my,{label:n(`storage.trash.loading`),rows:2}):b.length===0?(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,Q.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:b.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted`,children:C(e)}),(0,Q.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,Q.jsx)(`td`,{className:`num mono`,children:zE(e.bytes,t)}),(0,Q.jsx)(`td`,{className:`muted`,children:w(e.mode)}),(0,Q.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&_(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:zE(c.bytes,t),id:c.id})}),f&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>_(),children:n(`storage.trash.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void S(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function sD(e){let{job:t,...n}=e;return n}function cD(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/nD*100)/100));return e.target.reduceToBytes===void 0?{policy:sD(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:sD(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/nD*100)/100))}}async function lD(e){await new Promise(t=>window.setTimeout(t,e))}function uD({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=La(i),o=(0,Z.useRef)(!!a),[s,c]=(0,Z.useState)(()=>a?.policy??null),[l,u]=(0,Z.useState)(()=>!a),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(()=>a?.targetMode??`percent`),[x,S]=(0,Z.useState)(()=>a?.percent??`25`),[C,w]=(0,Z.useState)(()=>a?.reduceGb??`4`),[T,E]=(0,Z.useState)(()=>a?.thresholdGb??`5`),D=(0,Z.useRef)(null),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(!1),A=(0,Z.useRef)(0),j=(0,Z.useCallback)(e=>{let t=cD(e);c(t.policy),E(t.thresholdGb),b(t.targetMode),S(t.percent),w(t.reduceGb),o.current=!0,Va(i,t),O.current=!1},[i]),M=(0,Z.useCallback)(()=>{O.current=!0},[]),N=(0,Z.useCallback)(e=>{k.current=e},[]),P=(0,Z.useCallback)(async t=>{let r=++A.current;o.current||u(!0),v(null);try{let n=await fetch(`${e}/api/storage/cleanup-policy`,{signal:t});if(!n.ok)throw Error(`load_failed`);let i=await n.json();if(t?.aborted||r!==A.current||O.current||k.current)return;j(i)}catch{if(t?.aborted||r!==A.current)return;o.current||(c(null),v(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===A.current&&u(!1)}},[e,j,n]);(0,Z.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{P(e.signal)},0);return()=>{window.clearTimeout(t),A.current+=1,e.abort()}},[P]),(0,Z.useEffect)(()=>()=>{D.current?.abort(),D.current=null},[]);let F=()=>{if(!s)return null;let e=T.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(y===`reduce`){let e=C.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*nD)}}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*nD)},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 lD(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=sD(n),j(n);let r=n.job;if(r&&r.status!==`running`){if(r.startedAt===u&&r.lastOutcome){f=r.lastOutcome;break}if(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:zE(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:zE(f.freedBytes??0,t)})),r()):v(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;v(n(`storage.policy.runFailed`))}finally{D.current===i&&(D.current=null),a.aborted||m(!1)}},R=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,Q.jsx)(`div`,{className:`storage-policy-enable`,children:(0,Q.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void I({enabled:!s.enabled}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,Q.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,Q.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,Q.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,Q.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:T,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>N(!0),onChange:e=>{M(),E(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(Vc,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{M(),E(Bc(T,.1,0,1e4,.1))},onDecrement:()=>{M(),E(Bc(T,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`percent`,disabled:d||p,onChange:()=>{M(),b(`percent`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),y===`percent`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:x,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>N(!0),onChange:e=>{M(),S(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(Vc,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{M(),S(Bc(x,1,1,100))},onDecrement:()=>{M(),S(Bc(x,-1,1,100))}})]})]}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`reduce`,disabled:d||p,onChange:()=>{M(),b(`reduce`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),y===`reduce`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:C,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>N(!0),onChange:e=>{M(),w(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(Vc,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{M(),w(Bc(C,.1,0,1e4,.1))},onDecrement:()=>{M(),w(Bc(C,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,Q.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;I({schedule:t})},children:[(0,Q.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,Q.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,Q.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,Q.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,Q.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;I({mode:t})},children:[(0,Q.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,Q.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,Q.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,Q.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[R(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:zE(s.lastRun.freedBytes,t)})}`:``]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,Q.jsx)(`span`,{className:`storage-policy-meta-value`,children:R(s.nextRun)})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void I(),children:n(`storage.policy.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,Q.jsx)(`span`,{className:`storage-policy-actions__status${_?` is-error`:``}`,role:_?`alert`:`status`,"aria-live":`polite`,children:_??h??``})]})]}):(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:_&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:_})})}function dD({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,Z.useState)(`policy`),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=[{id:`policy`,label:n(`storage.cleanupCard.tab.policy`),ref:u},{id:`quarantine`,label:n(`storage.cleanupCard.tab.quarantine`),ref:d}],p=e=>{l(e),window.requestAnimationFrame(()=>(e===`policy`?u:d).current?.focus())},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(c===`policy`?`quarantine`:`policy`)):e.key===`Home`?(e.preventDefault(),p(`policy`)):e.key===`End`&&(e.preventDefault(),p(`quarantine`))};return(0,Q.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,Q.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,Q.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,Q.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,Q.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,Q.jsx)(uD,{apiBase:e,locale:t,t:n,onDone:o}),(0,Q.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,Q.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,Q.jsx)(aD,{apiBase:e,locale:t,t:n,onDone:o}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,Q.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,Q.jsx)(oD,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function fD({apiBase:e}){let{t:n,locale:r}=t(),i=`ocx.storage.report.v1:${e}`,a=La(i),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(0),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)({apiBase:e,settled:!1,hasEntries:!1}),p=(0,Z.useCallback)(async t=>{try{let r=await fetch(`${e}/api/storage`,{signal:t});if(!r.ok)throw Error(n(`storage.error`));let a=await r.json();return Va(i,a),u.current&&(u.current=!1,s(n(`storage.rescanned`))),a}catch(e){throw u.current&&(u.current=!1,s(n(`storage.error`))),t.aborted?e:Error(n(`storage.error`),{cause:e})}},[e,i,n]),m=Ua(`storage-report:${e}`,[e],p,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),h=m.state,g=h.data??a,_=h.refreshing||h.showSkeleton&&!g,v=m.refresh,y=(0,Z.useCallback)(()=>{s(null),u.current=!0,v(),l(e=>e+1)},[v]),b=(0,Z.useCallback)(t=>{f({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=d.apiBase===e&&d.settled,S=d.apiBase===e&&d.hasEntries,C=g?.error!==void 0,w=!_&&!h.showError&&!C&&g.total.fileCount===0&&x&&!S,T=g?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!g&&!C,D=E&&(g.total.fileCount>0||!x||S);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{id:`storage-page-title`,children:n(`storage.title`)}),(0,Q.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,Q.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:o??``}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:_,onClick:()=>void y(),children:[(0,Q.jsx)(re,{}),` `,n(`storage.refresh`)]})]})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`storage.subtitle`)}),g&&g.error===void 0&&(0,Q.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,Q.jsx)(`code`,{className:`mono storage-page-meta__home`,title:g.codexHome,children:g.codexHome}),(0,Q.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[n(`storage.snapshot.lastScan`),`:`,` `,new Date(g.generatedAt).toLocaleString(r)]})]}),h.showSkeleton&&!g?(0,Q.jsx)(my,{label:n(`storage.loading`),rows:5}):h.kind===`failed-cold`&&!g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:h.error instanceof Error?h.error.message:n(`storage.error`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:n(`common.retry`)})]}):C?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:n(`storage.error`)})}):(0,Q.jsxs)(Q.Fragment,{children:[h.showError&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:n(`storage.error`)}),w?(0,Q.jsx)(ln,{title:n(`storage.empty`)}):g&&g.total.fileCount>0&&(0,Q.jsx)(tD,{report:g,locale:r,apiBase:e})]}),g&&g.error===void 0&&h.refreshing&&!h.showSkeleton&&(0,Q.jsx)(hy,{live:!h.showError,children:n(`storage.loading`)}),E&&(0,Q.jsx)(dD,{apiBase:e,locale:r,t:n,archivedCount:T,showQuarantine:D,trashReloadToken:c,onDone:()=>void y(),onTrashEntriesChange:b})]})}var pD=`/api/codex-auth/features/default-mode-request-user-input`;function mD({apiBase:e}){let t=O(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(!1),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(0),h=(0,Z.useCallback)(async()=>{if(f.current)return;let t=++m.current,n=A(15e3);try{let i=await fetch(`${e}${pD}`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(f.current||t!==m.current)return;p.current=o.enabled===!0,r(p.current),a(!0),l(!1)}catch{!f.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=sa(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,Z.useCallback)(async()=>{if(f.current||!i||c)return;let n=!p.current,o=p.current;p.current=n,r(n),f.current=!0,s(!0),d(null),m.current++;try{let i=await fetch(`${e}${pD}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await hn(i)??{};if(o.ok!==!0)throw Error(String(i.status));p.current=o.enabled===!0,r(p.current),a(!0),d({tone:`ok`,message:t(o.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){p.current=o,r(o);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);d({tone:`err`,message:n})}finally{f.current=!1,s(!1)}},[e,i,c,t]),_=o||!i||c;return(0,Q.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,Q.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
|
|
8
|
+
default_mode_request_user_input = true`})]}),(0,Q.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:t(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:_,"aria-pressed":n,"aria-label":t(`codexAuth.requestUserInput`),title:t(`codexAuth.requestUserInput`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Q.jsx)(`div`,{className:`codex-request-user-input-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function hD({apiBase:e}){let t=O(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(!1),p=(0,Z.useRef)(0),m=(0,Z.useCallback)(async()=>{if(f.current)return;let t=++p.current,n=A(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(f.current||t!==p.current)return;r(o.ultraFastTier===!0),a(!0),l(!1)}catch{!f.current&&t===p.current&&l(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{m()},0),t=sa(()=>{m()},3e4);return()=>{window.clearTimeout(e),t()}},[m]);let h=(0,Z.useCallback)(async()=>{if(f.current||!i||c)return;let a=!n;f.current=!0,s(!0),d(null),r(a);let o=A(15e3);try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({ultraFastTier:a}),signal:o.signal});if(!n.ok)throw Error(`save`);let i=await n.json(),s=typeof i.ultraFastTier==`boolean`?i.ultraFastTier:a;r(s),d({tone:`ok`,message:t(s?`codexAuth.ultraFastEnabled`:`codexAuth.ultraFastDisabled`)})}catch{r(!a),d({tone:`err`,message:t(`codexAuth.ultraFastFailed`)})}finally{o.clear(),f.current=!1,s(!1)}},[e,n,i,c,t]),g=o||!i||c;return(0,Q.jsxs)(`div`,{className:`card card-row codex-ultrafast-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-ultrafast-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.ultraFastTitle`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.ultraFastLoadFailed`:`codexAuth.ultraFastDesc`)})]}),(0,Q.jsxs)(`div`,{className:`codex-ultrafast-controls`,children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m()},children:t(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{h()},disabled:g,"aria-pressed":n,"aria-label":t(`codexAuth.ultraFastTitle`),title:t(`codexAuth.ultraFastTitle`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Q.jsx)(`div`,{className:`codex-ultrafast-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function gD(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`);return t}function _D({pending:e,thresholds:t,onCancel:n,onConfirm:r}){let i=O(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=o.current;return e&&!e.open&&e.showModal(),s.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Q.jsxs)(`dialog`,{ref:o,className:`modal-overlay`,"aria-labelledby":`${a}-title`,"aria-describedby":`${a}-body`,"aria-busy":e||void 0,onCancel:e=>{e.preventDefault(),n()},onKeyDown:t=>{if(t.key!==`Tab`||e)return;let n=t.shiftKey?s.current:c.current,r=t.shiftKey?c.current:s.current;document.activeElement===n&&(t.preventDefault(),r?.focus())},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`common.close`),disabled:e,onClick:n}),(0,Q.jsxs)(`div`,{className:`modal-card codex-main-hard-lock-dialog`,role:`document`,children:[(0,Q.jsx)(`h3`,{id:`${a}-title`,children:i(`codexAuth.mainHardLockConfirmTitle`,t)}),(0,Q.jsx)(`p`,{id:`${a}-body`,className:`modal-desc`,children:i(`codexAuth.mainHardLockConfirmBody`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:s,type:`button`,className:`btn btn-ghost`,disabled:e,onClick:n,children:i(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn btn-primary`,disabled:e,onClick:r,children:i(e?`common.saving`:`codexAuth.mainHardLockConfirm`)})]})]})]})}function vD(e){return(0,Q.jsx)(yD,{...e},e.apiBase)}function yD({apiBase:e,onSaved:t}){let n=O(),r=(0,Z.useId)(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(!1),y=(0,Z.useRef)(!1),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(!1),T=(0,Z.useCallback)(async()=>{if(v.current)return;let t=++b.current;x.current?.abort();let n=A(15e3);x.current=n.controller;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let i=gD(await r.json());if(!y.current||t!==b.current)return;a(i),s(!1),p(null)}catch{y.current&&t===b.current&&s(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{y.current=!0;let e=window.setTimeout(()=>{T()},0),t=sa(()=>{T()},3e4);return()=>{y.current=!1,b.current+=1,x.current?.abort(),window.clearTimeout(e),t()}},[T]),(0,Z.useEffect)(()=>{g||m||!w.current||(S.current&&!S.current.disabled?(S.current.focus(),w.current=!1):C.current?.focus())},[g,m,o,i]);let E=async()=>{let e=!1;try{e=await t()}catch{}y.current&&d(!e)},D=async t=>{if(v.current||!i)return;v.current=!0,b.current+=1,x.current?.abort(),h(!0),l(!1),d(!1),p(null);let n=A(15e3),r=!1;try{let i=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLock:t}),signal:n.signal});if(!i.ok)throw Error(`save`);let o=await i.json();if(!o||typeof o!=`object`||!(`ok`in o)||o.ok!==!0)throw Error(`unconfirmed`);let c=gD(o);r=!0,y.current&&(a(c),s(!1),p(c.codexMainAccountHardLock))}catch{y.current&&(l(!0),s(!0))}finally{n.clear()}r&&await E(),v.current=!1,y.current&&(h(!1),_(!1),r||T())},k=()=>{v.current||_(!1)},j=async()=>{v.current||(v.current=!0,b.current+=1,h(!0),await E(),v.current=!1,y.current&&h(!1))},M=i?.codexMainAccountHardLock,N=tu(i?.mainAccountHardLock.thresholds);return(0,Q.jsxs)(`section`,{ref:C,id:`codex-main-hard-lock-setting`,tabIndex:-1,className:`card card-row codex-main-hard-lock-setting`,"aria-labelledby":`${r}-title`,"aria-busy":m||!i&&!o||void 0,onBlurCapture:e=>{e.relatedTarget!==null&&!e.currentTarget.contains(e.relatedTarget)&&(w.current=!1)},children:[(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-copy`,children:[(0,Q.jsx)(`strong`,{id:`${r}-title`,children:n(`codexAuth.mainHardLockTitle`,N)}),(0,Q.jsx)(`div`,{id:`${r}-desc`,className:`card-sub`,children:n(`codexAuth.mainHardLockDesc`,N)})]}),(0,Q.jsx)(`button`,{ref:S,type:`button`,className:`toggle ${M===!0?`on`:``}`,disabled:m||M===void 0||o,"aria-pressed":M,"aria-label":n(`codexAuth.mainHardLockTitle`,N),"aria-describedby":`${r}-desc`,onClick:()=>{v.current||M===void 0||o||(w.current=!0,M?D(!1):_(!0))},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-feedback`,children:[i?.mainAccountHardLock.externalUsage&&(0,Q.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Q.jsx)(`p`,{role:`status`,children:n(`codexAuth.mainExternalUsageWarning`)})}),(c||o)&&(0,Q.jsxs)(`p`,{role:`alert`,children:[n(c?`codexAuth.mainHardLockSaveFailed`:`codexAuth.mainHardLockLoadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:m,onClick:()=>{T()},children:n(`common.retry`)})]}),f!==null&&!u&&(0,Q.jsx)(`p`,{role:`status`,children:n(f?`codexAuth.mainHardLockEnabled`:`codexAuth.mainHardLockDisabled`,N)}),u&&(0,Q.jsxs)(`p`,{role:`status`,children:[n(`codexAuth.mainHardLockRefreshFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:m,onClick:()=>{j()},children:n(`common.retry`)})]})]}),g&&(0,Q.jsx)(_D,{pending:m,thresholds:N,onCancel:k,onConfirm:()=>{D(!0)}})]})}function bD({apiBase:e}){let t=O(),[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(!1),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(0),h=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++m.current,n=A(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(p.current||t!==m.current)return;if(typeof o.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);f.current=o.codexAccountPickerEnabled,r(o.codexAccountPickerEnabled),a(!0),l(!1)}catch{!p.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=sa(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,Z.useCallback)(async()=>{if(p.current||!i)return;let n=f.current,o=!n;f.current=o,r(o),p.current=!0,s(!0),d(null),m.current+=1;try{let n=await hn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexAccountPickerEnabled:o})}))??{};if(n.ok!==!0||typeof n.codexAccountPickerEnabled!=`boolean`)throw Error(`unconfirmed`);f.current=n.codexAccountPickerEnabled,r(n.codexAccountPickerEnabled),a(!0),l(!1),d(n.catalogRefreshPending===!0?{tone:`warn`,message:t(`codexAuth.catalogRefreshPending`)}:{tone:`ok`,message:t(`codexAuth.accountPickerUpdated`)})}catch{f.current=n,r(n),d({tone:`err`,message:t(`codexAuth.accountPickerUpdateFailed`)})}finally{p.current=!1,s(!1)}},[e,i,t]),_=c&&!i;return(0,Q.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":o||!i&&!_||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.accountPickerTitle`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:_?`status`:void 0,children:t(_?`codexAuth.accountPickerLoadFailed`:i?n?`codexAuth.accountPickerOnDesc`:`codexAuth.accountPickerOffDesc`:`common.loading`)}),i&&n&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.accountPickerCompatibility`)}),i&&c&&(0,Q.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:t(`codexAuth.accountPickerRefreshFailed`)})]}),(0,Q.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},disabled:o,children:t(`common.retry`)}),i&&(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:o,"aria-pressed":n,"aria-label":t(`codexAuth.accountPickerTitle`),title:t(`codexAuth.accountPickerTitle`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Q.jsx)(`div`,{className:`codex-account-picker-feedback is-${u.tone}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function xD(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 SD({state:e,busy:t,onEnable:n}){let r=O();return e===null?null:(0,Q.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===`pool`?(0,Q.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,Q.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===`pool`&&(0,Q.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,Q.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>qt(`providers`),children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,Q.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,Q.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,Q.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>qt(`providers`),children:r(`codexAuth.openProviders`)})]})]})}function CD(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 wD({apiBase:e}){return(0,Q.jsx)(TD,{apiBase:e},e)}function TD({apiBase:e}){let t=O(),n=au(e),{load:r}=n,i=(0,Z.useRef)(!1);(0,Z.useLayoutEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,Z.useCallback)(()=>i.current?r(!1):Promise.resolve(!1),[r]),o=`ocx.codex-auth.config.v1:${e}`,s=La(o),[c,l]=(0,Z.useState)(()=>s?.bannerState??null),[u,d]=(0,Z.useState)(()=>s?.accountModeState??null),f=(0,Z.useRef)(null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(``),_=(0,Z.useCallback)(async()=>{let t=A(15e3);try{let n=await fetch(`${e}/api/config`,{signal:t.signal});if(!n.ok)throw Error(String(n.status));let r=await n.json(),i=Rp(CD(r));if(i===`absent`||i===`disabled`||i===`invalid`){l(i);let e=i===`disabled`?`disabled`:`absent`;d(e),Va(o,{bannerState:i,accountModeState:e});return}let a=xD(r);l(a),d(a),Va(o,{bannerState:a,accountModeState:a})}catch{}finally{t.clear()}},[e,o]);(0,Z.useEffect)(()=>{f.current!==e&&(f.current=e,Promise.resolve().then(()=>{_()}));let t=sa(()=>{_()},3e4);return()=>{t()}},[e,_]);let v=async()=>{m(!0),g(``);try{if(c!==`absent`&&c!==`disabled`)return;await Gp(e,c),await _()}catch(e){e instanceof Wp?g(t(e.i18nKey)):g(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{m(!1)}};return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(Bd,{apiBase:e,controller:n,hasMainHardLockSetting:!0,accountModeState:u,banner:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(SD,{state:c,busy:p,onEnable:()=>{v()}}),h&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:h})]}),advancedExtras:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(bD,{apiBase:e}),(0,Q.jsx)(mD,{apiBase:e}),(0,Q.jsx)(hD,{apiBase:e}),(0,Q.jsx)(vD,{apiBase:e,onSaved:a})]})})})}var ED={"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`},DD={"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`},OD={"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`},kD={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 AD({descriptor:e,toggle:t,bytes:n,transitionOnly:r=!1,busy:i,writesRefused:a,onToggle:o,onReset:s,onSelectBase:c,baseSelection:l,onOpen:u}){let d=O(),f=ED[e.id],p=f?d(f):e.id,m=OD[e.id],h=t?.defaultedUserValue??e.default??!0,g=l?.kind==="default";return(0,Q.jsxs)(`li`,{className:`codex-set-prompt__row`,"data-layer-id":e.id,"data-layer-class":e.class,children:[(0,Q.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:e.order===null?`·`:e.order+1}),(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>u(e.id),children:p}),e.key&&(0,Q.jsx)(`code`,{className:`codex-set-prompt__key`,children:e.key}),n!==null&&n>0&&(0,Q.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:d(`codexSet.dialog.sourceBytes`,{bytes:n}),children:n>=1024?Math.round(n/1024)+` KB`:n+` B`}),e.class===`base`&&c?(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${g?`on`:``}`,"aria-checked":g,"aria-label":p,disabled:i||a||l?.kind===`external`,onClick:()=>{c(!g)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}):e.class===`config-toggle`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${h?`on`:``}`,"aria-checked":h,"aria-label":p,disabled:i||a,onClick:()=>{o(e.id,!h)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),t!==void 0&&t.userFileValue!==null&&s&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:i||a,onClick:()=>{s(e.id)},children:d(`codexSet.row.resetDefault`,{value:String(t.default)})})]}):e.class===`feature-gated`?(0,Q.jsxs)(`span`,{className:`codex-set-prompt__note`,children:[d(`codexSet.row.featureGated`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>qt(`integrations/codex`),children:d(`codexSet.row.openFeatures`)})]}):(0,Q.jsx)(`span`,{className:`codex-set-prompt__note codex-set-prompt__note--locked`,children:d(r?`codexSet.row.onChange`:m||`codexSet.row.alwaysOn`)})]})}function jD({descriptor:e,toggle:t,text:n,probe:r,busy:i,onToggle:a,onReset:o,onClose:s,onRemeasure:c}){let l=O(),u=(0,Z.useRef)(null),d=`codex-set-layer-dialog-`+e.id;(0,Z.useEffect)(()=>{let e=u.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),s()},[s]),p=kD[e.class],m=ED[e.id],h=DD[e.id],g=OD[e.id];return(0,Q.jsxs)(`dialog`,{ref:u,className:`modal-overlay`,"aria-labelledby":d,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":l(`common.close`),tabIndex:-1,onClick:s}),(0,Q.jsxs)(`div`,{className:`modal-card codex-set-layer-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:d,children:m?l(m):e.id}),e.class===`config-toggle`&&t&&(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${t.defaultedUserValue?`on`:``}`,"aria-checked":t.defaultedUserValue,"aria-label":m?l(m):e.id,disabled:i,onClick:()=>{a(e.id,!t.defaultedUserValue)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:s,children:l(`common.close`)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:l(h||`codexSet.dialog.unknownLayer`)}),(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.class`)}),(0,Q.jsx)(`span`,{children:l(p)})]}),e.key&&(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.key`)}),(0,Q.jsx)(`code`,{className:`api-code`,children:e.key}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{navigator.clipboard?.writeText(e.key??``)},children:l(`codexSet.dialog.copyKey`)})]}),e.class===`config-toggle`&&t&&(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.fileValue`)}),(0,Q.jsx)(`span`,{children:t.userFileValue===null?l(`codexSet.dialog.absentDefault`,{value:String(t.default)}):l(`codexSet.dialog.setValue`,{value:String(t.userFileValue),fallback:String(t.default)})}),t.userFileValue!==null&&o&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:i,onClick:()=>{o(e.id)},children:l(`codexSet.row.resetDefault`,{value:String(t.default)})})]}),e.class===`runtime-conditional`&&g&&(0,Q.jsx)(`p`,{className:`muted small`,children:l(g)}),e.class===`feature-gated`&&(0,Q.jsx)(`div`,{className:`codex-set-layer-dialog__line`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>qt(`integrations/codex`),children:l(`codexSet.row.openFeatures`)})}),n?.reason===`ok`&&n.text?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:l(`codexSet.dialog.sourceText`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:l(`codexSet.dialog.sourceBytes`,{bytes:n.bytes})})]}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-layer-dialog__text`,children:n.text})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted small codex-set-layer-dialog__no-text`,children:n?.reason===`empty-source`?l(`codexSet.dialog.emptySource`,{path:n.sourcePath??``}):n?.reason===`not-rendered`?l(`codexSet.dialog.notRendered`):n?.reason===`unmapped`?l(`codexSet.dialog.unmapped`):n?.reason===`not-exposed`?l(`codexSet.dialog.notExposed`):r&&r.ok===!1?r.failure?.kind===`program-not-found`?l(`codexSet.dialog.probeNotFound`):r.failure?.kind===`command-unsupported`?l(`codexSet.dialog.probeUnsupported`):r.failure?.kind===`output-invalid`?l(`codexSet.dialog.probeInvalid`):r.failure?.kind===`execution-failed`||r.failure?.kind===`request-failed`?l(`codexSet.dialog.probeFailed`):l(`codexSet.dialog.probeBusy`):l(`codexSet.dialog.textUnavailable`)}),r&&r.ok===!1&&r.failure===void 0&&c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:l(`common.retry`)})]})]})]})}var MD=65536;function ND(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 PD(e){return e.replace(/\r\n/g,`
|
|
9
|
+
`).replace(/\r/g,`
|
|
10
|
+
`).replace(/\t/g,` `)}function FD(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(n!==`
|
|
11
|
+
`&&(e<32||e===127)||e>=55296&&e<=57343)return{position:t};t+=1}return null}function ID(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=PD(e.body),i=ND(r);if(i>65536)return{kind:`body-too-large`,bytes:i};let a=FD(r);if(a)return{kind:`invalid-character`,position:a.position};let o=ND([...t.filter(t=>t.enabled&&t.id!==e.id).map(e=>e.body),...e.enabled?[r]:[]].join(`
|
|
12
|
+
|
|
13
|
+
`));return o>131072?{kind:`composed-too-large`,bytes:o}:null}function LD(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 RD(e){return e.filter(e=>e.enabled).map(e=>e.body).join(`
|
|
14
|
+
|
|
15
|
+
`)}var zD=null;function BD(){return zD??1e4}function VD(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 HD({layer:e,index:t,total:n,busy:r,onToggle:i,onEdit:a,onDelete:o,onMove:s}){let c=O();return(0,Q.jsxs)(`li`,{className:`codex-set-prompt__row codex-set-custom__row`,"data-custom-id":e.id,onKeyDown:i=>{!i.altKey||r||(i.key===`ArrowUp`&&t>0?(i.preventDefault(),s(e.id,-1)):i.key===`ArrowDown`&&t<n-1&&(i.preventDefault(),s(e.id,1)))},children:[(0,Q.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:t+1}),(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>a(e.id),children:e.title}),(0,Q.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:c(`codexSet.dialog.sourceBytes`,{bytes:ND(e.body)}),children:ND(e.body)>=1024?Math.round(ND(e.body)/1024)+` KB`:ND(e.body)+` B`}),(0,Q.jsxs)(`span`,{className:`codex-set-custom__reorder`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveUp`,{title:e.title}),disabled:t===0||r,onClick:()=>s(e.id,-1),children:`↑`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveDown`,{title:e.title}),disabled:t===n-1||r,onClick:()=>s(e.id,1),children:`↓`})]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${e.enabled?`on`:``}`,"aria-checked":e.enabled,"aria-label":e.title,disabled:r,onClick:()=>i(e.id,!e.enabled),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-set-custom__delete`,"aria-label":c(`codexSet.custom.delete`,{title:e.title}),disabled:r,onClick:()=>o(e.id),children:`×`})]})}var UD=8192,WD=[{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 GD(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 KD(e){let t=[],n=[];for(let r of WD){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 GD(e)>UD&&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 qD({layer:e,seed:t,others:n,busy:r,navigation:i,onSave:a,onClose:o}){let s=O(),c=(0,Z.useRef)(null),[l,u]=(0,Z.useState)(e?.title??t?.title??``),[d,f]=(0,Z.useState)(e?.body??t?.body??``),p=(0,Z.useRef)(new Map),[m,h]=(0,Z.useState)(!1),g=e?.id??null,_=(0,Z.useRef)(g),v=(0,Z.useRef)({title:l,body:d});(0,Z.useEffect)(()=>{v.current={title:l,body:d}},[l,d]),(0,Z.useEffect)(()=>{if(_.current===g)return;_.current!==null&&p.current.set(_.current,v.current),_.current=g;let t=g===null?void 0:p.current.get(g);u(t?.title??e?.title??``),f(t?.body??e?.body??``)},[g,e]),(0,Z.useEffect)(()=>{h([...p.current].some(([e,t])=>{if(e===g)return!1;let r=n.find(t=>t.id===e);return r===void 0||t.title!==r.title||t.body!==r.body}))},[g,n]);let[y,b]=(0,Z.useState)(null),x=`codex-set-custom-dialog`,S=e?.title??t?.title??``,C=e?.body??t?.body??``,w=l!==S||d!==C;(0,Z.useEffect)(()=>{let e=c.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let T=(0,Z.useCallback)(()=>{if(w||m){b({kind:`close`});return}o()},[w,m,o]),E=(0,Z.useCallback)(e=>{e.preventDefault(),T()},[T]),D={id:e?.id??null,title:l,body:d,enabled:e?.enabled??!0},k=ID(D,n),A=PD(d),j=A!==d,M=(0,Z.useMemo)(()=>KD(A),[A]),N=ND(A),P=e=>{r||k!==null||e!==g||a({...D,body:A})},F=()=>{if(!(r||k!==null)){if(m){b({kind:`save`,targetId:g});return}P(g)}},I=k?k.kind===`title-empty`?s(`codexSet.custom.titleRequired`):k.kind===`title-too-long`?s(`codexSet.custom.titleTooLong`,{count:k.length,max:80}):k.kind===`title-multiline`?s(`codexSet.custom.titleMultiline`):k.kind===`body-too-large`?s(`codexSet.custom.bodyTooLarge`,{bytes:k.bytes,max:MD}):k.kind===`composed-too-large`?s(`codexSet.custom.composedTooLarge`,{bytes:k.bytes}):s(`codexSet.custom.invalidCharacter`,{position:k.position}):null;return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":x,onCancel:E,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:T}),(0,Q.jsxs)(`div`,{className:`modal-card codex-set-custom-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:x,children:s(e?`codexSet.custom.editTitle`:`codexSet.custom.newTitle`)}),i&&(0,Q.jsxs)(`span`,{className:`codex-set-custom-dialog__nav`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":s(`codexSet.custom.prevLayer`),disabled:i.position<=1||r||y!==null,onClick:i.onPrev,children:`←`}),(0,Q.jsx)(`span`,{className:`codex-set-custom-dialog__nav-pos`,children:s(`codexSet.custom.navPosition`,{position:i.position,total:i.total})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":s(`codexSet.custom.nextLayer`),disabled:i.position>=i.total||r||y!==null,onClick:i.onNext,children:`→`})]})]}),(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`codexSet.custom.titleLabel`)}),(0,Q.jsx)(`input`,{type:`text`,value:l,maxLength:100,onChange:e=>u(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`codexSet.custom.bodyLabel`)}),(0,Q.jsx)(`textarea`,{rows:10,value:d,onChange:e=>f(e.target.value)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:s(`codexSet.custom.bodySize`,{bytes:N,max:MD})}),j&&(0,Q.jsx)(`p`,{className:`muted small codex-set-custom-dialog__normalized`,children:s(`codexSet.custom.normalized`)}),I&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:I}),M.length>0&&(0,Q.jsx)(`ul`,{className:`codex-set-custom-dialog__lint`,children:M.map((e,t)=>(0,Q.jsxs)(`li`,{"data-lint-rule":e.rule,"data-lint-level":e.level,children:[s(e.messageKey),e.span&&(0,Q.jsx)(`code`,{className:`codex-set-custom-dialog__span`,children:A.slice(e.span[0],e.span[1])})]},e.rule+`:`+t))}),y?(0,Q.jsxs)(`div`,{className:`modal-actions codex-set-custom-dialog__discard`,role:`alertdialog`,"aria-labelledby":`codex-set-custom-dialog-discard`,children:[(0,Q.jsx)(`span`,{id:`codex-set-custom-dialog-discard`,className:`muted small`,children:s(y.kind===`save`?`codexSet.custom.discardOthersAndSave`:`codexSet.custom.discardPrompt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>b(null),children:s(`codexSet.custom.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:y.kind===`save`&&(k!==null||r||y.targetId!==g),onClick:()=>y.kind===`save`?P(y.targetId):o(),children:s(y.kind===`save`?`common.save`:`common.discard`)})]}):(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k!==null||r,onClick:F,children:s(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:T,children:s(`common.cancel`)})]})]})]})}var JD=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(`
|
|
16
|
+
`)},{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(`
|
|
17
|
+
`)},{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(`
|
|
18
|
+
`)},{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(`
|
|
19
|
+
`)},{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(`
|
|
20
|
+
`)}]);function YD({onBlank:e,onPreset:t,disabled:n,presets:r=JD}){let i=O(),[a,o]=(0,Z.useState)(!1),s=(0,Z.useRef)(null),c=a&&!n;(0,Z.useEffect)(()=>{if(!c)return;let e=e=>{s.current?.contains(e.target)||o(!1)},t=e=>{e.key===`Escape`&&o(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let l=e=>{o(!1),e()};return r.length===0?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm codex-set-custom__add`,disabled:n,onClick:e,children:i(`codexSet.custom.add`)}):(0,Q.jsxs)(`div`,{className:`codex-set-preset`,ref:s,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm codex-set-custom__add`,"aria-expanded":c,disabled:n,onClick:()=>o(e=>!e),children:i(`codexSet.custom.add`)}),c&&(0,Q.jsxs)(`div`,{className:`codex-set-preset__menu`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`codex-set-preset__item`,onClick:()=>l(e),children:(0,Q.jsx)(`span`,{className:`codex-set-preset__name`,children:i(`codexSet.preset.blank`)})}),r.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`codex-set-preset__item`,"data-preset-id":e.id,onClick:()=>l(()=>t(e.body,i(e.nameKey))),children:[(0,Q.jsx)(`span`,{className:`codex-set-preset__name`,children:i(e.nameKey)}),(0,Q.jsx)(`span`,{className:`codex-set-preset__desc`,children:i(e.descriptionKey)}),(0,Q.jsx)(`span`,{className:`codex-set-preset__provenance`,children:i(e.provenanceKey)}),(0,Q.jsx)(`span`,{className:`codex-set-preset__preview`,children:e.body})]},e.id))]})]})}var XD=48,ZD=`new`;function QD({variants:e,selection:t,maxVariants:n,busy:r,importPreview:i,importRefusal:a,onSelect:o,onSave:s,onDelete:c,onImport:l,onImportTitle:u,onClose:d}){let f=O(),p=(0,Z.useRef)(null),m=[{kind:`default`},...e.map(e=>({kind:`variant`,variant:e})),...e.length<n?[{kind:`new`}]:[]],h=t.kind===`variant`?Math.max(0,m.findIndex(e=>e.variant?.id===t.id)):0,[g,_]=(0,Z.useState)(h),v=m[Math.min(g,m.length-1)],[y,b]=(0,Z.useState)(v.variant?.title??``),[x,S]=(0,Z.useState)(v.variant?.body??``),C=v.kind==="default"?null:v.variant?.id??ZD,w=(0,Z.useRef)(new Map),T=(0,Z.useRef)(C),E=(0,Z.useRef)(v),D=(0,Z.useRef)(null),k=(0,Z.useRef)(new Set),A=(0,Z.useRef)({title:y,body:x});(0,Z.useEffect)(()=>{A.current={title:y,body:x}},[y,x]),(0,Z.useEffect)(()=>{let t=k.current,n=new Set(e.map(e=>e.id)),r=D.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(T.current!==C&&T.current!==null){let t=A.current,a=e.find(e=>e.id===T.current)??E.current.variant,o=a===void 0?t.title===``&&t.body===``:t.title===a.title&&t.body===a.body,s=T.current!==ZD&&!n.has(T.current),c=i&&r!==null&&T.current===(r.id??ZD)&&t.title===r.title&&t.body===r.body;o||s||c?w.current.delete(T.current):w.current.set(T.current,t)}for(let e of[...w.current.keys()])e!==ZD&&!n.has(e)&&w.current.delete(e);if(r&&i&&w.current.delete(r.id??ZD),r&&(i||r.id!==null&&!n.has(r.id))&&(D.current=null),k.current=n,T.current!==C){let e=C===null?void 0:w.current.get(C);b(e?.title??v.variant?.title??``),S(e?.body??v.variant?.body??``)}T.current=C,E.current=v},[C,v,e]);let[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{P([...w.current].some(([t,n])=>{if(t===C)return!1;if(t===ZD)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}))},[C,e,y,x]);let F=N||C!==null&&(y!==(v.variant?.title??``)||x!==(v.variant?.body??``)),[I,L]=(0,Z.useState)(i?.effectiveTitle??``),R=i?.effectiveTitle??null,[z,B]=(0,Z.useState)(R);R!==z&&(B(R),L(R??``));let V=(0,Z.useCallback)(e=>{_(t=>{let n=t+e;return n<0?m.length-1:n>=m.length?0:n})},[m.length]);(0,Z.useEffect)(()=>{let e=p.current;e&&!e.open&&e.showModal()},[]);let H=(0,Z.useRef)(null),U=e=>{H.current={x:e.clientX,y:e.clientY}},W=e=>{let t=H.current;if(H.current=null,!t||r||j!==null)return;let n=e.clientX-t.x,i=e.clientY-t.y;Math.abs(n)<XD||Math.abs(n)<=Math.abs(i)||V(n<0?1:-1)},G=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)))},ee=(0,Z.useCallback)(()=>{if(F){M({kind:`close`});return}d()},[F,d]),K=(0,Z.useCallback)(e=>{e.preventDefault(),ee()},[ee]),q=v.kind==="default"?t.kind==="default":v.kind===`variant`&&t.kind===`variant`&&t.id===v.variant.id,te=t.kind===`external`,ne=PD(x),J=ND(ne),Y=FD(ne),re=J>65536?{kind:`body-too-large`,bytes:J}:Y===null?null:{kind:`invalid-character`,position:Y.position},ie=ne!==x,X=KD(ne),ae=re?re.kind===`body-too-large`?f(`codexSet.custom.bodyTooLarge`,{bytes:re.bytes,max:MD}):f(`codexSet.custom.invalidCharacter`,{position:re.position}):null,oe=async e=>{if(r||re!==null||x.trim().length===0||e!==C)return;let t={title:y,body:x},n=y.replace(/[\r\n]+/g,` `).trim()||v.variant?.id||``;if(D.current={id:v.variant?.id??null,title:n,body:ne},!await s({id:v.variant?.id??null,title:y,body:ne})){D.current=null;return}let i=e??ZD;if(w.current.delete(i),i!==ZD&&T.current===e&&A.current.title===t.title&&A.current.body===t.body&&(A.current={title:n,body:ne},b(n),S(ne)),j?.kind===`save`){for(let e of[...w.current.keys()])e!==i&&w.current.delete(e);M(null)}};return(0,Q.jsx)(`dialog`,{ref:p,className:`modal-overlay codex-set-base-dialog`,"aria-label":f(`codexSet.base.title`),onCancel:K,onClose:d,onKeyDown:G,onPointerDown:U,onPointerUp:W,children:(0,Q.jsxs)(`div`,{className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:f(`codexSet.base.title`)}),(0,Q.jsxs)(`span`,{className:`codex-set-base-dialog__nav`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":f(`codexSet.base.prev`),disabled:r||m.length<2||j!==null,onClick:()=>V(-1),children:`←`}),(0,Q.jsx)(`span`,{className:`codex-set-base-dialog__pos`,"data-slot-kind":v.kind,children:f(`codexSet.base.position`,{position:g+1,total:m.length})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":f(`codexSet.base.next`),disabled:r||m.length<2||j!==null,onClick:()=>V(1),children:`→`})]})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:f(`codexSet.base.swipeHint`)}),m.length>1&&(0,Q.jsx)(`div`,{className:`codex-set-base-dialog__dots`,"aria-hidden":`true`,children:m.map((e,t)=>(0,Q.jsx)(`span`,{className:`codex-set-base-dialog__dot${t===g?` active`:``}`},t))}),te&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:f(`codexSet.base.externalBlocked`,{path:t.path})}),te&&(i?(0,Q.jsxs)(Q.Fragment,{children:[a!==null&&(0,Q.jsx)(`p`,{className:`muted small`,children:a}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.importPreview`,{path:i.resolvedPath??i.rawPath??``})}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-custom__adopt-preview`,children:i.serialized}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.importFormat`,{bodyBytes:i.bodyBytes,serializedBytes:i.serializedBytes})}),(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{children:f(`codexSet.base.importTitle`)}),(0,Q.jsx)(`input`,{type:`text`,value:I,disabled:r,maxLength:80,onChange:e=>{L(e.target.value),u(e.target.value)}})]}),I.trim()!==i.effectiveTitle&&(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.importTitlePending`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:r||I.trim()!==i.effectiveTitle,onClick:()=>l(!0,I.trim()||void 0),children:f(`codexSet.base.importConfirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:ee,children:f(`common.cancel`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[a!==null&&(0,Q.jsx)(`p`,{className:`muted small`,children:a}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:r,onClick:()=>l(!1),children:f(`codexSet.base.import`)})]})),v.kind==="default"?(0,Q.jsxs)(`div`,{className:`codex-set-base-dialog__default`,children:[(0,Q.jsx)(`strong`,{children:f(`codexSet.base.defaultTitle`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.defaultBody`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{children:f(`codexSet.base.variantTitle`)}),(0,Q.jsx)(`input`,{type:`text`,value:y,disabled:r||te,onChange:e=>b(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`field`,children:[(0,Q.jsx)(`span`,{children:f(`codexSet.base.variantBody`)}),(0,Q.jsx)(`textarea`,{rows:12,value:x,disabled:r||te,onChange:e=>S(e.target.value)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.custom.bodySize`,{bytes:J,max:MD})}),ie&&(0,Q.jsx)(`p`,{className:`muted small codex-set-custom-dialog__normalized`,children:f(`codexSet.custom.normalized`)}),ae&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:ae}),X.length>0&&(0,Q.jsx)(`ul`,{className:`codex-set-custom-dialog__lint`,children:X.map((e,t)=>(0,Q.jsxs)(`li`,{"data-lint-rule":e.rule,"data-lint-level":e.level,children:[f(e.messageKey),e.span&&(0,Q.jsx)(`code`,{className:`codex-set-custom-dialog__span`,children:ne.slice(e.span[0],e.span[1])})]},e.rule+`:`+t))}),(0,Q.jsx)(`p`,{className:`muted small`,children:f(`codexSet.base.replacesWarning`)})]}),j?(0,Q.jsxs)(`div`,{className:`modal-actions codex-set-custom-dialog__discard`,role:`alertdialog`,"aria-labelledby":`codex-set-base-dialog-discard`,children:[(0,Q.jsx)(`span`,{id:`codex-set-base-dialog-discard`,className:`muted small`,children:f(j.kind===`save`?`codexSet.custom.discardOthersAndSave`:`codexSet.custom.discardPrompt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>M(null),children:f(`codexSet.custom.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:j.kind===`save`&&(re!==null||r||x.trim().length===0||j.targetKey!==C),onClick:()=>j.kind===`save`?void oe(j.targetKey):d(),children:f(j.kind===`save`?`common.save`:`common.discard`)})]}):(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[v.kind!=="default"&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:r||te||re!==null||x.trim().length===0,onClick:()=>{if(!(r||re!==null)){if(N){M({kind:`save`,targetKey:C});return}oe(C)}},children:f(`common.save`)}),!q&&v.kind!==`new`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:r||te,onClick:()=>o(v.kind==="default"?{kind:`default`}:{kind:`variant`,id:v.variant.id}),children:f(`codexSet.base.use`)}),q&&(0,Q.jsx)(`span`,{className:`pill`,children:f(`codexSet.base.inUse`)}),v.kind===`variant`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,disabled:r||te,onClick:()=>c(v.variant.id),children:f(`common.delete`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:ee,children:f(`common.close`)})]})]})})}function $D(e){return`codex-prompt:`+e}var eO={"journal-present":`codexSet.drift.journalPresent`,"projection-stale":`codexSet.drift.projectionStale`,"store-missing":`codexSet.drift.storeMissing`,"owned-malformed":`codexSet.drift.ownedMalformed`};function tO({apiBase:e}){let t=O(),n=$D(e),[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),T=(0,Z.useRef)(0),E=(0,Z.useRef)(!1),D=(0,Z.useRef)(null),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let P=(0,Z.useCallback)(()=>{A(null)},[]),F=(0,Z.useCallback)(async t=>{let n=await fetch(e+`/api/codex-prompt`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},[e]),I=Ua(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}Ut(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):(Ut(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||E.current)return;r&&(E.current=!0,D.current&&=(clearTimeout(D.current),null));let s=++T.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:x?.previewSha256}:{confirm:!1,...a===void 0?{}:{title:a}})}),c=await o.json();if(!(r||s===T.current))return;if(!o.ok||!c.ok){if(I.refresh(),c.code===`stale_revision`){i(t(`codexSet.prompt.staleRevision`));return}w(c.code===`import_body_changed`?t(`codexSet.base.importChanged`):c.message??t(`codexSet.base.importFailed`)),r&&S(null);return}if(c.snapshot){Ut(n,c.snapshot),P(),S(null),w(null);return}w(null),S(c.preview??null)}catch{if(!(r||s===T.current))return;i(t(`codexSet.prompt.writeFailed`)),I.refresh()}finally{r&&(E.current=!1),(r||s===T.current)&&o(e=>e===`base-import`?null:e)}},H=e=>{E.current||(T.current+=1,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,V(!1,e)},350))},U=()=>{T.current+=1,D.current&&=(clearTimeout(D.current),null),c(null),S(null),w(null),E.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`)),Ut(n,{...L,custom:c}),I.refresh(),!1):(Ut(n,o.snapshot),P(),!0)}catch{return i(t(`codexSet.prompt.writeFailed`)),I.refresh(),!1}finally{o(null)}},G=async e=>{if(!L)return;let t=L.custom,n=e.id===null?[...t,{id:LD(t),title:e.title,body:e.body,enabled:!0}]:t.map(t=>t.id===e.id?{...t,title:e.title,body:e.body}:t);await W(n,e.id??`new`)&&u(null)},ee=async r=>{if(L){o(`adopt`),i(``);try{let a=await fetch(e+`/api/codex-prompt/adopt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r?{confirm:!0,revision:L.revision}:{confirm:!1})}),o=await a.json();if(!a.ok||!o.ok){i(o.message??t(`codexSet.custom.adoptRefused`)),m(null),g(o.code===`adopt_unsupported_form`?{path:o.path,line:o.line,rawLine:o.rawLine}:null);return}if(o.snapshot){Ut(n,o.snapshot),P(),m(null);return}m(o.preview??null)}catch{i(t(`codexSet.prompt.writeFailed`))}finally{o(null)}}},K=async r=>{if(!(!L||L.drift===null)){v(!0),i(``);try{let a=await fetch(e+`/api/codex-prompt/repair`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r?{confirm:!0,revision:L.revision}:{confirm:!1})}),o=await a.json();if(!a.ok||!o.ok){if(o.code===`stale_revision`){I.refresh(),P(),i(t(`codexSet.prompt.staleRevision`));return}i(o.message??t(`codexSet.prompt.repairFailed`));return}o.snapshot?Ut(n,o.snapshot):I.refresh(),P()}catch{i(t(`codexSet.prompt.repairFailed`))}finally{v(!1)}}},q=[...L?.inventory??[]].filter(e=>e.class!==`extension-unknown`).sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),te=new Set([`realtime`,`model-switch`]),ne=q.filter(e=>!te.has(e.id)),J=q.filter(e=>te.has(e.id)),Y=q.find(e=>e.id===s)??null,re=l===null||l===`new`?-1:L?.custom.findIndex(e=>e.id===l)??-1,ie=re>=0?L.custom[re]:null,X=l!==null&&l!==`new`&&L!==void 0&&re<0;return(0,Z.useEffect)(()=>{if(k!==null)return;let t=new AbortController,n=!1;return(async()=>{try{let r=await fetch(e+`/api/codex-prompt/text`,{signal:t.signal});if(!r.ok){n||A({ok:!1,failure:{kind:`request-failed`}});return}let i=await r.json();n||A(i)}catch{n||A({ok:!1,failure:{kind:`request-failed`}})}})(),()=>{n=!0,t.abort()}},[k,e]),(0,Q.jsxs)(`div`,{className:`panel codex-set-prompt`,children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:t(`codexSet.prompt.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k===null||a!==null,onClick:P,children:t(`codexSet.prompt.remeasure`)})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:t(`codexSet.prompt.timing`)}),R.refreshing&&(0,Q.jsx)(hy,{live:!R.showError,children:t(`common.loading`)}),R.showSkeleton&&(0,Q.jsx)(my,{label:t(`common.loading`),rows:5}),L&&!L.readable&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`codexSet.prompt.unreadable`)}),R.showError&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`codexSet.prompt.loadFailed`)}),(r||X)&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:X?t(`codexSet.custom.layerGone`):r}),L?.drift&&(0,Q.jsxs)(`div`,{className:`notice codex-set-prompt__drift`,role:`alert`,"data-drift":L.drift,children:[(0,Q.jsx)(`span`,{children:t(eO[L.drift])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:_,onClick:()=>{K(!0)},children:t(`codexSet.prompt.repair`)})]}),(0,Q.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:ne.map(e=>(0,Q.jsx)(AD,{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];if(!n){c(e.id);return}B(`/api/codex-prompt/base/select`,{kind:`variant`,id:n.id})}):void 0,baseSelection:L?.baseSelection,onOpen:c},e.id))}),J.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`row codex-set-prompt__group`,children:(0,Q.jsx)(`strong`,{children:t(`codexSet.group.transition`)})}),(0,Q.jsx)(`p`,{className:`muted small`,children:t(`codexSet.group.transitionDesc`)}),(0,Q.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:J.map(e=>(0,Q.jsx)(AD,{descriptor:e,toggle:L?.toggles.find(t=>t.id===e.id),bytes:k?.layers?.[e.id]?.bytes??null,transitionOnly:!0,busy:a===e.id,writesRefused:L?.readable===!1,onToggle:(e,t)=>{z(e,t)},onReset:e=>{z(e,null)},onOpen:c},e.id))})]}),L&&!L.extensionLayersEnumerable&&(0,Q.jsx)(`p`,{className:`muted small codex-set-prompt__extensions`,children:t(`codexSet.prompt.extensionsUnknown`)}),Y&&(Y.class===`base`&&L?(0,Q.jsx)(QD,{variants:L.baseVariants,selection:L.baseSelection,maxVariants:L.maxBaseVariants,busy:a!==null||!L.readable,importPreview:x,importRefusal:C,onSelect:e=>{B(`/api/codex-prompt/base/select`,e)},onSave:e=>B(`/api/codex-prompt/base`,e),onDelete:e=>{B(`/api/codex-prompt/base`,{id:e,delete:!0})},onImport:(e,t)=>{V(e,t)},onImportTitle:H,onClose:U}):(0,Q.jsx)(jD,{descriptor:Y,toggle:L?.toggles.find(e=>e.id===Y.id),text:k?.layers?.[Y.id],probe:k,busy:a!==null,onToggle:(e,t)=>{z(e,t)},onReset:e=>{z(e,null)},onClose:()=>c(null),onRemeasure:P})),L&&(0,Q.jsxs)(`section`,{className:`codex-set-custom`,children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:t(`codexSet.custom.heading`)}),L.developerInstructionsState===`external`?null:(0,Q.jsx)(YD,{disabled:L.custom.length>=32||a!==null||!L.readable,onBlank:()=>{b(null),u(`new`)},onPreset:(e,t)=>{b({body:e,title:t}),u(`new`)}})]}),L.custom.length>=32&&(0,Q.jsx)(`p`,{className:`muted small`,children:t(`codexSet.custom.limitReached`,{max:32})}),L.developerInstructionsState===`external`&&L.modelInstructionsFile===null&&(0,Q.jsxs)(`div`,{className:`codex-set-custom__adopt`,children:[(0,Q.jsx)(`p`,{className:`muted small`,children:t(`codexSet.custom.notOwned`)}),h&&(0,Q.jsx)(`p`,{className:`muted small codex-set-custom__adopt-refusal`,children:t(`codexSet.custom.adoptUnsupported`,{path:h.path??``,line:h.line??0})}),p?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`pre`,{className:`api-code codex-set-custom__adopt-preview`,children:p.decodedBody}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:a!==null,onClick:()=>{ee(!0)},children:t(`codexSet.custom.adoptConfirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>m(null),children:t(`common.cancel`)})]})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:a!==null,onClick:()=>{ee(!1)},children:t(`codexSet.custom.adopt`)})]}),L.baseSelection.kind===`external`&&(0,Q.jsxs)(`p`,{className:`muted small codex-set-custom__replaced`,children:[t(`codexSet.custom.baseReplaced`,{path:L.baseSelection.path}),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>c(`base-instructions`),children:t(`codexSet.custom.baseReplacedOpen`)})]}),(0,Q.jsx)(`ul`,{className:`codex-set-prompt__rows`,children:L.custom.map((e,t)=>(0,Q.jsx)(HD,{layer:e,index:t,total:L.custom.length,busy:a!==null||!L.readable,onToggle:(e,t)=>{W(L.custom.map(n=>n.id===e?{...n,enabled:t}:n),e)},onEdit:u,onDelete:f,onMove:(e,t)=>{W(VD(L.custom,e,t),e)}},e.id))}),L.custom.length>0&&(()=>{let e=RD(L.custom),n=ND(e);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:n>131072?`notice notice-err`:`muted small`,children:t(`codexSet.custom.composedSize`,{bytes:n,max:131072})}),e.length>0&&(0,Q.jsxs)(`details`,{className:`codex-set-custom__preview`,children:[(0,Q.jsx)(`summary`,{className:`muted small`,children:t(`codexSet.custom.composedPreview`)}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-custom__preview-body`,children:e})]})]})})(),j&&(0,Q.jsxs)(`div`,{className:`notice codex-set-custom__deleted`,role:`status`,children:[(0,Q.jsx)(`span`,{children:t(`codexSet.custom.deletedNamed`,{title:j.layer.title})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:a!==null,onClick:()=>{let{layer:e,index:t}=j,n=[...L.custom];n.splice(Math.min(t,n.length),0,e),N.current&&clearTimeout(N.current),N.current=null,(async()=>{if(!await W(n,e.id)){N.current=setTimeout(()=>M(null),BD());return}M(null)})()},children:t(`common.undo`)})]}),d&&(0,Q.jsxs)(`div`,{className:`notice codex-set-custom__confirm`,role:`alertdialog`,"aria-labelledby":`codex-set-delete-confirm`,children:[(0,Q.jsx)(`span`,{id:`codex-set-delete-confirm`,children:t(`codexSet.custom.deleteConfirmNamed`,{title:L.custom.find(e=>e.id===d)?.title??``})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:()=>{let e=d,t=L.custom.findIndex(t=>t.id===e),n=t>=0?L.custom[t]:null;f(null),(async()=>{!await W(L.custom.filter(t=>t.id!==e),e)||!n||(N.current&&clearTimeout(N.current),M({layer:n,index:t}),N.current=setTimeout(()=>M(null),BD()))})()},children:t(`common.delete`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>f(null),children:t(`common.cancel`)})]})]}),l&&L&&!X&&(0,Q.jsx)(qD,{layer:l===`new`?null:ie,seed:l===`new`?y:null,others:L.custom,busy:a!==null,navigation:re>=0&&L.custom.length>1?{position:re+1,total:L.custom.length,onPrev:()=>{re>0&&u(L.custom[re-1].id)},onNext:()=>{re<L.custom.length-1&&u(L.custom[re+1].id)}}:void 0,onSave:G,onClose:()=>{u(null),b(null)}})]})}var nO=`/api/codex/desktop-compatibility/`,rO=e=>!!e&&typeof e==`object`&&!Array.isArray(e),iO=class extends Error{code;constructor(e){super(e),this.code=e}};async function aO(e){let t;try{t=await e.json()}catch{throw new iO(`invalid_response`)}if(!rO(t))throw new iO(`invalid_response`);if(!e.ok||t.ok!==!0){let e=t.error??(rO(t.activation)?t.activation.reason:void 0)??(rO(t.launch)?t.launch.reason:void 0);throw new iO(typeof e==`string`&&/^[a-z][a-z_-]{0,79}$/.test(e)?e:`operation_unconfirmed`)}return t}function oO(e){if(!rO(e)||typeof e.startOnProxyStart!=`boolean`||typeof e.revision!=`string`||!/^[a-f0-9]{64}$/.test(e.revision))throw new iO(`invalid_startup_settings`);return{startOnProxyStart:e.startOnProxyStart,revision:e.revision}}async function sO(e,t){return oO((await aO(await fetch(e+`/api/codex/desktop-compatibility/settings`,{signal:t}))).settings)}async function cO(e,t,n,r){return oO((await aO(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 lO(e){if(!rO(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 iO(`invalid_certificate_status`);return{supported:e.supported,state:e.state,busy:e.busy,...e.fingerprint===void 0?{}:{fingerprint:e.fingerprint},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},renewalDue:e.renewalDue===!0}}function uO(e){if(!rO(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 iO(`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 iO(`invalid_runtime_status`);t.contextFailure=e.contextFailure}if(e.usage!==void 0){if(!rO(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 iO(`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(!rO(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 iO(`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 dO(e,t){return uO((await aO(await fetch(e+`/api/codex/desktop-compatibility/runtime`,{signal:t}))).runtime)}async function fO(e,t){return lO((await aO(await fetch(e+`/api/codex/desktop-compatibility/certificate`,{signal:t}))).certificate)}async function pO(e,t){let[n,r]=await Promise.all([fO(e,t),dO(e,t)]);return{certificate:n,runtime:r}}async function mO(e,t,n){if(t.target===`certificate`&&t.action!==`prepare`&&(!t.fingerprint||!/^[A-F0-9]{64}$/.test(t.fingerprint)))throw new iO(`certificate_fingerprint_required`);await aO(await fetch(e+nO+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 hO({apiBase:e,active:t}){let n=O(),r=`desktop-compatibility-startup:${e}`,i=zt(r,t=>sO(e,t),{enabled:t,deadlineMs:15e3,staleAfterMs:0}),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),d=(0,Z.useRef)({alive:!0,pending:!1,operation:null});(0,Z.useEffect)(()=>{let e=d.current;return e.alive=!0,()=>{e.alive=!1,e.operation?.controller.abort(),e.operation?.clear()}},[]);async function f(t){let n=d.current;if(n.pending||t&&!i.data)return;n.pending=!0,o(!0),u(null);let a=A(15e3);n.operation=a;try{t&&await cO(e,i.data,!i.data.startOnProxyStart,a.signal);let o=await sO(e,a.signal);n.alive&&(Ut(r,o),c(!1))}catch(e){n.alive&&(c(!0),u(e instanceof iO?e.code:`connection_unconfirmed`))}finally{a.clear(),n.operation=null,n.pending=!1,n.alive&&o(!1)}}let p=i.error instanceof iO?i.error.code:i.error?`connection_unconfirmed`:null;return(0,Q.jsxs)(`div`,{className:`panel`,children:[(0,Q.jsx)(on,{on:i.data?.startOnProxyStart===!0,label:n(`desktopCompat.autoStart`),showLabel:!0,disabled:a||s||!i.lastAttemptOk||i.refreshing,onClick:()=>void f(!0)}),(0,Q.jsx)(`p`,{className:`muted text-control`,children:n(`desktopCompat.autoStartHint`)}),(l||p)&&(0,Q.jsxs)(`p`,{className:`notice-err`,role:`alert`,children:[n(`desktopCompat.error`),` `,(0,Q.jsx)(`code`,{children:l??p})]}),(s||p)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:a,onClick:()=>void f(!1),children:n(`desktopCompat.refresh`)})]})}var gO={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`},_O={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 vO({apiBase:e,active:n}){let{t:r,locale:i}=t(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),_=(0,Z.useRef)({alive:!0,pending:!1,generation:0,operations:new Set}),v=`desktop-compatibility-certificate:${e}`,y=`desktop-compatibility-runtime:${e}`,b=zt(v,t=>fO(e,t),{enabled:n,deadlineMs:15e3,staleAfterMs:0}),x=zt(y,t=>dO(e,t),{enabled:n,deadlineMs:1e4,staleAfterMs:0,pollMs:5e3}),S=b.data&&x.data?{certificate:b.data,runtime:x.data}:null,C=!a&&b.lastAttemptOk&&x.lastAttemptOk&&!b.refreshing&&!x.refreshing,w=s||b.loading||x.loading,T=b.error??x.error,E=l??(T?T instanceof iO?T.code:`connection_unconfirmed`:null);(0,Z.useEffect)(()=>{let e=_.current;return e.alive=!0,()=>{e.alive=!1,e.generation++,e.pending=!1;for(let t of e.operations)t.controller.abort(),t.clear();e.operations.clear()}},[]);let D=(0,Z.useCallback)(async t=>{let n=_.current;if(n.pending)return;n.pending=!0;let r=++n.generation;c(!0),u(null),f(!1),o(!0);let i=A(t?14e4:15e3);n.operations.add(i);try{t&&await mO(e,t,i.signal);let a=await pO(e,i.signal);n.alive&&n.generation===r&&(Ut(v,a.certificate),Ut(y,a.runtime),o(!1),f(!!t),m(null),g(!1))}catch(e){n.alive&&n.generation===r&&(u(e instanceof iO?e.code:`connection_unconfirmed`),m(null),g(!1))}finally{n.operations.delete(i),i.clear(),n.generation===r&&(n.pending=!1,n.alive&&c(!1))}},[e,v,y]),O=!!S?.certificate.supported&&!!S.runtime.supported,k=S?.runtime.phase===`off`&&!S.certificate.busy,j=S?.runtime.phase===`running`,M=[];if(S&&O){let e=S.certificate;k&&e.state===`missing`&&M.push({target:`certificate`,action:`prepare`}),k&&e.fingerprint&&(e.state===`prepared`&&M.push({target:`certificate`,action:`trust`,fingerprint:e.fingerprint}),[`trusted`,`expired`,`renewal-required`,`unknown`].includes(e.state)&&M.push({target:`certificate`,action:`remove-trust`,fingerprint:e.fingerprint}),[`prepared`,`trusted`,`expired`,`renewal-required`].includes(e.state)&&M.push({target:`certificate`,action:`renew`,fingerprint:e.fingerprint})),k&&e.state===`trusted`&&M.push({target:`runtime`,action:`start`}),j&&M.push({target:`runtime`,action:`launch`},{target:`runtime`,action:`observe`},{target:`runtime`,action:`apply`}),(j||S.runtime.phase===`cleanup-required`)&&M.push({target:`runtime`,action:`stop`})}return(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h2`,{children:r(`desktopCompat.title`)}),(0,Q.jsx)(`p`,{className:`muted text-body`,children:r(`desktopCompat.description`)}),(0,Q.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.localOnly`)}),(0,Q.jsx)(hO,{apiBase:e,active:n}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:w,onClick:()=>void D(),children:r(w?`common.loading`:`desktopCompat.refresh`)}),E&&(0,Q.jsxs)(`div`,{className:`notice-err`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:r(E in _O?_O[E]:`desktopCompat.error`)}),(0,Q.jsx)(`code`,{children:E})]}),d&&(0,Q.jsx)(`p`,{className:`notice-ok`,role:`status`,children:r(`desktopCompat.done`)}),S&&(0,Q.jsxs)(Q.Fragment,{children:[!O&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:r(`desktopCompat.unsupported`)}),(0,Q.jsxs)(`dl`,{children:[(0,Q.jsx)(`dt`,{children:r(`desktopCompat.certificate`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:S.certificate.state})}),S.certificate.fingerprint&&(0,Q.jsx)(`dd`,{className:`mono text-label`,style:{overflowWrap:`anywhere`},children:S.certificate.fingerprint}),S.certificate.expiresAt!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{children:r(`desktopCompat.expiry`)}),(0,Q.jsx)(`dd`,{children:new Date(S.certificate.expiresAt).toLocaleString(i)})]}),(0,Q.jsx)(`dt`,{children:r(`desktopCompat.runtime`)}),(0,Q.jsxs)(`dd`,{children:[(0,Q.jsx)(`code`,{children:S.runtime.phase}),S.runtime.usage&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,(0,Q.jsx)(`code`,{children:S.runtime.usage.mode})]})]})]}),S.certificate.renewalDue&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:r(`desktopCompat.renewalDue`)}),S.runtime.usage?.mode===`apply`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:r(`desktopCompat.trialRisk`)}),S.runtime.usage?.mode===`observe`&&S.runtime.usage.phase.endsWith(`awaiting-original-response`)&&(0,Q.jsx)(`p`,{className:`notice-warn`,role:`status`,children:r(`desktopCompat.cacheRefreshHint`)}),S.runtime.contextFailure&&(0,Q.jsx)(`p`,{className:`notice-warn`,role:`status`,children:r(_O[S.runtime.contextFailure])}),j&&(0,Q.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.reconnectHint`)}),S.runtime.usage?.observation&&(0,Q.jsx)(`p`,{className:`muted text-control`,role:`status`,children:r(`desktopCompat.observation`,{json:S.runtime.usage.observation.jsonSnapshots,sse:S.runtime.usage.observation.streamSnapshots,streams:S.runtime.usage.observation.validatedActiveStreams})})]}),(0,Q.jsx)(`div`,{className:`row`,style:{flexWrap:`wrap`,gap:`var(--space-2)`},children:M.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:w||!C,onClick:()=>{[`trust`,`remove-trust`,`renew`,`apply`].includes(e.action)?(m(e),g(!1),f(!1)):D(e)},children:r(gO[e.action])},e.action))}),p&&(0,Q.jsxs)(`fieldset`,{disabled:w,children:[(0,Q.jsx)(`legend`,{children:r(gO[p.action])}),(0,Q.jsx)(`p`,{className:`notice-warn`,children:r(p.action===`apply`?`desktopCompat.trialRisk`:`desktopCompat.risk`)}),p.action===`apply`&&(0,Q.jsx)(`p`,{className:`muted text-control`,children:r(`desktopCompat.cacheRefreshHint`)}),p.target===`certificate`&&p.fingerprint&&(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:p.fingerprint}),(0,Q.jsxs)(`label`,{className:`row`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:h,onChange:e=>g(e.target.checked)}),r(`desktopCompat.acknowledge`)]}),(0,Q.jsxs)(`div`,{className:`row`,style:{gap:`var(--space-2)`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!h||!C,onClick:()=>void D(p),children:r(`desktopCompat.confirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{m(null),g(!1)},children:r(`common.cancel`)})]})]})]})}function yO(e){let{t:n}=t();return e.connected?(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h2`,{children:n(`desktopCompat.title`)}),(0,Q.jsx)(`p`,{className:`notice-warn`,children:n(`desktopCompat.connectedUnavailable`)})]}):(0,Q.jsx)(vO,{...e},e.apiBase)}var bO=[`multiauth`,`prompt`,`desktop`];function xO(){let e=window.location.hash.replace(/^#\/?/,``);return e===`codex-set/desktop`?`desktop`:e===`codex-set/prompt`?`prompt`:`multiauth`}function SO(e){window.location.hash=e===`multiauth`?`codex-set`:`codex-set/${e}`}function CO(e){if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(e.key))return;e.preventDefault();let t=bO.indexOf(xO()),n=bO[e.key===`Home`?0:e.key===`End`?bO.length-1:(t+(e.key===`ArrowRight`?1:-1)+bO.length)%bO.length];SO(n),document.getElementById(`codex-set-tab-${n}`)?.focus()}function wO({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=O(),[i,a]=(0,Z.useState)(xO),[o,s]=(0,Z.useState)(()=>xO()===`prompt`),[c,l]=(0,Z.useState)(()=>xO()===`multiauth`),[u,d]=(0,Z.useState)(()=>xO()===`desktop`);(0,Z.useEffect)(()=>{let e=()=>a(xO());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let f=o||i===`prompt`,p=c||i===`multiauth`;f!==o&&s(!0),p!==c&&l(!0);let m=u||i===`desktop`;return m!==u&&d(!0),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`nav.codexSet`),children:[(0,Q.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:()=>SO(`multiauth`),onKeyDown:CO,children:r(`codexSet.tab.multiauth`)}),(0,Q.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:()=>SO(`prompt`),onKeyDown:CO,children:r(`codexSet.tab.prompt`)}),(0,Q.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:()=>SO(`desktop`),onKeyDown:CO,children:r(`desktopCompat.title`)})]}),f&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-prompt`,"aria-labelledby":`codex-set-tab-prompt`,hidden:i!==`prompt`,children:(0,Q.jsx)(tO,{apiBase:e})}),p&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-multiauth`,"aria-labelledby":`codex-set-tab-multiauth`,hidden:i!==`multiauth`,children:(0,Q.jsx)(wD,{apiBase:e})}),m&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`codex-set-panel-desktop`,"aria-labelledby":`codex-set-tab-desktop`,hidden:i!==`desktop`,children:(0,Q.jsx)(yO,{apiBase:t,active:i===`desktop`,connected:n})})]})}var TO=[`qoder`,`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`],EO={qoder:`api.clientConfig.clientQoder`,opencode:`api.clientConfig.clientOpencode`,pi:`api.clientConfig.clientPi`,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`},DO={qoder:`/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`},OO=new Set([`opencode`,`kimi`,`prime`,`aside`,`hermes`]),kO={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`},AO={...kO,opencode:DO.opencode??null,pi:DO.pi??null,omp:DO.omp??null,hermes:DO.hermes??null,openclaw:DO.openclaw??null,kimi:DO.kimi??null,gajae:DO.gajae??null,dsh:DO.dsh??null,mcode:DO.mcode??null,zcode:DO.zcode??null,prime:DO.prime??null,aside:DO.aside??null,raycast:DO.raycast??null,omo:DO.omo??null,cline:DO.cline??null,commandcode:DO.commandcode??null,kilo:DO.kilo??null,droid:DO.droid??null,qoder:DO.qoder??null},jO=[kO.grok],MO=new Set([...[...OO].map(e=>DO[e]).filter(e=>e!==void 0),...jO]);function NO(e){return AO[e]}function PO({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?MO.has(e)?(0,Q.jsx)(`span`,{className:`${i} client-mark--mask`,style:{...a,maskImage:`url(${e})`,WebkitMaskImage:`url(${e})`},"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`${i} client-mark--img`,style:a,"aria-hidden":`true`,children:(0,Q.jsx)(`img`,{src:e,alt:``,width:n,height:n})}):(0,Q.jsx)(`span`,{className:`${i} client-mark--monogram`,style:a,"aria-hidden":`true`,children:t.slice(0,1)})}function FO(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function IO(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 LO(e){return e.id}function RO(e,t,n){let r=(0,Z.useRef)(0),i=(0,Z.useRef)(!1),a=(0,Z.useCallback)((e=`pairing`)=>{r.current++,n(e)},[n]),o=(0,Z.useCallback)(()=>{i.current=!1,r.current++},[]);return(0,Z.useLayoutEffect)(()=>(i.current=!0,a(`lifecycle`),o),[e,t,a,o]),(0,Z.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&a(`session`)},t=()=>{ut()&&a(`lifecycle`)};window.addEventListener(h,e),window.addEventListener(C,e);let n=dt(t);return()=>{window.removeEventListener(h,e),window.removeEventListener(C,e),n()}},[a]),{generation:r,invalidate:a,current:(0,Z.useCallback)(e=>i.current&&t&&!ut()&&r.current===e,[t])}}function zO(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 BO=new Set([`required`,`accepted`,`rejected`]);function VO(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`&&BO.has(t.bearer)&&BO.has(t.dedicated)&&BO.has(t.xApiKey)})}var HO=new Set([`fixed`,`api-surfaces`,`claude-code-legacy`,`invalid`]),UO=[`responses`,`chat`,`messages`];function WO(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n={};for(let e of UO){let r=t[e];if(!r||typeof r!=`object`||Array.isArray(r))return;let{enabled:i,source:a}=r;if(typeof i!=`boolean`||!HO.has(a))return;n[e]={enabled:i,source:a}}return n}function GO(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 KO={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 qO(e){let t=e||KO.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 JO(e,t){let n=new Date(e);return!e||Number.isNaN(n.getTime())?`—`:n.toLocaleDateString(t)}function YO({url:e}){return(0,Q.jsx)(XO,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,Q.jsx)(`code`,{className:`api-code api-code-inline api-endpoint-url`,children:e})})}function XO({text:e,hintKey:n,copiedKey:r,className:i,children:a}){let{t:o}=t(),s=(0,Z.useId)(),c=(0,Z.useRef)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(null),g=l||d;(0,Z.useEffect)(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]),(0,Z.useLayoutEffect)(()=>{if(!g)return;let e=()=>{let e=c.current;if(!e)return;let t=e.getBoundingClientRect();m({top:Math.max(8,t.top-8),left:t.left+t.width/2})};return e(),window.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[g]);let _=()=>u(!0),v=()=>u(!1),y=async()=>{try{await navigator.clipboard.writeText(e),f(!0),h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>f(!1),1500)}catch{f(!1)}},b=g&&p?(0,Jt.createPortal)((0,Q.jsx)(`span`,{id:s,className:`ocx-tooltip-bubble api-copy-tip-fixed`,role:`tooltip`,style:{top:p.top,left:p.left},children:o(d?r:n)}),document.body):null,x={ref:c,className:`ocx-tooltip ${i}`,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(n),"aria-describedby":g?s:void 0};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,...x,children:a}),b]})}function ZO({text:e}){return(0,Q.jsx)(XO,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,Q.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}var QO=`claude/code`,$O={fixed:`api.surface.source.fixed`,"api-surfaces":`api.surface.source.explicit`,"claude-code-legacy":`api.surface.source.inherited`,invalid:`api.surface.source.invalid`},ek=[{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 tk({apiBase:e,endpoints:n,surfaces:r,onChanged:i}){let{t:a}=t(),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=async t=>{if(!o){s(!0),l(null);try{let n=await Wm(e,{messagesEnabled:!t.enabled});n.kind===`ok`?i():l(n.kind===`unavailable`?`unavailable`:`failed`)}finally{s(!1)}}};return(0,Q.jsx)(`div`,{className:`api-endpoints api-surface-cards`,children:ek.map(e=>{let t=r[e.id],i=t.enabled?a(`api.surface.on`):a(`api.surface.off`);return(0,Q.jsxs)(`div`,{className:`api-surface-card${t.enabled?``:` api-surface-card-off`}`,"data-surface":e.id,children:[(0,Q.jsxs)(`div`,{className:`api-surface-card-head`,children:[(0,Q.jsx)(`span`,{className:`api-surface-card-title`,children:a(e.titleKey)}),e.id===`messages`?(0,Q.jsx)(on,{on:t.enabled,disabled:o,onClick:()=>{u(t)},label:`${a(`api.surface.messagesToggle`)}: ${i}`}):null,(0,Q.jsx)(`span`,{className:`badge ${t.enabled?`badge-green`:`badge-muted`}`,children:i})]}),(0,Q.jsx)(YO,{url:e.url(n)}),(0,Q.jsx)(`span`,{className:`small ${t.source===`invalid`?`api-surface-invalid`:`muted`}`,children:a($O[t.source])}),e.id===`messages`?(0,Q.jsxs)(Q.Fragment,{children:[t.enabled?null:(0,Q.jsx)(`span`,{className:`muted small`,children:a(`api.surface.closedNote`)}),t.enabled?(0,Q.jsx)(`span`,{className:`muted small`,children:a(`api.surface.messagesCloseNote`)}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm api-surface-card-link`,onClick:()=>qt(QO),children:a(`api.surface.openClaude`)}),c?(0,Q.jsx)($,{tone:`err`,children:a(c===`unavailable`?`api.surface.toggleUnavailable`:`api.surface.toggleFailed`)}):null]}):null]},e.id)})})}function nk(e,t){return t(e===`required`?`api.auth.required`:e===`accepted`?`api.auth.accepted`:`api.auth.rejected`)}function rk({endpoints:e,claudeCodeEnabled:n,authMatrix:r,surfaces:i,apiBase:a,onSurfacesChanged:o}){let{t:s}=t(),c=i&&a!==void 0&&o?{surfaces:i,apiBase:a,onChanged:o}:null;return(0,Q.jsxs)(`div`,{className:`panel api-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:s(`api.endpointsTitle`)}),(0,Q.jsxs)(`div`,{className:`api-endpoints`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:s(`api.baseUrl`)}),(0,Q.jsx)(YO,{url:e.baseUrl})]}),c?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:s(`api.responsesEndpoint`)}),(0,Q.jsx)(YO,{url:e.responses})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:s(`api.chatCompletionsEndpoint`)}),(0,Q.jsx)(YO,{url:e.chatCompletions})]}),n&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:s(`api.messagesEndpoint`)}),(0,Q.jsx)(YO,{url:e.messages})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted small`,children:s(`api.modelsEndpoint`)}),(0,Q.jsx)(YO,{url:e.models})]})]}),c?(0,Q.jsx)(tk,{endpoints:e,...c}):null,(0,Q.jsx)(`p`,{className:`muted small`,children:s(`api.endpointNote`)}),(0,Q.jsxs)(`div`,{className:`api-auth-matrix-block`,children:[(0,Q.jsx)(`h4`,{className:`api-auth-matrix-title`,children:s(`api.authTitle`)}),(0,Q.jsx)(`div`,{className:`api-auth-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`api-auth-matrix`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:s(`api.auth.endpoint`)}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`code`,{children:`Authorization: Bearer`})}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`code`,{children:`x-opencodex-api-key`})}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`code`,{children:`x-api-key`})})]})}),(0,Q.jsx)(`tbody`,{children:r.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.endpoint})}),(0,Q.jsx)(`td`,{children:nk(e.bearer,s)}),(0,Q.jsx)(`td`,{children:nk(e.dedicated,s)}),(0,Q.jsx)(`td`,{children:nk(e.xApiKey,s)})]},e.endpoint))})]})}),(0,Q.jsx)(`p`,{className:`muted small`,children:s(`api.authLoopback`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:s(`api.authBaseUrlNote`)})]})]})}function ik({keys:e,keysLoading:n=!1,keysLoadFailed:r,newName:i,creating:a,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}=t();return(0,Q.jsxs)(Q.Fragment,{children:[o&&(0,Q.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:v(`api.newKeyTitle`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:v(`api.newKeyNote`)}),(0,Q.jsxs)(`div`,{className:`api-form-row`,children:[(0,Q.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:o}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:m,children:s?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Te,{}),` `,v(`api.copied`)]}):v(`api.copy`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:p,children:v(`api.dismiss`)})]}),(0,Q.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:v(`api.generateTitle`)}),(0,Q.jsxs)(`div`,{className:`api-form-row`,children:[(0,Q.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:v(`api.keyNamePlaceholder`),"aria-label":v(`api.keyNamePlaceholder`),value:i,maxLength:64,onChange:e=>d(e.target.value),className:`input`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:a,children:[(0,Q.jsx)(N,{}),` `,v(a?`api.generating`:`api.generate`)]})]})]}),u&&(0,Q.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":n,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:n?v(`api.activeKeysLoading`):v(`api.activeKeys`,{count:e.length})}),n?(0,Q.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":v(`common.loading`)}):e.length>0?(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:v(`api.colName`)}),(0,Q.jsx)(`th`,{children:v(`api.colKey`)}),(0,Q.jsx)(`th`,{children:v(`api.colCreated`)}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:e.name}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.prefix})}),(0,Q.jsx)(`td`,{children:JO(e.createdAt,l)}),(0,Q.jsx)(`td`,{children:c===e.id?(0,Q.jsxs)(`span`,{className:`api-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>_(e.id),children:v(`api.confirm`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,children:v(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":v(`api.deleteAria`),onClick:()=>h(e.id),children:(0,Q.jsx)(ve,{})})})]},e.id))})]})}):r?(0,Q.jsx)(`p`,{className:`muted`,children:v(`api.keysLoadFailed`)}):(0,Q.jsx)(`p`,{className:`muted`,children:v(`api.noKeys`)})]})]})}function ak({filteredModels:e,modelsLoading:n,modelsRefreshing:r=!1,modelsLoadFailed:i,modelCount:a,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}=t();return(0,Q.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,Q.jsxs)(`div`,{className:`api-panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:v(`api.modelsTitle`)}),(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:v(`api.modelsCount`,{count:e.length})})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:v(`api.modelsSubtitle`)}),(0,Q.jsx)(`input`,{type:`search`,className:`input`,value:s,onChange:e=>d(e.target.value),placeholder:v(`api.modelsSearch`),"aria-label":v(`api.modelsSearch`)}),i&&(0,Q.jsxs)(`div`,{className:`api-models-error`,children:[(0,Q.jsx)(`p`,{className:`muted small`,role:`alert`,children:v(`api.modelsLoadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:v(`common.retry`)})]}),r&&!n&&(0,Q.jsx)(`p`,{className:`muted small`,"aria-live":`polite`,children:v(`api.modelsLoading`)}),n?(0,Q.jsx)(my,{label:v(`api.modelsLoading`),rows:3}):o?e.length===0?(0,Q.jsx)(`p`,{className:`muted small api-models-empty`,children:a===0?v(`api.modelsEmpty`):v(`api.modelsNoMatch`,{query:s.trim()})}):(0,Q.jsx)(`div`,{className:`api-models-scroll`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:v(`api.colModel`)}),(0,Q.jsx)(`th`,{children:v(`api.colSource`)}),(0,Q.jsx)(`th`,{children:v(`api.colProtocols`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=LO(e),n=FO(u);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`api-model-cell`,children:[(0,Q.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,Q.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,Q.jsx)(`td`,{children:g(e)}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`api-model-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{f(t)},children:v(c===t?`api.modelCopied`:`api.copyModelId`)}),n.map(n=>{let r=l[t]?.[n],i=r?.state??`idle`;return(0,Q.jsxs)(`span`,{className:`api-model-test-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:i===`testing`||!h,title:h?void 0:v(`api.auth.testNeedsFreshKey`),onClick:()=>{p(e,n)},children:v(`api.auth.testProtocol`,{protocol:_(n)})}),i!==`idle`&&(0,Q.jsx)(`span`,{className:`api-test-note api-test-note--${i}`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:i===`testing`?v(`api.testingModel`):i===`ok`?v(`api.testSucceeded`):r?.detail??v(`api.testFailed`)})]},n)})]})})]},t)})})]})}):null]})}function ok({endpoints:e,claudeCodeEnabled:n}){let{t:r}=t(),i=JSON.stringify(r(`api.usageSampleInput`)),a=`curl ${e.chatCompletions} \\
|
|
21
|
+
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
22
|
+
-H "Content-Type: application/json" \\
|
|
23
|
+
-d '{
|
|
24
|
+
"model": "gpt-5.6-luna",
|
|
25
|
+
"messages": [{"role": "user", "content": ${i}}]
|
|
26
|
+
}'`,o=`curl ${e.responses} \\
|
|
27
|
+
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
28
|
+
-H "Content-Type: application/json" \\
|
|
29
|
+
-d '{
|
|
30
|
+
"model": "gpt-5.6-luna",
|
|
31
|
+
"input": ${i}
|
|
32
|
+
}'`,s=`curl ${e.messages} \\
|
|
33
|
+
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
34
|
+
-H "Content-Type: application/json" \\
|
|
35
|
+
-d '{
|
|
36
|
+
"model": "claude-sonnet-4-6",
|
|
37
|
+
"max_tokens": 64,
|
|
38
|
+
"messages": [{"role": "user", "content": ${i}}]
|
|
39
|
+
}'`;return(0,Q.jsxs)(`section`,{className:`panel api-panel awi-usage-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:r(`api.workspace.usageExamples`)}),(0,Q.jsxs)(`div`,{className:`awi-usage-panel-body`,children:[(0,Q.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Q.jsx)(`h4`,{className:`awi-usage-example-title`,children:r(`api.usageChatTitle`)}),(0,Q.jsx)(ZO,{text:a})]}),(0,Q.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Q.jsx)(`h4`,{className:`awi-usage-example-title`,children:r(`api.usageResponsesTitle`)}),(0,Q.jsx)(ZO,{text:o})]}),n&&(0,Q.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,Q.jsx)(`h4`,{className:`awi-usage-example-title`,children:r(`api.usageMessagesTitle`)}),(0,Q.jsx)(ZO,{text:s})]})]})]})}function sk({client:e,apiBase:t,onOpenDetails:n,onCopy:r,onDownload:i}){let a=O(),[o,s]=(0,Z.useState)(0),c=[t,e,String(o)].join(`|`),[l,u]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let n=new AbortController,r=!1;return(async()=>{try{let i=await fetch(`${t}/api/client-config?client=${encodeURIComponent(e)}`,{signal:n.signal});if(!i.ok)throw Error(String(i.status));let a=await i.json();if(r)return;u({key:c,data:a,failed:!1})}catch{if(r)return;u({key:c,data:null,failed:!0})}})(),()=>{r=!0,n.abort()}},[t,e,c]);let d=l!==null&&l.key===c?l:null,f=d?.data??null,p=d?.failed??!1,m=d===null,h=a(EO[e]),g=DO[e],_=f?.text??``,v=(0,Z.useCallback)(t=>{f&&n(e,f,_,t.currentTarget)},[e,f,_,n]);return(0,Q.jsxs)(`li`,{className:`awi-clientconfig-row`,children:[(0,Q.jsx)(`span`,{className:`awi-clientconfig-mark`,children:(0,Q.jsx)(PO,{src:g??null,label:h,size:20})}),(0,Q.jsxs)(`span`,{className:`awi-clientconfig-identity`,children:[(0,Q.jsx)(`span`,{className:`awi-clientconfig-name`,children:h}),(0,Q.jsx)(`span`,{className:`muted text-label awi-clientconfig-meta`,children:m?a(`api.clientConfig.loading`):p||!f?(0,Q.jsx)(`span`,{role:`alert`,children:a(`api.clientConfig.rowError`,{client:h})}):a(`api.clientConfig.rowMeta`,{destination:f.destination,count:f.modelCount})})]}),(0,Q.jsx)(`span`,{className:`awi-clientconfig-row-actions`,children:p&&!m?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e=>e+1),children:a(`common.retry`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":a(`api.clientConfig.copyAria`,{client:h}),disabled:!f,onClick:()=>{f&&r(e,_)},children:a(`api.clientConfig.copy`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"aria-label":a(`api.clientConfig.downloadAria`,{client:h}),disabled:!f,onClick:()=>{f&&i(e,f,_)},children:a(`api.clientConfig.download`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":a(`api.clientConfig.detailsAria`,{client:h}),disabled:!f,onClick:v,children:a(`api.clientConfig.details`)})]})})]})}function ck({client:e,envelope:t,json:n,hasKeys:r,onClose:i,onCopy:a,onDownload:o}){let s=O(),c=(0,Z.useRef)(null),l=`awi-clientconfig-dialog-${e}`;(0,Z.useEffect)(()=>{let e=c.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]);let u=(0,Z.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,Q.jsxs)(`div`,{className:`modal-card awi-clientconfig-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:l,children:s(EO[e])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:s(`common.close`)})]}),(0,Q.jsx)(`pre`,{className:`api-code api-example-pre awi-clientconfig-json`,tabIndex:0,role:`group`,"aria-label":s(`api.clientConfig.jsonLabel`,{client:s(EO[e])}),children:n}),(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-count`,children:s(`api.clientConfig.modelCount`,{count:t.modelCount})}),t.modelsWithoutLimits>0&&(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-degraded`,children:s(`api.clientConfig.missingLimits`,{count:t.modelsWithoutLimits,total:t.modelCount})}),!r&&e!==`cline`&&t.apiKeyEnv!==``&&(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-nokey`,children:s(`api.clientConfig.noKeyYet`,{env:t.apiKeyEnv})}),(0,Q.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.destination`)}),(0,Q.jsx)(ZO,{text:t.destination})]}),(0,Q.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[e!==`cline`&&t.apiKeyEnv!==``&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.envHint`)}),(0,Q.jsx)(ZO,{text:t.exportHint})]}),(0,Q.jsx)(`p`,{className:`muted small awi-clientconfig-merge`,children:s(e===`cline`?`api.clientConfig.clineBundle`:`api.clientConfig.mergeWarning`)}),(e===`cline`||t.apiKeyEnv!==``)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label awi-clientconfig-where-title`,children:s(`api.clientConfig.whereDisclosure`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:s(e===`cline`?`integrations.semantics.cline`:`api.clientConfig.whereBody`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:s(`api.clientConfig.copy`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:o,children:s(`api.clientConfig.download`)})]})]})]})}function lk({apiBase:e,baseUrl:t,hasKeys:n}){let r=O(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(``),c=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(i!==null)return;let e=c.current;e&&(c.current=null,e.isConnected&&e.focus())},[i]);let l=(0,Z.useCallback)(async(e,t,n)=>{try{await navigator.clipboard.writeText(t),s(n?r(`api.clientConfig.copiedAnnounceClient`,{client:r(EO[e])}):r(`api.clientConfig.copiedAnnounce`))}catch{s(r(`api.clientConfig.copyFailed`))}},[r]),u=(0,Z.useCallback)((e,t,n)=>{let i=URL.createObjectURL(new Blob([n],{type:t.mediaType})),a=document.createElement(`a`);a.href=i,a.download=t.filename,a.click(),URL.revokeObjectURL(i),s(r(e===`cline`?`api.clientConfig.clineDownloaded`:`api.clientConfig.downloadedAnnounce`,{filename:t.filename,destination:t.destination}))},[r]),d=(0,Z.useCallback)(()=>a(null),[]),f=(0,Z.useCallback)((e,t,n,r)=>{c.current=r,a({client:e,envelope:t,json:n})},[]);return(0,Q.jsxs)(`section`,{className:`panel api-panel awi-clientconfig-panel`,children:[(0,Q.jsx)(`div`,{className:`api-panel-head awi-clientconfig-head`,children:(0,Q.jsx)(`h3`,{className:`panel-title`,children:r(`api.clientConfig.title`)})}),(0,Q.jsx)(`ul`,{className:`awi-clientconfig-rows`,"aria-label":r(`api.clientConfig.rowsLabel`),children:TO.map(t=>(0,Q.jsx)(sk,{client:t,apiBase:e,onOpenDetails:f,onCopy:(e,t)=>{l(e,t,!0)},onDownload:u},t))}),(0,Q.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:r(`api.baseUrl`)}),(0,Q.jsx)(ZO,{text:t})]}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:o}),i&&(0,Q.jsx)(ck,{client:i.client,envelope:i.envelope,json:i.json,hasKeys:n,onClose:d,onCopy:()=>{l(i.client,i.json,!1)},onDownload:()=>u(i.client,i.envelope,i.json)})]})}var uk=[`pairing_required`,`standalone_required`,`join_port_mismatch`],dk=[`connecting`,`connected`,`reconnecting`,`failed`,`idle`],fk=[`standalone`,`home`,`child`],pk=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}},mk=160;function hk(e){return typeof e==`object`&&!!e}function gk(e){return e<32||e>=127&&e<=159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e===65279}function _k(e){if(typeof e!=`string`)return null;let t=Array.from(e,e=>gk(e.codePointAt(0)??0)?` `:e).join(``).replace(/\s+/g,` `).trim();if(!t)return null;let n=Array.from(t);return n.length>mk?`${n.slice(0,159).join(``)}\u2026`:t}function vk(e){return typeof e==`string`&&e.length>0}function yk(e){return typeof e==`string`&&dk.includes(e)}function bk(e){if(!hk(e)||!fk.includes(e.role))throw Error(`invalid status`);let t=e.listener;if(!hk(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(!hk(e)||!vk(e.id)||!vk(e.alias)||![`hub-initiated`,`client-initiated`].includes(String(e.direction))||!yk(e.state)||!vk(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(!hk(e.child)||!vk(e.child.alias)||!yk(e.child.state)||!vk(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=uk.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 xk(e){let t;try{t=await e.json()}catch{}if(!e.ok){let n=hk(t)&&hk(t.error)?t.error:null;throw new pk(n&&typeof n.code==`string`?n.code:`unknown`,e.status,_k(n?.hint))}if(t==null)throw new pk(`invalid_body`,e.status);return t}async function Sk(e,t,n){return xk(await fetch(`${e}${t}`,{...n,cache:`no-store`}))}async function Ck(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!hk(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 wk=1e3,Tk=5e3,Ek=145e3,Dk=2e3;function Ok(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 kk(e,t,n,r={}){let i=r.now??Date.now,a=r.sleep??Ok,o=i()+Ek,s=!1;for(;;){if(n.aborted)return`aborted`;let c=await Ck(e,AbortSignal.any([n,AbortSignal.timeout(Dk)]),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?Tk:wk,n)}}var Ak=/^ocx_pair_[A-Za-z0-9_-]{43}$/,jk=1e4,Mk=class extends Error{kind;constructor(e){super(`pairing_${e}`),this.kind=e,this.name=`PairingError`}},Nk=16384;function Pk(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 Fk(e,t=Nk){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{await n.cancel()}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 Ik(e){return Pk(e)?!0:e.headers.get(`content-type`)?.toLowerCase().includes(`text/html`)?Pk(e,await Fk(e)):!1}async function Lk(e,t,n,r){r?.throwIfAborted();let i=t.trim();if(!Ak.test(i))throw new Mk(`invalid-code`);let a=n??((e,t)=>window.fetch(e,t)),o=c(`shared`);return l(jk,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 Mk(`unreachable`)}if(!n.ok){if(await Ik(n))throw new Mk(`cloudflare-challenge`);try{await n.body?.cancel()}catch{}throw n.status===401?new Mk(`refused`):n.status===403?new Mk(`origin-denied`):new Mk(`request-failed`)}let s;try{s=await n.text()}catch(e){throw r?.aborted?e:new Mk(`invalid-response`)}if(t.throwIfAborted(),Pk(n,s))throw new Mk(`cloudflare-challenge`);if(!o.install(s))throw o.rollback(),new Mk(`invalid-response`);return o}).catch(e=>{throw o.rollback(),r?.throwIfAborted(),e instanceof Mk?e:new Mk(`unreachable`)})}async function Rk(e,t,n){n?.throwIfAborted();let r=t??((e,t)=>u(`shared`,e,t??{}));return l(jk,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 Mk(`unreachable`)}if(t.throwIfAborted(),!n.ok){if(await Ik(n))throw new Mk(`cloudflare-challenge`);try{await n.body?.cancel()}catch{}throw n.status===401?new Mk(`remote-link-unauthorized`):n.status===403?new Mk(`remote-link-forbidden`):new Mk(`request-failed`)}if(await Ik(n))throw new Mk(`cloudflare-challenge`);if(!E(`shared`))throw new Mk(`invalid-response`);try{let e=await n.json();t.throwIfAborted(),bk(e)}catch{throw t.throwIfAborted(),new Mk(`invalid-response`)}}).catch(e=>{throw n?.throwIfAborted(),e instanceof Mk?e:new Mk(`unreachable`)})}function zk({target:e,onConnected:t,onPairingStart:n,local:r=!1,focusOnMount:i=!1}){let a=O(),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{i&&h.current?.focus()},[i]);let g=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{g.current?.abort(),m.current?.rollback()},[]);let _=sl(),v=`ocx gui pair --origin "${window.location.origin}"`,y=_.outcomeFor(v);return(0,Q.jsxs)(`section`,{className:`card connect-pairing`,"aria-labelledby":`connect-pairing-title`,children:[(0,Q.jsx)(`h2`,{id:`connect-pairing-title`,children:a(r?`connection.pairing.code`:`connection.pairing.title`)}),(0,Q.jsxs)(`p`,{children:[!r&&(0,Q.jsxs)(Q.Fragment,{children:[a(`connection.pairing.hub`),`: `]}),(0,Q.jsx)(`code`,{children:e.serverOrigin})]}),!r&&(0,Q.jsx)(`p`,{children:a(`connection.pairing.getCode`)}),(0,Q.jsx)(`pre`,{style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:(0,Q.jsx)(`code`,{children:v})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>_.copy(v,v),children:a(y===`copied`?`startup.copied`:`startup.copy`)}),y===`unavailable`&&(0,Q.jsx)(`p`,{role:`status`,children:a(`prov.linkCopyUnavailable`)}),!r&&(0,Q.jsx)(`p`,{children:a(`connection.pairing.askOperator`)}),(0,Q.jsx)(`p`,{children:a(`connection.pairing.notApiKey`)}),(0,Q.jsxs)(`form`,{onSubmit:async r=>{if(r.preventDefault(),g.current)return;m.current||n?.(),l(!0),d(null);let i=new AbortController;g.current=i;try{m.current||(m.current=await Lk(e,o,void 0,i.signal),i.signal.aborted&&(m.current.rollback(),m.current=null,i.signal.throwIfAborted()),s(``),p(!0)),i.signal.aborted||(await t(i.signal),i.signal.throwIfAborted(),m.current?.commit(),m.current=null,p(!1))}catch(e){if(!i.signal.aborted){let t=e instanceof Mk?e.kind:`unreachable`;(t===`remote-link-unauthorized`||t===`remote-link-forbidden`)&&(m.current?.rollback(),m.current=null,p(!1)),d(t)}}finally{i.signal.aborted||l(!1),g.current===i&&(g.current=null)}},className:`api-form-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`connect-pairing-code`,className:`field-label`,children:a(`connection.pairing.code`)}),(0,Q.jsx)(`input`,{ref:h,id:`connect-pairing-code`,name:`pairingCode`,value:o,onChange:e=>s(e.currentTarget.value),autoComplete:`off`,spellCheck:!1,disabled:c||f,className:`input mono`,"aria-invalid":!!u||void 0,"aria-describedby":u?`connect-pairing-error`:void 0}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:c||!f&&!o.trim(),children:a(c?`connection.pairing.submitting`:f?`connection.pairing.retryValidation`:`connection.pairing.submit`)}),u&&(0,Q.jsx)(`p`,{id:`connect-pairing-error`,className:`alert alert-err`,role:`alert`,children:a(f?`connection.pairing.validationPending`:u===`invalid-code`?`connection.pairing.notApiKey`:u===`unreachable`?`connection.pairing.networkError`:u===`request-failed`?`connection.pairing.requestError`:u===`origin-denied`?`connection.pairing.originDenied`:u===`cloudflare-challenge`?`connection.pairing.cloudflareChallenge`:u===`remote-link-unauthorized`||u===`remote-link-forbidden`?`connection.pairing.sessionNotAuthorized`:u===`invalid-response`?`connection.pairing.responseError`:`connection.pairing.error`)})]}),e.transport===`relay`&&(0,Q.jsx)(`p`,{className:`text-muted`,children:a(`connection.pairing.relayWarning`)})]})}function Bk({keys:e,keysLoading:t,keysLoadFailed:n,attributionSince:r,usageMetadata:i,localeTag:a,apiBase:o,active:s=!0,onPairingStart:c,busy:l,onSelect:u,onDelete:d,onReveal:f}){let m=O(),[h,g]=(0,Z.useState)({}),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),k=(0,Z.useRef)(null),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(!1),[P,I]=(0,Z.useState)(null),[L,R]=(0,Z.useState)(null),z=(0,Z.useRef)(null),B=RO(o,s,(0,Z.useCallback)(e=>{let t=z.current;z.current=null,g({}),v(null),b(null),S(n=>e===`session`?t??n:e===`pairing`?n:null),w(null),E(null),k.current!==null&&window.clearTimeout(k.current),k.current=null},[]));(0,Z.useEffect)(()=>{if(!A)return;let e=window.setTimeout(()=>N(!0),300);return()=>window.clearTimeout(e)},[A]);let V=(0,Z.useRef)(new Set),H=e=>{let t=h[e.id];return t!==void 0&&t.startsWith(e.prefix.replace(/\.\.\.$/,``))?t:void 0},U=l||P!==null,W=D(o).shared,G=p()&&window.location.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(window.location.hostname)&&W.serverOrigin===window.location.origin,ee=async e=>{let t=B.generation.current;if(!B.current(t))return;let n=e.id;if(b(null),S(null),H(e)!==void 0){g(({[n]:e,...t})=>t);return}if(!(!f||_)){z.current=n,v(n);try{let e=await f(n);if(!B.current(t)||V.current.has(n))return;e.ok?g(t=>({...t,[n]:e.key})):e.kind===`denied`?(B.invalidate(),c?.(),S(n)):b(n)}catch{B.current(t)&&b(n)}finally{B.current(t)&&(z.current=null,v(null))}}},K=e=>{w(t=>t===e?null:t),E(e)},q=(e,t)=>{let n=B.generation.current;if(!B.current(n))return;E(null);let r;try{r=navigator.clipboard?.writeText?.(t)}catch{r=void 0}if(!r){K(e);return}r.then(()=>{!B.current(n)||V.current.has(e)||(w(e),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{w(t=>t===e?null:t),k.current=null},2e3))},()=>{B.current(n)&&K(e)})};(0,Z.useEffect)(()=>()=>{k.current!==null&&window.clearTimeout(k.current)},[]);let te=async e=>{if(!(!d||!M||P)){I(e),R(null);try{await d(e)?(V.current.add(e),j(null),N(!1),g(({[e]:t,...n})=>n)):R(e)}finally{I(null)}}};return(0,Q.jsxs)(`div`,{className:`panel api-panel awi-keylist-panel`,"aria-busy":t,children:[(0,Q.jsx)(`div`,{className:`api-panel-head`,children:(0,Q.jsx)(`h3`,{className:`panel-title`,children:t?m(`api.activeKeysLoading`):m(`api.activeKeys`,{count:e.length})})}),(0,Q.jsx)(gr,{data:i}),x!==null&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`warn`,children:m(`api.key.revealDenied`)}),G&&(0,Q.jsx)(zk,{local:!0,target:W,onPairingStart:()=>{B.invalidate(),c?.()},onConnected:()=>{B.invalidate(),c?.(),S(null)}})]}),t?(0,Q.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":m(`common.loading`)}):e.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:m(n?`api.keysLoadFailed`:`api.noKeys`)}):(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl awi-keylist-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:m(`api.colName`)}),(0,Q.jsx)(`th`,{children:m(`api.colKey`)}),(0,Q.jsx)(`th`,{children:m(`api.attribution.requests7d`)}),(0,Q.jsx)(`th`,{children:m(`api.attribution.lastUsed`)}),d&&(0,Q.jsx)(`th`,{className:`awi-keylist-actions-col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:m(`api.colActions`)})})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=H(e),n=A===e.id;return(0,Q.jsxs)(`tr`,{className:n?`awi-keylist-row is-confirming`:`awi-keylist-row`,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`awi-keylist-name`,disabled:U,onClick:()=>u(e.id),children:e.name})}),(0,Q.jsx)(`td`,{className:`awi-keylist-keycell`,children:f?(0,Q.jsxs)(`span`,{className:`awi-keylist-keywrap`,children:[(0,Q.jsx)(`button`,{type:`button`,className:t?`awi-keylist-key is-revealed`:`awi-keylist-key`,"aria-expanded":t!==void 0,"aria-label":m(t?`api.key.hideAria`:`api.key.revealAria`,{name:e.name}),title:m(t?`api.key.hideHint`:`api.key.revealHint`),disabled:_===e.id,onClick:()=>{ee(e)},children:(0,Q.jsx)(`code`,{children:t??e.prefix})}),t&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm awi-keylist-copy`,onClick:()=>q(e.id,t),children:C===e.id?m(`api.copied`):m(`api.copy`)}),T===e.id&&(0,Q.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:m(`api.key.copyFailedShort`)}),y===e.id&&(0,Q.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:m(`api.key.revealFailed`)})]}):(0,Q.jsx)(`code`,{children:e.prefix})}),(0,Q.jsx)(`td`,{children:r?e.usage.ambiguous?m(`api.attribution.railAmbiguous`):e.usage.requests7d.toLocaleString(a):m(`api.attribution.unavailable`)}),(0,Q.jsx)(`td`,{children:!r||e.usage.ambiguous?`—`:e.usage.lastUsedAt?JO(e.usage.lastUsedAt,a):m(i?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)}),d&&(0,Q.jsxs)(`td`,{className:`awi-keylist-actions`,children:[n?(0,Q.jsxs)(`span`,{className:`awi-keylist-confirm`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,"aria-label":m(`api.key.deleteRowAria`,{name:e.name}),disabled:!M||P!==null,onClick:()=>{te(e.id)},children:P===e.id?m(`api.key.deleting`):m(`api.key.deleteShort`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P!==null,onClick:()=>{j(null),N(!1),R(null)},children:m(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`awi-keylist-delete`,"aria-label":m(`api.key.deleteRowAria`,{name:e.name}),title:m(`api.workspace.deleteKey`),disabled:U,onClick:()=>{R(null),N(!1),j(e.id)},children:(0,Q.jsx)(F,{width:16,height:16,"aria-hidden":`true`})}),L===e.id&&(0,Q.jsx)(`span`,{className:`awi-delete-error awi-keylist-inline-error`,role:`alert`,children:m(`api.deleteFailed`)})]})]},e.id)})})]})})]})}var Vk=class extends Error{code;constructor(e){super(e),this.code=e}},Hk=2097152;async function Uk(e,t,n,r,i){if(!r.size||r.size>25e6)throw new Vk(`size`);if(!n.trim())throw new Vk(`auth`);i.throwIfAborted();let a=A(13e4),o=()=>a.controller.abort(i.reason);i.addEventListener(`abort`,o,{once:!0});try{let i=new FormData;i.set(`file`,r),i.set(`model`,t),i.set(`response_format`,`json`);let o=await v(e,{method:`POST`,headers:{"X-OpenCodex-API-Key":n.trim()},body:i,signal:a.signal});if(!o.ok)throw o.body?.cancel().catch(()=>{}),new Vk(o.status===401||o.status===403?`auth`:o.status===429?`rateLimit`:o.status===413?`size`:o.status>=500?`unavailable`:`invalid`);let s=o.body?.getReader();if(!s)throw new Vk(`protocol`);let c=()=>{s.cancel().catch(()=>{})};a.signal.addEventListener(`abort`,c,{once:!0});let l=``,u=0,d=new TextDecoder;try{for(a.signal.throwIfAborted();;){let e=await s.read();if(a.signal.throwIfAborted(),e.done)break;if(u+=e.value.byteLength,u>Hk)throw new Vk(`protocol`);l+=d.decode(e.value,{stream:!0})}l+=d.decode()}finally{a.signal.removeEventListener(`abort`,c),s.cancel().catch(()=>{}),s.releaseLock()}let f;try{f=JSON.parse(l)}catch{throw new Vk(`protocol`)}if(!f||typeof f!=`object`||typeof f.text!=`string`)throw new Vk(`protocol`);return f.text}catch(e){throw i.aborted?i.reason:a.signal.aborted?new Vk(`timeout`):e instanceof Vk?e:new Vk(`network`)}finally{i.removeEventListener(`abort`,o),a.clear()}}function Wk(e){let t=new TextEncoder().encode(e.trim());if(!t.length||t.length>4096)throw new Vk(`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 Gk={type:`session.update`,session:{instructions:``,audio:{output:{voice:`cove`}},delegation:{type:`client`}}},Kk=new Set([`session.started`,`session.updated`,`delegation.created`,`output_audio.delta`]);function qk(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 Vk(`invalid`);t.searchParams.set(`model`,e.model);let n=new WebSocket(t.href,Wk(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(Gk))}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`);return}if(n.type===`error`||n.type===`protocol.error`){c(`failed`,`protocol`);return}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`))}Kk.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 Jk(e,t,n,r){let i=new URL(e);t&&i.searchParams.set(`model`,n);let a=t?Gk:{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();
|
|
40
|
+
if (!key) throw new Error("missing_data_key");
|
|
41
|
+
const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(key)))
|
|
42
|
+
.replace(/\\+/g, "-").replace(/\\//g, "_").replace(/=+$/, "");
|
|
43
|
+
const ws = new WebSocket(${JSON.stringify(i.href)},
|
|
44
|
+
["opencodex-audio", "opencodex-key." + encoded]);
|
|
45
|
+
ws.onopen = () => ws.send(JSON.stringify(${JSON.stringify(a)}));
|
|
46
|
+
ws.onmessage = ({ data }) => console.log(JSON.parse(data).type);
|
|
47
|
+
// After session.started, send your protocol's audio frames.
|
|
48
|
+
// Dictation: mono PCM16 at the declared sample_rate_hz (48000 here).
|
|
49
|
+
// Live Voice: input_audio.append / output_audio.delta, 24 kHz mono.
|
|
50
|
+
const closeSession = () => ws.send(JSON.stringify({ type: "session.close" }));`}function Yk(e,t){return[`curl ${JSON.stringify(e)}`,` -H "X-OpenCodex-API-Key: $OPENCODEX_API_KEY"`,` -F "file=@recording.wav" -F "model=${t}"`].join(` \\
|
|
51
|
+
`)}function Xk({value:e,onChange:t}){let n=O(),r=(0,Z.useId)();return(0,Q.jsxs)(`label`,{className:`audio-api-field`,htmlFor:r,children:[(0,Q.jsx)(`span`,{children:n(`audio.key`)}),(0,Q.jsx)(`input`,{id:r,className:`input`,type:`password`,autoComplete:`off`,spellCheck:!1,maxLength:4096,value:e,onChange:e=>t(e.target.value)})]})}function Zk({code:e}){let t=O();return e?(0,Q.jsx)(`p`,{className:`audio-api-error`,role:`alert`,children:t(`audio.error.${e}`)}):null}function Qk({audio:e}){let t=O(),[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useId)(),m=(0,Z.useId)();(0,Z.useEffect)(()=>()=>{f.current?.abort(),f.current=null},[]);let h=()=>{f.current?.abort(),f.current=null,s(!1)},g=async()=>{if(!e?.transcriptionConfigured||!i||!n.trim()||f.current)return;let t=new AbortController;f.current=t,s(!0),d(null),l(null);try{let r=await Uk(e.transcriptionEndpoint,e.transcriptionModel,n,i,t.signal);f.current===t&&l(r)}catch(e){f.current===t&&!t.signal.aborted&&d(e instanceof Vk?e.code:`network`)}finally{f.current===t&&(f.current=null,s(!1))}};return(0,Q.jsxs)(`section`,{className:`audio-api-section`,"aria-labelledby":m,children:[(0,Q.jsxs)(`header`,{className:`audio-api-head`,children:[(0,Q.jsx)(`h3`,{id:m,children:t(`audio.dictation`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:t(e?.transcriptionConfigured?`audio.configured`:e?`audio.notConfigured`:`audio.unknown`)})]}),e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`audio-api-endpoints`,children:[(0,Q.jsx)(`code`,{children:e.transcriptionModel}),(0,Q.jsx)(YO,{url:e.transcriptionEndpoint})]}),(0,Q.jsxs)(`form`,{className:`audio-api-form`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,Q.jsx)(Xk,{value:n,onChange:e=>{h(),d(null),r(e)}}),(0,Q.jsxs)(`label`,{className:`audio-api-field`,htmlFor:p,children:[(0,Q.jsx)(`span`,{children:t(`audio.file`)}),(0,Q.jsx)(`input`,{id:p,className:`input`,type:`file`,accept:`audio/*,.mp4,.webm`,onChange:e=>{h(),d(null),l(null),a(e.target.files?.[0]??null)}})]}),(0,Q.jsxs)(`div`,{className:`audio-api-actions`,children:[(0,Q.jsxs)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:o||!e.transcriptionConfigured||!i||!n.trim(),children:[(0,Q.jsx)(Be,{width:16,height:16,"aria-hidden":`true`}),t(o?`audio.transcribing`:`audio.transcribe`)]}),o&&(0,Q.jsxs)(`button`,{className:`btn`,type:`button`,onClick:h,children:[(0,Q.jsx)(ve,{width:16,height:16,"aria-hidden":`true`}),t(`common.cancel`)]})]})]}),(0,Q.jsx)(Zk,{code:u}),c!==null&&(0,Q.jsxs)(`div`,{className:`audio-api-result`,"aria-live":`polite`,children:[(0,Q.jsx)(`h4`,{children:t(`audio.transcript`)}),c?(0,Q.jsx)(ZO,{text:c}):(0,Q.jsx)(`p`,{className:`muted small`,children:t(`audio.emptyTranscript`)})]}),(0,Q.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Q.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Q.jsx)(ZO,{text:Yk(e.transcriptionEndpoint,e.transcriptionModel)}),(0,Q.jsxs)(`div`,{className:`audio-api-head`,children:[(0,Q.jsx)(`h4`,{children:t(`audio.streaming`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:t(e.dictationConfigured?`audio.configured`:`audio.notConfigured`)})]}),(0,Q.jsx)(YO,{url:e.dictationStreamEndpoint}),(0,Q.jsx)(ZO,{text:Jk(e.dictationStreamEndpoint,!1,e.transcriptionModel,t(`audio.key`))})]})]})]})}function $k({audio:e}){let t=O(),[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)(`idle`),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)([]),u=(0,Z.useRef)(null),d=(0,Z.useId)();(0,Z.useEffect)(()=>()=>{u.current?.dispose?.(),u.current=null},[]);let f=()=>{u.current&&(u.current?.dispose?.(),u.current=null,a(`disconnected`))},p=()=>{if(!e?.liveConfigured||!n.trim()||u.current)return;s(null),l([]);let t={};u.current=t;try{t.dispose=qk({endpoint:e.liveEndpoint,model:e.liveModel,key:n,onState:(e,n)=>{u.current===t&&(a(e),s(n??null),(e===`failed`||e===`disconnected`)&&(u.current=null))},onEvent:e=>{u.current===t&&l(t=>[...t.slice(-7),e])}})}catch(e){u.current=null,a(`failed`),s(e instanceof Vk?e.code:`network`)}},m=i===`connecting`||i===`connected`;return(0,Q.jsxs)(`section`,{className:`audio-api-section`,"aria-labelledby":d,children:[(0,Q.jsxs)(`header`,{className:`audio-api-head`,children:[(0,Q.jsx)(`h3`,{id:d,children:t(`audio.liveVoice`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:t(e?.liveConfigured?`audio.configured`:e?`audio.notConfigured`:`audio.unknown`)})]}),e&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`audio-api-endpoints`,children:[(0,Q.jsx)(`code`,{children:e.liveModel}),(0,Q.jsx)(YO,{url:e.liveEndpoint}),(0,Q.jsx)(YO,{url:e.realtimeCallsEndpoint})]}),(0,Q.jsxs)(`form`,{className:`audio-api-form`,onSubmit:e=>{e.preventDefault(),p()},children:[(0,Q.jsx)(Xk,{value:n,onChange:e=>{f(),s(null),l([]),r(e)}}),(0,Q.jsxs)(`div`,{className:`audio-api-actions`,children:[(0,Q.jsxs)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:m||!e.liveConfigured||!n.trim(),children:[(0,Q.jsx)(st,{width:16,height:16,"aria-hidden":`true`}),t(`audio.connect`)]}),m&&(0,Q.jsxs)(`button`,{className:`btn`,type:`button`,onClick:f,children:[(0,Q.jsx)(ve,{width:16,height:16,"aria-hidden":`true`}),t(`audio.disconnect`)]}),(0,Q.jsx)(`span`,{className:`audio-api-status`,role:`status`,children:t(`audio.state.${i}`)})]})]}),(0,Q.jsx)(Zk,{code:o}),c.length>0&&(0,Q.jsx)(`pre`,{className:`audio-api-events`,"aria-label":t(`audio.events`),children:c.join(`
|
|
52
|
+
`)}),(0,Q.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Q.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Q.jsx)(ZO,{text:Jk(e.liveEndpoint,!0,e.liveModel,t(`audio.key`))})]})]})]})}function eA({keys:e,apiBase:t,active:n=!0,onPairingStart:r,attributionSince:i,historyTruncated:a,usageMetadata:o,authMatrix:s,keysLoading:c,keysLoadFailed:l,endpoints:u,claudeCodeEnabled:d,surfaces:f,onSurfacesChanged:p,localeTag:m,newName:h,creating:g,newKey:_,copied:v,rotationSecret:y=null,rotationCopied:b=!1,filteredModels:x,planModels:S,modelsLoading:C,modelsRefreshing:w=!1,modelsLoadFailed:T,modelCount:E,hasModelData:D,modelQuery:k,copiedModelId:A,modelTests:j,canTestModels:M,onNewNameChange:N,onCreate:P,onDismissNewKey:I,onCopyKey:L,onDelete:R,onRevealKey:z,onRename:B,onRotationStart:V,onRotationCommit:H,onRotationAbort:U,onCopyRotationSecret:W,onDismissRotationSecret:G,onModelQueryChange:ee,onCopyModelId:K,onTestModel:q,onRetryModels:te,sourceLabel:ne,protocolLabel:J}){let Y=O(),[re,ie]=(0,Z.useState)(null),[X,ae]=(0,Z.useState)(!1),[oe,se]=(0,Z.useState)(!1),[ce,le]=(0,Z.useState)(!1),[ue,de]=(0,Z.useState)(!1),[fe,pe]=(0,Z.useState)(``),[me,he]=(0,Z.useState)(!1),[ge,_e]=(0,Z.useState)(!1),[ve,ye]=(0,Z.useState)(!1),[be,xe]=(0,Z.useState)(!1),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(!1),[Ee,De]=(0,Z.useState)(null),Oe=re?e.find(e=>e.id===re)??null:null,ke=Oe?y?.id===Oe.id?y.rotationId:Oe.pendingRotation?.id:void 0,Ae=ke!==void 0||!!V,je=ce||me||be,Me=()=>{let e=y;if(!e)return;let t=navigator.clipboard?.writeText?.(e.key);if(!t){Te(!0);return}t.then(()=>{Te(!1),De(e.rotationId),window.setTimeout(()=>De(null),2e3)}).catch(()=>{Te(!0)})},Ne=async e=>{if(!(!Oe||be)){xe(!0),Ce(!1);try{let t=ke;(e===`start`?await V?.(Oe.id)??!1:t&&(await(e===`commit`?H:U)?.(Oe.id,t)??!1))||Ce(!0)}finally{xe(!1)}}},Pe=(0,Z.useMemo)(()=>[{id:`keys`,label:Y(`api.section.keys`),meta:c?void 0:String(e.length)},{id:`connect`,label:Y(`api.section.connect`)},{id:`endpoints`,label:Y(`api.section.endpoints`)},{id:`plan`,label:Y(`api.section.plan`)},{id:`dictation`,label:Y(`audio.dictation`)},{id:`live-voice`,label:Y(`audio.liveVoice`)},{id:`models`,label:Y(`api.section.models`),meta:String(E)},{id:`examples`,label:Y(`api.section.examples`)}],[Y,e.length,c,E]),Fe=()=>{ae(!1),se(!1)},Ie=()=>{ie(null),Fe(),de(!1),_e(!1),ye(!1)};(0,Z.useEffect)(()=>{if(!X)return;let e=window.setTimeout(()=>se(!0),300);return()=>window.clearTimeout(e)},[X]);let Le=()=>{Oe&&ae(!0)},Re=async()=>{if(!(!Oe||!oe||ce)){le(!0),ye(!1);try{await R(Oe.id)?(Fe(),ie(null)):ye(!0)}finally{le(!1)}}},ze=()=>{Oe&&(pe(Oe.name),_e(!1),de(!0))},Be=async()=>{if(!Oe||me)return;let e=fe.trim();if(!e||e===Oe.name){de(!1);return}he(!0),_e(!1);try{await B(Oe.id,e)?de(!1):_e(!0)}finally{he(!1)}};return(0,Q.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!Oe&&(0,Q.jsx)(sC,{scope:`api`,items:Pe,ariaLabel:Y(`api.workspace.sections`),mobileReadingLine:108}),(0,Q.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,Q.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":Y(`api.workspace.details`),children:Oe?(0,Q.jsxs)(`div`,{className:`awi-detail`,children:[(0,Q.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:Ie,disabled:je,children:[(0,Q.jsx)(Ke,{className:`awi-back-chevron`,"aria-hidden":`true`}),Y(`modal.back`)]})}),(0,Q.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,Q.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,Q.jsx)(`h2`,{className:`awi-detail-title`,children:Oe.name}),(0,Q.jsx)(`span`,{className:`awi-detail-actions`,children:X?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{Re()},disabled:!oe||ce,children:[(0,Q.jsx)(F,{}),` `,Y(ce?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Fe,disabled:ce,children:Y(`common.cancel`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ze,disabled:ue,children:Y(`api.key.rename`)},`rename`),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:Le,"aria-label":Y(`api.deleteAria`),children:[(0,Q.jsx)(F,{}),` `,Y(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),X&&(0,Q.jsx)(`p`,{className:`muted awi-delete-hint`,children:Y(`api.workspace.deleteConfirm`)}),ve&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:Y(`api.deleteFailed`)}),ue&&(0,Q.jsxs)(`div`,{className:`awi-rename`,children:[(0,Q.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:Y(`api.key.name`)}),(0,Q.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:fe,maxLength:64,disabled:me,onChange:e=>pe(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Be())}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{Be()},disabled:me,children:Y(me?`api.key.renaming`:`api.key.saveName`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>de(!1),disabled:me,children:Y(`common.cancel`)}),ge&&(0,Q.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:Y(`api.key.renameFailed`)})]}),(0,Q.jsxs)(`div`,{className:`awi-section`,children:[(0,Q.jsx)(`h3`,{className:`awi-section-title`,children:Y(`api.workspace.keyDetails`)}),(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:Y(`api.workspace.keyPrefix`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:Oe.prefix})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:Y(`api.colCreated`)}),(0,Q.jsx)(`dd`,{children:JO(Oe.createdAt,m)})]})]})]}),Ae&&(0,Q.jsxs)(`div`,{className:`awi-section`,"aria-live":`polite`,children:[(0,Q.jsx)(`h3`,{className:`awi-section-title`,children:Y(`api.rotation.title`)}),ke?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:Y(`api.rotation.pending`)}),Oe.pendingRotation&&(0,Q.jsxs)(`p`,{className:`muted`,children:[Y(`api.rotation.expires`),` `,JO(Oe.pendingRotation.expiresAt,m)]}),y?.id===Oe.id&&(0,Q.jsxs)(`div`,{className:`api-key-reveal`,role:`status`,children:[(0,Q.jsx)(`p`,{children:Y(`api.rotation.secretOnce`)}),(0,Q.jsx)(`code`,{children:y.key}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:W??Me,children:b||Ee===y.rotationId?Y(`api.copied`):Y(`api.copy`)}),G&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:G,children:Y(`common.close`)})]}),we&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:Y(`api.key.copyFailed`)})]}),(H||U)&&(0,Q.jsxs)(`div`,{className:`awi-detail-actions`,children:[H&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:be,onClick:()=>{Ne(`commit`)},children:Y(`api.rotation.commit`)}),U&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:be,onClick:()=>{Ne(`abort`)},children:Y(`api.rotation.abort`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:Y(`api.rotation.description`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:be,onClick:()=>{Ne(`start`)},children:Y(be?`api.rotation.starting`:`api.rotation.start`)})]}),Se&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:Y(`api.rotation.failed`)})]}),(0,Q.jsxs)(`div`,{className:`awi-section`,children:[(0,Q.jsx)(`h3`,{className:`awi-section-title`,children:Y(`api.attribution.title`)}),(0,Q.jsx)(gr,{data:o}),i?Oe.usage.ambiguous?(0,Q.jsx)(`p`,{className:`muted`,children:Y(`api.attribution.ambiguous`)}):(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:Y(`api.attribution.requests7d`)}),(0,Q.jsx)(`dd`,{children:Oe.usage.requests7d.toLocaleString(m)})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a||o?.usageIncomplete?Y(`api.attribution.totalRequestsAvailable`):Y(`api.attribution.totalRequests`)}),(0,Q.jsx)(`dd`,{children:Oe.usage.totalRequests.toLocaleString(m)})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:Y(`api.attribution.lastUsed`)}),(0,Q.jsx)(`dd`,{children:Oe.usage.lastUsedAt?JO(Oe.usage.lastUsedAt,m):Y(o?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:a||o?.usageIncomplete?Y(`api.attribution.sinceAvailable`):Y(`api.attribution.since`)}),(0,Q.jsx)(`dd`,{children:JO(i,m)})]})]}):(0,Q.jsx)(`p`,{className:`muted`,children:Y(`api.attribution.unavailableDetail`)})]})]})]}):(0,Q.jsx)(`div`,{className:`awi-overview`,children:(0,Q.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,Q.jsxs)(`div`,{id:iC(`api`,`keys`),className:`awi-section-anchor`,children:[(0,Q.jsx)(ik,{keys:e,keysLoading:c,keysLoadFailed:l,newName:h,creating:g,newKey:_,copied:v,confirmDelete:null,localeTag:m,showKeyList:!1,onNewNameChange:N,onCreate:P,onDismissNewKey:I,onCopyKey:L,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,Q.jsx)(Bk,{keys:e,keysLoading:c,keysLoadFailed:l,attributionSince:i,usageMetadata:o,localeTag:m,apiBase:t,active:n,onPairingStart:r,busy:je,onDelete:R,onReveal:z,onSelect:e=>{ie(e),Fe(),de(!1),_e(!1),ye(!1)}})]}),(0,Q.jsx)(`div`,{id:iC(`api`,`connect`),className:`awi-section-anchor`,children:(0,Q.jsx)(lk,{apiBase:t,baseUrl:u.baseUrl,hasKeys:e.length>0})}),(0,Q.jsx)(`div`,{id:iC(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,Q.jsx)(rk,{endpoints:u,claudeCodeEnabled:d,authMatrix:s,surfaces:f,apiBase:t,onSurfacesChanged:p})}),(0,Q.jsx)(`div`,{id:iC(`api`,`plan`),className:`awi-section-anchor`,children:(0,Q.jsx)(qy,{apiBase:t,models:S??x,protocolLabel:J},t)}),(0,Q.jsx)(`div`,{id:iC(`api`,`dictation`),className:`awi-section-anchor`,children:n&&(0,Q.jsx)(Qk,{audio:u.audio},`${t}:${JSON.stringify(u.audio)}`)}),(0,Q.jsx)(`div`,{id:iC(`api`,`live-voice`),className:`awi-section-anchor`,children:n&&(0,Q.jsx)($k,{audio:u.audio},`${t}:${JSON.stringify(u.audio)}`)}),(0,Q.jsx)(`div`,{id:iC(`api`,`models`),className:`awi-section-anchor`,children:(0,Q.jsx)(ak,{filteredModels:x,modelsLoading:C,modelsRefreshing:w,modelsLoadFailed:T,modelCount:E,hasModelData:D,modelQuery:k,copiedModelId:A,modelTests:j,claudeCodeEnabled:d,onModelQueryChange:ee,onCopyModelId:K,onTestModel:q,onRetryModels:te,canTestModels:M,sourceLabel:ne,protocolLabel:J})}),(0,Q.jsx)(`div`,{id:iC(`api`,`examples`),className:`awi-section-anchor`,children:(0,Q.jsx)(ok,{endpoints:u,claudeCodeEnabled:d})})]})})})})]})}var tA=[],nA=15e3;function rA(e){let t=e.replace(/\/$/,``);if(!t)return KO;try{return new URL(t).host?qO(`${t}/v1/responses`):KO}catch{return KO}}function iA(e){if(!e||!VO(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!zO(e.usage)||!aA(e.pendingRotation)))return null;if(e.surfaces!==void 0&&!WO(e.surfaces)){let{surfaces:t,...n}=e;e=n}if(e.endpoints?.audio!==void 0&&!GO(e.endpoints.audio,e.endpoints.baseUrl)){let{audio:t,...n}=e.endpoints;return{...e,endpoints:n}}return e}function aA(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 oA({apiBase:e,active:n=!0}){let{t:r,locale:i}=t(),a=k.find(e=>e.code===i)?.htmlLang,o=`ocx.apikeys.list.v2:${e}`,s=`ocx.apikeys.models.v1:${e}`,c=`api-keys:${e}`,l=`api-models:${e}`,u=za(o),d=za(s),f=iA(u?.data??null),p=d?.data??null,h=(0,Z.useRef)(e);(0,Z.useLayoutEffect)(()=>{h.current=e},[e]);let[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(``),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)({}),[E,D]=(0,Z.useState)(``),[O,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!1),B=(0,Z.useRef)(!1),V=RO(e,n,(0,Z.useCallback)(()=>{N(null),F(!1),L(null),z(!1)},[])),H=(0,Z.useCallback)(async t=>{let n=await gn(await fetch(`${e}/api/keys`,{signal:t}));if(!n||!VO(n.authMatrix))throw Error(r(`api.keysLoadFailed`));let i=n.keys??[];if(i.some(e=>!zO(e.usage)||!aA(e.pendingRotation)))throw Error(r(`api.keysLoadFailed`));let a=i,s=qO(n.endpoint??``),c=WO(n.surfaces),l={keys:a,endpoints:{baseUrl:n.baseUrl??s.baseUrl,responses:n.responsesEndpoint??n.endpoint??KO.responses,chatCompletions:n.chatCompletionsEndpoint??s.chatCompletions,messages:n.messagesEndpoint??s.messages,models:n.modelsEndpoint??s.models,...GO(n.audio,n.baseUrl??s.baseUrl)?{audio:n.audio}:{}},claudeCodeEnabled:n.claudeCodeEnabled!==!1,...c?{surfaces:c}:{},...n.attributionSince?{attributionSince:n.attributionSince}:{},...n.historyTruncated===!0?{historyTruncated:!0}:{},...dr(n),authMatrix:n.authMatrix};return t.aborted||Ba(o,l),l},[e,o,r]),U=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/v1/models`,{signal:t});if(!n.ok)throw Error(r(`api.modelsLoadFailed`));let i=await n.json(),a=Array.isArray(i)?i:typeof i==`object`&&i&&Array.isArray(i.data)?i.data:null;if(!a)throw Error(r(`api.modelsLoadFailed`));let o=a.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`).map(e=>IO(e)).sort((e,t)=>LO(e).localeCompare(LO(t)));return Ba(s,o),o},[e,s,r]),W=Ua(c,[e],H,{isEmpty:e=>e.keys.length===0,initialData:f??void 0,initialDataCachedAt:u?.cachedAt??null,staleAfterMs:6e4,enabled:n}),G=Ua(l,[e],U,{isEmpty:e=>e.length===0,initialData:p??void 0,initialDataCachedAt:d?.cachedAt??null,staleAfterMs:6e4,enabled:n}),ee=W.state,K=G.state,q=ee.data??f,te=K.data??p??tA,ne=q?.keys??[],J=q?.endpoints??rA(e),Y=q?.claudeCodeEnabled??!0,re=q?.surfaces,ie=q?.attributionSince,X=q?.historyTruncated===!0,ae=q?.authMatrix??[],oe=W.refresh,se=G.refresh,ce=(0,Z.useMemo)(()=>{let e=b.trim().toLowerCase();return e?te.filter(t=>LO(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):te},[b,te]),le=async t=>{let n=V.generation.current;if(B.current)return!1;B.current=!0,j(!0),y(null),_(null);try{let i=t??E,a=await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:i||`default`})});a.ok&&(h.current===e?oe():Ht(c));let o=await hn(a,r(`api.createFailed`));return V.current(n)?typeof o?.key!=`string`||o.key.length===0?(y(r(`api.createFailed`)),!1):(N(o.key),D(``),!0):(_(e),!0)}catch{return y(r(`api.createFailed`)),!1}finally{B.current=!1,j(!1)}},ue=async t=>{y(null);let n=A(nA);try{return(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal})).ok?(oe(),!0):!1}catch{return!1}finally{n.clear()}},de=async t=>{let n=A(nA);try{let r=await fetch(`${e}/api/keys/reveal`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal,cache:`no-store`});if(r.status===401||r.status===403)return{ok:!1,kind:`denied`};if(!r.ok)return{ok:!1,kind:`failed`};let i=await r.json();return typeof i.key==`string`&&i.key?{ok:!0,key:i.key}:{ok:!1,kind:`failed`}}catch{return{ok:!1,kind:`failed`}}finally{n.clear()}},fe=async(t,n)=>{y(null);let r=A(nA);try{return(await fetch(`${e}/api/keys`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,name:n}),signal:r.signal})).ok?(oe(),!0):!1}catch{return!1}finally{r.clear()}},pe=async t=>{let n=V.generation.current;y(null),_(null);let i=A(nA);try{let a=await fetch(`${e}/api/keys/rotate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:i.signal});a.ok&&(h.current===e?oe():Ht(c));let o=await hn(a,r(`api.rotation.startFailed`));return V.current(n)?!o||typeof o.key!=`string`||!o.key||typeof o.rotationId!=`string`||!o.rotationId?!1:(L({id:t,key:o.key,rotationId:o.rotationId}),!0):(_(e),!0)}catch{return!1}finally{i.clear()}},me=async(t,n,r)=>{y(null);let i=A(nA);try{return(await fetch(`${e}${r===`commit`?`/api/keys/rotate/commit`:`/api/keys/rotate`}`,{method:r===`commit`?`POST`:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,rotationId:n}),signal:i.signal})).ok?(L(e=>e?.id===t?null:e),oe(),!0):!1}catch{return!1}finally{i.clear()}},he=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)&&y(r(`api.key.copyFailed`))}},ge=async()=>{if(!M)return;let e=V.generation.current;y(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),y(r(`api.key.copyFailed`))}},_e=async e=>{try{await navigator.clipboard.writeText(e),C(e),window.setTimeout(()=>C(t=>t===e?null:t),2e3)}catch{}},ve=e=>e.native?r(`api.sourceNative`):e.provider===`combo`?r(`api.sourceCombo`):e.custom?r(`api.sourceCustom`):be(e.provider,r),ye=e=>r(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),xe=(e,t)=>e===`responses`?{url:J.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:J.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:J.chatCompletions,body:{model:t,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1}},Se=(e,t,n)=>T(r=>({...r,[e]:{...r[e],[t]:n}})),Ce=async(e,t)=>{if(!M)return;let n=LO(e),i=xe(t,n);Se(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();Se(n,t,{state:`error`,detail:r.slice(0,160)||String(e.status)});return}Se(n,t,{state:`ok`})}catch(e){Se(n,t,{state:`error`,detail:e instanceof Error?e.message:r(`api.testFailed`)})}},we=r(`api.subtitle`).split(`{authHeader}`);return(0,Q.jsxs)(`section`,{className:`api-page`,"aria-busy":ee.refreshing||K.refreshing||void 0,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`api.title`)})}),(0,Q.jsxs)(`p`,{className:`page-sub`,children:[we[0],(0,Q.jsx)(`code`,{children:`x-opencodex-api-key`}),we[1]]}),g===e&&(0,Q.jsx)($,{tone:`warn`,children:r(`api.key.mutationHidden`)}),v&&(0,Q.jsx)($,{tone:`err`,children:v}),ee.showError&&q&&(0,Q.jsx)($,{tone:`err`,children:r(`api.keysLoadFailed`)}),ee.showSkeleton&&!q?(0,Q.jsx)(my,{label:r(`api.activeKeysLoading`),rows:4}):ee.kind===`failed-cold`&&!q?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:ee.error instanceof Error?ee.error.message:r(`api.keysLoadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>oe(),children:r(`common.retry`)})]}):(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(eA,{active:n,onPairingStart:()=>V.invalidate(),keys:ne,apiBase:e,attributionSince:ie,historyTruncated:X,usageMetadata:dr(q),authMatrix:ae,keysLoading:!1,keysLoadFailed:ee.showError,endpoints:J,claudeCodeEnabled:Y,surfaces:re,onSurfacesChanged:()=>{oe()},localeTag:a,newName:E,creating:O,newKey:M,copied:P,rotationSecret:I,rotationCopied:R,filteredModels:ce,planModels:te,modelsLoading:K.showSkeleton&&!K.data&&!p,modelsRefreshing:K.refreshing&&K.showError&&(K.data!==void 0||p!==null),modelsLoadFailed:K.showError,modelCount:te.length,hasModelData:K.data!==void 0||p!==null,modelQuery:b,copiedModelId:S,modelTests:w,onNewNameChange:D,onCreate:()=>{le()},onDismissNewKey:()=>N(null),onCopyKey:()=>{ge()},onDelete:ue,onRevealKey:de,onRename:fe,...m()?{onRotationStart:pe,onRotationCommit:(e,t)=>me(e,t,`commit`),onRotationAbort:(e,t)=>me(e,t,`abort`),onCopyRotationSecret:()=>{he()},onDismissRotationSecret:()=>L(null)}:{},onModelQueryChange:x,onCopyModelId:e=>{_e(e)},onTestModel:(e,t)=>{Ce(e,t)},onRetryModels:()=>{se({forceLoading:!0})},canTestModels:M!==null,sourceLabel:ve,protocolLabel:ye},e)})]})}var sA=[`none`,`live`,`stopped`,`disabled`,`broken`,`foreign`,`local`,`unknown`];function cA(e){return e===void 0?`none`:sA.find(t=>t===e)??`unknown`}function lA(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 uA(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 dA=`failed`;function fA({apiBase:e,reason:t,port:n,onStarted:r}){let i=O(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=async()=>{if(!a){o(!0),c(null);try{let t=await fetch(`${e}/api/claude-intercept/start`,{method:`POST`}),n=await t.json();!t.ok||!n.ok?c({reason:n.reason??dA,port:n.port}):r()}catch{c({reason:dA})}finally{o(!1)}}};return(0,Q.jsxs)(`span`,{role:`status`,children:[i(uA(s?.reason??t),{port:s?.port??n??``}),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:a,onClick:()=>void l(),children:i(a?`claude.intercept.starting`:`claude.intercept.start`)})]})}function pA(e){let[t,n]=(0,Z.useState)(!1),r=(0,Z.useRef)(!1);return{pending:t,change:async(t,i,a)=>{if(!r.current){r.current=!0,n(!0);try{i((await ey(e,`claude`,t)).desiredEnabled)}catch(e){a(e)}finally{r.current=!1,n(!1)}}}}}function mA(e,t){let n=(e??[]).map(e=>({value:e,label:q_(e)}));return[{value:``,label:t},...n]}function hA(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}function gA(){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 _A=829800;function vA(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 yA(e){return e===`200k`?`200k`:`1m`}var bA=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`],xA=/\[1m\]$/i,SA={ANTHROPIC_DEFAULT_OPUS_MODEL:`claude-opus-5-5`,ANTHROPIC_DEFAULT_SONNET_MODEL:`claude-sonnet-5`,ANTHROPIC_DEFAULT_FABLE_MODEL:`claude-fable-5-1`};function CA(e){return e.replace(xA,``)}function wA(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 TA(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 bA){let n=e.effectiveModelEnv[t];if(!n)continue;if(!r){if(SA[t]===CA(n))continue;i[t]=CA(n);continue}let a=wA(e,t);a&&(i[t]=xA.test(a)?n:CA(n))}return i}function EA(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=TA(e),s=bA.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(`
|
|
53
|
+
`)}function DA(e){return e?e.backend??`auto`:`inherit`}function OA(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 kA(e,t){let n={...e};return t===`anthropic`||t===`anthropic2`?n.anthropicInstance=t:n.anthropicInstance!==void 0&&(n.anthropicInstance=null),n}function AA(e,t){return{...e,model:t}}function jA(e){if(!e)return null;let t=(e.model??``).trim();return e.backend?{backend:e.backend,model:t,...e.anthropicInstance===void 0?{}:{anthropicInstance:e.anthropicInstance}}:!t&&e.anthropicInstance===void 0?null:{backend:null,model:t,...e.anthropicInstance===void 0?{}:{anthropicInstance:e.anthropicInstance}}}function MA({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function NA({supported:e,checked:t,onChange:n}){let r=O(),i=e?void 0:`claude-system-env-unsupported`;return(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,Q.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,Q.jsx)(`span`,{className:`desc`,id:i,children:(0,Q.jsx)(T,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,Q.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,Q.jsx)(MA,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function PA({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=O(),a=t??e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,Q.jsx)(cn,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,Q.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function FA(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 IA({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=O();return(0,Q.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(cn,{value:e.authMode,options:[{value:`auto`,label:i(`claude.authModeAuto`)},{value:`subscription`,label:i(`claude.authModeSubscription`)},{value:`proxy`,label:i(`claude.authModeProxy`)}],onChange:t=>r({...e,authMode:t}),label:i(`claude.authMode`),style:{minWidth:220},align:`right`,portal:!0})})]}),e.authModeOrigin&&(0,Q.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,Q.jsxs)(`span`,{children:[e.authModeOrigin===`manual`?i(`claude.effectiveMode.manual`,{mode:e.markerMode===`proxy`?i(`claude.authModeProxy`):i(`claude.authModeSubscription`)}):e.authModeOrigin===`auto-present`?i(`claude.effectiveMode.autoPresent`,{source:FA(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,Q.jsx)(NA,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(cn,{value:e.fastMode===null?`auto`:e.fastMode?`on`:`off`,options:[{value:`auto`,label:i(`claude.fastAuto`)},{value:`on`,label:i(`claude.fastOn`)},{value:`off`,label:i(`claude.fastOff`)}],onChange:t=>r({...e,fastMode:t===`auto`?null:t===`on`}),label:i(`claude.fastMode`),style:{minWidth:140},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.contextAccounting`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.contextAccountingDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(cn,{value:e.contextAccounting,options:[{value:`1m`,label:i(`claude.contextAccounting1m`)},{value:`200k`,label:i(`claude.contextAccounting200k`)}],onChange:t=>r({...e,contextAccounting:t===`200k`?`200k`:`1m`}),label:i(`claude.contextAccounting`),style:{minWidth:140},align:`right`,portal:!0})})]}),e.contextAccounting===`1m`&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,Q.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,Q.jsx)(MA,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.contextAccounting===`1m`&&e.autoContext&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,Q.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(cn,{value:e.autoCompactWindow===null?``:String(e.autoCompactWindow),options:t,onChange:t=>r({...e,autoCompactWindow:t===``?null:Number(t)}),label:i(`claude.autoCompactWindow`),style:{minWidth:130},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,Q.jsx)(MA,{label:i(`claude.injectAgents`),checked:e.injectAgents,onChange:t=>r({...e,injectAgents:t})})]}),[`webSearchSidecar`,`visionSidecar`].map(t=>{let a=e[t],o=t===`webSearchSidecar`?`claude.webSearchSidecar`:`claude.visionSidecar`,s=t===`webSearchSidecar`?`claude.webSearchSidecarHint`:`claude.visionSidecarHint`,c=`claude-sidecar-models-${t}`,l=a?.backend??e.sidecarPools?.[t]?.backend;return(0,Q.jsxs)(`div`,{className:`setting-row claudecode-sidecar-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label setting-copy`,children:[(0,Q.jsx)(`span`,{className:`title`,children:i(o)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,Q.jsxs)(`div`,{className:`setting-controls`,children:[(0,Q.jsx)(cn,{value:DA(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]:OA(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,Q.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:AA(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),autoComplete:`off`}),a&&(0,Q.jsx)(`datalist`,{id:c,children:n.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),l===`anthropic`&&(0,Q.jsx)(cn,{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]:kA(a,n)}),portal:!0}),l===`anthropic`&&a?.anthropicInstance&&e.sidecarPools?.[t]?.parent&&a.anthropicInstance!==e.sidecarPools[t].parent&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:i(`sidecar.poolMixed`)})]})]},t)})]})}function LA({manualEnv:e}){let t=O();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,Q.jsx)(T,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,Q.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,Q.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,Q.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function RA({rows:e,onRowsChange:t}){let n=O();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),e.length>0&&(0,Q.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,Q.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,Q.jsx)(`input`,{className:`input mono`,value:r.from,placeholder:n(`claude.mapFrom`),"aria-label":n(`claude.mapFrom`),onChange:n=>t(e.map((e,t)=>t===i?{...e,from:n.target.value}:e)),style:{flex:1}}),(0,Q.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,Q.jsx)(`input`,{className:`input mono`,value:r.to,placeholder:n(`claude.mapTo`),"aria-label":n(`claude.mapTo`),onChange:n=>t(e.map((e,t)=>t===i?{...e,to:n.target.value}:e)),style:{flex:1}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>t(e.filter((e,t)=>t!==i)),"aria-label":n(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,Q.jsx)(ve,{})})]},r.id))}),(0,Q.jsx)(`div`,{style:{marginTop:e.length>0?8:0},children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:gA(),from:``,to:``}]),children:[(0,Q.jsx)(N,{}),` `,n(`claude.addMapping`)]})})]})}var zA=`etc`;function BA(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:zA,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function VA({aliases:e}){let t=O();return(0,Q.jsxs)(`div`,{className:`claude-aliases`,children:[(0,Q.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,Q.jsx)(`div`,{className:`claude-aliases-scroll`,children:BA(e).map(([e,n])=>(0,Q.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,Q.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===zA?t(`claude.aliasProviderOther`):e,(0,Q.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,Q.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,Q.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,Q.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,Q.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}var HA=[`opus`,`sonnet`,`haiku`,`fable`];function UA({state:e,options:t,onChange:n,apiBase:r,dirty:i}){let a=O(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(``),g=t.map(e=>e.value===``?{...e,label:a(`claude.tierDefaults.unset`)}:e);async function _(e){l(!0),d(``),p(!1),h(``);try{let t=await fetch(`${r}/api/claude-code/model-defaults`,e?{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({fingerprint:o?.fingerprint})}:void 0);if(!t.ok){let e=await t.json();if(e.code===`settings_recovery_required`){s(null),p(!0),d(a(`claude.tierDefaults.recovery`)),typeof e.backupPath==`string`&&h(e.backupPath);return}throw Error(`apply_refused`)}let n=await hn(t);e?(s(null),d(a(`claude.tierDefaults.applied`))):s(n)}catch{s(null),p(!0),d(a(`claude.tierDefaults.failed`))}finally{l(!1)}}return(0,Q.jsxs)(Q.Fragment,{children:[HA.map(t=>{let r=e.tierModels?.[t]??``,i=r&&!g.some(e=>e.value===r)?[...g,{value:r,label:r}]:g;return(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsx)(`span`,{className:`setting-label`,children:a(`claudeDesktop.family.${t}`)}),(0,Q.jsx)(cn,{value:r,options:i,label:a(`claudeDesktop.family.${t}`),onChange:r=>{s(null),n({...e,tierModels:{...e.tierModels,[t]:r}})}})]},t)}),(0,Q.jsxs)(`div`,{className:`btn-row`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:c||i,onClick:()=>void _(!1),children:[(0,Q.jsx)(De,{}),` `,a(`claude.tierDefaults.preview`)]}),o&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:c||i||!o.changes.length,onClick:()=>void _(!0),children:[(0,Q.jsx)(Te,{}),` `,a(`claude.tierDefaults.apply`)]})]}),o&&(0,Q.jsx)(`pre`,{children:o.changes.length?o.changes.map(e=>`${e.key}\n${e.before??`-`} -> ${e.after}`).join(`
|
|
54
|
+
|
|
55
|
+
`):a(`claude.tierDefaults.applied`)}),u&&(0,Q.jsx)(`p`,{role:f?`alert`:`status`,children:u}),m&&(0,Q.jsx)(`pre`,{children:m})]})}var WA=[`authMode`,`systemEnv`,`fastMode`,`autoContext`,`autoCompactWindow`,`contextAccounting`,`injectAgents`,`smallFastModel`,`tierModels`,`webSearchSidecar`,`visionSidecar`];function GA(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 KA(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:GA(t),webSearchSidecar:jA(e.webSearchSidecar),visionSidecar:jA(e.visionSidecar)}}function qA(e){return JSON.stringify([KA(e.state,e.rows),e.rows.map(e=>[e.from,e.to])])}function JA(e,t){return qA(e)!==qA(t)}function YA(e){return Object.fromEntries(WA.map(t=>[t,e[t]]))}function XA(e,t){return{...t,...YA(e)}}function ZA(e,t){return{...e,...YA(t)}}function QA(e,t){return!e||e.adoptNextRead||!e.savePending&&!JA(e.draft,e.baseline)?{draft:t,baseline:t,adoptNextRead:!1,savePending:e?.savePending}:{draft:{state:XA(e.draft.state,t.state),rows:e.draft.rows},baseline:t,adoptNextRead:!1,savePending:e.savePending}}function $A(e,t){return{state:{...e,...YA(t.state)},rows:Object.entries(GA(t.rows)).map(([e,t])=>({id:gA(),from:e,to:t}))}}function ej(e,t){if(!e)return e;let n=$A(e.baseline.state,t),r=n.rows,i=qA(e.draft)===qA(t);return{draft:i?{state:e.draft.state,rows:r}:e.draft,baseline:n,adoptNextRead:i}}function tj(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:cA(e.sharedProxy),contextAccounting:yA(e.contextAccounting),servedContextAccounting:yA(e.servedContextAccounting??e.contextAccounting)}}var nj=new Map,rj=e=>nj.get(e)??0,ij=e=>{nj.set(e,rj(e)+1)},aj=Symbol(`claude-code-live`),oj=new Map;function sj(e,t,n){for(let r of oj.get(e)??[])r(t,n)}var cj={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 lj({title:e,count:t,children:n}){let r=(0,Z.useId)();return(0,Q.jsxs)(`section`,{className:`ccw-section`,"aria-labelledby":r,children:[(0,Q.jsxs)(`h3`,{className:`ccw-section-title`,id:r,children:[e,t==null?null:(0,Q.jsx)(`span`,{className:`count`,children:t})]}),n]})}function uj({apiBase:e,active:n=!0}){let r=O(),{locale:i}=t(),a=k.find(e=>e.code===i)?.htmlLang??`en`,o=`ocx.claude-code.v1:${e}`,s=`claude-code:${e}`,c=(0,Z.useMemo)(()=>za(o),[o]),l=(0,Z.useMemo)(()=>c?.data?{...c.data,state:tj(c.data.state)}:null,[c]),[u,d]=(0,Z.useState)(()=>l?{draft:l,baseline:l,adoptNextRead:!1}:null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(!1),{pending:b,change:x}=pA(e),[S,C]=(0,Z.useState)(!1),w=(0,Z.useRef)(!1),T=(0,Z.useCallback)(async t=>{let n=rj(o),i=await hn(await fetch(`${e}/api/claude-code`,{signal:t}),r(`claude.loadFail`));if(!i)throw Error(r(`claude.loadFail`));let a={state:tj({...i,authMode:i.authMode===`proxy`||i.authMode===`subscription`?i.authMode:`auto`,...hA(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:gA(),from:e,to:String(t)}))};if(t.aborted)throw Error(`Claude Code request aborted`);return n===rj(o)?(Ba(o,a),a):{...a,superseded:!0}},[e,o,r]),E=Ua(s,[e],T,{isEmpty:()=>!1,enabled:n,initialData:l??void 0,initialDataCachedAt:c?.cachedAt??null,staleAfterMs:6e4}),D=E.state,[A,j]=(0,Z.useState)(D.data);if(D.data!==A){j(D.data);let e=D.data;e&&!e.superseded&&d(t=>QA(t,{state:e.state,rows:e.rows}))}let M=D.data??l,N=u?.draft.state??M?.state??null,P=u?.draft.rows??M?.rows??[],F=u!==null&&JA(u.draft,u.baseline),I=e=>{d(t=>t&&{...t,draft:{...t.draft,state:e},adoptNextRead:!1})},L=e=>{d(t=>t&&{...t,draft:{...t.draft,rows:e},adoptNextRead:!1})},R=e=>{let t=za(o)?.data;t&&Ba(o,{...t,state:{...t.state,...e}}),sj(o,{kind:`live`,fields:e},aj)},[z]=(0,Z.useState)(()=>Symbol(`claude-code-page`));(0,Z.useEffect)(()=>{let e=(e,t)=>{if(e.kind===`live`){let{fields:t}=e;d(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;d(e=>QA(e,t))}},t=oj.get(o)??new Set;return t.add(e),oj.set(o,t),()=>{t.delete(e)}},[o,z]);let B=(0,Z.useMemo)(()=>mA(N?.available,r(`claude.smallFastModelUnsetOption`)),[N?.available,r]),V=(0,Z.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,_A,9e5,1e6].sort((e,t)=>e-t),t=N?.autoCompactWindow??null,n=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:r(`claude.autoCompactDefault`,{value:vA(_A,a)})},...n.map(e=>({value:String(e),label:vA(e,a)}))]},[N?.autoCompactWindow,r,a]),H=async()=>{N&&(_(``),await x(!N.enabled,e=>{ij(o),R({enabled:e}),E.refresh()},e=>{y(!1),_(e instanceof Error&&e.message?e.message:r(`claude.networkError`))}))},U=async()=>{if(!N||w.current)return;w.current=!0,C(!0),_(``);let t=!N.cliFirstParty;try{let n=await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cliFirstParty:t})});if(!n.ok){let e=await n.json().catch(()=>null),t={intercept_disabled:`claude.firstParty.refusal.interceptDisabled`,intercept_unavailable:`claude.firstParty.refusal.interceptUnavailable`,foreign_env:`claude.firstParty.refusal.foreignEnv`,ca_unavailable:`claude.firstParty.refusal.caUnavailable`,unreadable:`claude.firstParty.refusal.unreadable`,write_failed:`claude.firstParty.refusal.writeFailed`},i=e?.code&&e.code in t?t[e.code]:`claude.saveFailed`;throw Error(e?.code&&[`disabled`,`client_role`,`ephemeral_port`,`port_in_use`,`port_mismatch`,`stopped`,`failed`].includes(e.code)?r(uA(e.code),{port:e.port??``,bound:e.bound??``,configured:e.configured??``}):r(i))}await hn(n,r(`claude.saveFailed`)),ij(o),R({cliFirstParty:t}),E.refresh()}catch(e){y(!1),_(e instanceof Error&&e.message?e.message:r(`claude.networkError`))}finally{w.current=!1,C(!1)}},W=async()=>{if(!N||!u||f)return;let t=u.draft;_(``),h(``),p(!0),d(e=>e&&{...e,savePending:!0}),ij(o);try{await hn(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(KA(t.state,t.rows))}),r(`claude.saveFailed`)),ij(o);let n=za(o)?.data,i=$A(n?.state??t.state,t);Ba(o,i),sj(o,{kind:`saved`,copy:i},z),d(e=>ej(e,t)),y(!0),h(``),_(r(`claude.saved`)),E.refresh()}catch(e){d(e=>e&&{...e,savePending:!1}),y(!1),h(e instanceof Error&&e.message?e.message:r(`claude.networkError`))}finally{p(!1)}},G=()=>{_(``),h(``),d(e=>e&&{draft:{state:ZA(e.draft.state,e.baseline.state),rows:e.baseline.rows},baseline:e.baseline,adoptNextRead:!1})};if(D.kind===`disabled`&&!M)return null;if(D.showSkeleton&&!M)return(0,Q.jsx)(my,{label:r(`claude.loading`),rows:3});if(D.kind===`failed-cold`){let e=D.error instanceof Error?D.error.message:r(`claude.loadFail`);return(0,Q.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E.refresh(),children:r(`common.retry`)})]})}if(!N)return null;let ee=(0,Q.jsxs)(`div`,{className:`setting-row claudecode-connection-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`claudecode-connection-label`,children:r(`claude.enabledLabel`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claude.subtitle`)})]}),(0,Q.jsx)(on,{on:N.enabled,onClick:()=>void H(),disabled:b,label:r(`claude.toggleAria`)})]});return(0,Q.jsxs)(`div`,{className:`claudecode-workspace-shell claudecode-doc`,children:[g&&(0,Q.jsx)($,{tone:v?`ok`:`err`,children:g}),D.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`claude.loadFail`)}),(0,Q.jsx)(`div`,{className:`card claudecode-connection-card`,children:(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`claudecode-first-party-label`,children:r(`claude.firstParty.label`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claude.firstParty.desc`)})]}),(0,Q.jsx)(on,{on:N.cliFirstParty,onClick:()=>void U(),disabled:S,label:r(`claude.firstParty.aria`)})]})}),!N.interceptRunning&&(0,Q.jsx)(fA,{apiBase:e,reason:N.interceptReason,port:N.interceptFailurePort,onStarted:()=>E.refresh()}),N.cliFirstParty&&(0,Q.jsx)($,{tone:`warn`,children:r(`claude.firstParty.risk`)}),(()=>{let e=lA(N),t=e&&cj[e];return t?(0,Q.jsx)($,{tone:`warn`,children:r(t)}):null})(),(0,Q.jsx)(lj,{title:r(`claude.quickstart`),children:(0,Q.jsx)(LA,{manualEnv:EA(N)})}),(0,Q.jsx)(lj,{title:r(`claude.workspace.settings`),children:(0,Q.jsx)(IA,{state:N,autoCompactOptions:V,availableModels:N.available??[],onStateChange:I})}),(0,Q.jsx)(lj,{title:r(`claude.tierDefaults.title`),children:(0,Q.jsx)(UA,{state:N,options:B,onChange:I,apiBase:e,dirty:!!u&&JA(u.draft,u.baseline)})}),(0,Q.jsx)(lj,{title:r(`claude.smallFastModel`),children:(0,Q.jsx)(PA,{value:N.smallFastModel,tierHaikuModel:N.tierModels?.haiku,options:B,onChange:e=>I({...N,smallFastModel:e})})}),(0,Q.jsx)(lj,{title:r(`claude.modelMap`),count:P.length,children:(0,Q.jsx)(RA,{rows:P,onRowsChange:L})}),(0,Q.jsx)(lj,{title:r(`claude.aliases`),count:N.aliases.length,children:(0,Q.jsx)(VA,{aliases:N.aliases})}),(0,Q.jsx)(`div`,{className:`card claudecode-master-card`,children:ee}),(0,Q.jsxs)(`div`,{className:`ccw-savebar`,role:`region`,"aria-label":r(`claude.saveBar.label`),children:[m&&(0,Q.jsx)(`span`,{className:`ccw-savebar-error`,role:`alert`,children:m}),(0,Q.jsx)(`span`,{className:`ccw-savebar-state${F?` dirty`:``}`,"aria-live":`polite`,"aria-atomic":`true`,children:r(F?`claude.saveBar.dirty`:`claude.saveBar.clean`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!F||f,onClick:G,children:r(`claude.saveBar.revert`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:f,onClick:()=>{W()},children:r(`common.save`)})]})]})}function dj({apiBase:e,active:t=!0,embedded:n=!1}){let r=O();return(0,Q.jsxs)(`section`,{className:`claude-page${n?` claude-page--embedded`:``}`,children:[!n&&(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`nav.claude`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`claude.pageSub`)}),(0,Q.jsx)(uj,{apiBase:e,active:t},e)]})}function fj(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 pj(e){return new Set(Object.keys(e))}function mj(e,t){return t!==null&&e===t}function hj(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function gj(e){return{read(t){let n=hj(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=hj(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function _j(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function vj(e){return e.label||e.route}function yj({apiBase:e,bindings:n,suggestions:r,models:i,onSaved:a}){let{t:o}=t(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),h=(0,Z.useMemo)(()=>i.filter(e=>e.available),[i]),g=(0,Z.useMemo)(()=>new Set(Object.keys(n)),[n]),_=(0,Z.useMemo)(()=>r.filter(e=>!g.has(e)),[r,g]),v=(0,Z.useMemo)(()=>Object.entries(n).sort(([e],[t])=>e.localeCompare(t)),[n]),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 hn(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(``),a(n.modelBindings)}catch(e){m(e instanceof Error?e.message:o(`claudeDesktop.firstParty.bindings.saveFailed`))}finally{f(null)}}};return(0,Q.jsxs)(`section`,{className:`claude-bindings`,"aria-labelledby":`claude-bindings-title`,children:[(0,Q.jsx)(`h3`,{id:`claude-bindings-title`,className:`claude-bindings-title`,children:o(`claudeDesktop.firstParty.bindings.title`)}),(0,Q.jsx)(`p`,{className:`claude-bindings-hint`,children:o(`claudeDesktop.firstParty.bindings.hint`)}),p&&(0,Q.jsx)($,{tone:`err`,children:p}),v.length===0?(0,Q.jsx)(`p`,{className:`claude-bindings-empty`,children:o(`claudeDesktop.firstParty.bindings.empty`)}):(0,Q.jsx)(`ul`,{className:`claude-bindings-list`,children:v.map(([e,t])=>{let n=h.some(e=>e.route===t);return(0,Q.jsxs)(`li`,{className:`claude-bindings-row`,children:[(0,Q.jsx)(`code`,{className:`claude-bindings-id`,title:e,children:e}),(0,Q.jsx)(Ke,{className:`claude-bindings-arrow`,width:12,height:12,"aria-hidden":`true`}),(0,Q.jsxs)(`select`,{className:`input claude-bindings-select`,"aria-label":o(`claudeDesktop.firstParty.bindings.routeLabel`),value:t,disabled:d!==null,onChange:t=>void x({set:{[e]:t.target.value}},e),children:[!n&&(0,Q.jsx)(`option`,{value:t,children:t}),h.map(e=>(0,Q.jsx)(`option`,{value:e.route,children:vj(e)},e.route))]}),(0,Q.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,Q.jsx)(ve,{width:12,height:12,"aria-hidden":`true`})})]},e)})}),(0,Q.jsxs)(`div`,{className:`claude-bindings-add`,children:[(0,Q.jsx)(`input`,{className:`input claude-bindings-input`,type:`text`,list:`claude-bindings-suggestions`,"aria-label":o(`claudeDesktop.firstParty.bindings.pickerLabel`),placeholder:o(`claudeDesktop.firstParty.bindings.pickerPlaceholder`),value:s,disabled:d!==null,onChange:e=>c(e.target.value)}),(0,Q.jsx)(`datalist`,{id:`claude-bindings-suggestions`,children:_.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),(0,Q.jsxs)(`select`,{className:`input claude-bindings-select`,"aria-label":o(`claudeDesktop.firstParty.bindings.routeLabel`),value:l,disabled:d!==null,onChange:e=>u(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:o(`claudeDesktop.firstParty.bindings.routePlaceholder`)}),h.map(e=>(0,Q.jsx)(`option`,{value:e.route,children:vj(e)},e.route))]}),(0,Q.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 bj(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 xj(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 Sj({apiBase:e,picker:n,onUpdated:r,pickerReason:i,pickerFailurePort:a}){let{t:o}=t(),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=s??n,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})}),n;if(t.ok)n=await hn(t,o(`claudeDesktop.updateFailed`));else{try{n=await t.json()}catch{throw Error(o(`claudeDesktop.updateFailed`))}if(!n.picker)throw Error(o(uA(n.reason),{port:n.port??``}))}if(!n||n.ok!==!0&&!n.picker||!n.picker||!bj(n.picker))throw Error(o(`claudeDesktop.updateFailed`));c(n.picker),r?.(n.picker)}catch(e){f(e instanceof Error?e.message:o(`claudeDesktop.updateFailed`))}finally{u(!1)}}};return(0,Q.jsxs)(`section`,{className:`claude-picker`,"aria-labelledby":`claude-picker-title`,children:[!p.listenerReady&&i&&(0,Q.jsx)(`span`,{role:`status`,children:o(uA(i===`port_in_use`&&!a?`failed`:i),{port:a??``})}),!p.listenerReady&&!i&&(0,Q.jsx)(fA,{apiBase:e,onStarted:()=>{c(null),r?.(p)}}),(0,Q.jsxs)(`div`,{className:`claude-picker-header`,children:[(0,Q.jsxs)(`div`,{className:`claude-picker-copy`,children:[(0,Q.jsx)(`h3`,{id:`claude-picker-title`,className:`claude-picker-title`,children:o(`claudeDesktop.picker.title`)}),(0,Q.jsx)(`p`,{className:`claude-picker-hint`,children:o(`claudeDesktop.picker.hint`)})]}),(0,Q.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,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),(0,Q.jsxs)(`p`,{className:`claude-picker-state claude-picker-state-${p.reason}`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`claude-picker-state-dot`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:o(xj(p.reason))}),p.reason===`trust_pending`&&p.hint&&(0,Q.jsx)(`code`,{children:p.hint})]}),(0,Q.jsx)(`p`,{className:`claude-picker-models`,children:o(`claudeDesktop.picker.models`,{count:p.models})}),(0,Q.jsx)(`p`,{className:`claude-picker-offline-note`,role:`note`,children:o(`claudeDesktop.picker.offlineNote`)})]})}var Cj=[`opus`,`fable`,`sonnet`,`haiku`];function wj(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 Tj(e,t){let n=Object.fromEntries(Cj.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 Cj){let i=n[e].toSorted(),a=t.defaults[e];r[e]=a&&i.includes(a)?a:i[0]??null}return r}function Ej(e,t,n){return e.filter(e=>(t.assignments[e.route]?.family??`opus`)===n).length}function Dj(e,t,n){return e.defaults[n]??t[n]??``}function Oj(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 kj(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 Aj=gj(`ocx.claudeDesktop.collapsedFamilies.v2`),jj=[`first-party`,`gateway`];function Mj(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 Nj(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.health;if(t.mode!==void 0&&!jj.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&&!Mj(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 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 Pj={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function Fj(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 Ij(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:Cj.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 Lj(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}var Rj=`route`;function zj({route:e,t}){let[n=``,r=``]=t(`claudeDesktop.roles.unavailableOption`,{route:Rj}).split(Rj);return(0,Q.jsxs)(`span`,{className:`claude-role-option`,children:[n&&(0,Q.jsx)(`span`,{className:`claude-role-option__status`,children:n}),(0,Q.jsx)(`span`,{className:`claude-role-option__route`,children:e}),r&&(0,Q.jsx)(`span`,{className:`claude-role-option__status`,children:r})]})}function Bj(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 Vj(e){return za(e)?.data??null}function Hj(e){return za(e)?.cachedAt??null}function Uj(e){let t=Vj(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?Fj(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function Wj({apiBase:e,active:n=!0}){let{t:r,locale:i}=t(),a=k.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,Z.useMemo)(()=>Uj(o),[o]),[l,u]=(0,Z.useState)(()=>c.profile),[d,f]=(0,Z.useState)(()=>c.savedProfile),[p,m]=(0,Z.useState)(()=>c.destinations),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)({}),[C,w]=(0,Z.useState)({}),[T,E]=(0,Z.useState)(()=>Aj.read()??new Set(Cj)),[D,O]=(0,Z.useState)({}),[A,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(6),[P,F]=(0,Z.useState)(null),I=(0,Z.useRef)(null),L=(0,Z.useCallback)(async t=>{let n=await hn(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(Lj(n,r(`claudeDesktop.loadFail`)));let i=Ij(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f(Fj(i)),m(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),Aj.read()===null){let e=Object.fromEntries(Cj.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;E(pj(e))}return Ba(o,a),a},[e,o,r,m,u,f]),R=Ua(s,[e],L,{isEmpty:()=>!1,enabled:n,initialData:c.held??void 0,initialDataCachedAt:Hj(o),staleAfterMs:6e4}),z=R.state,B=z.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),V=B?.data??null,H=l??B?.profile??null,U=d??B?.profile??null,W=B?Object.fromEntries(B.data.models.map(e=>[e.route,B.profile.assignments[e.route]?.family??`opus`])):{},G=Object.keys(p).length>0?p:W,ee=(0,Z.useMemo)(()=>H!==null&&U!==null&&JSON.stringify(H)!==JSON.stringify(U),[H,U]),K=(0,Z.useMemo)(()=>{let e=Object.fromEntries(Cj.map(e=>[e,[]]));if(!V||!H)return e;for(let t of V.models)e[H.assignments[t.route]?.family??`opus`].push(t);return e},[V,H]),q=(0,Z.useMemo)(()=>V&&H?Tj(V.models,H):{opus:null,fable:null,sonnet:null,haiku:null},[V,H]),te=`ocx.claude-desktop.status.v1:${e}`,ne=`claude-desktop-status:${e}`,J=za(te),Y=J&&Nj(J.data)?J.data:null,re=Ua(ne,[e],async t=>{let n=await gn(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!Nj(n))throw Error(`Claude Desktop status unavailable`);return Ba(te,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:n,initialData:Y??void 0}),ie=re.state,X=ie.data??Y,ae=ie.showError,oe=X!==null,se=oe||ae,ce=X?.mode??`gateway`,le=P??ce,ue=oe&&le!==ce,de=X?.firstParty?.modelBindings,fe=de?JSON.stringify(de):null,[pe,me]=(0,Z.useState)(null),[he,ge]=(0,Z.useState)(fe);he!==fe&&(ge(fe),me(null));let _e=pe??de??{},ve=(0,Z.useMemo)(()=>X?.firstParty?.pickerSuggestions??[],[X]),ye=(e,t,n=!1)=>{H&&(!n&&H.assignments[e]?.family===t||(u(r=>r&&wj(r,e,t,n)),m(n=>({...n,[e]:t})),v(r(`claudeDesktop.moved`,{route:e,family:r(Pj[t])}))))},be=e=>{let t=_j(T,e);Aj.write(t),E(t)},xe=async t=>{if(!(!H||y)){b(`save`),g(null);try{await hn(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:H})}),r(`claudeDesktop.saveFailed`)),f(Fj(H)),t?(b(`apply`),(await hn(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:le})}),r(`claudeDesktop.applyFailed`)))?.saved===!1?(g({tone:`warn`,text:r(`claudeDesktop.appliedMarkerUnsaved`)}),v(r(`claudeDesktop.appliedMarkerUnsaved`))):(g({tone:`ok`,text:r(`claudeDesktop.savedApplied`)}),v(r(`claudeDesktop.savedAppliedAnnounce`))),F(null)):(g({tone:`ok`,text:r(`claudeDesktop.saved`)}),v(r(`claudeDesktop.savedAnnounce`))),re.refresh()}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.updateFailed`);g({tone:`err`,text:t}),v(t)}finally{b(null)}}},Se=()=>{if(!H)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(H,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),v(r(`claudeDesktop.exported`))},Ce=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(r(`claudeDesktop.importExpected`));let n=Ij({...V,profile:e});u(n),g({tone:`ok`,text:r(`claudeDesktop.importReady`)}),v(r(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.importInvalid`);g({tone:`err`,text:t}),v(r(`claudeDesktop.importFailed`,{error:t}))}},we=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&ye(n,t)};if(z.kind===`disabled`&&!B)return null;if(z.showSkeleton&&!B)return(0,Q.jsx)(my,{label:r(`claudeDesktop.loading`),rows:4});if(z.kind===`failed-cold`){let e=z.error instanceof Error?z.error.message:r(`claudeDesktop.loadFail`);return(0,Q.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>R.refresh(),children:r(`claudeDesktop.retry`)})]})}if(!V||!H)return null;let Te=Dj(H,q,`opus`),Ee=Dj(H,q,`haiku`),De=new Map(V.models.map(e=>[e.route,e])),Oe=(e,t,n)=>{let i=Oj(V.models,t||null).map(e=>({value:e.route,label:e.label}));if(e&&!i.some(t=>t.value===e)){let t=De.get(e);i.unshift({value:e,label:t?.available===!1||!t?(0,Q.jsx)(zj,{route:e,t:r}):e})}return n?i.unshift({value:``,label:r(`claudeDesktop.roles.unset`)}):e||i.unshift({value:``,label:r(`claudeDesktop.roles.pick`)}),i},ke=e=>{if(!e)return;let t=De.get(e);return t?.available?t.label:r(`claudeDesktop.roles.unavailableOption`,{route:e})},Ae=kj(V.models,Te||null,Ee||null),je=Ej(V.models,H,`haiku`)===0;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,Q.jsx)(`p`,{className:`claude-panel-lead`,children:r(`claudeDesktop.subtitle`,{port:V.port})})}),(0,Q.jsxs)(`fieldset`,{className:`claude-mode-picker`,disabled:y!==null||!se,children:[(0,Q.jsx)(`legend`,{children:r(`claudeDesktop.mode.legend`)}),jj.map(e=>(0,Q.jsxs)(`label`,{className:`claude-mode-option${se&&le===e?` active`:``}`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`claude-desktop-mode`,value:e,checked:se&&le===e,onChange:()=>F(e)}),(0,Q.jsxs)(`span`,{className:`claude-mode-title`,children:[r(e===`first-party`?`claudeDesktop.mode.firstParty`:`claudeDesktop.mode.gateway`),e===`gateway`&&(0,Q.jsx)(`span`,{className:`claude-mode-default`,children:r(`claudeDesktop.mode.defaultBadge`)}),oe&&ce===e&&(0,Q.jsx)(`span`,{className:`claude-mode-current`,children:r(`claudeDesktop.mode.current`)})]}),(0,Q.jsx)(`span`,{className:`claude-mode-hint`,children:r(e===`first-party`?`claudeDesktop.mode.firstPartyHint`:`claudeDesktop.mode.gatewayHint`)})]},e)),le===`first-party`&&(0,Q.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:r(`claudeDesktop.mode.firstPartyRisk`)}),ue&&(0,Q.jsx)(`span`,{className:`claude-mode-switch-note`,children:r(`claudeDesktop.mode.switchNote`)})]}),(0,Q.jsxs)(`div`,{className:`claude-status-bar ${ae&&!X?`not-applied`:X?X.desiredEnabled?ce===`gateway`&&X.activeProfile===!1?`not-applied`:X.stale?`stale`:X.applied?`applied`:`not-applied`:`not-applied`:`pending`}`,"aria-busy":!X&&!ae||void 0,children:[(0,Q.jsx)(`span`,{className:`claude-status-dot`}),(0,Q.jsx)(`span`,{children:ae&&!X?r(`claudeDesktop.loadFail`):X?X.desiredEnabled?ce===`gateway`&&X.activeProfile===!1?r(`claudeDesktop.status.notActiveProfile`):X.stale?r(`claudeDesktop.status.stale`):X.applied?r(ce===`first-party`?`claudeDesktop.status.appliedFirstParty`:`claudeDesktop.status.applied`):r(`claudeDesktop.status.notApplied`):r(`claudeDesktop.status.disabled`):r(`claudeDesktop.loading`)}),X?.firstParty&&ce===`first-party`&&X.desiredEnabled&&(0,Q.jsx)(`span`,{className:`claude-status-health`,children:X.firstParty.interceptRunning?r(`claudeDesktop.firstParty.proxyRunning`,{port:X.firstParty.proxyPort}):(0,Q.jsx)(fA,{apiBase:e,reason:X.firstParty.interceptReason,port:X.firstParty.proxyPort,onStarted:()=>re.refresh()})}),X?.health.lastRequestAt&&(0,Q.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(X.health.lastRequestAt).toLocaleTimeString(a)]}),X&&X.health.requestCount>0&&(0,Q.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:X.health.requestCount,errors:X.health.errorCount})}),(0,Q.jsxs)(`span`,{className:`claude-status-actions`,children:[(0,Q.jsx)(`span`,{className:`claude-dirty${ee?` active`:``}`,children:r(ee?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,Q.jsxs)(`span`,{className:`claude-save-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!ee||y!==null,onClick:()=>void xe(!1),children:r(y===`save`?`claudeDesktop.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:y!==null,onClick:()=>void xe(!0),children:y===`apply`?r(`claudeDesktop.applying`):y===`save`?r(`claudeDesktop.saving`):X?.desiredEnabled===!1?r(`claudeDesktop.enableApply`):r(ue?`claudeDesktop.switchModeApply`:`claudeDesktop.saveApply`)})]})]})]}),X?.riskWarning&&le!==`first-party`&&(0,Q.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:r(`claudeDesktop.mode.firstPartyRisk`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:_}),h&&(0,Q.jsx)($,{tone:h.tone,children:h.text}),z.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),ae&&X&&(0,Q.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),ce===`first-party`&&X?.firstParty?.picker&&(0,Q.jsx)(Sj,{apiBase:e,picker:X.firstParty.picker,pickerReason:X.firstParty.pickerReason,pickerFailurePort:X.firstParty.pickerFailurePort,onUpdated:()=>void re.refresh()},`${X.firstParty.picker.reason}:${X.firstParty.picker.desired}:${X.firstParty.picker.effective}:${X.firstParty.picker.models}:${X.firstParty.picker.hint??``}`),ce===`first-party`&&(0,Q.jsx)(yj,{apiBase:e,bindings:_e,suggestions:ve,models:V.models,onSaved:e=>{me(e),re.refresh()}}),V.models.length===0&&(0,Q.jsx)(ln,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),V.models.length>0&&(0,Q.jsxs)(`section`,{className:`card claude-desktop-roles`,"aria-labelledby":`claude-desktop-roles-title`,children:[(0,Q.jsx)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-roles-title`,children:r(`claudeDesktop.roles.title`)}),ce===`first-party`&&(0,Q.jsx)(`p`,{className:`claude-desktop-roles-scope`,children:r(`claudeDesktop.roles.gatewayScope`)}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:r(`claudeDesktop.roles.default`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claudeDesktop.roles.defaultDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(cn,{value:Te,options:Oe(Te,Ee,!1),onChange:e=>{e&&ye(e,`opus`,!0)},label:r(`claudeDesktop.roles.default`),title:ke(Te),disabled:y!==null,style:{minWidth:240},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:r(`claudeDesktop.roles.quick`)}),(0,Q.jsx)(`span`,{className:`desc`,children:r(`claudeDesktop.roles.quickDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(cn,{value:Ee,options:Oe(Ee,Te,je),onChange:e=>{e&&ye(e,`haiku`,!0)},label:r(`claudeDesktop.roles.quick`),title:ke(Ee),disabled:y!==null,style:{minWidth:240},align:`right`,portal:!0})})]})]}),(0,Q.jsxs)(`section`,{className:`claude-desktop-list`,"aria-labelledby":`claude-desktop-list-title`,children:[(0,Q.jsxs)(`div`,{className:`claude-desktop-list-head`,children:[(0,Q.jsxs)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-list-title`,children:[r(`claudeDesktop.roles.listTitle`),(0,Q.jsx)(`span`,{className:`count`,children:V.models.length})]}),(0,Q.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,Q.jsx)(`input`,{ref:I,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void Ce(e)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>I.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Se,children:r(`claudeDesktop.exportJson`)})]})]}),V.models.length>0&&(0,Q.jsx)(`p`,{className:`claude-desktop-list-hint`,children:r(`claudeDesktop.roles.listHint`)}),V.models.length>0&&(0,Q.jsx)(`ul`,{className:`card claude-desktop-list-rows`,children:Ae.slice(0,M).map(e=>{let t=Bj(e.contextWindow,r);return(0,Q.jsxs)(`li`,{className:`claude-desktop-list-row`,children:[(0,Q.jsxs)(`span`,{className:`claude-desktop-list-names`,children:[(0,Q.jsx)(`strong`,{title:e.label,children:e.label}),e.label!==e.route&&(0,Q.jsx)(`code`,{title:e.route,children:e.route})]}),e.route===Te&&(0,Q.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),e.route===Ee&&(0,Q.jsx)(`span`,{className:`claude-row-default claude-row-quick`,children:r(`claudeDesktop.roles.quickBadge`)}),t&&(0,Q.jsx)(`span`,{className:`claude-model-context`,children:t}),e.supports1m===!0&&(0,Q.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),!e.available&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:r(`claudeDesktop.unavailable`)})]},e.route)})}),Ae.length>M&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>N(e=>e+6),children:r(`models.showMore`,{n:Ae.length-M})})]}),(0,Q.jsxs)(`details`,{className:`claude-desktop-advanced`,open:A,onToggle:e=>j(e.currentTarget.open),children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsxs)(`span`,{className:`claude-desktop-advanced-title`,children:[(0,Q.jsx)(Ke,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:A?`rotate(90deg)`:`none`}}),r(`claudeDesktop.advanced.title`)]}),(0,Q.jsx)(`span`,{className:`claude-desktop-advanced-chips`,children:Cj.map(e=>{let t=K[e].length,n=H.defaults[e],i=q[e];return(0,Q.jsxs)(`span`,{className:`claude-desktop-advanced-chip`,children:[(0,Q.jsx)(`b`,{children:r(Pj[e])}),i?(0,Q.jsx)(`code`,{title:i,children:i}):(0,Q.jsx)(`span`,{children:r(`claudeDesktop.advanced.empty`)}),t>0&&(0,Q.jsx)(`span`,{className:`claude-desktop-advanced-count`,children:t}),t>0&&n===null&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),i&&n!==null&&i!==n&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.temporaryDefault`)})]},e)})})]}),(0,Q.jsx)(`p`,{className:`claude-desktop-advanced-desc`,children:r(`claudeDesktop.advanced.desc`)}),(0,Q.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:Cj.map(e=>{let t=K[e],n=fj(t,x[e]??``,C[e]??6),i=T.has(e),a=q[e];return(0,Q.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>we(t,e),children:[(0,Q.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,Q.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>be(e),children:[(0,Q.jsx)(Ke,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,Q.jsx)(`span`,{className:`ocx-group-name`,children:r(Pj[e])}),(0,Q.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,Q.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&H.defaults[e]===null&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==H.defaults[e]&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,Q.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,Q.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:x[e]??``,onChange:t=>{let n=t.target.value;S(t=>({...t,[e]:n})),w(t=>({...t,[e]:6}))}}),(0,Q.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,Q.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,Q.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=H.assignments[t.route],i=Bj(t.contextWindow,r),a=G[t.route]??`opus`,o=D[t.route]??mj(t.route,q[e]);return(0,Q.jsxs)(`article`,{className:`claude-model-card${o?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>O(e=>({...e,[t.route]:!o})),children:[(0,Q.jsx)(Ke,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,Q.jsxs)(`span`,{className:`claude-model-names`,children:[(0,Q.jsx)(`strong`,{title:t.label,children:t.label}),(0,Q.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,Q.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,Q.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,Q.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,Q.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,Q.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),H.defaults[e]===t.route&&(0,Q.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,Q.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,Q.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[q[e]===t.route&&H.defaults[e]!==t.route&&(0,Q.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,Q.jsxs)(`div`,{className:`claude-field`,children:[(0,Q.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,Q.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,Q.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:H.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(Pj[e])})]}),(0,Q.jsxs)(`div`,{className:`claude-move-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,Q.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:Cj.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(Pj[e])},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>ye(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>w(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})]})}function Gj(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 Kj=gj(`ocx.grok.collapsedGroups.v2`),qj=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],Jj=new Set(qj.map(e=>e.id));function Yj(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 Xj({apiBase:e,active:t=!0}){let n=O(),r=`ocx.grok.status.v1:${e}`,i=za(r),a=i?.data??null,[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(()=>Kj.read()??new Set(Jj)),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(``),g=(0,Z.useCallback)(async t=>{let i=await hn(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 Ba(r,a),a},[e,r,n]),_=`grok-status:${e}`,v=Ua(_,[e],g,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:i?.cachedAt??null,staleAfterMs:6e4,enabled:t}),{state:y}=v,b=v.refresh,x=y.data??a,S=(0,Z.useMemo)(()=>new Set(x?.excluded??[]),[x]),C=o??S,w=(0,Z.useMemo)(()=>o!==null&&(o.size!==S.size||[...o].some(e=>!S.has(e))),[o,S]),T=(0,Z.useMemo)(()=>new Map((x?.models??[]).map(e=>[e.id,e.alias])),[x]),E=e=>{let t=_j(c,e);Kj.write(t),l(t)},D=e=>{let t=e?new Set(qj.map(e=>e.id)):new Set;Kj.write(t),l(t)},k=(e,t)=>{s(n=>{let r=new Set(n??S);return t?r.delete(e):r.add(e),r})},A=async t=>{if(!u){d(`save`),p(null);try{await hn(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...C]})}),n(`grok.saveFailed`));let i=[...C];if(x&&Ut(_,{...x,excluded:i}),s(null),t){d(`apply`);let t=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.message??e.error??n(`grok.applyFailed`))}let r=await t.json().catch(()=>({}));r.skippedReason?(p({tone:`err`,text:r.message??n(`grok.applySkipped`)}),h(r.message??n(`grok.applySkipped`))):(p({tone:`ok`,text:n(`grok.savedApplied`)}),h(n(`grok.savedApplied`))),await b()}else p({tone:`ok`,text:n(`grok.saved`)}),h(n(`grok.saved`)),x&&Ba(r,{...x,excluded:i})}catch(e){let t=e instanceof Error?e.message:n(`grok.saveFailed`);p({tone:`err`,text:t}),h(t)}finally{d(null)}}};if(y.showSkeleton&&!x)return(0,Q.jsx)(`section`,{className:`grok-page`,children:(0,Q.jsx)(my,{label:n(`grok.loading`),rows:4})});if(y.kind===`failed-cold`){let e=y.error instanceof Error?y.error.message:n(`grok.loadFail`);return(0,Q.jsxs)(`section`,{className:`grok-page`,children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>b(),children:n(`common.retry`)})]})}return(0,Q.jsxs)(`section`,{className:`grok-page`,"aria-busy":y.refreshing||void 0,children:[(0,Q.jsx)(`h2`,{className:`page-title`,children:n(`grok.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`grok.subtitle`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:m}),f&&(0,Q.jsx)($,{tone:f.tone,children:f.text}),y.showError&&(0,Q.jsx)($,{tone:`err`,children:n(`grok.loadFail`)}),x&&x.candidates.length>0&&(0,Q.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,Q.jsx)(`span`,{className:`claude-dirty${w?` active`:``}`,children:n(w?`grok.unsaved`:`grok.upToDate`)}),(0,Q.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!w||u!==null,onClick:()=>void A(!1),children:n(u===`save`?`grok.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!w||u!==null,onClick:()=>void A(!0),children:n(u===`apply`?`grok.applying`:u===`save`?`grok.saving`:`grok.saveApply`)})]})]}),x?.present?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,Q.jsx)(`span`,{children:n(`grok.endpoint`)}),(0,Q.jsx)(`code`,{children:x.baseUrl??`—`})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:(0,Q.jsx)(`code`,{children:x.configPath})})]}):(0,Q.jsxs)(ln,{title:n(`grok.notConfiguredTitle`),children:[n(`grok.notConfiguredHint`),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`code`,{children:x?.configPath})]}),x&&x.candidates.length>0&&(0,Q.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,Q.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>D(!0),disabled:u!==null,children:[(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`}),` `,n(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>D(!1),disabled:u!==null,children:[(0,Q.jsx)(Ke,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,n(`models.expandAll`)]})]}),qj.map(e=>{let t=Gj(x.candidates,T,C,e.id);if(t.total===0)return null;let r=c.has(e.id);return(0,Q.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,Q.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,Q.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>E(e.id),children:[(0,Q.jsx)(Ke,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,Q.jsx)(`span`,{className:`ocx-group-name`,children:n(e.tkey)}),(0,Q.jsx)(`span`,{className:`ocx-group-count`,children:n(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!r&&(0,Q.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,Q.jsxs)(`div`,{className:`grok-model-row`,children:[(0,Q.jsx)(on,{on:e.enabled,onClick:()=>k(e.id,!e.enabled),disabled:u!==null,label:n(`grok.toggleModel`,{id:e.id})}),(0,Q.jsxs)(`span`,{className:`grok-model-names`,children:[(0,Q.jsx)(`strong`,{title:e.id,children:e.id}),(0,Q.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,Q.jsx)(`span`,{className:`claude-model-context`,children:Yj(e.contextWindow,n)})]},e.id))})]},e.id)})]})]})}async function Zj(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor`,{signal:t});if(!n.ok)return null;let r=await gn(n);return!r||typeof r!=`object`||!r.gateway||!r.privateInference?null:r}catch{return null}}async function Qj(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor/local-installer`,{signal:t});if(!n.ok)return null;let r=await gn(n);return!r||typeof r!=`object`||typeof r.available!=`boolean`?null:r}catch{return null}}function $j({value:e,label:t}){let n=O(),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);let o=async()=>{try{await navigator.clipboard.writeText(e),i(!0),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>i(!1),1500)}catch{i(!1)}};return(0,Q.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Q.jsx)(`span`,{className:`cursor-gateway-label`,children:t}),(0,Q.jsx)(`code`,{className:`cursor-gateway-value`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void o(),"aria-label":`${n(`integrations.cursor.copy`)} ${t}`,children:n(r?`integrations.cursor.copied`:`integrations.cursor.copy`)})]})}function eM({labelKey:e,installed:t,path:n,version:r}){let i=O();return(0,Q.jsxs)(`div`,{className:`cursor-detect-row`,"data-installed":t?`true`:`false`,children:[(0,Q.jsx)(`span`,{className:`cursor-detect-name`,children:i(e)}),(0,Q.jsx)(`span`,{className:`badge ${t?`badge-green`:`badge-muted`}`,children:i(t?`integrations.cursor.detected`:`integrations.cursor.notFound`)}),t&&n&&(0,Q.jsxs)(`span`,{className:`cursor-detect-path muted`,children:[r?`${r} · `:``,n]})]})}function tM({apiBase:e}){let t=O(),[n,r]=(0,Z.useState)(`idle`),[i,a]=(0,Z.useState)(null),o=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>o.current?.abort(),[]);let s=async()=>{o.current?.abort();let t=new AbortController;o.current=t,r(`checking`);let n=await Qj(e,t.signal);t.signal.aborted||(a(n),r(`done`))};return n===`done`&&i?.available&&i.url!==null?(0,Q.jsxs)(`span`,{"data-cursor-installer-hint":!0,children:[t(`integrations.cursor.installerIntro`,{version:i.version??t(`integrations.cursor.unknownVersion`)}),` `,(0,Q.jsx)(`a`,{href:i.url,target:`_blank`,rel:`noreferrer`,"data-cursor-installer-url":!0,children:t(`integrations.cursor.installerOpen`)}),`.`]}):(0,Q.jsxs)(Q.Fragment,{children:[n===`done`&&(0,Q.jsxs)(`span`,{"data-cursor-installer-unavailable":!0,children:[t(`integrations.cursor.installerUnavailable`),` `]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void s(),disabled:n===`checking`,"data-cursor-installer-check":!0,children:t(n===`checking`?`integrations.cursor.installerChecking`:`integrations.cursor.installerCheck`)})]})}function nM({apiBase:e,active:n}){let{t:r,locale:i}=t(),[a,o]=(0,Z.useState)(()=>Date.now()),s=(0,Z.useCallback)(async t=>{let n=await Zj(e,t);if(!n)throw Error(`cursor status unavailable`);return o(Date.now()),n},[e]),c=Ua(`integration-cursor-page:${e}`,[e],s,{isEmpty:()=>!1,enabled:n,pollMs:15e3,pauseWhenHidden:!0}),l=c.state.data??null,u=Bo(r);return(0,Q.jsxs)(`section`,{className:`integration-native-page cursor-page`,"aria-labelledby":`cursor-integration-title`,children:[(0,Q.jsx)(`h3`,{id:`cursor-integration-title`,children:r(`integrations.cursor.title`)}),(0,Q.jsx)(`p`,{children:r(`integrations.cursor.intro`)}),c.state.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`integrations.cursor.unavailable`)}),!l&&!c.state.showError&&(0,Q.jsx)(my,{label:r(`integrations.cursor.loading`),rows:4}),l&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:r(`integrations.cursor.detection`)}),(0,Q.jsx)(eM,{labelKey:`integrations.cursor.privateInference`,installed:l.privateInference.installed,path:l.privateInference.path,version:l.privateInference.version}),(0,Q.jsx)(eM,{labelKey:`integrations.cursor.regular`,installed:l.regularCursor.installed,path:l.regularCursor.path,version:null}),!l.privateInference.installed&&(0,Q.jsxs)($,{tone:`warn`,children:[r(l.regularCursor.installed?`integrations.cursor.regularOnly`:`integrations.cursor.nothingFound`),` `,(0,Q.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,"data-cursor-guide":`notice`,children:r(`integrations.cursor.guide`)}),l.regularCursor.installed&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`span`,{"data-cursor-installer":!0,children:(0,Q.jsx)(tM,{apiBase:e})})]})]})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:r(`integrations.cursor.gateway`)}),(0,Q.jsx)(`p`,{className:`muted`,children:r(`integrations.cursor.gatewayHint`)}),(0,Q.jsx)($j,{label:r(`integrations.cursor.baseUrl`),value:l.gateway.baseUrl}),l.gateway.apiKeyMode===`placeholder`?(0,Q.jsx)($j,{label:r(`integrations.cursor.apiKey`),value:l.gateway.placeholder}):(0,Q.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Q.jsx)(`span`,{className:`cursor-gateway-label`,children:r(`integrations.cursor.apiKey`)}),(0,Q.jsx)(`span`,{className:`cursor-gateway-value`,children:r(`integrations.cursor.apiKeyCredential`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>qt(`integrations/keys`),children:r(`integrations.tab.keys`)})]})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,"data-seen":l.lastSeen?`true`:`false`,children:[(0,Q.jsx)(`h4`,{children:r(`integrations.cursor.connection`)}),l.lastSeen?(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`span`,{className:`badge ${a-l.lastSeen.at<864e5?`badge-green`:`badge-muted`}`,children:r(`integrations.cursor.seen`,{time:zo(l.lastSeen.at,u,a),ua:l.lastSeen.userAgent})})}):(0,Q.jsx)(`p`,{className:`muted`,children:r(`integrations.cursor.neverSeen`)})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:r(`integrations.cursor.models`)}),(0,Q.jsx)(`p`,{className:`muted`,children:l.effortTable.source===`bundle`?r(`integrations.cursor.ladderFromBundle`,{version:l.effortTable.version??r(`integrations.cursor.unknownVersion`)}):r(`integrations.cursor.ladderFromStatic`)}),(0,Q.jsxs)(`table`,{className:`cursor-model-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`integrations.cursor.colModel`)}),(0,Q.jsx)(`th`,{children:r(`integrations.cursor.colReasoning`)}),(0,Q.jsx)(`th`,{children:r(`integrations.cursor.colContext`)})]})}),(0,Q.jsx)(`tbody`,{children:l.models.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.id})}),(0,Q.jsx)(`td`,{children:e.reasoning?e.reasoning.join(` · `):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`cursor-no-control`,title:r(`integrations.cursor.noControlTitle`),"aria-label":r(`integrations.cursor.noControlTitle`),children:r(`integrations.cursor.noControl`)}),e.effortRows.length>0?(0,Q.jsx)(`span`,{className:`cursor-effort-rows`,children:r(e.effortRows.length===1?`integrations.cursor.effortRowsOne`:`integrations.cursor.effortRowsMany`,{n:e.effortRows.length})}):(0,Q.jsx)(`span`,{className:`cursor-effort-rows muted`,children:r(`integrations.cursor.effortRowsOff`)})]})}),(0,Q.jsx)(`td`,{children:e.context?`${q(e.context.defaultWindow,i)} · ${q(e.context.longWindow,i)}`:r(`integrations.cursor.singleWindow`)})]},e.id))})]}),l.models.some(e=>e.tableLess)&&(0,Q.jsx)(`p`,{className:`muted`,"data-cursor-tableless-hint":!0,children:r(`integrations.cursor.tableLessHint`)})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,children:r(`integrations.cursor.guide`)})})]})]})}var rM={"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`},iM={"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 aM({state:e,installed:t,id:n}){let r=O(),i=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,Q.jsx)(`span`,{id:n,className:iM[i],"data-integration-state":i,children:r(rM[i])})}var oM={apply:`integrations.plan.operation.apply`,overwrite:`integrations.plan.operation.overwrite`,disable:`integrations.plan.operation.disable`,restore:`integrations.plan.operation.restore`},sM={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`},cM={none:`integrations.plan.foreign.none`,unowned:`integrations.plan.foreign.unowned`,"foreign-edit":`integrations.plan.foreign.foreignEdit`,drift:`integrations.plan.foreign.drift`},lM={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 uM({plan:e,missingStorePath:t}){let n=O(),r=e.refusalReason?lM[e.refusalReason]:void 0,i=e.supersededReason===`missing-store`?e.missingStoreDocument:void 0,a=i===void 0?n(r??`integrations.plan.refused`):t===void 0?n(`integrations.plan.refusal.missingStore`,{document:i}):n(`integrations.status.missingStore`,{path:t,document:i});return(0,Q.jsxs)(`div`,{className:`integration-plan-details`,children:[(0,Q.jsx)(`p`,{className:`integration-plan-operation`,children:n(`integrations.plan.operation`,{operation:n(oM[e.operation])})}),e.foreignEdit!==`none`&&(0,Q.jsx)(`p`,{children:n(cM[e.foreignEdit])}),!e.willChange&&e.canApply&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:n(e.operation===`disable`?`integrations.plan.noop.disabled`:`integrations.plan.noop.applied`)}),e.profileId!==void 0&&(0,Q.jsx)(`p`,{children:n(`integrations.plan.noop.profilePreference`)})]}),!e.canApply&&(0,Q.jsx)(`p`,{children:a}),e.changes.length>0&&(0,Q.jsx)(`ul`,{className:`integration-plan-changes`,children:e.changes.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:n(sM[e.kind])}),` `,(0,Q.jsx)(`code`,{children:e.path})]},`${e.kind}:${e.path}`))})]})}function dM({plan:e,plans:t,missingStorePath:n}){let r=O();return!e&&(!t||t.length===0)?null:(0,Q.jsxs)(`section`,{className:`integration-plan`,"aria-labelledby":`integration-plan-heading`,children:[(0,Q.jsx)(`h4`,{id:`integration-plan-heading`,children:r(`integrations.plan.heading`)}),e&&(0,Q.jsx)(uM,{plan:e,missingStorePath:n}),t?.map(e=>(0,Q.jsxs)(`section`,{className:`integration-plan-group`,children:[(0,Q.jsx)(`h5`,{children:e.label}),(0,Q.jsx)(uM,{plan:e.plan})]},`${e.clientId}:${e.plan.fingerprint}`))]})}function fM({copyKey:e,vars:t}){let n=O()(e,t),r=t?.path;if(!r||!n.includes(r))return(0,Q.jsx)(`p`,{children:n});let[i,...a]=n.split(r);return(0,Q.jsxs)(`p`,{children:[i,(0,Q.jsx)(`code`,{children:r}),a.join(r)]})}function pM(e){return e.changes.some(e=>e.kind===`snapshot`||e.kind===`journal`)}function mM({copy:e,plan:t=null,plans:n,hasUnboundAction:r=!1,planStale:i=!1,planLoading:a=!1,planFailure:o=null,missingStorePath:s,onConfirm:c,onClose:l}){let u=O(),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),b=`integration-consequence-dialog-title`,x=t!==null||a||o!==null||n!==void 0,S=v?.sourceFingerprint===(t?.fingerprint??null)?v.plan:t,C=v?.sourceFingerprint===(t?.fingerprint??null),w=n!==void 0&&!r&&!n.some(e=>e.plan.canApply),T=!x||(S?pM(S):n?.some(e=>pM(e.plan))===!0),E=(0,Z.useCallback)(()=>{m||l()},[l,m]);(0,Z.useEffect)(()=>{let e=d.current,t=document.activeElement;return f.current=t?.tagName===`BUTTON`?t:null,e&&!e.open&&e.showModal(),p.current?.focus(),()=>{e?.open&&e.close(),f.current?.isConnected&&f.current.focus?.()}},[]);let D=(0,Z.useCallback)(e=>{e.preventDefault(),E()},[E]),k=(0,Z.useCallback)(async()=>{if(!m){h(!0),_(null);try{await c(S??void 0)}catch(e){if(e instanceof Sv&&e.stalePlan){y({sourceFingerprint:t?.fingerprint??null,plan:e.stalePlan});return}_(e instanceof Error?e.message:u(`integrations.error.generic`))}finally{h(!1)}}},[S,c,m,t?.fingerprint,u]),A=[(0,Q.jsx)(fM,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,Q.jsx)(fM,{copyKey:e.breakageKey,vars:e.vars},`breakage`)];return T&&A.push((0,Q.jsx)(fM,{copyKey:e.undoKey,vars:e.vars},`undo`)),e.sideEffectKey&&A.push((0,Q.jsx)(fM,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,Q.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":b,"aria-busy":m,onCancel:D,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:E}),(0,Q.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:b,children:u(e.titleKey,e.vars)}),(0,Q.jsx)(`button`,{ref:p,type:`button`,className:`btn btn-ghost btn-sm`,onClick:E,disabled:m,children:u(`common.close`)})]}),(0,Q.jsx)(`div`,{className:`integration-consequence-body`,children:A}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[a&&(0,Q.jsx)(`p`,{children:u(`integrations.preview.loading`)}),m&&(0,Q.jsx)(`p`,{children:u(`integrations.mutation.pending`)}),(C||i)&&(0,Q.jsx)($,{tone:`err`,children:u(`integrations.preview.stale`)}),o&&(0,Q.jsx)($,{tone:`err`,children:o})]}),(0,Q.jsx)(dM,{plan:S,plans:n,missingStorePath:s}),g&&(0,Q.jsx)($,{tone:`err`,children:g}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void k(),disabled:m||a||!!o||x&&!S&&n===void 0||w||S?.canApply===!1,children:u(e.confirmKey)})})]})]})}function hM({apiBase:e,row:t,onClose:n,onRestored:r,profileId:i,onReconcile:a}){let o=O(),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),d=(0,Z.useRef)(n),f=(0,Z.useRef)(r),p=(0,Z.useRef)(a),m=(0,Z.useRef)(o),h=(0,Z.useRef)(null),g=(0,Z.useRef)(0),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(!0),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(null),[D,k]=(0,Z.useState)(null),A=t.clientId===`aside`?i??t.profileId:void 0,j=_?.plan??null,M=j?.foreignEdit===`drift`;(0,Z.useEffect)(()=>{d.current=n,f.current=r,p.current=a,m.current=o},[n,a,r,o]);let N=(0,Z.useCallback)(()=>{C||(g.current+=1,h.current?.abort(),h.current=null,d.current())},[C]);(0,Z.useEffect)(()=>{let e=s.current,t=document.activeElement;return c.current=t?.tagName===`BUTTON`?t:null,l.current=t?.closest?.(`section, [role='region'], main`)??null,e&&!e.open&&e.showModal(),()=>{e?.open&&e.close();let t=l.current;if(u.current&&t?.isConnected){t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.();return}let n=c.current;if(n?.isConnected){n.focus?.();return}t?.isConnected&&(t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.())}},[]);let P=(0,Z.useCallback)(async()=>{let n=new AbortController,r=g.current+1;g.current=r,h.current?.abort(),h.current=n,b(!0),E(null),k(null),v(null),S(!1);try{let i=!1,a=await Pv(e,t.opId,i,n.signal,A);if(a.refusalReason===`drift_requires_confirm`&&(i=!0,a=await Pv(e,t.opId,i,n.signal,A)),n.signal.aborted||r!==g.current)return;v({plan:a,confirmDrift:i})}catch(e){if(n.signal.aborted||r!==g.current)return;if(Ev(e)){p.current?.(),d.current();return}E(m.current(`integrations.preview.failed`))}finally{!n.signal.aborted&&r===g.current&&(h.current=null,b(!1))}},[e,t.opId,A]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{P()},0);return()=>{window.clearTimeout(e),g.current+=1,h.current?.abort(),h.current=null}},[P]);let F=(0,Z.useCallback)(e=>{e.preventDefault(),N()},[N]),I=async()=>{if(C||y||!_||!_.plan.canApply)return;let n=_.confirmDrift;w(!0),k(null);try{await Iv(e,{opId:t.opId,confirmDrift:n,profileId:A,binding:Dv(_.plan)}),u.current=!0,f.current(),d.current()}catch(r){if(t.clientId===`aside`&&p.current?.(),r instanceof Sv&&r.stalePlan){let i=r.stalePlan,a=n;w(!1);try{if(i.refusalReason===`drift_requires_confirm`){let n=new AbortController,r=g.current+1;g.current=r,h.current?.abort(),h.current=n,b(!0),a=!0;try{i=await Pv(e,t.opId,a,n.signal,A)}finally{!n.signal.aborted&&r===g.current&&(h.current=null,b(!1))}if(n.signal.aborted||r!==g.current)return}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;if(Ev(e)){p.current?.(),d.current();return}E(m.current(`integrations.preview.failed`));return}v({plan:i,confirmDrift:a}),S(!0);return}k(sy(o,r)),w(!1)}};return(0,Q.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`integration-restore-title`,"aria-busy":C,onCancel:F,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:N}),(0,Q.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,role:`document`,children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h3`,{id:`integration-restore-title`,children:o(M?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:o(M?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[y&&(0,Q.jsx)(`p`,{children:o(`integrations.preview.loading`)}),C&&(0,Q.jsx)(`p`,{children:o(`integrations.mutation.pending`)}),x&&(0,Q.jsx)($,{tone:`err`,children:o(`integrations.preview.stale`)})]}),(0,Q.jsx)(dM,{plan:j}),T&&(0,Q.jsx)($,{tone:`err`,children:T}),D&&(0,Q.jsx)($,{tone:`err`,children:D}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:N,disabled:C,children:o(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void I(),disabled:C||y||!j?.canApply||!!T,children:o(C?`integrations.restore.pending`:M?`integrations.restore.confirmDrift`:`integrations.restore.confirm`)})]})]})]})}var gM={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,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`},_M={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`,overwrite:`integrations.kind.overwrite`};function vM(e){return e===`current`||e===`stale`}function yM(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 bM(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 xM(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 SM(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=xM(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 CM(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 wM(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 TM(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=wM(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 EM(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 DM(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:gM[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&(vM(e.state)||nv(e)),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function OM(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=[yM(e.codex,t,e.nativeSettled),SM(e.claude,n,e.nativeSettled),CM(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),TM(e.grok,r,e.nativeSettled),EM(e.cursor)];for(let t of tv){let n=i.get(t);if(n){a.push(DM(n));continue}e.clientsSettled||a.push({id:t,hash:`integrations/${t}`,labelKey:gM[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:bM(e.keyPhase,e.keyCount),rows:a}}function kM(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 AM=6;function jM({row:e,showClient:t,onRestore:n,onDelete:r}){let i=O();return(0,Q.jsxs)(`li`,{className:`integration-history-row`,children:[(0,Q.jsx)(`span`,{className:`integration-history-kind`,children:i(_M[e.kind])}),t&&(0,Q.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,Q.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:i(`integrations.action.snapshotExpired`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e),children:e.undoable?i(`integrations.action.undo`):i(`integrations.action.restorePoint`)}),e.deletable&&r&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e),"aria-label":i(`integrations.rollback.deleteAria`,{at:new Date(e.at).toLocaleString()}),children:i(`integrations.rollback.delete`)})]})}function MM({rows:e,showClient:t,onRestore:n,onDelete:r}){let i=O(),[a,o]=(0,Z.useState)(AM),[s,...c]=e;if(!s)return null;let l=c.slice(0,a),u=c.length-l.length;return(0,Q.jsxs)(`div`,{className:`integration-history`,children:[(0,Q.jsx)(`ul`,{className:`integration-history-list`,children:(0,Q.jsx)(jM,{row:s,showClient:t,onRestore:n,onDelete:r})}),c.length>0&&(0,Q.jsxs)(`details`,{className:`integration-history-older`,children:[(0,Q.jsx)(`summary`,{children:i(`integrations.rollback.older`)}),(0,Q.jsx)(`ul`,{className:`integration-history-list`,children:l.map(e=>(0,Q.jsx)(jM,{row:e,showClient:t,onRestore:n,onDelete:r},e.opId))}),u>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm integration-history-more`,onClick:()=>o(e=>e+AM),children:i(`integrations.rollback.showMore`,{n:String(Math.min(u,AM))})})]})]})}var NM={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`},PM={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`},FM={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`},IM={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`},LM={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`},RM={titleKey:`integrations.bulk.title`,changesKey:`integrations.bulk.body`,breakageKey:`integrations.bulk.breakage`,undoKey:`integrations.bulk.undo`,confirmKey:`integrations.bulk.confirm`};function zM(e){return e.flatMap(e=>e.plan?[{clientId:e.clientId,label:e.label,plan:e.plan}]:[])}function BM(e){return e.state===`current`||e.state===`stale`||nv(e)}function VM({row:e,pending:t,result:n,onOpen:r,onToggle:i,onOverwrite:a}){let o=O(),s=e.detail??(e.detailKey?o(e.detailKey,e.detailVars??void 0):null),c=e.toggleBlocked!==null&&(e.applied||e.toggleBlocked.reason===`orphaned_marker`),l=c&&e.toggleBlocked&&(e.toggle===`claude`||e.toggle===`grok`||e.toggle===`codex`)?sy(o,new Yv(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,u=e.toggleOn??e.applied,d=e.status!==null&&nv(e.status);return(0,Q.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,children:[(0,Q.jsxs)(`div`,{className:`integration-card-head`,children:[(0,Q.jsx)(PO,{src:NO(e.id),label:o(e.labelKey),size:20}),(0,Q.jsx)(`h4`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:r,children:o(e.labelKey)})}),(0,Q.jsx)(aM,{state:e.state,installed:e.installed})]}),s&&(0,Q.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:s}),e.status?.reason===`candidate-conflict`&&e.status.conflictPaths?.map(e=>(0,Q.jsx)($,{tone:`err`,children:o(`integrations.status.candidateConflict`,{path:e})},e)),n?.tone===`err`&&(0,Q.jsx)($,{tone:`err`,children:n.text}),n?.tone===`ok`&&(0,Q.jsx)($,{tone:`ok`,children:n.text}),(0,Q.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&i&&(0,Q.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,Q.jsx)(on,{on:u,onClick:i,disabled:e.state===`unknown`||!e.installed||(e.state===`conflict`||e.state===`unsafe`)&&!d||c||t,label:o(u?`integrations.action.disable`:`integrations.action.apply`)}),l&&(0,Q.jsx)(`p`,{className:`integration-toggle-blocked`,children:l})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,tabIndex:-1,children:o(`integrations.action.settings`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:a,disabled:t,children:o(`integrations.action.overwrite`)})]})]})}function HM({apiBase:e,active:t=!0}){let n=O(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)({}),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(0),C=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(p!==null)return;let e=C.current;e&&(C.current=null,e.isConnected&&e.focus())},[p]),(0,Z.useEffect)(()=>()=>{b.current+=1,S.current+=1,y.current?.abort(),x.current?.abort()},[]);let w=(0,Z.useCallback)(async t=>(await Av(e,t)).clients,[e]),T=(0,Z.useCallback)(async t=>(await Mv(e,void 0,t)).operations,[e]),E=(0,Z.useCallback)(t=>zv(e,t),[e]),D=(0,Z.useCallback)(t=>Bv(e,t),[e]),k=(0,Z.useCallback)(t=>Vv(e,t),[e]),A=(0,Z.useCallback)(t=>Hv(e,t),[e]),j=(0,Z.useCallback)(t=>Uv(e,t),[e]),M=(0,Z.useCallback)(t=>Zj(e,t),[e]),N=(0,Z.useCallback)(async t=>(await $v(e,t))?.clients??null,[e]),P=Ua(`integration-states:${e}`,[e],w,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.states.v1:${e}`}),F=Ua(`integration-journal-all:${e}`,[e],T,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.journal.v1:${e}`}),I=Ua(`integration-codex:${e}`,[e],E,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.codex.v1:${e}`}),L=Ua(`integration-keys:${e}`,[e],D,{isEmpty:()=>!1,enabled:t,sessionCacheKey:`ocx.integrations.keys.v1:${e}`}),R=Ua(`integration-claude:${e}`,[e],k,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude.v1:${e}`}),z=Ua(`integration-claude-desktop:${e}`,[e],A,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude-desktop.v1:${e}`}),B=Ua(`integration-grok:${e}`,[e],j,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.grok.v1:${e}`}),V=Ua(`integration-cursor:${e}`,[e],M,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.cursor.v1:${e}`}),H=Ua(`integration-native:${e}`,[e],N,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.native.v1:${e}`}),U=P.state.data??[],W=F.state.data??[],G=U.filter(BM),ee=U.filter(e=>e.installed),K=P.state.data!==void 0,q=H.state.data??null,te=q!==null,ne=L.state.kind===`cold`||L.state.kind===`retrying-cold`?`checking`:L.state.kind===`failed-cold`||L.state.kind===`failed-with-stale`?`unavailable`:`settled`,{keysRow:J,rows:Y}=OM({clients:U,clientsSettled:K,codex:I.state.data??null,keyCount:L.state.data??null,keyPhase:ne,claude:R.state.data??null,claudeDesktop:z.state.data??null,grok:B.state.data??null,cursor:V.state.data??null,native:q,nativeSettled:te}),re=kM(Y),ie=()=>{P.refresh(),F.refresh(),I.refresh(),L.refresh(),R.refresh(),z.refresh(),B.refresh(),H.refresh()},X=async()=>{if(r||_||G.length===0)return;let t=new AbortController,i=S.current+1;S.current=i,x.current?.abort(),x.current=t,v({actions:[],loading:!0,failure:null,stale:!1,failures:[]});try{let r=await Promise.all(G.map(async r=>{let i=Y.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 Nv(e,r.clientId,`disable`,t.signal);return{clientId:r.clientId,label:i?n(i.labelKey):r.clientId,plan:a}}));if(t.signal.aborted||i!==S.current)return;x.current=null,v({actions:r,loading:!1,failure:null,stale:!1,failures:[]})}catch(e){if(t.signal.aborted||i!==S.current)return;if(x.current=null,Ev(e)){v(null),ie();return}v({actions:[],loading:!1,failure:n(`integrations.preview.failed`),stale:!1,failures:[]})}},ae=()=>{S.current+=1,x.current?.abort(),x.current=null,v(null)},oe=async t=>{if(r||t.actions.length===0)return;i(!0),o(null);let a=[...t.failures],s=[];for(let r of t.actions){if(r.plan&&!r.plan.canApply){a.push(`${r.clientId}: ${n(`integrations.plan.refused`)}`);continue}try{await Fv(e,r.clientId,{enabled:!1,...r.plan?{binding:Dv(r.plan)}:{}})}catch(e){if(r.plan&&e instanceof Sv&&e.stalePlan){s.push({...r,plan:e.stalePlan});continue}a.push(`${r.clientId}: ${sy(n,e)}`)}}if(s.length>0){ie(),i(!1),v({actions:s,loading:!1,failure:null,stale:!0,failures:a}),o(a.length===0?null:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})});return}let c=!1;try{c=(await Av(e)).clients.some(BM)}catch{a.push(n(`integrations.error.stale`))}c&&a.length===0&&a.push(n(`integrations.error.stale`)),ie(),i(!1),v(null),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},se=W[0]?.at,[ce,le]=(0,Z.useState)(null),ue=()=>{H.refresh(),I.refresh(),R.refresh(),B.refresh()},de=(e,t)=>{f(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},fe=async(t,r,i)=>{if(!ce&&t.toggle){le(t.id),de(t.id,null);try{if(t.status){if(!i&&t.status.clientId!==`aside`)return;await Fv(e,t.status.clientId,{enabled:r,...i?{overwriteConflict:i.operation===`overwrite`,binding:Dv(i)}:{}}),ie()}else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await ey(e,t.toggle,r);i.reason===`non_loopback_removed`?de(t.id,{tone:`ok`,text:n(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&de(t.id,{tone:`ok`,text:n(`integrations.native.msg.nonLoopbackSuperseded`)}),ue()}}catch(e){if(t.status&&e instanceof Sv&&e.stalePlan)throw e;if(de(t.id,{tone:`err`,text:sy(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&ue(),t.status)throw Error(sy(n,e,void 0,t.togglePath??void 0),{cause:e})}finally{le(null)}}},pe=async(t,r)=>{if(!t.status||h)return;let i=new AbortController,a=b.current+1;b.current=a,y.current?.abort(),y.current=i,g({row:t,operation:r,plan:null,loading:!0,failure:null});try{let n=await Nv(e,t.status.clientId,r,i.signal);if(i.signal.aborted||a!==b.current)return;y.current=null,g({row:t,operation:r,plan:n,loading:!1,failure:null})}catch(e){if(i.signal.aborted||a!==b.current)return;if(y.current=null,Ev(e)){g(null),ie();return}g({row:t,operation:r,plan:null,loading:!1,failure:n(`integrations.preview.failed`)})}},me=()=>{b.current+=1,y.current?.abort(),y.current=null,g(null)},he=(e,t)=>{if(e.status&&e.status.clientId!==`aside`){pe(e,t?`apply`:`disable`);return}if(e.status?.clientId===`aside`){fe(e,t).catch(()=>{});return}if(t||e.id===`claude`||e.toggle===null){fe(e,t);return}let n=document.activeElement;C.current=n?.tagName===`BUTTON`?n:null,m(e)};return(0,Q.jsxs)(`section`,{className:`integrations-overview`,children:[(0,Q.jsxs)(`div`,{className:`integration-summary`,children:[(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,Q.jsx)(`strong`,{children:re.detected})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,Q.jsx)(`strong`,{children:re.applied})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,Q.jsx)(`strong`,{children:re.stale})]}),re.unknown>0&&(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,Q.jsx)(`strong`,{children:re.unknown})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,Q.jsx)(`strong`,{children:se?new Date(se).toLocaleString():n(`integrations.status.unknown`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void X(),disabled:r||!!_||G.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,Q.jsx)(`h3`,{children:n(`integrations.catalog.title`)}),(0,Q.jsx)(UM,{row:J}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),P.state.kind===`failed-cold`&&(0,Q.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),P.state.kind===`failed-with-stale`&&(0,Q.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,Q.jsx)($,{tone:a.tone,children:a.text}),Y.length===0?P.state.kind===`failed-cold`?null:(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,Q.jsx)(`ul`,{className:`integration-cards`,children:Y.map(e=>(0,Q.jsx)(VM,{row:e,pending:ce!==null,result:d[e.id]??null,onOpen:()=>qt(e.hash),onToggle:e.toggle?()=>he(e,!(e.toggleOn??e.applied)):null,onOverwrite:e.status!==null&&e.status.state===`conflict`&&e.status.reason!==`candidate-conflict`&&e.installed?()=>void pe(e,`overwrite`):null},e.id))}),K&&ee.length===0&&(0,Q.jsxs)(`div`,{className:`integration-empty`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,Q.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,Q.jsx)(`h3`,{children:n(`integrations.rollback.title`)}),F.state.showSkeleton?(0,Q.jsx)(my,{label:n(`integrations.rollback.title`),rows:2}):F.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[n(`integrations.rollback.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void F.refresh(),children:n(`common.retry`)})]}):W.length===0?(0,Q.jsxs)(`div`,{className:`integration-empty`,children:[(0,Q.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,Q.jsx)(MM,{rows:W,showClient:!0,onRestore:c,onDelete:u}),s&&(0,Q.jsx)(hM,{apiBase:e,row:s,onClose:()=>c(null),onRestored:ie,onReconcile:ie}),l&&(0,Q.jsx)(mM,{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:l.configPath}},onClose:()=>u(null),onConfirm:async()=>{try{await Lv(e,l.opId,void 0,l.clientId===`aside`?l.profileId:void 0)}catch(e){if(Cv(e)){u(null),await F.refresh();return}throw Error(sy(n,e),{cause:e})}u(null),await F.refresh()}}),p&&(0,Q.jsx)(mM,{copy:{...p.toggle===`claude-desktop`?FM:p.id===`codex`?PM:NM,vars:{path:p.togglePath??``}},onClose:()=>m(null),onConfirm:async()=>{await fe(p,!1),m(null)}}),h&&h.row.status&&(0,Q.jsx)(mM,{copy:h.operation===`overwrite`?{titleKey:`integrations.dialog.overwrite.title`,changesKey:h.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:h.row.status.configPath}}:h.operation===`disable`?LM:IM,plan:h.plan,planLoading:h.loading,planFailure:h.failure,onClose:me,onConfirm:async e=>{e&&(await fe(h.row,e.operation!==`disable`,e),g(null))}}),_&&(0,Q.jsx)(mM,{copy:RM,plans:zM(_.actions),hasUnboundAction:_.actions.some(e=>e.plan===null),planStale:_.stale,planLoading:_.loading,planFailure:_.failure,onClose:ae,onConfirm:async()=>{await oe(_)}})]})}function UM({row:e}){let t=O(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,Q.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,Q.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,Q.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>qt(e.hash),children:t(`integrations.action.manageKeys`)})]})}function WM({install:e}){let t=O();return(0,Q.jsxs)(Q.Fragment,{children:[e.plan===`free`&&(0,Q.jsx)($,{tone:`warn`,children:t(`integrations.raycast.proRequired`)}),e.plan===`unknown`&&(0,Q.jsx)(`p`,{className:`page-sub`,"data-raycast-plan":`unknown`,children:t(`integrations.raycast.planUnknown`)}),!e.aiDirPresent&&(0,Q.jsx)(`p`,{className:`page-sub`,"data-raycast-ai-dir":`absent`,children:t(`integrations.raycast.revealConfig`)})]})}function GM({reasoning:e,defaults:t,disabled:n,onChange:r,onReview:i}){let a=O(),o=new Map(e.models.map(e=>[e.model,new Set(e.efforts)])),s=Object.entries(t).filter(([e,t])=>!o.get(e)?.has(t)),c=(e,n)=>{let i={...t};n?i[e]=n:delete i[e],r(i)};return(0,Q.jsxs)(`section`,{className:`droid-reasoning-panel`,"aria-labelledby":`droid-reasoning-title`,children:[(0,Q.jsxs)(`div`,{className:`droid-reasoning-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{id:`droid-reasoning-title`,children:a(`integrations.droidReasoning.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`integrations.droidReasoning.description`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:i,disabled:n,children:a(`integrations.droidReasoning.saveReview`)})]}),e.models.length>0?(0,Q.jsx)(`ul`,{className:`droid-reasoning-list`,children:e.models.map(e=>{let r=t[e.model]??``,i=e.efforts.includes(r),o=[{value:``,label:a(`integrations.droidReasoning.noDefault`)},...!i&&r?[{value:r,label:a(`integrations.droidReasoning.unsupportedEffort`,{effort:r})}]:[],...e.efforts.map(e=>({value:e,label:e}))];return(0,Q.jsxs)(`li`,{className:`droid-reasoning-row`,children:[(0,Q.jsxs)(`div`,{className:`droid-reasoning-model`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`code`,{children:e.model})]}),e.efforts.length>0?(0,Q.jsx)(cn,{value:r,options:o,onChange:t=>c(e.model,t),disabled:n,label:a(`integrations.droidReasoning.modelDefault`,{model:e.label})}):(0,Q.jsx)(`span`,{className:`muted text-caption`,children:a(`integrations.droidReasoning.noEfforts`)})]},e.model)})}):(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`integrations.droidReasoning.noModels`)}),s.length>0&&(0,Q.jsxs)(`div`,{className:`droid-reasoning-unsupported`,role:`status`,children:[(0,Q.jsx)(`p`,{children:a(`integrations.droidReasoning.unsupportedTitle`)}),(0,Q.jsx)(`ul`,{children:s.map(([e,t])=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e}),` `,a(`integrations.droidReasoning.unsupportedEffort`,{effort:t}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:()=>c(e,``),children:a(`integrations.droidReasoning.clear`)})]},e))})]})]})}function KM(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 qM={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`},JM={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`},YM={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,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`},XM={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,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`};function ZM(e){return(0,Q.jsx)(QM,{...e},JSON.stringify([e.apiBase,e.client,e.profileId]))}function QM({apiBase:e,client:t,active:n=!0,profileId:r,profileLabel:i}){let a=O(),o=r===void 0?t:`${t}:${r}`,[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(0);(0,Z.useEffect)(()=>()=>{b.current+=1,y.current?.abort()},[]);let x=(0,Z.useCallback)(n=>jv(e,t,n,r),[e,t,r]),S=(0,Z.useCallback)(async n=>(await Mv(e,t,n,r)).operations,[e,t,r]),C=Ua(`integration-state:${e}:${o}`,[e,t,r],x,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${o}`}),w=Ua(`integration-journal:${e}:${o}`,[e,t,r],S,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${o}`}),T=C.state.data??null,E=T&&(r===void 0||T.profileId===r&&typeof T.enabled==`boolean`)?T:null,D=w.state.data??[],k=()=>{C.refresh(),w.refresh()},A=()=>{u(null),k()},j=async(n,i=t===`droid`&&n!==`disable`&&l?.scopeKey===o?l.values:void 0)=>{if(!E||s||_)return;let c=i===void 0?void 0:{...i},u=new AbortController,d=b.current+1;b.current=d,y.current?.abort(),y.current=u,v({operation:n,plan:null,loading:!0,failure:null});try{let i=await Nv(e,t,n,u.signal,r,c);if(u.signal.aborted||d!==b.current)return;y.current=null,v({operation:n,plan:i,loading:!1,failure:null,droidReasoningDefaults:c})}catch(e){if(u.signal.aborted||d!==b.current)return;if(y.current=null,Ev(e)){v(null),k();return}v({operation:n,plan:null,loading:!1,failure:a(`integrations.preview.failed`)})}},M=()=>{b.current+=1,y.current?.abort(),y.current=null,v(null)},N=async n=>{if(!(!E||s)){c(!0),f(null);try{await Fv(e,t,{enabled:n.operation!==`disable`,overwriteConflict:n.operation===`overwrite`,profileId:r,binding:Dv(n),...n.operation!==`disable`&&_?.droidReasoningDefaults!==void 0?{droidReasoningDefaults:_.droidReasoningDefaults}:{}}),v(null),t===`droid`&&u(null)}catch(e){throw k(),e instanceof Sv&&e.stalePlan?e:Error(sy(a,e),{cause:e})}finally{k(),c(!1)}}},P=()=>void j(L?`disable`:`apply`);if(!E)return(0,Q.jsx)(`section`,{className:`integration-client-page`,children:C.state.showError?(0,Q.jsxs)($,{tone:`err`,children:[a(`integrations.error.load`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:k,disabled:C.state.refreshing,children:a(`common.retry`)})]}):(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`common.loading`)})});let F=nv(E),I=E.state===`current`||E.state===`stale`||F,L=r===void 0?I:E.enabled===!0,R=r!==void 0&&(C.state.showError||C.state.refreshing),z=(!E.installed||(E.state===`conflict`||E.state===`unsafe`)&&!F)&&!(r!==void 0&&L);return(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Q.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Q.jsx)(PO,{src:NO(t),label:a(XM[t]),size:24}),(0,Q.jsx)(`h3`,{children:i??a(XM[t])}),(0,Q.jsx)(aM,{state:E.state,installed:E.installed,id:`integration-state-${t}${r===void 0?``:`-${r}`}`}),(0,Q.jsx)(on,{on:L,onClick:P,disabled:z||s||R,label:a(L?`integrations.action.disable`:`integrations.action.apply`)})]}),r!==void 0&&C.state.showError&&(0,Q.jsxs)($,{tone:`err`,children:[a(`integrations.aside.loadError`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:k,disabled:s||C.state.refreshing,children:a(`common.retry`)})]}),E.state===`stale`&&L&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void j(`apply`),disabled:s,children:a(`integrations.action.refresh`)}),t===`droid`&&E.droidReasoning&&(0,Q.jsx)(GM,{reasoning:E.droidReasoning,defaults:l?.scopeKey===o?l.values:E.droidReasoning.defaults,disabled:s||_!==null,onChange:e=>u({scopeKey:o,values:e}),onReview:()=>void j(`apply`)}),E.installed&&E.state===`conflict`&&E.reason!==`candidate-conflict`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void j(`overwrite`),disabled:s,children:a(`integrations.action.overwrite`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:a(YM[t])}),(0,Q.jsx)(`p`,{className:`integration-path`,children:E.configPath}),E.reason===`candidate-conflict`&&E.conflictPaths?.map(e=>(0,Q.jsx)($,{tone:`err`,children:a(`integrations.status.candidateConflict`,{path:e})},e)),E.raycast&&(0,Q.jsx)(WM,{install:E.raycast}),E.supersededBy&&(0,Q.jsx)($,{tone:`err`,children:E.supersededReason===`missing-store`&&E.missingStoreDocument!==void 0?a(`integrations.status.missingStore`,{path:E.supersededBy,document:E.missingStoreDocument}):a(`integrations.status.supersededStore`,{path:E.supersededBy})}),E.appliedAt&&(0,Q.jsxs)(`p`,{className:`integration-meta`,children:[a(`integrations.status.appliedAt`),`: `,new Date(E.appliedAt).toLocaleString()]}),E.retentionDegraded&&(0,Q.jsx)($,{tone:`err`,children:a(`integrations.retention.degraded`)}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),(0,Q.jsx)(`h4`,{children:a(`integrations.rollback.title`)}),w.state.showSkeleton?(0,Q.jsx)(my,{label:a(`integrations.rollback.title`),rows:2}):w.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[a(`integrations.rollback.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void w.refresh(),children:a(`common.retry`)})]}):D.length===0?(0,Q.jsx)(`p`,{className:`page-sub`,children:a(`integrations.rollback.empty`)}):(0,Q.jsx)(MM,{rows:D,onRestore:m,onDelete:g}),p&&(0,Q.jsx)(hM,{apiBase:e,row:p,profileId:r,onClose:()=>m(null),onRestored:()=>{t===`droid`?A():k()},onReconcile:k}),h&&(0,Q.jsx)(mM,{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:h.configPath}},onClose:()=>g(null),onConfirm:async()=>{try{await Lv(e,h.opId,void 0,r)}catch(e){if(Cv(e)){g(null),await w.refresh();return}throw Error(sy(a,e),{cause:e})}g(null),await w.refresh()}}),_&&(0,Q.jsx)(mM,{copy:_.operation===`overwrite`?KM(E.reason,E.configPath):_.operation===`disable`?JM:qM,plan:_.plan,planLoading:_.loading,planFailure:_.failure,missingStorePath:E.supersededReason===`missing-store`?E.supersededBy:void 0,onClose:M,onConfirm:async e=>{e&&await N(e)}})]})}function $M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eN(){throw new Sv(502,{code:`invalid_aside_profile_response`})}async function tN(e,t){let n=await Tv(await fetch(`${e}/api/client-integrations/aside/profiles`,{signal:t}));(!$M(n)||!Array.isArray(n.profiles)||typeof n.allEnabled!=`boolean`)&&eN();let r=n.profiles.map(e=>$_(e)??eN());new Set(r.map(e=>e.profileId)).size!==r.length&&eN();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))&&eN(),{profiles:r,allEnabled:n.allEnabled,enabledCount:i,appliedCount:a,total:r.length,...typeof n.error==`string`?{error:n.error}:{}}}async function nN(e,t){let n=await Tv(await fetch(`${e}/api/client-integrations/aside/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,signal:t}));(!$M(n)||typeof n.ok!=`boolean`||!Array.isArray(n.results))&&eN(),n.results.some(e=>!$M(e)||e.client!==`aside`)&&eN();let r=ev(n.results)??eN();return n.ok!==r.every(e=>e.ok)&&eN(),{ok:n.ok,results:r}}var rN={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`},iN={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 aN({apiBase:e,active:t=!0}){let n=O(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),s=(0,Z.useRef)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(new Map),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(0);(0,Z.useEffect)(()=>()=>{h.current+=1,m.current?.abort()},[]);let g=(0,Z.useCallback)(t=>tN(e,t),[e]),_=Ua(`aside-profiles:${e}`,[e],g,{enabled:t,isEmpty:e=>!e.error&&e.profiles.length===0,sessionCacheKey:`ocx.integrations.aside-profiles.v1:${e}`}),v=_.state.data,y=v?.profiles??[],b=_.state.showError||!!v?.error,x=a!==null||_.state.refreshing||f!==null,S=e=>e.name||n(`integrations.aside.profile`,{id:e.profileId}),C=e=>d(t=>{let r=new Map(t);for(let t of e)t.ok?r.delete(t.profileId):r.set(t.profileId,cy(n,t));return r}),w=(e,t)=>{e instanceof Sv&&`results`in e.body&&e.body.results?.length?(C(e.body.results),l(n(`integrations.aside.partial`))):t===void 0?l(sy(n,e)):d(r=>new Map(r).set(t,sy(n,e)))},T=async(t,r,i)=>{if(!s.current){s.current=!0,o(r??`all`),l(null);try{let n=await Fv(e,`aside`,{enabled:t,profileId:r,...i?{binding:Dv(i)}:{}});C(n.results??(r===void 0?y.map(e=>e.profileId):[r]).map(e=>({profileId:e,ok:!0})))}catch(e){if(i&&e instanceof Sv&&e.stalePlan)throw e;if(w(e,r),i)throw Error(sy(n,e),{cause:e})}finally{_.refresh(),s.current=!1,o(null)}}},E=async(t,r)=>{if(s.current||f)return;let i=new AbortController,a=h.current+1;h.current=a,m.current?.abort(),m.current=i,p({profile:t,enabled:r,plan:null,loading:!0,failure:null});try{let n=await Nv(e,`aside`,r?`apply`:`disable`,i.signal,t.profileId);if(i.signal.aborted||a!==h.current)return;m.current=null,p({profile:t,enabled:r,plan:n,loading:!1,failure:null})}catch(e){if(i.signal.aborted||a!==h.current)return;if(m.current=null,Ev(e)){p(null),_.refresh();return}p({profile:t,enabled:r,plan:null,loading:!1,failure:n(`integrations.preview.failed`)})}},D=()=>{h.current+=1,m.current?.abort(),m.current=null,p(null)},k=async()=>{if(!s.current){s.current=!0,o(`sync`),l(null);try{let t=await nN(e);C(t.results),t.ok||l(n(`integrations.aside.partial`))}catch(e){w(e)}finally{_.refresh(),s.current=!1,o(null)}}};return r?(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,autoFocus:!0,onClick:()=>{i(null),_.refresh()},children:n(`integrations.aside.back`)}),u.has(r.profileId)&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(r.profileId)})}),(0,Q.jsx)(ZM,{apiBase:e,client:`aside`,active:t,profileId:r.profileId,profileLabel:S(r)},r.profileId)]}):(0,Q.jsxs)(`section`,{className:`integration-client-page`,"aria-busy":x,children:[(0,Q.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Q.jsx)(PO,{src:NO(`aside`),label:n(`integrations.tab.aside`),size:24}),(0,Q.jsx)(`h3`,{children:n(`integrations.aside.profilesTitle`)})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.profilesHint`)}),(0,Q.jsxs)(`div`,{className:`aside-profile-toolbar`,children:[(0,Q.jsx)(on,{on:v?.allEnabled??!1,mixed:!!(v&&v.enabledCount>0&&v.enabledCount<v.total),onClick:()=>void T(!v?.allEnabled),disabled:x||b||y.length===0,label:n(`integrations.aside.all`),showLabel:!0}),(0,Q.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.applied`,{count:v?.appliedCount??0,total:v?.total??0})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:x||b||!v?.enabledCount,onClick:()=>void k(),children:n(`integrations.aside.syncNow`)})]}),c&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:c})}),[...u].filter(([e])=>!y.some(t=>t.profileId===e)).map(([e,t])=>(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsxs)(`span`,{className:`aside-profile-failure`,children:[n(`integrations.aside.profile`,{id:e}),`: `,t]})},e)),b&&(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{children:n(`integrations.aside.loadError`)}),v?.error&&(0,Q.jsx)(`span`,{className:`text-caption`,children:v.error}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>_.refresh(),disabled:x,children:n(`common.retry`)})]}),_.state.showSkeleton&&(0,Q.jsx)(my,{label:n(`common.loading`),rows:3}),!_.state.showSkeleton&&!b&&v&&y.length===0&&(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.empty`)}),y.length>0&&(0,Q.jsx)(`div`,{className:`aside-profile-list`,children:y.map(e=>{let t=S(e),r=e.state===`current`||e.state===`stale`,o=e.enabled!==r||e.enabled&&e.state===`stale`,s=(!e.installed||e.state===`unsafe`||e.state===`conflict`)&&!e.enabled;return(0,Q.jsxs)(`div`,{className:`aside-profile-row`,"aria-busy":a===e.profileId,children:[(0,Q.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-label":n(`integrations.aside.details`,{name:t}),onClick:()=>i(e),disabled:x||b,children:t}),(0,Q.jsxs)(`div`,{className:`aside-profile-meta`,children:[(0,Q.jsx)(`code`,{children:e.profileId}),e.current&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.current`)})]}),o&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.pending`)}),e.error&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:e.error}),u.has(e.profileId)&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(e.profileId)})})]}),(0,Q.jsxs)(`div`,{className:`aside-profile-controls`,children:[(0,Q.jsx)(aM,{state:e.state,installed:e.installed,id:`aside-profile-state-${e.profileId}`}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:x||b,"aria-label":n(`integrations.aside.retry`,{name:t}),onClick:()=>void E(e,e.enabled),children:n(`common.retry`)}),(0,Q.jsx)(on,{on:e.enabled,onClick:()=>void E(e,!e.enabled),disabled:x||b||s,label:n(`integrations.aside.toggle`,{name:t})})]})]},e.profileId)})}),f&&(0,Q.jsx)(mM,{copy:f.enabled?rN:iN,plan:f.plan,planLoading:f.loading,planFailure:f.failure,onClose:D,onConfirm:async e=>{e&&(await T(f.enabled,f.profile.profileId,e),p(null))}})]})}function oN(e){return e.proposedModel===e.model&&(e.proposedEffort==null||e.proposedEffort===e.effort)}function sN({apiBase:e,busy:t,apply:n}){let r=O(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)({}),[m,h]=(0,Z.useState)(null),g=async()=>{a(!0),l(null),h(null);try{let t=await hn(await fetch(`${e}/api/codex-agent-roles/auto-assign`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),r(`integrations.lazycodexRoles.auto.failed`));d(t??null),p({})}catch(e){d(null),l(e instanceof Error&&e.message?e.message:r(`integrations.lazycodexRoles.auto.failed`))}finally{a(!1)}},_=(u?.proposals??[]).filter(e=>e.status===`proposed`&&e.proposedModel&&!f[e.role]&&!oN(e)),v=async e=>{let t=await n(e.role,e.proposedModel,e.proposedEffort??void 0);return t&&p(t=>({...t,[e.role]:!0})),t},y=async()=>{s(!0);let e=0,t=_.length;for(let t of _)await v(t)&&(e+=1);h(r(`integrations.lazycodexRoles.auto.appliedCount`,{count:String(e),total:String(t)})),s(!1)},b=i||o||t;return(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign`,children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.lazycodexRoles.auto.hint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:b,onClick:()=>void g(),children:r(i?`integrations.lazycodexRoles.auto.running`:`integrations.lazycodexRoles.auto.button`)})]}),c&&(0,Q.jsx)($,{tone:`err`,children:c}),u&&(0,Q.jsxs)(`section`,{className:`lazycodex-auto-assign-panel`,"aria-labelledby":`lazycodex-auto-assign-title`,children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Q.jsx)(`h5`,{id:`lazycodex-auto-assign-title`,children:r(`integrations.lazycodexRoles.auto.title`)}),(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.sizedWith`,{model:u.sizingModel})}),(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:b||_.length===0,onClick:()=>void y(),children:r(`integrations.lazycodexRoles.auto.applyAll`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:o,onClick:()=>{d(null),h(null)},children:r(`integrations.lazycodexRoles.auto.discard`)})]})]}),u.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:r(`integrations.lazycodexRoles.auto.sizingFailed`,{error:u.sizingError})}),m&&(0,Q.jsx)($,{tone:`ok`,children:m}),(0,Q.jsx)(`ul`,{className:`lazycodex-auto-assign-list`,children:u.proposals.map(e=>(0,Q.jsxs)(`li`,{"aria-label":r(`integrations.lazycodexRoles.auto.proposalFor`,{role:e.role}),children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-head`,children:[(0,Q.jsx)(`code`,{children:e.role}),e.tier&&e.effortIntent&&(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.tierEffort`,{tier:r(lC[e.tier]),effort:r(uC[e.effortIntent])})})]}),e.status===`unsized`?(0,Q.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.unsized`,{reason:e.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-change`,children:[(0,Q.jsx)(`span`,{children:e.model?(0,Q.jsx)(`code`,{children:e.model}):r(`integrations.lazycodexRoles.none`)}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),e.proposedModel?(0,Q.jsxs)(`code`,{children:[e.proposedModel,e.proposedEffort?` · ${e.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.unassigned`,{reason:e.reason??``})}),e.status===`proposed`&&(f[e.role]||oN(e)?(0,Q.jsx)(`span`,{className:`lazycodex-auto-assign-done`,children:f[e.role]?r(`integrations.lazycodexRoles.auto.applied`):r(`integrations.lazycodexRoles.auto.alreadySet`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:b,onClick:()=>void v(e),children:r(`integrations.lazycodexRoles.auto.apply`)}))]}),e.rationale&&(0,Q.jsx)(`p`,{children:e.rationale}),e.moveUpIf&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.moveUp`,{text:e.moveUpIf})}),e.moveDownIf&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.auto.moveDown`,{text:e.moveDownIf})})]})]},e.role))})]})]})}var cN={absent:`integrations.lazycodexRoles.omoAbsent`,skipped_comments:`integrations.lazycodexRoles.omoComments`,invalid:`integrations.lazycodexRoles.omoInvalid`,write_failed:`integrations.lazycodexRoles.omoFailed`};function lN({apiBase:e,active:t}){let n=O(),[r,i]=(0,Z.useState)({}),[a,o]=(0,Z.useState)({}),[s,c]=(0,Z.useState)({}),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=(0,Z.useCallback)(async t=>{let r=await hn(await fetch(`${e}/api/codex-agent-roles`,{signal:t}),n(`integrations.lazycodexRoles.loadFailed`));if(r?.lazycodex?.detected!==!0)return{detected:!1,roles:[],omoJsonc:null,available:[],efforts:[]};let[i,a]=await Promise.all([fetch(`${e}/api/subagent-models`,{signal:t}).then(e=>hn(e,n(`integrations.lazycodexRoles.loadFailed`))),fetch(`${e}/api/injection-model`,{signal:t}).then(e=>hn(e,n(`integrations.lazycodexRoles.loadFailed`))).catch(()=>null)]);return{detected:!0,roles:r.roles??[],omoJsonc:r.omoJsonc??null,available:i?.available??[],efforts:a?.efforts??[]}},[e,n]),m=`lazycodex-role-models:${e}`,h=Ua(m,[e],p,{isEmpty:e=>e.roles.length===0,enabled:t}),g=h.state.data,_=(0,Z.useRef)(g);(0,Z.useLayoutEffect)(()=>{_.current=g},[g]);let v=async(t,r,a=void 0,d)=>{if(l!==null)return!1;let p=a===void 0?s[t]?.sent:a;if(r===void 0&&p===void 0)return!1;u(t),f(null);try{let a=(await hn(await fetch(`${e}/api/codex-agent-roles/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...r===void 0?{}:{model:r},...p===void 0?{}:{effort:p}})}),n(`integrations.lazycodexRoles.saveFailed`,{role:t})))?.omoJsonc?.status,s=_.current,l=s?.roles.find(e=>e.role===t),u=p===void 0?l?l.effort??null:d||null:p,g=u??``,v=r??l?.model??null;if(s){let e={...s,roles:s.roles.map(e=>e.role===t?{...e,model:r??e.model,effort:u,omoJsoncModel:r!==void 0&&(a===`written`||a===`unchanged`)?r:e.omoJsoncModel}:e)};_.current=e,Ut(m,e)}let y=a?cN[a]:void 0,b=v??n(`integrations.lazycodexRoles.none`),x=g?`${b} · ${g}`:b;f(y?{tone:`warn`,text:n(y,{role:t,model:x})}:{tone:`ok`,text:n(`integrations.lazycodexRoles.saved`,{role:t,model:x})});let S=a===`write_failed`,C=(e,n)=>{let{[t]:r,...i}=e;return S?{...i,[t]:n}:i};return i(e=>C(e,r??``)),o(e=>C(e,g)),c(e=>C(e,{sent:p})),await h.refresh(),!0}catch{return f({tone:`err`,text:n(`integrations.lazycodexRoles.saveFailed`,{role:t})}),!1}finally{u(null)}},y=(e,t)=>{let r=[...new Set([...e.model?[e.model]:[],...g?.available??[]])];return[...t===``?[{value:``,label:n(`integrations.lazycodexRoles.choose`)}]:[],...r.map(e=>({value:e,label:e}))]};return h.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[n(`integrations.lazycodexRoles.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h.refresh(),children:n(`common.retry`)})]}):g?.detected?(0,Q.jsxs)(`section`,{id:`lazycodex-role-models`,className:`lazycodex-role-models`,"aria-labelledby":`lazycodex-role-models-title`,children:[(0,Q.jsx)(`h4`,{id:`lazycodex-role-models-title`,children:n(`integrations.lazycodexRoles.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.lazycodexRoles.hint`)}),g.omoJsonc?.state===`comments`&&(0,Q.jsx)($,{tone:`warn`,children:n(`integrations.lazycodexRoles.omoCommentsState`)}),d&&(0,Q.jsx)($,{tone:d.tone,children:d.text}),g.roles.length===0?(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`integrations.lazycodexRoles.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(sN,{apiBase:e,busy:l!==null,apply:v}),(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`integrations.lazycodexRoles.role`)}),(0,Q.jsx)(`th`,{children:n(`integrations.lazycodexRoles.current`)}),(0,Q.jsxs)(`th`,{children:[n(`integrations.lazycodexRoles.model`),` · `,n(`integrations.lazycodexRoles.effort`)]})]})}),(0,Q.jsx)(`tbody`,{children:g.roles.map(e=>{let t=r[e.role]??e.model??``,c=a[e.role]??e.effort??``,u=c!==(e.effort??``),d=t!==``&&t!==e.model||u,f=s[e.role],p=f!==void 0&&(t!==``||f.sent!==void 0);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.role})}),(0,Q.jsx)(`td`,{children:e.model?(0,Q.jsx)(`code`,{children:e.effort?`${e.model} · ${e.effort}`:e.model}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`integration-meta`,children:n(`integrations.lazycodexRoles.none`)}),e.effort&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,(0,Q.jsx)(`code`,{children:e.effort})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`lazycodex-role-models-edit`,children:[(0,Q.jsx)(cn,{value:t,options:y(e,t),label:n(`integrations.lazycodexRoles.modelFor`,{role:e.role}),disabled:l!==null,onChange:t=>i(n=>({...n,[e.role]:t}))}),(0,Q.jsx)(cn,{value:c,options:[{value:``,label:n(`integrations.lazycodexRoles.effortDefault`)},...[...new Set([...e.effort?[e.effort]:[],...g.efforts])].map(e=>({value:e,label:e}))],label:n(`integrations.lazycodexRoles.effortFor`,{role:e.role}),disabled:l!==null,onChange:t=>o(n=>({...n,[e.role]:t}))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!(d||p)||l!==null,onClick:()=>void v(e.role,t||void 0,u?c||null:void 0,e.effort??``),children:l===e.role?n(`common.saving`):n(p&&!d?`integrations.lazycodexRoles.retryMirror`:`common.save`)})]})})]},e.role)})})]})})]})]}):null}var uN=[{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:`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:`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`}],dN=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`,`qoder`]);function fN(e=window.location.hash){let t=fg(e);return t===`claude/desktop`?`claudeDesktop`:t===`claude`||t.startsWith(`claude/`)?`claude`:uN.find(e=>e.hash===t)?.id??`overview`}function pN(e){return`integrations-tab-${e}`}function mN(e){return`integrations-panel-${e}`}function hN(e){return e===`overview`||e===`keys`?null:AO[e]??null}function gN({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=O(),[i,a]=(0,Z.useState)(fN),[o,s]=(0,Z.useState)(()=>new Set([fN()])),c=(0,Z.useRef)(null),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)(!1);c.current===null&&(c.current=new Map),(0,Z.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/clients`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{!e.signal.aborted&&Array.isArray(t?.selectedClients)&&u(t.selectedClients.filter(e=>typeof e==`string`))}).catch(()=>{}),()=>e.abort()},[n,t]);let p=async()=>{f(!0);try{await fetch(`${t}/api/machine/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`})}finally{f(!1)}},m=e=>{a(e),s(t=>t.has(e)?t:new Set([...t,e]))};(0,Z.useEffect)(()=>{let e=()=>m(fN());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let h=(e,t)=>{let n=uN.find(t=>t.id===e);n&&(qt(n.hash),m(e),t&&window.requestAnimationFrame(()=>{c.current.get(e)?.focus({preventScroll:!0})}))},g=e=>{let t=uN.findIndex(e=>e.id===i),n=null;e.key===`ArrowLeft`?n=(t-1+uN.length)%uN.length:e.key===`ArrowRight`?n=(t+1)%uN.length:e.key===`Home`?n=0:e.key===`End`&&(n=uN.length-1),n!==null&&(e.preventDefault(),h(uN[n].id,!0))};return(0,Q.jsxs)(`section`,{className:`integrations-page`,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:r(`nav.connect`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.subtitle`)}),n&&(0,Q.jsxs)(`section`,{className:`notice`,"aria-label":r(`connection.clients.title`),children:[(0,Q.jsx)(`strong`,{children:r(`connection.clients.title`)}),(0,Q.jsx)(`span`,{children:l.length>0?l.join(`, `):r(`connection.clients.none`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d,onClick:()=>void p(),children:r(d?`connection.clients.syncing`:`connection.clients.sync`)})]}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`integrations.tabsLabel`),children:uN.map(e=>(0,Q.jsxs)(`button`,{ref:t=>{t?c.current.set(e.id,t):c.current.delete(e.id)},type:`button`,role:`tab`,id:pN(e.id),"aria-selected":i===e.id,"aria-controls":mN(e.id),tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>h(e.id,!0),onKeyDown:g,children:[hN(e.id)&&(0,Q.jsx)(PO,{src:hN(e.id),label:r(e.labelKey),size:14}),r(e.labelKey)]},e.id))}),uN.map(t=>{if(!o.has(t.id))return null;let n=i===t.id;return(0,Q.jsxs)(`div`,{role:`tabpanel`,id:mN(t.id),"aria-labelledby":pN(t.id),hidden:!n,children:[t.id===`overview`&&(0,Q.jsx)(HM,{apiBase:e,active:n}),t.id===`keys`&&(0,Q.jsx)(oA,{apiBase:e,active:n}),t.id===`codex`&&(0,Q.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,Q.jsx)(`h3`,{id:`codex-integration-title`,children:r(`integrations.codex.title`)}),(0,Q.jsx)(`p`,{children:r(`integrations.codex.body`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>qt(`startup`),children:r(`integrations.codex.openService`)})]}),t.id===`grok`&&(0,Q.jsx)(Xj,{apiBase:e,active:n}),t.id===`claude`&&(0,Q.jsx)(dj,{apiBase:e,active:n,embedded:!0}),t.id===`claudeDesktop`&&(0,Q.jsx)(`div`,{className:`claude-page claude-page--embedded`,children:(0,Q.jsx)(Wj,{apiBase:e,active:n},e)}),t.id===`cursor`&&(0,Q.jsx)(nM,{apiBase:e,active:n}),dN.has(t.id)&&(t.id===`aside`?(0,Q.jsx)(aN,{apiBase:e,active:n}):(0,Q.jsx)(ZM,{apiBase:e,client:t.id,active:n})),t.id===`omo`&&(0,Q.jsx)(lN,{apiBase:e,active:n})]},t.id)})]})}function _N(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 vN={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},yN={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},bN={desktop:`startup.protection.desktop`,service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function xN({ok:e,yes:t,no:n}){return(0,Q.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function SN({failed:e,data:n}){let{t:r}=t(),i=e?`startup-hero--risk`:n.status===`protected`?`startup-hero--safe`:n.status===`at-risk`?`startup-hero--risk`:`startup-hero--native`,a=e||n.status===`at-risk`?Ae:Te,o=n.routingKind===`opencodex-local`?`startup.routing.proxy`:n.routingKind===`custom-local`?`startup.routing.customLocal`:n.routingKind===`custom-remote`?`startup.routing.customRemote`:n.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`section`,{className:`panel startup-hero ${i}`,"aria-live":`polite`,children:[(0,Q.jsx)(`div`,{className:`startup-hero-icon`,children:(0,Q.jsx)(a,{})}),(0,Q.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,Q.jsx)(`span`,{className:`badge ${e||n.status===`at-risk`?`badge-amber`:`badge-green`}`,children:r(e?`startup.status.atRisk`:vN[n.status])}),(0,Q.jsx)(`h3`,{children:r(e?`startup.error`:yN[n.status])}),(0,Q.jsx)(`p`,{children:e?r(`startup.staleData`):n.status===`at-risk`?r(io(n)):r(`startup.safeDetail`)}),(0,Q.jsxs)(`p`,{className:`muted startup-state-line`,children:[r(o),` · `,r(bN[n.protection]),` · `,r(n.autostartEnabled?`startup.enabled`:`startup.disabled`)]}),(0,Q.jsx)(`p`,{className:`muted text-label`,children:r(`startup.subtitle`)})]})]})})}function CN({data:e,failed:n,loading:r=!1,installBusy:i,installResult:a,onInstall:o}){let{t:s}=t(),c=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,l=e.shimInstalled&&!e.shimHealthy&&e.shimActivationPending===!0,u=e.shimInstalled&&!e.shimHealthy&&!l,d=i!==null||n||r,f=d||no(e);return(0,Q.jsxs)(`section`,{className:`panel startup-details`,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:s(`startup.details`)}),(0,Q.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),e.desktop&&(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:s(`startup.protection.desktop`)}),(0,Q.jsx)(`span`,{children:s(!n&&e.desktop.viable?`startup.desktopHint`:io(e))})]}),(0,Q.jsx)(`div`,{className:`startup-detail-actions`,children:(0,Q.jsx)(xN,{ok:!n&&e.desktop.viable,yes:s(`startup.viable`),no:s(ro(e.desktop,n))})})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:s(`startup.service`)}),(0,Q.jsx)(`span`,{children:s(`startup.serviceHint`)})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Q.jsx)(xN,{ok:e.serviceViable,yes:s(`startup.viable`),no:s(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.service`)} - ${s(`startup.install`)}`,disabled:f,onClick:()=>o(`install-service`),children:s(i===`install-service`?`startup.installing`:`startup.install`)}),c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.service`)} - ${s(`startup.repair`)}`,disabled:f,onClick:()=>o(`install-service`,{repair:!0}),children:s(i===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:s(`startup.shim`)}),(0,Q.jsx)(`span`,{children:s(l?`startup.shimActivationHint`:`startup.shimHint`)})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Q.jsx)(xN,{ok:e.shimHealthy&&e.autostartEnabled,yes:s(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:s(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:l?`startup.shimActivationPending`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.shim`)} - ${s(`startup.install`)}`,disabled:d,onClick:()=>o(`install-shim`),children:s(i===`install-shim`?`startup.installing`:`startup.install`)}),u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.shim`)} - ${s(`startup.repair`)}`,disabled:d,onClick:()=>o(`install-shim`,{repair:!0}),children:s(i===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),a&&(0,Q.jsx)(`div`,{className:`notice ${a.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:a.kind===`success`?a.action===`install-service`?s(a.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):s(a.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${s(`startup.installFailed`)} ${a.detail??``}`})]})}function wN({tray:e,trayLoading:n,trayError:r,trayBusy:i,onTrayAction:a}){let{t:o}=t(),s=async()=>{await na({message:o(`startup.tray.uninstall`),tone:`danger`})&&a(`uninstall`)};return(0,Q.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:o(`startup.tray.title`)}),(0,Q.jsx)(Re,{})]}),(0,Q.jsx)(`p`,{className:`muted`,children:o(`startup.tray.hint`)}),(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o(`startup.tray.login`)}),(0,Q.jsx)(`span`,{children:o(`startup.tray.notProtection`)})]}),n||r||!e?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:o(n?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,Q.jsx)(xN,{ok:e.running&&!e.stale,yes:o(`startup.tray.running`),no:o(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,Q.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!n&&!r&&e&&!e.installed&&!e.stale&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:i,onClick:()=>a(`install`),children:o(`startup.tray.install`)}),!n&&!r&&e?.installed&&!e.stale&&!e.running&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:i,onClick:()=>a(`start`),children:o(`startup.tray.start`)}),!n&&!r&&e?.running&&!e.stale&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:i,onClick:()=>a(`stop`),children:o(`startup.tray.stop`)}),!n&&!r&&e&&(e.installed||e.stale)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:i,onClick:()=>{s()},children:o(`startup.tray.uninstall`)})]}),(r||e?.stale)&&(0,Q.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:o(`startup.tray.error`)})]})}function TN({data:e,copied:n,onCopy:r}){let{t:i}=t(),a=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,Q.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:i(`startup.recovery`)}),(0,Q.jsx)(de,{})]}),(0,Q.jsxs)(`details`,{className:`startup-recovery-details`,open:e.status!==`protected`,children:[(0,Q.jsx)(`summary`,{className:`muted`,children:i(no(e)?`startup.protection.desktop`:`startup.recoveryHint`)}),no(e)&&(0,Q.jsx)(`p`,{className:`muted`,children:i(io(e))}),(0,Q.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&!no(e)&&(0,Q.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(`startup.command.service`)}),(0,Q.jsx)(`code`,{children:a})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(a),children:i(n===a?`startup.copied`:`startup.copy`)})]}),(0,Q.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(`startup.command.shim`)}),(0,Q.jsx)(`code`,{children:e.commands.installShim})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e.commands.installShim),children:n===e.commands.installShim?i(`startup.copied`):i(`startup.copy`)})]}),(0,Q.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(`startup.command.native`)}),(0,Q.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e.commands.restoreNative),children:n===e.commands.restoreNative?i(`startup.copied`):i(`startup.copy`)})]})]}),e.status===`at-risk`&&e.recommendedCommand&&!no(e)&&(0,Q.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,Q.jsx)(Re,{}),` `,i(`startup.recommended`,{cmd:e.recommendedCommand})]})]})]})}var EN=`ocx.startup.page.v1:`;function DN(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function ON(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=DN([`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 kN({apiBase:e,machineApiBase:n=e,connected:r=!1}){let{t:i}=t(),a=`${EN}${e}`,o=(0,Z.useMemo)(()=>La(a),[a]),s=`startup-page:${e}`,[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(()=>o?.tray??null),[f,p]=(0,Z.useState)(()=>!o?.data),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(()=>o?.warning??null),[w,T]=(0,Z.useState)(()=>o?.fix??null),[E,D]=(0,Z.useState)(()=>!o?.data),O=(0,Z.useRef)(!!o?.data),k=(0,Z.useRef)(0),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{if(!r)return;let e=new AbortController;return fetch(`${n}/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()},[r,n]);let P=async e=>{N(!0);try{let t=await fetch(`${n}/api/machine/shim`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:e})});if(t.ok){let e=await t.json();j(e.shim??null)}}finally{N(!1)}};(0,Z.useEffect)(()=>()=>{k.current+=1},[e]);let F=(0,Z.useCallback)(async t=>{let n=++k.current,r=O.current;r||(p(!0),D(!0));try{let r=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=La(a);Va(a,{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(!_N(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([r,l]).then(([e,r])=>{if(t.aborted||n!==k.current)return;let o=s.platform===`win32`?r.tray:null;if(s.platform===`win32`?(d(o),_(r.error)):(d(null),_(!1)),p(!1),D(!1),e){let t=ON(e.codexRuntime,i,s.platform);C(t.warning),T(t.fix),Va(a,{data:s,warning:t.warning,fix:t.fix,tray:o});return}let c=La(a);Va(a,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:o})}),s}catch(e){throw t.aborted?e:(r||(d(null),_(!0),C(null),T(null)),D(!1),p(!1),e)}},[e,a,i]),I=Ua(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,Z.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(!_N(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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:i(`startup.title`)}),(0,Q.jsx)(`div`,{className:`startup-page-head-actions`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),disabled:B,children:[(0,Q.jsx)(re,{}),` `,i(`startup.refresh`)]})})]}),r&&(0,Q.jsxs)(`section`,{className:`notice startup-page-notice`,"aria-label":i(`connection.machine.title`),children:[(0,Q.jsx)(`strong`,{children:i(`connection.machine.title`)}),(0,Q.jsx)(`span`,{children:A?.healthy?i(`connection.machine.shimHealthy`):i(`connection.machine.shimNeedsAttention`)}),(0,Q.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`repair`),children:i(`connection.machine.repairShim`)}),A?.installed&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`uninstall`),children:i(`connection.machine.removeShim`)})]})]}),L.showSkeleton&&!z?(0,Q.jsx)(my,{label:i(`startup.loading`),rows:5}):L.kind===`failed-cold`?(0,Q.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,Q.jsx)($,{tone:`err`,children:L.error instanceof Error?L.error.message:i(`startup.error`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),children:i(`common.retry`)})]}):z?(0,Q.jsxs)(Q.Fragment,{children:[L.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`startup.error`)}),V&&(0,Q.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:i(`startup.staleData`)}),(E||S)&&(0,Q.jsx)(`div`,{className:`startup-runtime-notice-slot${E&&!S?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":E&&!S?!0:void 0,children:S&&(0,Q.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,Q.jsx)(`p`,{className:`startup-runtime-notice__text`,children:S}),w&&(0,Q.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,Q.jsx)(`code`,{children:w}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void H(w),children:i(c===w?`startup.copied`:`startup.copy`)})]})]})}),(0,Q.jsx)(SN,{failed:V,data:z}),(0,Q.jsx)(CN,{data:z,failed:V,loading:B,installBusy:v,installResult:b,onInstall:(e,t)=>{W(e,t)}}),z.platform===`win32`&&(0,Q.jsx)(wN,{tray:u,trayLoading:f,trayError:g,trayBusy:m,onTrayAction:e=>{U(e)}}),(0,Q.jsx)(TN,{data:z,copied:c,onCopy:e=>{H(e)}})]}):null]})}function AN(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function jN(e){return`'${e.replace(/'/g,`''`)}'`}function MN(e,t){return{posix:`printf '%s\\n' ${AN(e)} | ocx remote-workspace pair ${AN(t)} --pairing-code-stdin --root "$PWD" && ocx remote-workspace agent`,powershell:`$pairingCode = ${jN(e)}; $pairingCode | ocx remote-workspace pair ${jN(t)} --pairing-code-stdin --root (Get-Location).Path; if ($LASTEXITCODE -eq 0) { ocx remote-workspace agent }`}}var NN=[`codex`,`claude`,`pi`],PN={codex:`Codex`,claude:`Claude Code`,pi:`Pi`},FN={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`},IN={status:`remote.event.status`,tool:`remote.event.tool`,error:`remote.event.error`};function LN(e){return e===`codex`||e===`claude`||e===`pi`}function RN(e){return e===`read-only`||e===`workspace`}async function zN(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function BN({apiBase:e,hubOrigin:t}){let n=O(),r=Vt(`remote-workspace:${e}`,[e],async t=>await hn(await fetch(`${e}/api/remote-workspace`,{signal:t,cache:`no-store`}),n(`remote.loadFailed`)),{pollMs:3e3,deadlineMs:1e4}),i=r.data,[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(`codex`),[d,f]=(0,Z.useState)(`read-only`),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)({}),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(!1),D=(0,Z.useRef)(null),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),P=i?.devices??[],I=P.find(e=>e.id===a)??P.find(e=>e.online)??P[0]??null,L=I?.roots.find(e=>e.id===s)??I?.roots[0]??null,R=d===`workspace`&&(I?.capabilities.includes(`workspace.exec`)??!1),z=I&&!I.capabilities.includes(`workspace.exec`)?n(`remote.access.workspaceFilesOnly`):n(`remote.access.workspace`),B=NN.filter(e=>i?.runtimes?.[e]?.available),V=B.includes(l)?l:B[0]??l,H=i?.sessions??[],U=[...H].reverse().find(e=>e.status!==`stopped`),W=(H.find(e=>e.id===p)??(h?.id===p?h:null)??U??h)?.id,G=H.find(e=>e.id===W),ee=h?.id===W?h:null,K=(ee&&(!G||(ee.events.at(-1)?.sequence??0)>(G.events.at(-1)?.sequence??0))?ee:G)??U??h,q=y[K?.id??``]??``,te=e=>{let t=K?.id;t&&b(n=>({...n,[t]:typeof e==`function`?e(n[t]??``):e}))},ne=!!(i&&!r.lastAttemptOk),J=!!(K&&q.trim()&&x===null&&!C&&!T&&!ne&&K.status!==`running`&&K.status!==`starting`&&K.status!==`stopped`&&(K.status!==`failed`||K.resumable!==!1)&&!(K.status===`waiting_for_executor`&&!P.find(e=>e.id===K.deviceId)?.online)),Y=(0,Z.useMemo)(()=>_?MN(_.code,t):{posix:``,powershell:``},[_,t]),ie=async(t,n,r)=>{let i=await hn(await fetch(`${e}${t}`,n),r);if(i===void 0)throw Error(r);return i},X=async()=>{S(`pair`),A(null);try{let e=await ie(`/api/remote-workspace/pairing`,{method:`POST`},n(`remote.requestFailed`));v(e),M(null)}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{S(null)}},ae=async()=>{if(!(!I||!L)){S(`session`),A(null);try{let e=await ie(`/api/remote-workspace/sessions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:V,deviceId:I.id,rootId:L.id,accessMode:d})},n(`remote.requestFailed`));g(e),m(e.id),A({tone:`ok`,text:n(`remote.sessionStarted`)}),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{S(null)}}},oe=async()=>{if(!K||!J)return;let t=K,i=q;w(!0),A(null);let a;try{let o=await fetch(`${e}/api/remote-workspace/sessions/${t.id}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({prompt:i})});a=o.status;let s=await hn(o,n(`remote.requestFailed`));if(!s)throw Error(n(`remote.requestFailed`));te(e=>e===i?``:e),D.current!==t.id&&g(s),r.refresh()}catch(e){D.current!==t.id&&(A({tone:`err`,text:a!==void 0&&a>=400&&a<500?e instanceof Error?e.message:n(`remote.requestFailed`):n(`remote.submissionUnknown`)}),r.refresh())}finally{w(!1)}},se=async()=>{if(!K||T)return;let e=K;E(!0);try{await ie(`/api/remote-workspace/sessions/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),D.current=e.id,g({...e,status:`stopped`}),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{E(!1)}},ce=async e=>{if(await na({message:n(`remote.revokeConfirm`,{name:e.name}),confirmLabel:n(`common.remove`),tone:`danger`})){S(`revoke`);try{await ie(`/api/remote-workspace/devices/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),a===e.id&&o(``),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{S(null)}}},le=async(e,t)=>{M(await zN(t)?e:null)};return r.loading&&!i?(0,Q.jsx)(`div`,{className:`alert`,children:n(`remote.loading`)}):r.error&&!i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:n(`remote.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void r.refresh(),children:n(`common.retry`)})]}):i?.available===!1?(0,Q.jsx)($,{tone:`err`,children:n(`remote.hubRequired`)}):(0,Q.jsxs)(`section`,{className:`remote-workspace-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:n(`remote.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:n(`remote.subtitle`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void r.refresh(),disabled:r.refreshing,children:[(0,Q.jsx)(re,{}),` `,n(`remote.refresh`)]})]}),ne?(0,Q.jsx)($,{tone:`err`,children:n(`remote.loadFailed`)}):null,k?(0,Q.jsx)($,{tone:k.tone,children:k.text}):null,(0,Q.jsxs)(`div`,{className:`remote-workspace-grid`,children:[(0,Q.jsxs)(`div`,{className:`remote-workspace-column`,children:[(0,Q.jsxs)(`article`,{className:`panel panel-accent remote-pair-card`,children:[(0,Q.jsxs)(`div`,{className:`remote-panel-head`,children:[(0,Q.jsx)(`div`,{className:`remote-icon`,children:(0,Q.jsx)(st,{})}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:n(`remote.addComputer`)}),(0,Q.jsx)(`p`,{children:n(`remote.addComputerHint`)})]})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void X(),disabled:x!==null,children:[(0,Q.jsx)(N,{}),` `,n(`remote.createPairing`)]}),_?(0,Q.jsxs)(`div`,{className:`remote-pairing-result`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCode`)}),(0,Q.jsx)(`div`,{className:`remote-pairing-code`,children:_.code}),(0,Q.jsx)(`div`,{className:`remote-expiry`,children:n(`remote.pairingExpires`,{time:new Date(_.expiresAt).toLocaleTimeString()})}),(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCommandPosix`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:Y.posix})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void le(`posix`,Y.posix),children:n(j===`posix`?`remote.copied`:`remote.copyCommand`)}),(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCommandWindows`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:Y.powershell})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void le(`powershell`,Y.powershell),children:n(j===`powershell`?`remote.copied`:`remote.copyCommand`)})]}):null]}),(0,Q.jsxs)(`section`,{className:`panel remote-device-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Q.jsx)(`h3`,{children:n(`remote.devices`)}),(0,Q.jsx)(`span`,{children:P.length})]}),P.length===0?(0,Q.jsx)(`p`,{className:`remote-empty`,children:n(`remote.noDevices`)}):(0,Q.jsx)(`div`,{className:`remote-device-list`,children:P.map(e=>(0,Q.jsxs)(`div`,{className:`remote-device${I?.id===e.id?` selected`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`remote-device-main`,onClick:()=>{o(e.id),c(e.roots[0]?.id??``)},"aria-pressed":I?.id===e.id,children:[(0,Q.jsx)(`span`,{className:`remote-online-dot${e.online?` online`:``}`}),(0,Q.jsxs)(`span`,{className:`remote-device-copy`,children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsxs)(`small`,{children:[e.platform,` · `,e.online?n(`remote.online`):n(`remote.offline`),` · `,e.capabilities.includes(`workspace.exec`)?n(`remote.capability.full`):n(`remote.capability.files`)]})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`remote-revoke`,"aria-label":n(`remote.revoke`),disabled:x!==null||C||T,onClick:()=>void ce(e),children:(0,Q.jsx)(F,{})})]},e.id))})]})]}),(0,Q.jsxs)(`div`,{className:`remote-workspace-column remote-session-column`,children:[(0,Q.jsxs)(`section`,{className:`panel remote-launch-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Q.jsx)(`h3`,{children:n(`remote.newSession`)}),(0,Q.jsx)(rt,{})]}),(0,Q.jsxs)(`div`,{className:`remote-launch-fields`,children:[(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.device`)}),(0,Q.jsx)(cn,{value:I?.id??``,options:P.map(e=>({value:e.id,label:e.name})),onChange:e=>{o(e),c(P.find(t=>t.id===e)?.roots[0]?.id??``)},label:n(`remote.device`),disabled:P.length===0})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.folder`)}),(0,Q.jsx)(cn,{value:L?.id??``,options:(I?.roots??[]).map(e=>({value:e.id,label:e.label})),onChange:c,label:n(`remote.folder`),disabled:!I})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.runtime`)}),(0,Q.jsx)(cn,{value:V,options:NN.map(e=>({value:e,label:i?.runtimes?.[e]?.available?PN[e]:`${PN[e]} · ${n(`remote.unavailable`)}`})),onChange:e=>{LN(e)&&u(e)},label:n(`remote.runtime`)})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.access`)}),(0,Q.jsx)(cn,{value:d,options:[{value:`read-only`,label:n(`remote.access.readOnly`)},{value:`workspace`,label:z}],onChange:e=>{RN(e)&&f(e)},label:n(`remote.access`)})]})]}),I?(0,Q.jsxs)(`div`,{className:`remote-execution-map`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:PN[V]}),n(`remote.runsOnHub`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:I.name}),n(d===`read-only`?`remote.runsReadOnly`:R?`remote.runsFilesCommands`:`remote.runsFilesOnly`)]})]}):null,d===`workspace`&&!R&&I?(0,Q.jsx)($,{tone:`err`,children:n(`remote.execUnavailable`)}):null,!i?.runtimes?.[V]?.available&&i?.runtimes?.[V]?.reason?(0,Q.jsx)(`p`,{className:`remote-runtime-reason`,children:i.runtimes[V].reason}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary remote-start`,onClick:()=>void ae(),disabled:!I?.online||!L||!i?.runtimes?.[V]?.available||x!==null||C||T,children:[(0,Q.jsx)(de,{}),` `,n(`remote.startSession`)]})]}),(0,Q.jsxs)(`section`,{className:`panel remote-console-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:n(`remote.sessions`)}),K?(0,Q.jsxs)(`small`,{children:[PN[K.profile],` · `,K.deviceName,`/`,K.rootLabel,` · `,K.accessMode===`read-only`?n(`remote.access.readOnly`):K.capabilities.includes(`workspace.exec`)?n(`remote.access.workspace`):n(`remote.access.workspaceFilesOnly`)]}):null]}),K?(0,Q.jsx)(`span`,{className:`remote-status remote-status--${K.status}`,children:n(FN[K.status])}):null]}),H.length>1?(0,Q.jsx)(cn,{value:K?.id??``,options:H.map(e=>({value:e.id,label:`${PN[e.profile]} · ${e.deviceName}/${e.rootLabel}`})),onChange:m,label:n(`remote.sessions`)}):null,K?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`remote-events`,"aria-live":`polite`,"aria-label":n(`remote.events`),children:K.events.length===0?(0,Q.jsx)(`p`,{className:`remote-empty`,children:n(`remote.noEvents`)}):K.events.map(e=>(0,Q.jsxs)(`div`,{className:`remote-event remote-event--${e.type}`,children:[(0,Q.jsx)(`span`,{children:e.type===`assistant`?PN[K.profile]:n(IN[e.type])}),(0,Q.jsx)(`p`,{children:e.text})]},e.sequence))}),K.status===`failed`&&K.resumable===!1?(0,Q.jsx)($,{tone:`err`,children:n(`remote.notResumable`)}):null,(0,Q.jsxs)(`label`,{className:`remote-composer`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`remote.prompt`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:4,value:q,onChange:e=>te(e.target.value),placeholder:n(`remote.promptPlaceholder`),disabled:K.status===`stopped`||K.status===`failed`&&K.resumable===!1,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),oe())}})]}),(0,Q.jsxs)(`div`,{className:`remote-console-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void oe(),disabled:!J,children:n(`remote.send`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void se(),disabled:T||K.status===`stopped`,children:n(`remote.stop`)})]})]}):(0,Q.jsx)(`p`,{className:`remote-empty remote-empty--console`,children:n(`remote.noSessions`)})]})]})]})]})}function VN(){window.location.reload()}var HN={connecting:`remoteLink.status.connecting`,connected:`remoteLink.status.connected`,reconnecting:`remoteLink.status.reconnecting`,failed:`remoteLink.status.failed`,idle:`remoteLink.status.idle`},UN={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`},WN={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`},GN={pairing_required:`remoteLink.joinDenied.pairing_required`,standalone_required:`remoteLink.childDisabled`,join_port_mismatch:`remoteLink.error.join_port_mismatch`};function KN(e){return typeof e==`object`&&!!e}function qN(e){return typeof e==`string`&&e.length>0}function JN(e){if(!KN(e)||!Array.isArray(e.candidates))throw Error(`invalid candidates`);return e.candidates.map(e=>{if(!KN(e)||!qN(e.alias)||!qN(e.source))throw Error(`invalid candidate`);return{alias:e.alias,source:e.source}})}function YN(e){if(!KN(e)||!qN(e.alias)||!qN(e.fingerprint)||!qN(e.keyType))throw Error(`invalid probe`);return{alias:e.alias,fingerprint:e.fingerprint,keyType:e.keyType}}function XN(e){if(!KN(e)||!qN(e.alias)||!qN(e.fingerprint)||!qN(e.ocxVersion))throw Error(`invalid confirmation`);return{alias:e.alias,fingerprint:e.fingerprint,ocxVersion:e.ocxVersion}}function ZN(e){return e instanceof pk&&e.code in UN?UN[e.code]:`remoteLink.error.generic`}function QN(e){return{key:ZN(e),hint:e instanceof pk?e.hint:null}}function $N({error:e}){let t=O();return(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{className:`remote-link-error`,children:t(e.key)}),e.hint&&(0,Q.jsxs)(`span`,{className:`remote-link-hint`,children:[t(`remoteLink.reason.generic`),` `,(0,Q.jsx)(`code`,{children:e.hint})]})]})}function eP({apiBase:e,sessionReady:t,pairingRecoveryAvailable:n=!1,onRequestPairing:r,workspaceAvailable:i=!1,onOpenWorkspace:a,onChildReady:o=VN,restartWait:s}){let c=O(),[l,u]=(0,Z.useState)(`off`),[d,f]=(0,Z.useState)(`home`),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(`idle`),[w,E]=(0,Z.useState)([]),[k,A]=(0,Z.useState)(``),[j,M]=(0,Z.useState)(null),[P,I]=(0,Z.useState)(null),[L,R]=(0,Z.useState)(!1),[z,B]=(0,Z.useState)(null),[V,H]=(0,Z.useState)(null),[U,W]=(0,Z.useState)(null),[G,ee]=(0,Z.useState)(null),[K,q]=(0,Z.useState)(null),te=(0,Z.useRef)(null),ne=(0,Z.useRef)(null),J=(0,Z.useRef)(null),Y=(0,Z.useRef)(null),ie=(0,Z.useRef)([]),X=(0,Z.useRef)(null),ae=(0,Z.useRef)(0),oe=(0,Z.useRef)(null),se=(0,Z.useRef)(0),ce=(0,Z.useRef)(null),le=(0,Z.useRef)(!1),[ue,de]=(0,Z.useState)(!1),fe=n&&r&&(!t||v)?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:r,children:c(`connection.pairing.title`)}):null,pe=(0,Z.useCallback)(()=>{oe.current?.controller.abort();let e={controller:new AbortController,sequence:++se.current};return oe.current=e,e},[]),me=(0,Z.useCallback)(()=>{se.current+=1,oe.current?.controller.abort(),oe.current=null},[]),he=e=>oe.current?.sequence===e.sequence&&!e.controller.signal.aborted,ge=(0,Z.useCallback)(()=>{ae.current+=1,X.current?.controller.abort(),X.current=null},[]),_e=(0,Z.useCallback)(async()=>{if(!t||document.visibilityState===`hidden`||le.current)return;X.current?.controller.abort();let n=new AbortController,r=++ae.current;X.current={controller:n,sequence:r};try{let t=bk(await Sk(e,`/api/link/status`,{signal:n.signal}));if(n.signal.aborted||ae.current!==r)return;h(t),_(null),y(!1),U?u(`failed`):t.role===`child`?u(`connected`):t.links.length===0?u(e=>[`role-select`,`adding-child`,`confirming-host`,`applying`,`joining`,`restart-waiting`].includes(e)?e:`off`):t.links.some(e=>e.state===`failed`)?u(`failed`):t.links.some(e=>e.state===`reconnecting`)?u(`reconnecting`):t.links.some(e=>e.state===`connected`)&&u(`connected`)}catch(e){if(n.signal.aborted||ae.current!==r)return;_(ZN(e)),y(e instanceof pk&&(e.status===401||e.status===403))}finally{X.current?.sequence===r&&(X.current=null)}},[e,U,t]),ye=(0,Z.useEffectEvent)(()=>{_e()});(0,Z.useEffect)(()=>{if(!t)return;Promise.resolve().then(ye);let e=window.setInterval(ye,5e3),n=()=>{document.visibilityState===`visible`?ye():ge()};return document.addEventListener(`visibilitychange`,n),()=>{window.clearInterval(e),document.removeEventListener(`visibilitychange`,n),ge()}},[ge,t]),(0,Z.useEffect)(()=>{if(l!==`restart-waiting`)return;let t=new AbortController;return kk(e,ce.current,t.signal,{...s,onSlow:()=>de(!0)}).then(e=>{e===`ready`&&o()}),()=>t.abort()},[e,o,s,l]),(0,Z.useEffect)(()=>{if(!b){let e=ne.current?.open;ne.current?.close?.(),e&&te.current?.focus();return}let e=ne.current;e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``)),window.setTimeout(()=>e?.querySelector(`input, button`)?.focus(),0)},[b]),(0,Z.useEffect)(()=>{let e=J.current;if(!G){e?.close?.();return}e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``))},[G]);let be=()=>{me(),x(!1),C(`idle`),E([]),M(null),I(null),R(!1),H(null),W(null),B(null),u(e=>[`failed`,`adding-child`,`confirming-host`,`applying`,`joining`].includes(e)?`adding-child`:e)},xe=p(),Se=xe&&m?.joinAvailable===!0,Ce=m?.joinDenied?GN[m.joinDenied]:`remoteLink.joinDenied.unavailable`,we=D(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=pe();C(`loading`),E([]),H(null),W(null),B(`candidates`),M(null),I(null),R(!1);try{let n=await Sk(e,`/api/link/candidates`,{signal:t.controller.signal});if(!he(t))return;E(JN(n)),C(`ready`)}catch(e){if(!he(t))return;C(`failed`),H(QN(e))}finally{he(t)&&B(null)}},De=async()=>{x(!0),u(`adding-child`),await Ee()},Oe=async(t=k.trim(),n=oe.current??pe())=>{let r=t.trim();if(r){S===`failed`&&C(`idle`),B(`probe`),H(null),M(null),I(null),R(!1),W(null),u(`adding-child`);try{let t=await Sk(e,`/api/link/probe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal});if(!he(n))return;M(YN(t))}catch(e){if(!he(n))return;H(QN(e)),W({phase:`probe`,alias:r}),u(`failed`)}finally{he(n)&&B(null)}}},ke=async()=>{if(!j||!L)return;let t=oe.current;if(t){B(`confirm`),H(null);try{let n=await Sk(e,`/api/link/confirm-host`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:j.alias,fingerprint:j.fingerprint}),signal:t.controller.signal});if(!he(t))return;I(XN(n))}catch(e){if(!he(t))return;H(QN(e))}finally{he(t)&&B(null)}}},Ae=async(t=oe.current)=>{let n=P;if(!(!n||!t)){B(`apply`),H(null),W(null),u(`applying`);try{if(await Sk(e,`/api/link/apply`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:n.alias}),signal:t.controller.signal}),!he(t))return;be(),_e()}catch(e){if(!he(t))return;H(QN(e)),W({phase:`apply`,alias:n.alias}),u(`failed`)}finally{he(t)&&B(null)}}},je=async(t=P?.alias,n=oe.current??pe())=>{let r=t?.trim();if(!(!r||!Se)){B(`join`),H(null),W(null),u(`joining`);try{if(ce.current=(await Ck(e,n.controller.signal))?.pid??null,!he(n)||(await Sk(e,`/api/link/join`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal}),!he(n)))return;le.current=!0,ge(),be(),de(!1),u(`restart-waiting`)}catch(e){if(!he(n))return;H(QN(e)),W({phase:`join`,alias:r}),u(`failed`)}finally{he(n)&&B(null)}}},Me=async()=>{let t=(m?.links??[]).filter(e=>e.direction===`hub-initiated`&&(e.state===`failed`||e.state===`reconnecting`));if(t.length===0){await _e();return}B(`reconnect`),H(null);try{let n=(await Promise.allSettled(t.map(t=>Sk(e,`/api/link/${encodeURIComponent(t.id)}/reconnect`,{method:`POST`})))).find(e=>e.status===`rejected`);n&&H(QN(n.reason))}finally{await _e(),B(null)}},Ne=()=>{if(!U){Me();return}let e=pe();if(U.phase===`probe`){A(U.alias),Oe(U.alias,e);return}if(U.phase===`join`){je(U.alias,e);return}Ae(e)},Pe=()=>{ee(null),q(null),window.setTimeout(()=>Y.current?.focus(),0)},Fe=(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&&(ie.current[n]?.focus(),f(n===0?`home`:`child`))},Ie=async()=>{if(!G)return;let t=G;B(`remove`),q(null);try{await Sk(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 pk&&e.code===`remote_disconnect_failed`?ee({row:t.row,force:!0}):q(ZN(e))}finally{B(null)}},Le=m?.links??[],Re=d===`home`&&(l===`adding-child`||l===`confirming-host`||l===`applying`),ze=m?.role===`home`||Re?`remoteLink.role.home`:m?.role===`child`?`remoteLink.role.child`:`remoteLink.role.standalone`,Be=d===`child`&&!Se;return t?(0,Q.jsxs)(`div`,{className:`remote-link-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:c(`link.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:c(`link.subtitle`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void _e(),disabled:z!==null,children:[(0,Q.jsx)(re,{}),c(`link.refresh`)]})]}),i&&(0,Q.jsxs)(`section`,{className:`panel remote-link-workspace-card`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:c(`remoteLink.workspaceMoved.title`)}),(0,Q.jsx)(`p`,{children:c(`remoteLink.workspaceMoved.body`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:a??(()=>{window.location.hash=`remote-workspace`}),children:c(`remoteLink.workspaceMoved.open`)})]}),g&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`remote-link-error`,children:c(g)})}),fe&&(0,Q.jsx)(`section`,{className:`panel`,children:fe})]}),Le.length===0&&l===`off`&&(0,Q.jsxs)(`section`,{className:`panel remote-link-off-preview`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-switch-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:c(`link.switch`)}),(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(`link.switchOffHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`remote-link-switch`,"aria-checked":`false`,"aria-label":c(`link.switch`),onClick:()=>u(`role-select`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-preview-content`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-preview-row`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-preview-lines`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`span`,{className:`remote-link-status`,children:c(`remoteLink.status.idle`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-preview-row`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-preview-lines`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`span`,{className:`remote-link-status`,children:c(`remoteLink.role.child`)})]})]})]}),l===`role-select`&&(0,Q.jsxs)(`section`,{className:`panel remote-link-panel`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:c(`link.role.title`)}),(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(`link.role.hint`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-role-grid`,role:`radiogroup`,"aria-label":c(`link.role.title`),children:[(0,Q.jsxs)(`button`,{ref:e=>{ie.current[0]=e},type:`button`,role:`radio`,tabIndex:d===`home`?0:-1,"aria-checked":d===`home`,className:`remote-link-role-card`,onClick:()=>f(`home`),onKeyDown:e=>{[`ArrowRight`,`ArrowDown`,`ArrowLeft`,`ArrowUp`,`Home`,`End`].includes(e.key)&&(e.preventDefault(),Fe(0,e.key))},children:[(0,Q.jsx)(`strong`,{children:c(`link.role.home`)}),(0,Q.jsx)(`span`,{children:c(`link.role.homeHint`)})]}),(0,Q.jsxs)(`button`,{ref:e=>{ie.current[1]=e},type:`button`,role:`radio`,tabIndex:Se&&d===`child`?0:-1,"aria-checked":d===`child`,"aria-disabled":!Se,className:`remote-link-role-card`,onClick:()=>{Se&&(f(`child`),De())},onKeyDown:e=>{Se&&[`ArrowRight`,`ArrowDown`,`ArrowLeft`,`ArrowUp`,`Home`,`End`].includes(e.key)&&(e.preventDefault(),Fe(1,e.key))},children:[(0,Q.jsx)(`strong`,{children:c(`link.role.child`)}),(0,Q.jsx)(`span`,{children:c(`link.role.childHint`)})]})]}),!xe&&(0,Q.jsx)($,{tone:`warn`,children:c(`remoteLink.childDisabled`)}),xe&&m!==null&&!m.joinAvailable&&(0,Q.jsx)($,{tone:`warn`,children:c(Ce)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Be||m?.role===`child`,onClick:()=>void De(),children:c(d===`child`?`remoteLink.findHome.action`:`link.continue`)})]}),l===`role-select`&&Te&&m?.joinAvailable===!1&&m.joinDenied===`pairing_required`&&(0,Q.jsx)(zk,{local:!0,target:we,onConnected:()=>{_e()}}),(l===`connected`||l===`reconnecting`||l===`failed`||l===`restart-waiting`||m?.role===`child`||Le.length>0||l===`adding-child`||l===`confirming-host`||l===`applying`||l===`joining`)&&(0,Q.jsxs)(`section`,{className:`panel remote-link-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-toolbar`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:c(d===`child`&&xe?`remoteLink.findHome.title`:`link.children`)}),(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(l===`restart-waiting`?`remoteLink.restart.waiting`:ze)})]}),(0,Q.jsxs)(`button`,{ref:te,type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void De(),disabled:z!==null||l===`applying`||l===`joining`||l===`restart-waiting`||m?.role===`child`,children:[(0,Q.jsx)(N,{}),c(d===`child`&&xe?`remoteLink.findHome.action`:`link.addChild`)]})]}),l===`restart-waiting`?(0,Q.jsxs)(`div`,{className:`remote-link-restart`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:c(`remoteLink.restart.title`)}),(0,Q.jsx)(`p`,{children:c(`remoteLink.restart.body`)}),ue&&(0,Q.jsx)($,{tone:`warn`,children:c(`remoteLink.restart.slow`)})]}):m?.role===`child`?(0,Q.jsx)(`div`,{className:`remote-link-children`,"aria-live":`polite`,children:(0,Q.jsx)(`div`,{className:`remote-link-row`,children:(0,Q.jsxs)(`div`,{className:`remote-link-row-main`,children:[(0,Q.jsx)(`strong`,{children:m.child?.alias??c(`remoteLink.role.child`)}),m.child&&(0,Q.jsx)(`div`,{className:`remote-link-row-meta`,children:(0,Q.jsx)(`span`,{className:`remote-link-status`,"data-state":m.child.state,children:c(HN[m.child.state])})})]})})}):Le.length>0?(0,Q.jsx)(`div`,{className:`remote-link-children`,"aria-live":`polite`,children:Le.map(e=>(0,Q.jsxs)(`div`,{className:`remote-link-row`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-row-main`,children:[(0,Q.jsx)(`strong`,{children:e.alias}),(0,Q.jsxs)(`div`,{className:`remote-link-row-meta`,children:[(0,Q.jsx)(`span`,{className:`remote-link-status`,"data-state":e.state,children:c(HN[e.state])}),(0,Q.jsx)(`span`,{children:e.direction===`hub-initiated`?c(`remoteLink.direction.hub`):c(`remoteLink.direction.client`)}),e.reason&&(0,Q.jsx)(`span`,{className:`remote-link-error`,children:e.reason in WN?c(WN[e.reason]):(0,Q.jsxs)(Q.Fragment,{children:[c(`remoteLink.reason.generic`),` `,(0,Q.jsx)(`code`,{children:e.reason})]})})]})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:t=>{Y.current=t.currentTarget,ee({row:e,force:!1})},disabled:z!==null,children:[(0,Q.jsx)(F,{}),c(`link.disconnect`)]})]},e.id))}):(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(d===`child`&&xe?`remoteLink.findHome.empty`:`link.noChildren`)}),!b&&(l===`reconnecting`||l===`failed`&&(U!==null&&V?.key!==`remoteLink.error.join_restart_failed`||Le.some(e=>e.state===`failed`)))&&(0,Q.jsxs)(`div`,{className:`remote-link-status-message`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`remote-link-status`,"data-state":l===`failed`?`failed`:`reconnecting`,children:c(HN[l===`failed`?`failed`:`reconnecting`])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ne,disabled:z!==null,children:c(`link.retry`)})]}),l===`joining`&&(0,Q.jsx)(`p`,{className:`remote-link-info`,"aria-live":`polite`,children:c(`remoteLink.joining`)}),!b&&V&&(0,Q.jsx)($N,{error:V})]}),(0,Q.jsxs)(`dialog`,{ref:ne,className:`remote-link-sheet`,"aria-labelledby":`remote-link-sheet-title`,onCancel:e=>{e.preventDefault(),be()},children:[(0,Q.jsxs)(`div`,{className:`remote-link-sheet-head`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-sheet-title`,children:c(d===`child`&&xe?`remoteLink.findHome.title`:`link.sheetTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:be,"aria-label":c(`link.close`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsxs)(`div`,{className:`remote-link-sheet-body`,children:[d===`home`&&(0,Q.jsxs)(`div`,{className:`remote-link-info`,children:[(0,Q.jsx)(`p`,{children:c(`link.setup.relationship`)}),(0,Q.jsx)(`p`,{children:c(`link.setup.requirements`)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{children:c(d===`child`&&xe?`remoteLink.findHome.body`:`link.candidates`)}),S===`loading`&&(0,Q.jsx)(`p`,{className:`remote-link-info`,role:`status`,children:c(`link.loading`)}),S===`failed`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(`link.discoveryFailed`)}),b&&V&&(0,Q.jsx)($N,{error:V})]}),S===`ready`&&(w.length>0?(0,Q.jsx)(`div`,{className:`remote-link-candidates`,children:w.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`remote-link-candidate`,onClick:()=>A(e.alias),children:[(0,Q.jsx)(`span`,{children:e.alias}),(0,Q.jsx)(`small`,{children:e.source})]},`${e.source}:${e.alias}`))}):(0,Q.jsxs)(`div`,{className:`remote-link-info`,children:[(0,Q.jsx)(`p`,{children:c(`link.noCandidates`)}),(0,Q.jsx)(`p`,{children:c(d===`home`?`link.setup.emptyHome`:`link.setup.emptyLocal`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:`Host devbox
|
|
56
|
+
HostName devbox.example.com
|
|
57
|
+
User you
|
|
58
|
+
IdentityFile ~/.ssh/id_ed25519`})})]})),(0,Q.jsx)(`a`,{href:`https://opencodex.me/guides/remote-link/`,target:`_blank`,rel:`noopener noreferrer`,children:c(`link.setup.guide`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void Ee(),disabled:z!==null,children:c(S===`failed`?`link.retry`:`link.rescan`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-form`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`remote-link-alias`,children:c(`link.alias`)}),(0,Q.jsx)(`input`,{id:`remote-link-alias`,"aria-describedby":`remote-link-alias-help`,className:`input`,spellCheck:!1,value:k,onChange:e=>A(e.target.value),placeholder:c(`link.aliasPlaceholder`),autoComplete:`off`}),(0,Q.jsx)(`p`,{id:`remote-link-alias-help`,className:`remote-link-info`,children:c(`link.aliasRequired`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void Oe(),disabled:!k.trim()||z!==null,children:[(0,Q.jsx)(st,{}),c(z===`probe`?`link.probing`:`link.probe`)]})]}),j&&(0,Q.jsxs)(`div`,{className:`remote-link-panel`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`remote-link-info`,children:c(`link.hostFingerprint`)}),(0,Q.jsx)(`p`,{className:`remote-link-fingerprint`,children:(0,Q.jsx)(`code`,{children:j.fingerprint})}),(0,Q.jsx)(`span`,{className:`remote-link-info`,children:j.keyType})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:L,onChange:e=>R(e.target.checked)}),` `,c(`link.confirmFingerprint`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void ke(),disabled:!L||z!==null,children:c(z===`confirm`?`link.confirming`:`link.confirm`)})]}),P&&(0,Q.jsxs)(`div`,{className:`remote-link-panel`,children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(`link.ocxVersion`,{version:P.ocxVersion})}),d===`child`&&xe&&(0,Q.jsx)($,{tone:`warn`,children:c(`remoteLink.findHome.notice`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void(d===`child`&&xe?je():Ae()),disabled:z!==null||d===`child`&&!Se,children:c(d===`child`&&xe?z===`join`?`remoteLink.joining`:`remoteLink.findHome.connect`:z===`apply`?`link.applying`:`link.apply`)})]}),b&&S!==`failed`&&V&&(0,Q.jsx)($N,{error:V}),U&&V?.key!==`remoteLink.error.join_restart_failed`&&(0,Q.jsxs)(`div`,{children:[U.phase===`probe`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:c(`link.probeHelp`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:`ssh -o BatchMode=yes <alias> true`})})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:Ne,disabled:z!==null,children:c(`link.retry`)})]}),(0,Q.jsx)(`div`,{className:`remote-link-sheet-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:be,children:c(`link.cancel`)})})]})]}),(0,Q.jsx)(`dialog`,{ref:J,className:`remote-link-confirm-dialog`,"aria-labelledby":`remote-link-confirm-title`,onCancel:e=>{e.preventDefault(),Pe()},children:G&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{id:`remote-link-confirm-title`,children:G.force?c(`remoteLink.forceRemove.title`,{alias:G.row.alias}):c(`link.disconnect`)}),(0,Q.jsx)(`p`,{children:G.force?(0,Q.jsx)(T,{k:`remoteLink.forceRemove.body`,cmd:`ocx disconnect`,vars:{alias:G.row.alias}}):c(`link.disconnectConfirm`,{alias:G.row.alias})}),K&&(0,Q.jsx)(`p`,{className:`remote-link-error`,role:`alert`,children:c(K)}),(0,Q.jsxs)(`div`,{className:`remote-link-sheet-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:Pe,children:c(`link.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void Ie(),disabled:z===`remove`,children:G.force?c(`remoteLink.forceRemove.confirm`):c(`link.disconnect`)})]})]})})]}):(0,Q.jsxs)(`div`,{className:`remote-link-page`,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:c(`link.title`)})}),(0,Q.jsx)($,{tone:`warn`,children:c(`link.sessionRequired`)}),fe&&(0,Q.jsx)(`div`,{className:`panel`,children:fe})]})}function tP(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 nP=6e4,rP=7,iP=8,aP=.8;function oP(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 sP(e,t){return e.labelKey?t(e.labelKey):e.label??e.id}function cP(e,t){return e===`critical`?t(`quotaSummary.critical`):e===`warn`?t(`quotaSummary.warn`):``}function lP(e){try{return e.matches(`:focus-visible`)}catch{return!0}}function uP(e,t,n){(0,Z.useLayoutEffect)(()=>{if(!e)return;let r=()=>{let e=t.current,r=n.current;if(!e||!r)return;let i=e.getBoundingClientRect(),a=r.offsetWidth,o=document.documentElement.clientWidth||window.innerWidth,s=Math.max(iP,o-a-iP),c=Math.min(Math.max(i.left,iP),s);r.style.setProperty(`--qs-pop-top`,String(Math.round(i.bottom+rP))),r.style.setProperty(`--qs-pop-left`,String(Math.round(c))),r.style.setProperty(`--qs-pop-gap`,String(Math.round(i.bottom+rP)-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 dP({row:e,t,locale:n}){let[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(``),h=(0,Z.useId)(),g=!l&&(r||a||s),_=(0,Z.useCallback)(()=>{i(!1),o(!1),c(!1)},[]);(0,Z.useEffect)(()=>{if(!g)return;let e=e=>{d.current&&!d.current.contains(e.target)&&c(!1)},t=e=>{if(e.key===`Escape`){let e=p.current?.contains(document.activeElement);_(),e&&(f.current?.focus(),u(!0))}};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[g,_]),uP(g,f,p);let v=e=>{e.pointerType!==`touch`&&i(!0)},y=e=>{e.pointerType!==`touch`&&i(!1),u(!1)},b=t=>{if(t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;t.preventDefault();let n=m.current===`touch`;if(m.current=``,n&&!g){c(!0);return}_(),n||u(!0),Lg(e.provider)},{headline:x}=e,S=cP(e.severity,t);return(0,Q.jsxs)(`li`,{ref:d,className:`quota-summary-item quota-summary-item--${e.severity}`,onPointerEnter:v,onPointerLeave:y,onFocus:e=>{lP(e.target)&&(u(!1),o(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)},children:[(0,Q.jsxs)(`a`,{ref:f,href:`#${Mg(e.provider)}`,className:`quota-summary-chip${g?` quota-summary-chip--open`:``}`,"aria-expanded":g,"aria-controls":g?h:void 0,"aria-describedby":g?`${h}-table`:void 0,onPointerDown:e=>{m.current=e.pointerType},onClick:b,children:[(0,Q.jsx)(`span`,{className:`quota-summary-name`,children:e.label}),(0,Q.jsx)(`span`,{className:`quota-summary-pct`,children:We(x.percent)}),S&&(0,Q.jsx)(`span`,{className:`quota-summary-flag`,"aria-hidden":`true`,children:`!`}),S&&(0,Q.jsx)(`span`,{className:`sr-only`,children:S}),(0,Q.jsx)(`span`,{className:`sr-only`,children:t(`quotaSummary.openAccounts`)})]}),g&&(0,Q.jsxs)(`div`,{ref:p,id:h,className:`quota-summary-popover`,role:`group`,"aria-label":e.label,children:[(0,Q.jsxs)(`div`,{className:`quota-summary-popover-head`,children:[(0,Q.jsx)(`strong`,{children:e.label}),S&&(0,Q.jsx)(`span`,{className:`quota-summary-badge quota-summary-badge--${e.severity}`,children:S})]}),(0,Q.jsx)(`table`,{id:`${h}-table`,className:`quota-summary-table`,children:(0,Q.jsx)(`tbody`,{children:e.windows.map(e=>(0,Q.jsxs)(`tr`,{className:`quota-summary-row--${e.severity}`,children:[(0,Q.jsx)(`th`,{scope:`row`,children:sP(e,t)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-pct`,children:We(e.percent)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-reset`,children:e.resetAt===void 0?`-`:ds(e.resetAt,t,n)})]},e.id))})}),(0,Q.jsxs)(`div`,{className:`quota-summary-popover-foot`,children:[e.updatedAt!==void 0&&(0,Q.jsx)(`span`,{children:t(e.observed?`quotaSummary.observedAt`:`quotaSummary.dataAt`,{time:oP(e.updatedAt,n)})}),(0,Q.jsx)(`a`,{href:`#${Mg(e.provider)}`,className:`quota-summary-popover-link`,onPointerDown:e=>{m.current=e.pointerType},onClick:b,children:t(`quotaSummary.openAccounts`)})]})]})]})}var fP={overflow:!1,atStart:!0,atEnd:!0};function pP({rows:e,t,locale:n}){let r=(0,Z.useRef)(null),[i,a]=(0,Z.useState)(fP),o=(0,Z.useCallback)(()=>{let e=r.current;if(!e)return;let t=e.scrollWidth-e.clientWidth,n=t>1?{overflow:!0,atStart:e.scrollLeft<=1,atEnd:e.scrollLeft>=t-1}:fP;a(e=>e.overflow===n.overflow&&e.atStart===n.atStart&&e.atEnd===n.atEnd?e:n)},[]),s=e.map(e=>`${e.provider}:${e.label}:${We(e.headline.percent)}:${e.severity}`).join(`|`);(0,Z.useEffect)(()=>{let e=r.current;if(!e)return;let t=requestAnimationFrame(o),n=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>o());n?.observe(e);for(let t of Array.from(e.children))n?.observe(t);return()=>{cancelAnimationFrame(t),n?.disconnect()}},[o,s]);let c=e=>{let t=r.current;if(!t)return;let n=t.scrollWidth-t.clientWidth;if(e<0?t.scrollLeft<=1:t.scrollLeft>=n-1){o();return}let i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;t.scrollBy({left:e*Math.max(t.clientWidth*aP,80),behavior:i?`auto`:`smooth`})};return(0,Q.jsxs)(`div`,{className:`quota-summary-scroller${i.overflow?` quota-summary-scroller--overflow`:``}`,children:[i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--prev`,"aria-label":t(`quotaSummary.scrollPrev`),title:t(`quotaSummary.scrollPrev`),"aria-disabled":i.atStart,onClick:()=>c(-1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`«`})}),(0,Q.jsx)(`ul`,{ref:r,className:`quota-summary-list`,onScroll:o,children:e.map(e=>(0,Q.jsx)(dP,{row:e,t,locale:n},e.provider))}),i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--next`,"aria-label":t(`quotaSummary.scrollNext`),title:t(`quotaSummary.scrollNext`),"aria-disabled":i.atEnd,onClick:()=>c(1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`»`})})]})}function mP({apiBase:e}){let{t:n,locale:r}=t(),i=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`quota summary load failed`);let r=await n.json();return{fetchedAt:Date.now(),reports:ie(r?.reports)}},[e]),a=Ua(`ocx.quota-summary.provider-quotas.v1:${e}`,[e],i,{isEmpty:e=>Object.keys(e.reports).length===0,pollMs:nP,pauseWhenHidden:!0}),o=a.data;if(!o)return null;let s=Ze(o.reports,e=>be(e,n));if(s.length===0)return null;let c=!a.lastAttemptOk;return(0,Q.jsxs)(`section`,{className:`quota-summary-bar`,"aria-label":n(`quotaSummary.aria`),ref:tP,children:[(0,Q.jsx)(pP,{rows:s,t:n,locale:r}),(0,Q.jsx)(`span`,{className:`quota-summary-updated${c?` quota-summary-updated--stale`:``}`,title:c?n(`quotaSummary.refreshFailed`):void 0,children:n(`quotaSummary.updated`,{time:oP(o.fetchedAt,r)})}),(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,children:c?n(`quotaSummary.refreshFailed`):``})]})}var hP=3e5,gP=6e5,_P=`https://github.com/lidge-jun/opencodex`;async function vP(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function yP({apiBase:e,onOpenUpdate:t,onOpenTerminalCommand:n}){let r=O(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),c=Vt(`sidebar-star:${e}`,[e],t=>vP(`${e}/api/github/star`,t),{pollMs:hP}),l=Ya(e),u=Vt(`sidebar-update-badge:`+l,[l],e=>vP(l,e),{pollMs:Ka()?6e4:gP}),d=c.data?.state??null,f=o!==null&&o.basedOn===d?o.state:d??`not-starred`,p=c.data?.url??_P,m=f===`starred`,h=u.data,g=h?.updateAvailable===!0,_=h?.latestVersion??null,v=()=>window.open(p,`_blank`,`noopener,noreferrer`),y=async()=>{if(!(m||i)){if(f===`unauthenticated`){v();return}a(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){s({state:`starred`,basedOn:d});return}n?.state&&s({state:n.state,basedOn:d}),v()}catch{v()}finally{a(!1),c.refresh()}}},b=r(m?`sidebar.starred`:f===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),x=g&&_?r(`sidebar.updateAvailable`,{version:_}):Ka()?r(`sidebar.desktopUpdate`):r(`sidebar.checkUpdate`);return(0,Q.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Q.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:p,target:`_blank`,rel:`noreferrer`,children:[(0,Q.jsx)(je,{}),` `,r(`common.github`)]}),(0,Q.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--starred`:``}`,onClick:()=>{y()},disabled:i||m,"aria-label":b,"aria-pressed":m,title:b,children:(0,Q.jsx)(K,{"aria-hidden":`true`,...m?{fill:`currentColor`}:{}})}),(0,Q.jsxs)(`button`,{type:`button`,className:`sidebar-orb${g?` sidebar-orb--update`:``}`,onClick:t,"aria-label":x,title:x,children:[(0,Q.jsx)(Oe,{"aria-hidden":`true`}),g&&(0,Q.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]}),Ka()&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:n,"aria-label":r(`sidebar.terminalCommand`),title:r(`sidebar.terminalCommand`),children:(0,Q.jsx)(de,{"aria-hidden":`true`})})]})]})}var bP=`ocx-desktop-star-onboarding`,xP=`https://github.com/lidge-jun/opencodex`,SP=1200;function CP(){try{return window.localStorage.getItem(bP)!==null}catch{return!0}}function wP(){try{window.localStorage.setItem(bP,`seen`)}catch{}}function TP(e){window.location.assign(e)}function EP({apiBase:e,enabled:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(CP);(0,Z.useEffect)(()=>{if(!t||i||!Ka())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=>{if(e){if(e.state===`starred`){wP(),a(!0);return}r(e)}})},SP);return()=>{window.clearTimeout(o),n.abort()}},[e,t,i]);let o=(0,Z.useCallback)(()=>{wP(),a(!0)},[]);return i||!t||!n?null:(0,Q.jsx)(DP,{apiBase:e,status:n,onClose:o})}function DP({apiBase:e,status:t,onClose:n}){let r=O(),i=(0,Z.useId)(),a=(0,Z.useId)(),o=(0,Z.useRef)(null),[s,c]=(0,Z.useState)(`prompt`),l=t.url??xP,u=t.state===`not-starred`;(0,Z.useEffect)(()=>{let e=o.current;e&&!e.open&&e.showModal()},[]);let d=(0,Z.useCallback)(e=>{e.preventDefault(),s!==`starring`&&n()},[n,s]),f=()=>{TP(l),n()},p=async()=>{c(`starring`);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`});if((t.ok?await t.json():null)?.ok===!0){Ut(`sidebar-star:${e}`,{state:`starred`,url:l}),c(`thanks`);return}}catch{}c(`failed`)},m=s===`thanks`,h=s===`failed`;return(0,Q.jsxs)(`dialog`,{ref:o,"aria-labelledby":i,"aria-describedby":a,className:`modal-overlay star-onboarding-overlay`,onCancel:d,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>{s!==`starring`&&n()}}),(0,Q.jsxs)(`div`,{className:`modal-card star-onboarding`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`span`,{className:`star-onboarding-mark${m?` star-onboarding-mark--done`:``}`,"aria-hidden":`true`,children:(0,Q.jsx)(K,{...m?{fill:`currentColor`}:{}})}),(0,Q.jsx)(`h3`,{id:i,className:`star-onboarding-title`,children:r(m?`onboarding.star.thanks`:`onboarding.star.title`)}),(0,Q.jsx)(`p`,{id:a,className:`star-onboarding-body`,children:r(m?`onboarding.star.thanksBody`:h?`onboarding.star.failed`:`onboarding.star.body`)}),m?(0,Q.jsx)(`div`,{className:`star-onboarding-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:n,autoFocus:!0,children:r(`onboarding.star.done`)})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`star-onboarding-actions`,children:[u&&!h?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:s===`starring`,onClick:()=>{p()},autoFocus:!0,children:[(0,Q.jsx)(K,{"aria-hidden":`true`}),r(s===`starring`?`onboarding.star.starring`:`onboarding.star.cta`)]}):(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,autoFocus:!0,children:[(0,Q.jsx)(je,{"aria-hidden":`true`}),r(h?`onboarding.star.openPage`:`onboarding.star.cta`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:s===`starring`,onClick:n,children:r(`onboarding.star.later`)})]}),(0,Q.jsxs)(`p`,{className:`star-onboarding-hint`,children:[r(u&&!h?`onboarding.star.ghHint`:`onboarding.star.browserHint`),u&&!h&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`button`,{type:`button`,className:`star-onboarding-link`,disabled:s===`starring`,onClick:f,children:r(`onboarding.star.openPage`)})]})]})]})]})]})}var OP=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:Ue,pages:[`dashboard`]},{id:`connect`,tkey:`nav.connect`,Icon:st,pages:[`integrations`],embedded:[`claude`]},{id:`codex-set`,tkey:`nav.codexSet`,Icon:Xe,pages:[`codex-set`]},{id:`providers`,tkey:`nav.providers`,Icon:ce,pages:[`providers`]},{id:`models`,tkey:`nav.models`,Icon:Ie,pages:[`models`]},{id:`subagents`,tkey:`nav.subagents`,Icon:Ye,pages:[`subagents`]},{id:`advisor`,tkey:`nav.advisor`,Icon:Ye,pages:[`advisor`]},{id:`usage-logs`,tkey:`nav.usageLogs`,Icon:j,pages:[`usage`,`logs`,`storage`]},{id:`remote`,tkey:`nav.remote`,Icon:rt,pages:[`remote`,`remote-workspace`]}];function kP(e){return OP.find(t=>t.pages.includes(e)||t.embedded?.includes(e))??null}function AP(e,t){return e.pages.filter(e=>e!==`remote-workspace`||t.remoteWorkspaceAvailable)}function jP({items:e,currentPage:t,onNavigate:n,ariaLabel:r,onFocusOrphaned:i}){let a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(i);(0,Z.useLayoutEffect)(()=>{s.current=i}),(0,Z.useLayoutEffect)(()=>{let e=a.current;return()=>{e&&e.contains(e.ownerDocument.activeElement)&&s.current?.()}},[]),(0,Z.useLayoutEffect)(()=>{let t=a.current,n=o.current;!t||n===null||t.contains(t.ownerDocument.activeElement)||e.some(e=>e.page===n)||(t.querySelector(`[aria-current="page"]`)??t.querySelector(`button`))?.focus()},[e]);let c=()=>[...a.current?.querySelectorAll(`button`)??[]],l=e=>{let t=c(),n=t.indexOf(e.currentTarget),r=null;e.key===`ArrowRight`?r=(n+1)%t.length:e.key===`ArrowLeft`?r=(n-1+t.length)%t.length:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r]?.focus())};return(0,Q.jsx)(`nav`,{ref:a,className:`section-switcher`,"aria-label":r,onFocus:e=>{o.current=e.target.dataset.sectionPage??null},onBlur:e=>{if(a.current?.contains(e.relatedTarget))return;let t=e.target;window.setTimeout(()=>{t.isConnected&&(o.current=null)},0)},children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`section-switcher-btn`,"data-section-page":e.page,"aria-current":e.page===t?`page`:void 0,onClick:()=>{e.page!==t&&n(e.page)},onKeyDown:l,children:e.label},e.page))})}var MP=[`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 NP(){try{for(let e of MP)localStorage.removeItem(e)}catch{}}function PP(){let[e,t]=(0,Z.useState)(dg);(0,Z.useEffect)(()=>{NP()},[]);let n=(0,Z.useCallback)(e=>{let n=Sg(e);n.replaceTo&&Kt(n.replaceTo),t(n.page)},[]);return(0,Z.useEffect)(()=>{let e=()=>{n(Wt(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,Z.useEffect)(()=>{let n=Sg(Wt(window.location.hash));n.replaceTo&&Kt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{qt(n?`${e}/${n}`:e),t(e)}}}var FP=15e3,IP=3e3;function LP(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 RP(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 zP(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=FP,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=IP}=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 RP(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:LP(u,l.status,i)}:d?{status:`accepted`}:{status:`unknown`,message:o()}}var BP=`ocx-desktop-zoom`,VP=.5,HP=.1;function UP(e){return e===`macos`||e===`linux`}function WP(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,VP),3)*100)/100:1}function GP(e,t){return t===`reset`?1:WP(e+(t===`in`?HP:-.1))}function KP(e){return Math.round(e*100)}function qP(e=typeof localStorage>`u`?void 0:localStorage){try{let t=e?.getItem(BP);return t==null?1:WP(Number(t))}catch{return 1}}function JP(e,t=typeof localStorage>`u`?void 0:localStorage){try{t?.setItem(BP,String(e))}catch{}}function YP(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 XP(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 ZP(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 QP=`ocx-sidebar-collapsed`;function $P(e=typeof localStorage>`u`?void 0:localStorage){try{return e?.getItem(QP)===`1`}catch{return!1}}function eF(e){try{localStorage.setItem(QP,e?`1`:`0`)}catch{}}function tF(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function nF({shortcut:e=!1}={}){let[t,n]=(0,Z.useState)($P),r=(0,Z.useCallback)(()=>n(e=>!e),[]);return(0,Z.useEffect)(()=>{eF(t)},[t]),(0,Z.useEffect)(()=>{if(!e)return;let t=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||(e.key===`b`||e.key===`B`)&&(tF(e.target)||(e.preventDefault(),r()))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[r,e]),{collapsed:t,toggle:r}}function rF({managed:e}){let[t,n]=(0,Z.useState)(qP),r=(0,Z.useCallback)(e=>n(t=>GP(t,e)),[]),i=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{e&&(ZP(t),JP(t))},[e,t]),(0,Z.useEffect)(()=>{if(!e)return;let t=Xa(),n=e=>{let n=YP(e,t);n&&(e.preventDefault(),e.stopImmediatePropagation(),r(n))},a=e=>{if(!e.ctrlKey)return;e.preventDefault(),e.stopImmediatePropagation();let t=XP(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:KP(t),canZoomIn:t<3,canZoomOut:t>VP,step:r}}function iF({percent:e,canZoomIn:t,canZoomOut:n,onStep:r}){let i=O();return(0,Q.jsxs)(`div`,{className:`zoom-control`,role:`group`,"aria-label":i(`zoom.label`),title:i(`zoom.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!n,onClick:()=>r(`out`),"aria-label":i(`zoom.out`),title:i(`zoom.out`),children:(0,Q.jsx)(L,{"aria-hidden":!0})}),(0,Q.jsxs)(`button`,{type:`button`,className:`zoom-control__value`,onClick:()=>r(`reset`),"aria-label":i(`zoom.reset`),title:i(`zoom.reset`),children:[e,`%`]}),(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!t,onClick:()=>r(`in`),"aria-label":i(`zoom.in`),title:i(`zoom.in`),children:(0,Q.jsx)(N,{"aria-hidden":!0})})]})}var aF=[{mode:`light`,tkey:`theme.light`,Icon:J},{mode:`dark`,tkey:`theme.dark`,Icon:he},{mode:`system`,tkey:`theme.system`,Icon:rt}];function oF({theme:e,onChange:t}){let n=O();return(0,Q.jsx)(`div`,{className:`theme-switch`,role:`group`,"aria-label":n(`theme.label`),children:aF.map(({mode:r,tkey:i,Icon:a})=>(0,Q.jsx)(`button`,{type:`button`,className:`theme-switch__btn`,"aria-pressed":e===r,"aria-label":n(i),title:n(i),onClick:()=>t(r),children:(0,Q.jsx)(a,{"aria-hidden":!0})},r))})}function sF(e){try{window.__TAURI__?.core?.invoke?.(e).catch(()=>{})}catch{}}var cF=`a, button, input, select, textarea, summary, [role='button'], [role='link'], [contenteditable]`;function lF(e){return e instanceof Element&&e.closest(cF)!==null}function uF(){return{onMouseDown:e=>{e.button!==0||lF(e.target)||sF(`plugin:window|start_dragging`)},onDoubleClick:e=>{lF(e.target)||sF(`plugin:window|toggle_maximize`)}}}function dF(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 fF({collapsed:e,onToggle:t}){let n=O()(e?`nav.expandSidebar`:`nav.collapseSidebar`);return(0,Q.jsx)(`div`,{className:`sidebar-top`,...uF(),children:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-collapse`,onClick:t,"aria-expanded":!e,"aria-controls":`app-sidebar`,"aria-label":n,title:n,children:(0,Q.jsx)(V,{})})})}function pF({children:e}){return(0,Q.jsx)(`div`,{className:`main-top`,...uF(),children:e})}var mF={dashboard:`nav.dashboard`,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`},hF=``,gF=D(hF);w(gF),d();var _F=`ocx-theme`;function vF({available:e,apiBase:t,hubOrigin:n,onOpenRemoteLink:r}){let i=O();return e?(0,Q.jsx)(BN,{apiBase:t,hubOrigin:n}):(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h2`,{children:i(`nav.remoteWorkspace`)}),(0,Q.jsxs)($,{tone:`warn`,children:[i(`link.workspaceUnavailable`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:r,children:i(`nav.remote`)})]})]})}function yF(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 bF(){let e=localStorage.getItem(_F);return e===`light`||e===`dark`?e:`system`}function xF(){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 SF(){let{page:e,navigateToPage:r}=PP(),[i,a]=(0,Z.useState)(ES);(0,Z.useEffect)(()=>{let e=()=>a(ES());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[o,c]=(0,Z.useState)(bF),{locale:l,setLocale:u}=t(),d=O(),[p,g]=(0,Z.useState)(gF),[_,v]=(0,Z.useState)(()=>!m()),[b,C]=(0,Z.useState)(!1),[T,D]=(0,Z.useState)(()=>E(`shared`)),[A,j]=(0,Z.useState)(0),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(!1),[R,z]=(0,Z.useState)(null),[B,V]=(0,Z.useState)(0),H=(0,Z.useCallback)((e,t)=>{z({tone:t,text:e}),V(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!E(`shared`)&&D(!1)};return window.addEventListener(h,e),()=>window.removeEventListener(h,e)},[]),(0,Z.useEffect)(()=>{let e=new AbortController;return y(hF,e.signal).then(async t=>{w(t),g(t),t.connected&&!E(`shared`)&&await x(`shared`,e.signal),!e.signal.aborted&&(D(E(`shared`)),C(!1),v(!0))}).catch(()=>{e.signal.aborted||(C(!0),v(!0))}),()=>e.abort()},[]);let U=S(`machine`,p),W=S(`shared`,p);(0,Z.useEffect)(()=>{if(!T)return;let e=new AbortController;return fetch(`${W}/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,T,W]);let G=T&&P,ee=kP(e),K=ee?AP(ee,{remoteWorkspaceAvailable:G}):[],q=e===`claude`?`integrations`:e,te=e===`remote`&&s()===`hub`,ne=te&&M,[J,Y]=(0,Z.useState)(!1),ie=Ka(),{collapsed:X,toggle:ae}=nF({shortcut:ie}),oe=ie&&Xa()===`macos`,se=ie&&UP(Xa()),ce=rF({managed:se}),le=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(oe&&le.current)return dF(le.current)},[oe]);let ue=(0,Z.useRef)(null),de=(0,Z.useRef)(null),fe=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=()=>Y(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,Z.useEffect)(()=>{if(!Ka())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;to(r)&&(e.preventDefault(),window.location.assign(r))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[]),(0,Z.useEffect)(()=>{let e=document.documentElement;o===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(_F)):(e.setAttribute(`data-theme`,o),localStorage.setItem(_F,o))},[o]),(0,Z.useEffect)(()=>{if(R?.tone!==`ok`)return;let e=window.setTimeout(()=>z(null),4500);return()=>window.clearTimeout(e)},[R,B]);let me=Vt(`app-healthz:${U}`,[U,_],async e=>{let t=await fetch(`${U}/healthz`,{signal:e});return t.ok?yF(await t.json()):null},{pollMs:3e4,enabled:_}),he=(0,Q.jsx)(oF,{theme:o,onChange:c}),ge=me.data??`2.86.0`,[_e,ye]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{if(!J)return;let e=e=>{e.key===`Escape`&&Y(!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}},[J]),(0,Z.useEffect)(()=>{if(J){fe.current=!0;let e=setTimeout(()=>de.current?.focus(),200);return()=>clearTimeout(e)}fe.current&&(fe.current=!1,ue.current?.focus())},[J]),(0,Z.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&Y(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[be,xe]=(0,Z.useState)(0),{restarting:Se,restart:Ce}=B_(W,{onSettled:()=>xe(e=>e+1),report:H}),we=async()=>{if(!await na({message:d(p.connected?`connection.disconnectConfirm`:`dash.stopConfirm`),confirmLabel:d(p.connected?`connection.disconnect`:`dash.stop`),tone:`danger`}))return;ye(!0);let e=await zP(U,{formatFailure:e=>d(`dash.stopFailed`,{status:String(e)}),formatStillRunning:()=>d(`dash.stopStillRunning`),formatUnknown:()=>d(`dash.stopUnknown`),mode:p.connected?`client`:`standalone`});e.status!==`accepted`&&(ye(!1),H(e.message,e.status===`rejected`?`err`:`warn`))},Te=async()=>{if(I)return;L(!0);let e=await f(`shared`);L(!1),e?D(!1):H(d(`connection.sessionLogoutFailed`),`err`)},Ee=(0,Q.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{r(`dashboard`),Y(!1)},"aria-label":d(`nav.goHome`),title:d(`nav.goHome`),...e===`dashboard`?{"aria-current":`page`}:{},children:[(0,Q.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":d(`app.logoAria`)}),(0,Q.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Q.jsxs)(`span`,{className:`ver`,title:ge,children:[`v`,ge]})]}),De=_&&e!==`startup`&&(!p.connected||T)&&(0,Q.jsx)(gy,{pageName:d(`quotaSummary.aria`),title:d(`errorBoundary.title`),message:d(`errorBoundary.message`),detailsLabel:d(`errorBoundary.details`),reloadLabel:d(`errorBoundary.reload`),children:(0,Q.jsx)(mP,{apiBase:W})},W);return(0,Q.jsxs)(`div`,{ref:le,className:`app${ie?` app--desktop`:``}${oe?` app--macos`:``}${X?` app--nav-collapsed`:``}`,children:[(0,Q.jsx)(EP,{apiBase:W,enabled:_&&!p.connected}),R&&(0,Q.jsx)(sn,{tone:R.tone,onDismiss:()=>z(null),dismissLabel:d(`common.close`),children:R.text}),(0,Q.jsxs)(`header`,{className:`mobile-topbar`,inert:J,...ie?uF():{},children:[(0,Q.jsx)(`button`,{ref:ue,type:`button`,className:`menu-toggle`,onClick:()=>Y(e=>!e),"aria-expanded":J,"aria-controls":`app-sidebar`,"aria-label":d(J?`nav.closeMenu`:`nav.openMenu`),title:d(J?`nav.closeMenu`:`nav.openMenu`),children:(0,Q.jsx)(pe,{})}),Ee,(0,Q.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[p.connected&&T&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Te()},disabled:I,"aria-label":d(I?`connection.sessionLoggingOut`:`connection.sessionLogout`),title:d(`connection.sessionLogout`),children:(0,Q.jsx)(ve,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:we,disabled:_e,"aria-label":d(p.connected?`connection.disconnect`:`dash.stop`),title:d(p.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(Re,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ce()},disabled:Se,"aria-label":d(`dash.codexRestart`),title:d(`dash.codexRestart`),children:(0,Q.jsx)(re,{})})]})]}),J&&(0,Q.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>Y(!1),"aria-hidden":`true`}),(0,Q.jsx)(fF,{collapsed:X,onToggle:ae}),(0,Q.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${J?` open`:``}`,ref:de,tabIndex:-1,children:[(0,Q.jsxs)(`div`,{className:`drawer-head`,children:[Ee,(0,Q.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>Y(!1),"aria-label":d(`nav.closeMenu`),title:d(`nav.closeMenu`),children:(0,Q.jsx)(ve,{})})]}),(0,Q.jsx)(`nav`,{children:OP.map(e=>{let{id:t,tkey:n,Icon:i}=e,a=ee?.id===t;return(0,Q.jsx)(`div`,{className:`nav-entry`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`nav-item${a?` active`:``}`,"data-page":e.pages[0],"data-group":t,onClick:()=>{r(e.pages[0]),Y(!1)},"aria-current":a?`page`:void 0,children:[(0,Q.jsx)(i,{}),` `,d(n)]})},t)})}),(0,Q.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Q.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Q.jsx)(qe,{"aria-hidden":!0}),(0,Q.jsx)(cn,{value:l,options:k.map(e=>({value:e.code,label:n(e.code)})),onChange:e=>u(e),label:d(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),se?(0,Q.jsxs)(`div`,{className:`sidebar-display-row`,children:[he,(0,Q.jsx)(iF,{percent:ce.percent,canZoomIn:ce.canZoomIn,canZoomOut:ce.canZoomOut,onStep:ce.step})]}):(0,Q.jsxs)(`div`,{className:`sidebar-action-row sidebar-action-row--theme`,children:[(0,Q.jsx)(`span`,{className:`sidebar-action-label`,children:d(`theme.label`)}),he]}),(0,Q.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,Q.jsx)(`span`,{className:`sidebar-action-label`,children:d(`dash.actions`)}),(0,Q.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[p.connected&&T&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Te()},disabled:I,"aria-label":d(I?`connection.sessionLoggingOut`:`connection.sessionLogout`),title:d(`connection.sessionLogout`),children:(0,Q.jsx)(ve,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:we,disabled:_e,"aria-label":d(_e?`dash.stopping`:p.connected?`connection.disconnect`:`dash.stop`),title:d(_e?`dash.stopping`:p.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(Re,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ce()},disabled:Se,"aria-label":d(Se?`dash.codexRestarting`:`dash.codexRestart`),title:d(Se?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Q.jsx)(re,{})})]})]}),(0,Q.jsx)(yP,{apiBase:W,onOpenUpdate:()=>{Y(!1),!Qa()&&r(`dashboard`,`update`)},onOpenTerminalCommand:()=>{Y(!1),eo()}})]})]}),(0,Q.jsxs)(`main`,{className:`main`,inert:J,children:[ie?(0,Q.jsx)(pF,{children:De}):De,(0,Q.jsxs)(`div`,{className:`main-inner${e===`models`&&i===`combos`?` main-inner--combos`:``}`,children:[_&&K.length>1&&(0,Q.jsx)(jP,{items:K.map(e=>({page:e,label:d(mF[e])})),currentPage:e,onNavigate:r,ariaLabel:d(`nav.sectionNavigation`),onFocusOrphaned:xF}),_&&p.link&&(0,Q.jsx)($,{tone:`warn`,children:p.link.home?d(`connection.linkManaged`,{home:p.link.home,linkId:p.link.linkId}):d(`connection.linkManagedUnnamed`,{linkId:p.link.linkId})}),(0,Q.jsx)(gy,{pageName:d(mF[q]),title:d(`errorBoundary.title`),message:d(`errorBoundary.message`),detailsLabel:d(`errorBoundary.details`),reloadLabel:d(`errorBoundary.reload`),children:_?(0,Q.jsxs)(Q.Fragment,{children:[b&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:d(`connection.machineUnavailable`)}),(p.connected&&!T||ne)&&(0,Q.jsx)(zk,{target:p.shared,focusOnMount:ne,onConnected:async e=>{ne&&await Rk(W,void 0,e),e.throwIfAborted(),N(!1),D(E(`shared`)),j(e=>e+1)}},`${p.shared.serverOrigin}:${p.shared.bootstrapPath}`),e===`dashboard`&&(0,Q.jsx)(Po,{apiBase:W,connected:p.connected,authenticationPending:p.connected&&!T,refreshEpoch:A}),e===`startup`&&(0,Q.jsx)(kN,{apiBase:W,machineApiBase:U,connected:p.connected}),e===`providers`&&(0,Q.jsx)(Vg,{apiBase:W}),e===`models`&&(0,Q.jsx)(YS,{apiBase:W,restartEpoch:be,connected:p.connected,catalogSyncedAt:p.catalogSyncedAt,reportRestart:H},W),e===`subagents`&&(0,Q.jsx)(vC,{apiBase:W},W),e===`advisor`&&(0,Q.jsx)(eC,{apiBase:W},W),e===`logs`&&(0,Q.jsx)(MT,{apiBase:W}),e===`usage`&&(0,Q.jsx)(LE,{apiBase:W,connected:p.connected,apiKeyId:p.apiKeyId}),e===`storage`&&(0,Q.jsx)(fD,{apiBase:W}),e===`remote`&&!ne&&(0,Q.jsx)(eP,{apiBase:W,sessionReady:T,pairingRecoveryAvailable:te,onRequestPairing:()=>N(!0),workspaceAvailable:G,onOpenWorkspace:()=>r(`remote-workspace`)},`${W}:${A}`),e===`remote-workspace`&&(0,Q.jsx)(vF,{available:G,apiBase:W,hubOrigin:p.shared.serverOrigin,onOpenRemoteLink:()=>r(`remote`)}),e===`codex-set`&&(0,Q.jsx)(wO,{apiBase:W,machineApiBase:U,connected:p.connected}),q===`integrations`&&(0,Q.jsx)(gN,{apiBase:W,machineApiBase:U,connected:p.connected})]}):(0,Q.jsx)(`div`,{className:`alert`,children:d(`connection.discovering`)})},q)]})]})]})}export{vF as RemoteWorkspaceRoute,SF as default};
|