@coseung2/opencodex 2.8.0-cs.15 → 2.8.0-cs.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/gui/dist/assets/{index-BhXIu7c0.js → index-Ch-99jy3.js} +2 -2
  2. package/gui/dist/index.html +1 -1
  3. package/package.json +1 -1
  4. package/packages/ocx-notch/README.md +3 -1
  5. package/src/adapters/base.ts +12 -0
  6. package/src/adapters/identity.ts +1 -1
  7. package/src/adapters/kiro-calibration.ts +83 -0
  8. package/src/adapters/kiro-constants.ts +11 -2
  9. package/src/adapters/kiro-errors.ts +11 -0
  10. package/src/adapters/kiro-events.ts +19 -1
  11. package/src/adapters/kiro-thinking.ts +18 -2
  12. package/src/adapters/kiro-tools.ts +12 -3
  13. package/src/adapters/kiro.ts +300 -78
  14. package/src/adapters/openai-chat.ts +1 -42
  15. package/src/adapters/openai-responses.ts +126 -9
  16. package/src/adapters/xai-schema-analysis.ts +78 -0
  17. package/src/adapters/xai-tool-schema.ts +274 -0
  18. package/src/adapters/xai-web-search.ts +138 -0
  19. package/src/bridge.ts +61 -6
  20. package/src/cli/observe.ts +18 -3
  21. package/src/codex/app-server-processes.ts +3 -5
  22. package/src/codex/catalog/effort.ts +4 -2
  23. package/src/codex/catalog/metadata.ts +42 -9
  24. package/src/codex/catalog/parsing.ts +17 -2
  25. package/src/codex/catalog/provider-fetch.ts +9 -3
  26. package/src/codex/catalog/sync.ts +11 -5
  27. package/src/codex/data/upstream-models.json +169 -0
  28. package/src/grok/inject.ts +1 -1
  29. package/src/lib/errors.ts +18 -0
  30. package/src/lib/token-estimate.ts +42 -38
  31. package/src/lib/translator-budget.ts +34 -0
  32. package/src/oauth/index.ts +10 -4
  33. package/src/oauth/kiro.ts +71 -6
  34. package/src/oauth/store.ts +3 -1
  35. package/src/oauth/types.ts +4 -0
  36. package/src/providers/derive.ts +7 -5
  37. package/src/providers/opencode-go-transport.ts +59 -0
  38. package/src/providers/quota.ts +68 -60
  39. package/src/providers/registry.ts +41 -10
  40. package/src/providers/xai-transport.ts +10 -0
  41. package/src/responses/compaction.ts +8 -1
  42. package/src/responses/namespace-aliases.ts +56 -0
  43. package/src/responses/parser.ts +12 -0
  44. package/src/responses/reasoning-envelope.ts +9 -1
  45. package/src/responses/snapshot-policy.ts +108 -0
  46. package/src/responses/state.ts +23 -10
  47. package/src/responses/turn-termination.ts +108 -0
  48. package/src/responses/xai-custom-tool-compat.ts +237 -0
  49. package/src/server/grok-responses-snapshot-repair.ts +338 -0
  50. package/src/server/index.ts +2 -1
  51. package/src/server/relay-eager.ts +1 -0
  52. package/src/server/request-log-conversation.ts +8 -0
  53. package/src/server/request-log.ts +5 -4
  54. package/src/server/responses/core.ts +233 -16
  55. package/src/server/responses-image-gen-repair.ts +2 -2
  56. package/src/server/sse-payload-rewrite.ts +20 -3
  57. package/src/types.ts +10 -1
  58. package/src/usage/cost.ts +0 -0
  59. package/src/usage/expected-prices.ts +7 -0
  60. package/src/usage/log.ts +1 -2
  61. package/vendor/ocx-notch/win32-x64/ocx-notch.exe +0 -0
@@ -44,7 +44,7 @@ v2: spawn_agent を備えたマルチスレッドエージェント。すべて
44
44
 
45
45
  変更は新規セッションに適用されます。`,"dash.multiAgent":`サブエージェント`,"models.v2Conflict":`[agents] max_threads が設定されています — codex は起動を拒否します; config.toml から削除してください`,"models.v2Applied":`サブエージェントモードを更新しました — 新規セッションに適用(ピッカーを更新するには Codex アプリを再起動)`,"models.v2ThreadsLabel":`最大スレッド数`,"models.v2ThreadsDefault":`デフォルト (4)`,"models.v2ThreadsApplied":`スレッド上限を更新しました — 新規セッションに適用`,"models.v2ThreadsInvalid":`スレッド上限は 1 以上の整数にしてください`,"models.v2ThreadsApply":`適用`,"models.capValue":`上限 {value}`,"models.contextCappedValue":`{value} 上限`,"models.setAll":`すべて設定`,"models.setAllHint":`{value} のコンテキスト上限をすべてのルーティング済みプロバイダーに適用します。ネイティブプロバイダーには影響しません。`,"models.collapseAll":`すべて折りたたむ`,"models.expandAll":`すべて展開`,"models.orderHint":`ピッカーの順序: サブエージェントの選択(選択順) → 残りのルーティングモデルはプロバイダー別、次にモデル ID 別のアルファベット順 → ネイティブモデル。表示切り替えはモデルをフィルタするだけで、この順序は変更しません。`,"models.custom":`カスタム…`,"models.customApply":`適用`,"models.customPlaceholder":`トークン (例: 420000)`,"models.applied":`適用しました — 次回の Codex ターンで有効になります。`,"models.saveFailed":`保存に失敗しました`,"models.networkError":`ネットワークエラー — プロキシは起動していますか?`,"models.loadFail":`モデルの読み込みに失敗しました — プロキシは起動していますか?`,"models.noRouted":`ルーティングモデルがありません`,"models.noRoutedHint":`まずプロバイダーにログインするか追加してください。`,"models.emptyDiscovery":`モデルが見つかりませんでした。プロバイダーのエンドポイントを確認するか、静的/カスタムモデルを追加してください。`,"models.emptyDiscoveryDisabled":`ライブモデル検出がオフで、静的モデルも設定されていません。`,"models.discoveryFailedBadge":`検出に失敗`,"models.discoveryFailedHttp":`モデル検出に失敗しました(HTTP {status})。`,"models.discoveryFailedBlocked":`モデル検出は宛先ポリシーによりブロックされました。`,"models.discoveryFailedInvalidResponse":`モデル検出が無効な応答を返しました。`,"models.discoveryFailedNetwork":`ネットワークエラーによりモデル検出に失敗しました。`,"models.discoveryFailedProvider":`プロバイダーがモデル検出エラーを報告しました。`,"models.discoveryFailedGeneric":`モデル検出に失敗しました。`,"models.openProviderSettings":`プロバイダー設定を開く`,"models.loading":`読み込み中…`,"models.search":`モデルを検索…`,"models.showMore":`さらに {n} 件表示`,"models.allowlistLabel":`選択のみ`,"models.allowlistHint":`チェックしたモデルのみカタログに送信します(空 = すべて)。数千のモデルを公開するプロバイダーで有用です。`,"models.selectedCount":`{n} 件選択`,"sub.subtitle":`Codex の {cmd} は最初の 5 モデル(優先度順)のみをオーバーライドとして通知します。ここで最大 5 つを選んでください — ネイティブ gpt またはルーティング — opencodex がカタログ優先度を設定し、これらが先頭に来るようにします。他のモデルも正確な名前で呼び出し可能です; これは表示のみを制御します。`,"sub.featured":`おすすめ`,"sub.orderHint":`ここでの表示順が Codex モデルピッカーの上位 1〜5 番目の位置と {cmd} のデフォルトモデル候補を決定します。`,"sub.noneSelected":`未選択 — 以下のリストから選んでください。`,"sub.models":`モデル`,"sub.search":`モデルを検索(ネイティブ gpt + ルーティング)…`,"sub.noModels":`モデルがありません — まずプロバイダーにログインするか追加してください。`,"sub.saved":`{n} 件のモデルを保存しました。新規 Codex セッションを開始(または {cmd} を実行)して spawn_agent オーバーライドとして確認してください。`,"sub.saveFailed":`保存に失敗しました`,"sub.networkError":`ネットワークエラー — プロキシは起動していますか?`,"sub.loadFail":`モデルの読み込みに失敗しました — プロキシは起動していますか?`,"sub.loading":`読み込み中…`,"sub.moveUp":`{m} を上へ移動`,"sub.moveDown":`{m} を下へ移動`,"sub.removeAria":`{m} を削除`,"sub.workspace.addToFeatured":`{m} をおすすめに追加`,"sub.workspace.allModels":`すべてのモデル`,"sub.workspace.featuredFull":`おすすめリストがいっぱいです(最大 5)`,"sub.workspace.mainAria":`サブエージェントのモデル詳細`,"sub.workspace.notFeatured":`おすすめ未設定`,"sub.workspace.priority":`優先度`,"sub.workspace.removeFromFeatured":`{m} をおすすめから削除`,"sub.workspace.selectModel":`モデルを選択`,"sub.workspace.selectModelDesc":`一覧からモデルを選んで詳細を確認し、spawn_agent のおすすめに設定します。`,"sub.workspace.selector":`公開セレクター`,"logs.title":`リクエストログ`,"logs.tabLogs":`ログ`,"logs.tabDebug":`デバッグ`,"logs.subtitle":`ローカル opencodex プロキシを経由した最近のリクエスト(新しい順)。`,"logs.autoRefresh":`自動更新`,"logs.noRequests":`まだリクエストがありません。`,"logs.loadError":`リクエストログを読み込めませんでした。`,"logs.filter.surface.label":`サーフェス`,"logs.filter.surface.all":`すべて`,"logs.filter.surface.claude":`Claude`,"logs.filter.surface.codex":`Codex`,"logs.filter.surface.grok":`Grok`,"logs.filter.interceptedHelpersOnly":`インターセプトされたヘルパーのみ`,"logs.badge.interceptedHelper":`I · {model}`,"logs.badge.interceptedHelperTitle":`インターセプトされたヘルパー要求`,"logs.filter.conversation.label":`会話`,"logs.filter.conversation.placeholder":`会話 ID を貼り付け`,"logs.filter.conversation.clear":`クリア`,"logs.filter.conversation.apply":`ログを絞り込み`,"logs.conversation.totals":`{requests} 件 · {tokens} トークン · {cost}`,"logs.conversation.scope":`合計は現在読み込まれている Logs リングのみです。`,"logs.conversation.excluded":`(~$ から価格なし {unpriced} / 未計測 {unmetered} を除外)`,"logs.detail.conversation":`会話`,"logs.badge.claude":`Claude`,"logs.badge.grok":`Grok`,"logs.col.time":`時刻`,"logs.col.request":`リクエスト`,"logs.col.model":`モデル`,"logs.col.effort":`負荷`,"logs.col.provider":`プロバイダー`,"logs.col.status":`状態`,"logs.col.tokens":`トークン`,"logs.col.tokPerSec":`tok/s`,"logs.col.estimatedCost":`~$`,"logs.metric.tokPerSecTitle":`リクエスト全体の所要時間あたりの出力トークン数`,"logs.metric.estimatedCostTitle":`API 定価相当額(実際の請求ではありません); 未対応の価格は利用できません`,"usage.cost.total":`API 定価相当額(この期間)`,"usage.cost.disclaimer":`請求明細ではありません。サブスクリプション利用量やプロバイダークレジットが代わりに適用される場合があります。`,"usage.cost.unpricedNote":`{count} 件のリクエストを除外(価格または使用量なし)`,"logs.detail.section.basic":`基本情報`,"logs.detail.section.performance":`パフォーマンス`,"logs.detail.section.cost":`API 定価相当額`,"logs.detail.section.attempts":`コンボの試行`,"logs.detail.section.usage":`生の使用量`,"logs.detail.ttft":`TTFT`,"logs.detail.costTotal":`定価相当額`,"logs.detail.totalTokens":`合計トークン`,"logs.detail.matchedKey":`一致した jawcode キー`,"logs.detail.priceSource":`価格ソース`,"logs.detail.unavailableReason":`利用不可の理由`,"logs.detail.copyRequestId":`リクエスト ID をコピー`,"logs.detail.copied":`コピーしました`,"logs.detail.source.jawcode":`jawcode カタログ`,"logs.detail.source.expected":`予想価格オーバーレイ`,"logs.detail.verification.verified":`検証済み`,"logs.detail.verification.derived":`ベースモデルから派生`,"logs.detail.attempt.target":`プロバイダー / モデル`,"logs.detail.attempt.reason":`結果 / 理由`,"logs.detail.attempt.completed":`完了`,"logs.detail.attempt.e2eNote":`トップレベルの tok/s はエンドツーエンドです; 各試行は自身の所要時間を使います。`,"logs.detail.reason.usage_missing":`使用量が報告されませんでした。`,"logs.detail.reason.usage_unsupported":`このプロバイダーは使用量を報告しません。`,"logs.detail.reason.output_missing":`正の出力トークン数が報告されませんでした。`,"logs.detail.reason.invalid_duration":`リクエストの所要時間が有効ではありません。`,"logs.detail.reason.price_unmatched":`一致する jawcode 価格が見つかりませんでした。`,"logs.detail.reason.invalid_cache_breakdown":`キャッシュトークンの詳細が合計入力トークンと矛盾しています。`,"logs.detail.reason.invalid_usage":`使用量に無効なトークン値が含まれています。`,"logs.detail.reason.combo_attempt_unavailable":`少なくとも 1 つのコンボ試行に価格を設定できませんでした。`,"logs.detail.estimate.usage_estimated":`プロバイダーの使用量は推定です。`,"logs.detail.estimate.cache_detail_missing":`キャッシュの詳細が利用できませんでした; 入力は上限の推定です。`,"logs.detail.estimate.expected_price_overlay":`検証済みの予想定価が使用されました。`,"logs.col.error":`エラー`,"logs.col.upstreamReason":`上流の理由`,"logs.col.duration":`所要時間`,"logs.tokens.reported":`報告済み`,"logs.tokens.unreported":`未報告`,"logs.tokens.unsupported":`非対応`,"logs.tokens.estimated":`推定`,"logs.tokens.input":`入力`,"logs.tokens.output":`出力`,"logs.tokens.cacheRead":`キャッシュ読み取り (c)`,"logs.tokens.cacheWrite":`キャッシュ書き込み (w)`,"logs.tokens.reasoning":`推論`,"logs.tokens.noCache":`キャッシュデータなし`,"logs.tokens.contextTotal":`アクティブコンテキスト`,"logs.tokens.noCacheNote":`このプロバイダーはキャッシュトークンを報告しません`,"logs.tokens.noCacheCursor":`Cursor のキャッシュ詳細は未報告`,"logs.tokens.noCacheCursorNote":`Cursor はキャッシュ read/write トークン数を公開しません。これは不明という意味で、キャッシュミスの確定ではありません`,"logs.tokens.estimatedNote":`推定(プロバイダーは正確な使用量を報告しません)`,"logs.details":`詳細`,"logs.detailTitle":`リクエストの詳細`,"logs.detailRaw":`生のログエントリ`,"debug.title":`デバッグ`,"debug.subtitle":`オプトインのプロバイダートランスポートおよび使用量抽出診断です。リクエストエラーと 502 はログタブに残ります。`,"debug.debug":`プロバイダーデバッグ`,"debug.usage":`使用量抽出`,"debug.injection":`インジェクションログ`,"debug.claude":`Claude インバウンド`,"debug.claudeInbound.title":`Claude インバウンドリクエスト`,"debug.claudeInbound.sub":`Claude Code/Desktop が実際に送信する内容(thinking、effort、metadata) — プロンプトテキストは保存されません。`,"debug.claudeInbound.empty":`まだキャプチャされたリクエストはありません。これがオンの状態で Claude からメッセージを送信してください。`,"debug.claudeInbound.time":`時刻`,"debug.claudeInbound.endpoint":`エンドポイント`,"debug.claudeInbound.model":`モデル`,"debug.claudeInbound.none":`なし`,"debug.reset":`ランタイムオーバーライドをクリア`,"debug.refresh":`更新`,"debug.follow":`追従`,"debug.streamProvider":`プロバイダー`,"debug.streamUsage":`使用量`,"debug.streamInjection":`インジェクション`,"debug.loading":`デバッグ設定を読み込み中…`,"debug.loadFailed":`デバッグ設定を読み込めませんでした。`,"debug.emptyTitle":`デバッグログはオフです`,"debug.empty":`上のカードでプロバイダーデバッグまたは使用量抽出をオンにしてください。プロキシ経由でリクエストを送信すると、ここに行が表示されます。`,"debug.noLinesTitle":`行を待機中`,"debug.noLines.provider":`プロバイダーデバッグはオンですが、トランスポートの異常(欠落または不正なフレーム、Cursor のダイヤル/再試行イベント)のみを記録します。Anthropic のようなプロバイダーでの正常なリクエストは行を生成しないことがあります。`,"debug.noLines.usage":`使用量抽出はオンですが、まだ何もキャプチャされていません。Codex 経由でチャット/リクエストを送信するとここに表示されます。`,"debug.noLines.injection":`インジェクションログはオンですが、まだ何もキャプチャされていません。コラボおよびサブエージェントのターンでのマルチエージェントガイダンスインジェクションと負荷上限の決定を記録します。`,"usage.title":`使用量`,"usage.subtitle":`プロキシからのローカルトークン会計です。欠損した使用量はゼロとして表示されることはありません。`,"usage.loading":`使用量データを読み込み中…`,"usage.empty":`まだ使用量が記録されていません。プロキシ経由でリクエストを送信するとここにアクティビティが表示されます。`,"usage.loadError":`使用量データを読み込めませんでした。`,"usage.range.all":`すべて`,"usage.range.available":`利用可能な履歴`,"usage.historyTruncated":`古い利用履歴が読み込まれていないため、合計は利用可能な履歴のみを対象とします。`,"usage.range.30d":`30日`,"usage.range.7d":`7日`,"usage.card.requests":`リクエスト`,"usage.card.measured":`計測`,"usage.card.reported":`報告`,"usage.card.totalTokens":`合計トークン`,"usage.card.cachedTokens":`キャッシュ読み取り`,"usage.card.cachedTokensHint":`プロバイダーキャッシュから提供されたプロンプトトークン(読み取り)。キャッシュ書き込みは存在する場合、下に表示されます。`,"usage.card.cacheWriteTokens":`キャッシュ書き込み`,"usage.card.coverage":`カバレッジ`,"usage.card.activeDays":`アクティブ日数`,"usage.section.heatmap":`日のアクティビティ`,"usage.section.overview":`概要`,"usage.section.models":`モデル`,"usage.section.providers":`プロバイダー`,"usage.section.coverage":`カバレッジ内訳`,"usage.workspace.report":`使用量レポート`,"usage.workspace.sections":`使用量セクション`,"usage.coverage.measured":`計測`,"usage.coverage.reported":`プロバイダー報告`,"usage.coverage.estimated":`推定`,"usage.coverage.note":`計測エントリにはプロバイダー報告および推定のトークン数が含まれます。未報告および非対応のリクエストは追跡されますが、ゼロトークンに水増しされることはありません。`,"usage.search.models":`モデルを検索…`,"usage.col.requests":`リクエスト`,"usage.col.measured":`計測`,"usage.col.reported":`報告`,"usage.col.tokens":`トークン`,"usage.col.share":`割合`,"usage.heatmap.less":`少ない`,"usage.heatmap.more":`多い`,"usage.dayMon":`月`,"usage.dayWed":`水`,"usage.dayFri":`金`,"usage.heatmap.tooltipTokens":`{tokens} トークン`,"usage.heatmap.tooltipRequests":`{requests} リクエスト`,"nav.storage":`ストレージ`,"storage.title":`ストレージ`,"storage.subtitle":`CODEX_HOME の使用状況を確認。クリーンアップはアクティブセッションに触れません。`,"storage.loading":`ストレージをスキャン中…`,"storage.empty":`CODEX_HOME が空か存在しません — 報告するものはありません。`,"storage.error":`ストレージのスキャンに失敗しました。CODEX_HOME が有効なディレクトリを指しているか確認してください。`,"storage.refresh":`再スキャン`,"storage.rescanned":`スキャンが完了しました。`,"storage.card.total":`合計サイズ`,"storage.card.files":`ファイル`,"storage.card.home":`CODEX_HOME`,"storage.snapshot.lastScan":`最終スキャン`,"storage.snapshot.scanning":`スキャン中…`,"storage.snapshot.unavailable":`まだスキャンがありません。`,"storage.cleanupCard.title":`容量を空ける`,"storage.cleanupCard.tabs":`クリーンアップオプション`,"storage.cleanupCard.tab.policy":`ポリシー`,"storage.cleanupCard.tab.quarantine":`隔離`,"storage.cleanup.noArchives":`クリーンアップ対象のアーカイブセッションはありません。`,"storage.section.buckets":`バケット`,"storage.section.largest":`最大ファイル`,"storage.workspace.overview":`概要`,"storage.workspace.selectBucket":`一覧からバケットを選ぶと内訳が表示されます。`,"storage.col.bucket":`バケット`,"storage.col.size":`サイズ`,"storage.col.files":`ファイル`,"storage.col.oldest":`最古`,"storage.col.newest":`最新`,"storage.col.rows":`DB 行`,"storage.rows.unknown":`不明(ロック中)`,"storage.bucket.sessions":`アクティブセッション`,"storage.bucket.archived_sessions":`アーカイブ済みセッション`,"storage.bucket.logs_db":`ログデータベース`,"storage.bucket.state_db":`状態データベース`,"storage.bucket.attachments":`添付`,"storage.bucket.deletion_manifests":`削除マニフェスト`,"storage.bucket.other":`その他`,"storage.cleanup.title":`アーカイブのクリーンアップ`,"storage.cleanup.help":`古いアーカイブセッションを割合で削除します。アクティブセッションには触れません。既定は隔離で、ファイルは CODEX_HOME/.trash へ移動します。`,"storage.cleanup.slider":`古いアーカイブの割合`,"storage.cleanup.percent":`{percent}%`,"storage.cleanup.preset":`{percent}`,"storage.cleanup.preview":`プレビュー`,"storage.cleanup.confirmTitle":`アーカイブクリーンアップの確認`,"storage.cleanup.confirmBody":`アーカイブ {count} 件(約 {size})、古い {percent}% を処理します。`,"storage.cleanup.moreFiles":`…ほか {n} 件`,"storage.cleanup.permanent":`完全に削除する(隔離しない)`,"storage.cleanup.permanentWarn":`完全削除は元に戻せません。`,"storage.cleanup.quarantineNote":`ファイルは CODEX_HOME 下の .trash へ移動します。隔離タブから復元できます。`,"storage.cleanup.cancel":`キャンセル`,"storage.cleanup.confirmQuarantine":`隔離する`,"storage.cleanup.confirmPermanent":`完全に削除`,"storage.cleanup.doneQuarantine":`{count} 件を隔離しました({size})。`,"storage.cleanup.donePermanent":`{count} 件を完全削除しました({size})。`,"storage.cleanup.previewFailed":`プレビューに失敗しました。`,"storage.cleanup.cleanupFailed":`クリーンアップに失敗しました。`,"storage.cleanup.err.codex_busy":`Codex が state.sqlite を使用中です — Codex を終了して再試行してください。`,"storage.cleanup.err.stale_preview":`プレビュー以降にアーカイブが変わりました — プレビューをやり直してください。`,"storage.cleanup.err.restore_pending_overlap":`選択したアーカイブは未完了の隔離復元と重なっています — 復元を完了するか再試行してください。`,"storage.cleanup.err.referenced_history":`選択したアーカイブはフォークまたはページング履歴から参照されています。`,"storage.cleanup.err.invalid_digest":`プレビューのダイジェストが無い、または無効です。`,"storage.cleanup.err.invalid_mode":`モードは quarantine または permanent である必要があります。`,"storage.cleanup.err.fs_failed":`ファイルシステムのクリーンアップに失敗しました。一部の変更は既に適用されている可能性があります — CODEX_HOME/.trash と表示されたリカバリパスを確認してください。`,"storage.cleanup.err.fs_failed_trash":`ファイルシステムのクリーンアップに失敗しました。一部の変更は既に適用されている可能性があります — {trashDir} と manifest.json で復旧可能なファイルを確認してください。`,"storage.cleanup.err.db_reconcile_failed":`Codex の状態データベースを更新できませんでした。`,"storage.cleanup.err.cleanup_failed":`クリーンアップに失敗しました。`,"storage.trash.title":`隔離`,"storage.trash.help":`CODEX_HOME/.trash へ移したアーカイブセッションです。復元すると JSONL とスレッド行が戻ります。`,"storage.trash.empty":`隔離エントリはありません。`,"storage.trash.loading":`隔離を読み込み中…`,"storage.trash.col.when":`隔離日時`,"storage.trash.col.files":`ファイル`,"storage.trash.col.size":`サイズ`,"storage.trash.col.mode":`モード`,"storage.trash.col.id":`エントリ`,"storage.trash.restore":`復元`,"storage.trash.confirmTitle":`隔離エントリを復元しますか?`,"storage.trash.confirmBody":`{id} から {count} 件(約 {size})をアーカイブセッションへ戻します。`,"storage.trash.cancel":`キャンセル`,"storage.trash.confirmRestore":`復元`,"storage.trash.done":`{count} 件を復元しました({size})。`,"storage.trash.restoreFailed":`復元に失敗しました。`,"storage.trash.listFailed":`隔離一覧を取得できませんでした。`,"storage.trash.mode.quarantine":`隔離`,"storage.trash.mode.permanent":`完全削除(未完了)`,"storage.trash.err.codex_busy":`Codex が state.sqlite を使用中です — Codex を終了して再試行してください。`,"storage.trash.err.invalid_trash":`隔離エントリ ID が無い、または無効です。`,"storage.trash.err.missing_trash":`隔離エントリが見つかりません。`,"storage.trash.err.dest_exists":`復元先が既に存在します — アーカイブファイルを削除または改名して再試行してください。`,"storage.trash.err.fs_failed":`ファイルシステムの復元に失敗しました。一部は既に復元されている可能性があります — archived_sessions と .trash を確認してください。`,"storage.trash.err.storage_mutation_busy":`別のストレージクリーンアップまたは復元が進行中です — しばらくして再試行してください。`,"storage.trash.err.db_reconcile_failed":`Codex の状態データベース行を復元できませんでした。`,"storage.trash.err.restore_failed":`復元に失敗しました。`,"storage.trash.err.restore_worker_timeout":`復元が長時間(10 分超)かかったため停止しました。`,"storage.trash.err.restore_worker_aborted":`シャットダウン中に復元がキャンセルされました。`,"storage.trash.err.restore_worker_failed":`復元ワーカーがクラッシュまたは予期しないエラーで失敗しました。`,"storage.policy.title":`自動クリーンアップ方針`,"storage.policy.help":`アーカイブがしきい値を超えたときの任意の一括クリーンアップ。既定はオフ — 自動では有効になりません。`,"storage.policy.loading":`方針を読み込み中…`,"storage.policy.loadFailed":`クリーンアップ方針を読み込めませんでした。`,"storage.policy.saveFailed":`クリーンアップ方針を保存できませんでした。`,"storage.policy.runFailed":`方針の実行に失敗しました。`,"storage.policy.alreadyRunning":`クリーンアップ方針の実行が既に進行中です。`,"storage.policy.invalid":`方針の値が無効です。`,"storage.policy.enabled":`自動クリーンアップを有効化`,"storage.policy.enabledHint":`既定はオフです。有効にすると選択したスケジュール(または今すぐ実行)でのみ動きます。`,"storage.policy.threshold":`アーカイブサイズが超えたら(GiB)`,"storage.policy.trigger":`トリガー`,"storage.policy.target":`クリーンアップ目標`,"storage.policy.targetPercent":`古いアーカイブを削除(%)`,"storage.policy.targetReduce":`アーカイブを次のサイズまで縮小(GiB)`,"storage.policy.thresholdInc":`しきい値を上げる`,"storage.policy.thresholdDec":`しきい値を下げる`,"storage.policy.percentInc":`パーセントを上げる`,"storage.policy.percentDec":`パーセントを下げる`,"storage.policy.reduceInc":`削減目標を上げる`,"storage.policy.reduceDec":`削減目標を下げる`,"storage.policy.schedule":`スケジュール`,"storage.policy.schedule.manual":`手動のみ`,"storage.policy.schedule.startup":`プロキシ起動時`,"storage.policy.schedule.daily":`毎日`,"storage.policy.schedule.weekly":`毎週`,"storage.policy.mode":`削除モード`,"storage.policy.mode.quarantine":`隔離(既定)`,"storage.policy.mode.permanent":`完全削除`,"storage.policy.permanentWarn":`完全削除モードは元に戻せません。確信がなければ隔離を使ってください。`,"storage.policy.lastRun":`前回の実行`,"storage.policy.lastRunDetail":`{count} 件削除 · {size} 解放`,"storage.policy.nextRun":`次回の実行`,"storage.policy.never":`なし`,"storage.policy.save":`保存`,"storage.policy.runNow":`今すぐ実行`,"storage.policy.running":`実行中…`,"storage.policy.saved":`方針を保存しました。`,"storage.policy.skippedDisabled":`方針が無効です — 先に有効化してください。`,"storage.policy.skippedUnder":`アーカイブサイズがしきい値未満です — 作業はありません。`,"storage.policy.skippedEmpty":`目標に合うアーカイブ候補がありません。`,"storage.policy.doneQuarantine":`方針が {count} 件を隔離しました({size})。`,"storage.policy.donePermanent":`方針が {count} 件を完全削除しました({size})。`,"modal.addNamed":`追加: {label}`,"modal.add":`プロバイダーを追加`,"modal.search":`プロバイダーを検索…`,"modal.logInWith":`{label} でログイン`,"modal.waitingBrowser":`ブラウザを待機中…`,"modal.providerName":`プロバイダー名`,"modal.adapter":`アダプター`,"modal.baseUrl":`ベース URL`,"modal.endpoint":`エンドポイント`,"modal.endpoint.tokenPlan":`トークンプラン`,"modal.endpoint.payAsYouGo":`従量課金`,"modal.endpoint.custom":`カスタム`,"modal.defaultModel":`デフォルトモデル(任意)`,"modal.allowPrivateNetwork":`ローカル/プライベートネットワークを許可`,"modal.allowPrivateNetworkHint":`意図的にセルフホストしたプロバイダーに対してのみ有効化してください。メタデータエンドポイントはブロックされたままです。`,"modal.nameRequired":`プロバイダー名は必須です`,"modal.baseUrlRequired":`ベース URL は必須です`,"modal.networkError":`ネットワークエラー — プロキシは起動していますか?`,"modal.loginFailStart":`ログインを開始できませんでした`,"modal.waitingLogin":`ブラウザログインを待機中…`,"modal.loggingIn":`ログイン中…`,"modal.loginTimeout":`ログインがタイムアウトしました — もう一度お試しください。`,"modal.back":`戻る`,"modal.badge.oauth":`OAuth`,"modal.customProvider":`カスタムプロバイダー`,"modal.failedStatus":`失敗 ({status})`,"modal.loginError":`ログインエラー: {error}`,"modal.badge.codexLogin":`Codex ログイン`,"modal.badge.local":`ローカル`,"modal.badge.apiKey":`API キー`,"modal.badge.direct":`ダイレクト`,"modal.badge.pool":`プール`,"modal.badge.free":`無料`,"modal.invalidPreset":`この組み込みプロバイダープリセットは不完全です。プロキシを再起動してもう一度お試しください。`,"modal.freeTierTitle":`無料枠`,"modal.freeTierDefault":`API キー不要です。そのまま利用できます。`,"modal.tab.accounts":`アカウント`,"modal.tab.free":`無料`,"modal.tab.paid":`有料`,"modal.accountsHint":`ChatGPT/Codex、OAuth プロバイダー、API キーアカウントにここからサインインします。OpenAI は組み込み済み — 再度追加せずログインしてください。`,"modal.accountsCodexAuthLink":`Codex 認証`,"modal.notListed":`プロバイダーが載っていませんか? カスタムを追加`,"modal.catalogLoading":`カタログを読み込み中…`,"modal.accountLogin":`ログイン`,"modal.accountLogout":`ログアウト`,"modal.accountAdd":`アカウントを追加`,"modal.accountManage":`管理`,"modal.accountCodexPool":`ChatGPT アカウントプール`,"modal.accountLoggedIn":`ログイン済み`,"modal.accountLoggedOut":`未ログイン`,"quota.fiveHourLimit":`5 時間上限`,"quota.weeklyLimit":`週間上限`,"quota.monthlyLimit":`30 日上限`,"quota.cursorFirstParty":`ファーストパーティモデル`,"quota.cursorApiUsage":`API 使用量`,"quota.totalSubscriptionCredits":`サブスクリプションクレジット合計`,"quota.usedPercent":`{pct}% 使用`,"quota.limitReached":`上限に達しました`,"quota.resetsToday":`今日 {time} にリセット`,"quota.resetsTomorrow":`明日 {time} にリセット`,"quota.resetsAt":`{when} にリセット`,"quota.resetsRelativeMinutes":`{n} 分後にリセット`,"quota.resetsRelativeHours":`{n} 時間後にリセット`,"pws.status.ready":`準備完了`,"pws.status.needsSetup":`セットアップが必要`,"pws.status.needsAttention":`要対応`,"pws.auth.chatgptPassthrough":`ChatGPT パススルー`,"pws.auth.noKey":`キー不要`,"pws.freeTitle":`無料料金(キーが必要な場合もあります)`,"pws.localTitle":`ローカルランタイム`,"pws.modelCountOne":`1 モデル`,"pws.modelCount":`{count} モデル`,"pws.rail.suffixDefault":` · デフォルト`,"pws.rail.suffixLocal":` · ローカル`,"pws.rail.suffixFree":` · 無料`,"pws.rail.selectAria":`{name} を選択 — {status}{suffix}`,"pws.searchPlaceholder":`プロバイダーを検索…`,"pws.filterAria":`プロバイダーを絞り込み`,"pws.providerFiltersAria":`プロバイダーフィルタ`,"pws.filters":`フィルタ`,"pws.filterStatus":`状態`,"pws.pricing":`料金`,"pws.paid":`有料`,"pws.filterType":`タイプ`,"pws.type.cloud":`クラウド`,"pws.type.local":`ローカル`,"pws.type.selfHosted":`セルフホスト`,"pws.type.login":`ログイン`,"pws.sort":`並べ替え`,"pws.sortProvidersAria":`プロバイダーを並べ替え`,"pws.sort.az":`A–Z`,"pws.sort.za":`Z–A`,"pws.sort.freePaid":`無料優先`,"pws.sort.paidFree":`有料優先`,"pws.sort.accountsFirst":`アカウント優先`,"pws.resetAll":`すべてリセット`,"pws.providerList":`プロバイダー一覧`,"pws.providersAria":`プロバイダー`,"pws.groupReady":`準備完了 ({count})`,"pws.groupNeedsSetup":`セットアップが必要 ({count})`,"pws.groupDisabled":`無効 ({count})`,"pws.noSearchResults":`検索に一致するプロバイダーがありません。`,"pws.noMatchFilters":`フィルタに一致するプロバイダーがありません。`,"pws.noProvidersConfigured":`プロバイダーが設定されていません。`,"pws.workspaceMainAria":`プロバイダーの詳細`,"pws.detailComingSoon":`詳細ビューは近日対応 — このプロバイダーの管理にはクラシックビューを使用してください。`,"pws.selectPrompt":`リストからプロバイダーを選択してください。`,"pws.connectFirst":`最初のプロバイダーを接続`,"pws.empty.browseFree":`無料プロバイダーを見る`,"pws.empty.browseFreeDesc":`サブスクリプションなしで始める`,"pws.empty.connectAccount":`アカウントを接続`,"pws.empty.connectAccountDesc":`ChatGPT やプロバイダーのログインを使用`,"pws.empty.addEndpoint":`エンドポイントを追加`,"pws.empty.addEndpointDesc":`カスタムベース URL と API キー`,"pws.tab.overview":`概要`,"pws.tab.models":`モデル`,"pws.tab.usage":`使用量`,"pws.tab.accounts":`アカウント`,"pws.tab.settings":`設定`,"pws.connection":`接続`,"pws.status.connected":`接続済み`,"pws.attentionTitle":`要対応`,"pws.attention.reauth":`アクティブアカウントの再認証が必要です`,"pws.attention.reauthForward":`アクティブな Codex アカウントの再認証が必要です — アカウントタブを開いて修正してください`,"pws.attention.missingCredentials":`資格情報が不足しています`,"pws.cell.auth":`認証`,"pws.cell.note":`メモ`,"pws.cell.defaultModel":`デフォルトモデル`,"pws.statsAria":`プロバイダー統計`,"pws.statsTitle":`統計`,"pws.stats.totalRequests":`リクエスト (30日)`,"pws.stats.totalTokens":`トークン (30日)`,"pws.stats.quotaUpdated":`クォータを更新しました`,"pws.stats.quotaTracked":`レート制限は使用量タブで追跡されます。`,"pws.stats.source":`ソース`,"pws.usageLast30d":`使用量 (過去30日)`,"pws.metricRequests":`リクエスト`,"pws.metricTokens":`トークン`,"pws.usageUnavailable":`まだ使用量が記録されていません。`,"pws.rateLimits":`レート制限`,"pws.quotaUnavailable":`このプロバイダーのクォータデータがありません。`,"pws.accountQuotaUnavailable":`レート制限データを一時的に取得できません。前回の値がある場合はそれを表示します。`,"pws.selected":`選択中`,"pws.copyModelId":`ID をコピー`,"pws.modelCopied":`コピーしました!`,"pws.modelsAvailable":`{count} 件利用可能`,"pws.modelSearchPlaceholder":`モデルを絞り込み…`,"pws.modelsLoading":`モデルを読み込み中…`,"pws.modelsLoadFailed":`モデルを読み込めませんでした。`,"pws.modelsNeedsReauth":`ライブモデル検出が動作するには再ログインが必要です。今は設定済みモデルを表示しています。`,"pws.modelsConfiguredFallback":`設定済みモデルを表示中(ライブ検出は利用不可)。`,"pws.modelsTruncated":`最初の {shown} / {total} モデルを表示中。リストを絞り込んでください。`,"pws.retry":`再試行`,"pws.noModels":`このプロバイダーで検出されたモデルはありません。`,"pws.noModelMatch":`フィルタに一致するモデルがありません。`,"pws.adapterBaseRequired":`アダプターとベース URL は必須です。`,"pws.addAccount":`アカウントを追加`,"pws.addKey":`API キーを追加`,"pws.apiKeys":`API キー`,"pws.authMode":`認証モード`,"pws.availableAccounts":`利用可能なアカウント`,"pws.accountOrdinal":`アカウント {count}`,"pws.accountsLoading":`アカウントを読み込み中…`,"pws.accountsLoadFailed":`アカウントを読み込めませんでした。`,"pws.retryAccounts":`再試行`,"pws.noAccounts":`まだアカウントが接続されていません。`,"pws.accountSwitching":`切り替え中…`,"pws.accountCurrent":`現在のアカウント`,"pws.defaultModelNone":`なし(プロバイダーのデフォルトを使用)`,"pws.discardSettings":`破棄`,"pws.jsonEditorDesc":`生のプロバイダー JSON 設定を編集します。変更はすぐに保存されます。`,"pws.jsonEditorTitle":`JSON エディタ — {name}`,"pws.jsonRestore":`復元`,"pws.jsonSave":`保存`,"pws.loggedInTitle":`ログイン済み`,"pws.notLoggedInTitle":`未ログイン`,"pws.note":`メモ`,"pws.allowPrivateNetwork":`ローカル/プライベートネットワークを許可`,"pws.liveModels":`プロバイダーからモデルを検出`,"pws.liveModelsDesc":`プロバイダーのライブモデルカタログを取得します。オフにすると設定済みの静的モデルのみを使用します。`,"pws.optionalPlaceholder":`任意`,"pws.providerId":`プロバイダー ID`,"pws.reauth":`再認証が必要`,"pws.reauthenticate":`再認証`,"pws.copyDoctor":`ocx doctor をコピー`,"pws.doctorCopied":`コピー済み`,"pws.healthCooldownHint":`クールダウンが終わるまで待ってください。まだこのアカウントをプローブしないでください。`,"pws.doctorCopyUnavailable":`クリップボードを利用できません`,"pws.healthLabel.rateLimited":`レート制限中`,"pws.healthLabel.quotaLimited":`クォータ制限中`,"pws.healthLabel.reauthRequired":`再認証が必要です`,"pws.healthLabel.refreshFailed":`更新に失敗しました`,"pws.healthLabel.metadataMismatch":`メタデータの不一致`,"pws.healthLabel.credentialConflict":`資格情報の競合`,"pws.healthSummary.rateLimited":`{provider} {account}: {until} までレート制限中です。それまでこのアカウントのルーティングは停止します。`,"pws.healthSummary.quotaLimited":`{provider} {account}: {until} までクォータ制限中です。それまでこのアカウントのルーティングは停止します。`,"pws.healthSummary.reauthRequired":`{provider} {account}: 再認証が必要です。`,"pws.healthSummary.credentialConflict":`{provider} {account}: 資格情報の競合があります。`,"pws.healthSummary.metadataMismatch":`{provider} {account}: メタデータが一致しません。`,"pws.healthSummary.staleCredentials":`{provider} {account}: 資格情報が不完全です。`,"pws.removeConfirm":`削除`,"pws.removeConfirmBody":`プロバイダー "{name}" を削除しますか? これは元に戻せません。`,"pws.removeDefaultConfirmBody":`既定のプロバイダー "{name}" を削除しますか? "{defaultProvider}" が既定のプロバイダーになります。この操作は元に戻せません。`,"pws.removeConfirmTitle":`プロバイダーを削除`,"pws.saveSettings":`保存`,"pws.saving":`保存中…`,"pws.settingsSaved":`設定を保存しました。`,"pws.settingsUnsavedBar":`未保存の変更があります。`,"pws.unsavedLeaveBody":`未保存の変更があります。保存してから移動しますか?`,"pws.unsavedLeaveTitle":`未保存の変更`,"pws.attentionRequired":`要対応`,"pws.attentionAria":`{name}: {reason}`,"pws.missingCredentials":`資格情報が不足しています`,"pws.editJsonDesc":`生のプロキシ設定を JSON として編集`,"pws.updatesUnavailable":`プロバイダーの更新は利用できません。`,"pws.dashboard.title":`プロバイダー概要`,"pws.dashboard.subtitle":`すべてのモデルプロバイダーを一か所で管理します。`,"pws.dashboard.rateLimits":`レート制限`,"pws.dashboard.recentlyUsed":`最近の使用`,"pws.dashboard.requests":`{count} リクエスト`,"pws.dashboard.checkedAgo":`{time} に確認`,"pws.dashboard.noQuota":`クォータデータなし`,"pws.dashboard.noUsage":`まだ使用量データはありません`,"pws.dashboard.noRateLimits":`まだレート制限データはありません`,"pws.capacity.estimate":`重み付きプール推定`,"pws.capacity.coverage":`{included}/{total} アカウント`,"pws.capacity.nextRecovery":`次の回復 {time}`,"pws.allProviders":`プロバイダー概要`,"pws.enabledLabel":`有効`,"pws.testConnection":`接続テスト`,"pws.testing":`テスト中…`,"pws.connectionOk":`接続 OK`,"pws.connectionFailed":`接続失敗`,"pws.connectionNotApplicable":`対象外 — このプロバイダーは静的モデルカタログを使用します。`,"pws.editSettings":`設定を編集`,"pws.viewUsage":`詳細な使用量を表示`,"pws.allSystemsOk":`すべてのシステムが稼働中`,"pws.apiKeyConfigured":`API キー設定済み`,"pws.addApiKey":`API キーを追加`,"pws.loggedInAs":`{email} としてログイン中`,"pws.notLoggedIn":`未ログイン`,"pws.passthrough":`Codex パススルー`,"pws.notes":`メモ`,"pws.notePlaceholder":`このプロバイダーについてのメモを追加...`,"pws.noteSaved":`メモを保存しました`,"pws.authSummary":`認証`,"time.justNow":`たった今`,"time.notChecked":`未確認`,"time.minutesAgo":`{n}分前`,"time.hoursAgo":`{n}時間前`,"time.daysAgo":`{n}日前`,"modal.noMatch":`一致なし。`,"modal.oauthDefaultNote":`アカウントでログイン — API キー不要です。`,"modal.oauthComingSoon":`{label} の OAuth ログインは次回の更新で対応予定です。今は API キーをお使いください。`,"modal.oauthComingSoonShort":`このプロバイダーの OAuth ログインは次回の更新で対応予定です — 今は API キーをお使いください。`,"modal.useApiKeyInstead":`代わりに API キーを使用`,"modal.setupGuide":`セットアップガイド`,"modal.setupStep1Prefix":`にアクセスし`,"modal.setupDashboardLink":`{label} ダッシュボード`,"modal.setupStep1Suffix":`から API キーをコピー`,"modal.setupStep2":`下の API キー欄に貼り付け`,"modal.setupStep3":`プロバイダーを追加をクリック — モデルは自動検出されます`,"modal.namePlaceholder":`例: openrouter`,"modal.duplicateWarn":`プロバイダー "{name}" は既存で、上書きされます。`,"modal.forwardHintPrefix":`キー不要 — プロキシはあなたの`,"modal.forwardCredentials":`codex ログイン`,"modal.forwardHintSuffix":`資格情報をこのプロバイダーに転送します。`,"modal.localHint":`API キーは保存されません。Cursor の静的な公開モデルカタログを Codex に追加しますが、ライブの Cursor トランスポートとネイティブのファイル/シェル実行は監査されるまで無効のままです。`,"modal.getApiKey":`{label} の API キーを取得`,"modal.apiKey":`API キー`,"modal.apiKeyTransport":`API キーヘッダー`,"modal.apiKeyTransportNative":`x-api-key (Anthropic 標準)`,"modal.apiKeyTransportBearer":`Authorization: Bearer`,"modal.apiKeyPlaceholder":`sk-… (または $ENV_VAR)`,"modal.defaultModelPlaceholder":`例: gpt-5.5`,"modal.baseUrlPlaceholder":`https://...`,"modal.baseUrlPlaceholderError":`ベース URL に未解決の {placeholder} が含まれています。実際の値に置き換えてください。`,"modal.baseUrlPlaceholderHint":`プロバイダーを追加する前に、ベース URL の {placeholder} を実際の Account ID に置き換えてください。`,"modal.adding":`追加中…`,"modal.useOauthLogin":`← OAuth ログインを使用`,"nav.codexAuth":`Codex 認証`,"nav.api":`API`,"nav.openMenu":`メニューを開く`,"nav.closeMenu":`メニューを閉じる`,"codexAuth.mainAccount":`メインアカウント`,"codexAuth.codexApp":`Codex App`,"codexAuth.appLogin":`アプリログイン`,"codexAuth.accountPool":`アカウントプール`,"codexAuth.accountModeTitle":`OpenAI アカウントモード`,"codexAuth.accountModePool":`プールモード`,"codexAuth.accountModePoolDesc":`メインログインと対象の追加アカウントがここでローテーションします。`,"codexAuth.accountModeDirect":`ダイレクトモード`,"codexAuth.accountModeDirectDesc":`リクエストはメインログインのみを使用します; 追加アカウントはプールモード用に保持されます。`,"codexAuth.openaiMissing":`組み込みの OpenAI プロバイダーが設定されていません。`,"codexAuth.openaiDisabled":`組み込みの OpenAI プロバイダーが無効です。`,"codexAuth.openaiUnavailableDesc":`OpenAI アカウントは引き続き利用できます。Codex リクエストをルーティングするにはプロバイダーを有効にしてください。`,"codexAuth.enableOpenai":`OpenAI を有効にする`,"codexAuth.enablingOpenai":`有効化中...`,"codexAuth.enableOpenaiFailed":`OpenAI プロバイダーを有効にできませんでした。`,"codexAuth.openaiPresetLoadFailed":`OpenAI プロバイダーのプリセットを読み込めませんでした。`,"codexAuth.openaiPresetUnavailable":`OpenAI プロバイダーのプリセットを利用できません。`,"codexAuth.openProviders":`プロバイダーを開く`,"codexAuth.add":`追加`,"codexAuth.refreshQuota":`クォータを更新`,"codexAuth.refreshingQuota":`更新中...`,"codexAuth.quotaRefreshed":`クォータを更新しました`,"codexAuth.quotaRefreshFailed":`クォータの更新に失敗しました`,"codexAuth.pauseExhausted":`上限到達を一括停止`,"codexAuth.pausingExhausted":`クォータを確認中...`,"codexAuth.pauseExhaustedSucceeded":`上限に達したアカウントを停止しました: {count}`,"codexAuth.pauseExhaustedNone":`使用率 100% が確認されたアカウントはありません。`,"codexAuth.pauseExhaustedFailed":`上限到達アカウントの確認と停止に失敗しました。`,"codexAuth.noPool":`まだプールアカウントは追加されていません。`,"codexAuth.pause":`一時停止`,"codexAuth.resume":`再開`,"codexAuth.paused":`一時停止中`,"codexAuth.pauseSucceeded":`{email} を一時停止しました`,"codexAuth.resumeSucceeded":`{email} をアカウントプールに戻しました`,"codexAuth.pauseFailed":`{email} を一時停止できませんでした。変更はありません。`,"codexAuth.resumeFailed":`{email} を再開できませんでした。変更はありません。`,"codexAuth.pausedHint":`再開するまで、自動切り替え、再試行、クールダウン復旧、手動選択の対象外です。`,"codexAuth.fiveHour":`5時間`,"codexAuth.weekly":`週`,"codexAuth.monthly":`30日`,"codexAuth.resets":`リセット`,"codexAuth.today":`今日`,"codexAuth.current":`現在`,"codexAuth.nextSession":`選択済み`,"codexAuth.poolPrepared":`プール準備済み`,"codexAuth.preparePoolTitle":`このアカウントをプールモード用に準備しますか?`,"codexAuth.preparePoolDesc":`ダイレクトリクエストはメインログインを使い続けます。このアカウントはプールモードが有効化された際の準備済みプール選択になります。`,"codexAuth.prepareForPool":`プール用に準備`,"codexAuth.poolPreparedToast":`{email} はプールモード用に準備されました`,"codexAuth.switchTitle":`アクティブアカウントを切り替えますか?`,"codexAuth.switchDesc":`既存および新規 Codex セッションの次のリクエストから適用されます。処理中のリクエストは現在のアカウントを維持します。`,"codexAuth.cacheWarning":`アカウントが変わっても OpenCodex は会話コンテキストを再生しますが、プロバイダー側のプロンプトキャッシュは再ウォームアップが必要な場合があります。`,"codexAuth.setAsNext":`アカウントを選択`,"codexAuth.cancel":`キャンセル`,"codexAuth.switchBack":`メインに戻しますか?`,"codexAuth.switchBackDesc":`既存および新規 Codex セッションの次のリクエストからアプリログインアカウントを使用します。`,"codexAuth.autoSwitch":`使用量ベースのプロアクティブ切り替え`,"codexAuth.autoSwitchQuotaDesc":`クォータ: 使用率が {threshold}% 以上になると、既に紐付いたタスクを含む次のリクエストが、使用率の低い適格アカウントへ移る場合があります。Go/Free は 30 日枠のみを使用します。`,"codexAuth.autoSwitchQuotaOffDesc":`使用量ベースのプロアクティブ切り替えはオフです。新規/未紐付けタスクの割り当てと障害回復は引き続き適用されます。`,"codexAuth.autoSwitchRoundRobinDesc":`ラウンドロビン割り当てはこのしきい値を使用せず、新規/未紐付けタスクを引き続きローテーションします。`,"codexAuth.autoSwitchFillFirstDesc":`フィルファースト: {threshold}% は新規/未紐付けタスクの使い切り基準です。正常な紐付け済みタスクはアカウントを維持します。`,"codexAuth.autoSwitchFillFirstOffDesc":`フィルファーストには新規/未紐付けタスクの使用量基準がありません。クールダウン、再認証、障害回復では引き続きルーティングが変わる場合があります。`,"codexAuth.failureRecoveryNote":`障害回復は別です。出力前の 429/402 拒否、クールダウン、再認証、除外、または設定済みの一時障害フェイルオーバーにより、別の適格アカウントが選ばれる場合があります。`,"codexAuth.autoSwitchThreshold":`使用量しきい値`,"codexAuth.autoSwitchThresholdAria":`使用量しきい値(パーセント)`,"codexAuth.autoSwitchThresholdInc":`使用量しきい値を上げる`,"codexAuth.autoSwitchThresholdDec":`使用量しきい値を下げる`,"codexAuth.autoSwitchLoadFailed":`使用量ベースの切り替え設定を読み込めませんでした。`,"codexAuth.autoSwitchThresholdInvalid":`1 から 100 までの整数を入力してください`,"codexAuth.autoSwitchUpdated":`使用量ベースのプロアクティブ切り替え設定を更新しました`,"codexAuth.autoSwitchUpdateFailed":`使用量ベースの切り替え更新を確認できませんでした。最後に確認された値を表示しています。`,"anthropicPool.title":`Claude アカウントプール(実験的)`,"anthropicPool.enabledDesc":`429 時にアカウントをクールダウンしてフェイルオーバーします。新規セッションは 5 時間使用率が {threshold}% 未満のアカウントを優先します。`,"anthropicPool.disabledDesc":`アクティブな Claude アカウントのみを使用します。実験的ルーティングを受け入れる場合のみ有効にしてください。`,"anthropicPool.experimentalWarning":`実験的で十分に検証されていません。自動的な複数アカウント回転に見える行為は Anthropic により制限される可能性があります。同一組織はクォータを共有することがあり、その場合プールしても効果がありません。リスクを理解していない場合はオフのままにしてください。`,"anthropicPool.needTwoAccounts":`プールを有効にする前に、Claude OAuth アカウントを 2 つ以上追加してください。`,"anthropicPool.threshold":`新規セッションの使用率しきい値`,"anthropicPool.thresholdAria":`新規セッションの使用率しきい値(パーセント)`,"anthropicPool.thresholdHelp":`0 はクォータに基づく選択を無効にします(アフィニティ + アクティブアカウントのみ)。デフォルト 80。`,"anthropicPool.thresholdInvalid":`0 から 100 までの整数を入力してください`,"anthropicPool.loadFailed":`Claude プール設定を読み込めませんでした。`,"anthropicPool.saveFailed":`Claude プール設定を保存できませんでした。`,"anthropicPool.on":`オン`,"anthropicPool.off":`オフ`,"accountPool.strategy":`ローテーション戦略`,"accountPool.strategyDesc":`OpenCodex が新規/未紐付けタスクへアカウントを割り当てる方法です。`,"accountPool.strategyQuota":`クォータ`,"accountPool.strategyRoundRobin":`ラウンドロビン`,"accountPool.strategyFillFirst":`フィルファースト`,"accountPool.strategyHintQuota":`クォータ戦略は使用量しきい値を超えると、既存タスクの次のリクエストも別アカウントへ再紐付けできます。`,"accountPool.strategyHintRoundRobin":`ラウンドロビンは有効な紐付けがないタスクだけをローテーションし、使用量しきい値は通常のローテーションを変えません。`,"accountPool.strategyHintFillFirst":`フィルファーストはしきい値を未紐付けタスクの使い切り基準として使用し、正常な紐付け済みタスクは親和性を維持します。`,"accountPool.unboundDefinition":`新規/未紐付けタスクとは、現在のアカウント紐付けがないリクエストです。既存の表示中タスクも、プロキシまたは親和性のリセット後は未紐付けになる場合があります。`,"accountPool.stickyLimit":`ローテーション前の新規/未紐付け割り当て数`,"accountPool.stickyLimitAria":`ローテーション前の新規/未紐付け割り当て数`,"accountPool.stickyLimitInc":`スティッキー上限を上げる`,"accountPool.stickyLimitDec":`スティッキー上限を下げる`,"accountPool.stickyLimitHelp":`次へ進む前に、この回数の新規/未紐付けタスクを選択アカウントへ割り当てます。カウンターは上流の成功後ではなく、タスクを紐付けた時点で増えます。`,"accountPool.stickyLimitInvalid":`1 から 100 までの整数を入力してください`,"accountPool.strategyLoadFailed":`ローテーション戦略を読み込めませんでした。`,"accountPool.strategyUpdateFailed":`ローテーション戦略を保存できませんでした。`,"codexAuth.switched":`次のリクエストでは {email} を使用します`,"codexAuth.loadFailed":`Codex アカウント設定を読み込めませんでした。`,"codexAuth.switchFailed":`アカウントを切り替えられませんでした。以前の選択はそのままです。`,"codexAuth.removeConfirm":`{id} を削除しますか?`,"codexAuth.removeFailed":`アカウントを削除できませんでした。何も変更されていません。`,"codexAuth.addTitle":`Codex アカウントを追加`,"codexAuth.addIdLabel":`アカウント ID (スラッグ)`,"codexAuth.addIdPlaceholder":`codex-work、codex-alt、team...`,"codexAuth.resetCreditsAria":`{count} 個のリセットクレジット`,"codexAuth.addJsonLabel":`auth.json の内容`,"codexAuth.addHelp":`別のマシンの ~/.codex/auth.json からコピー、または codex-auth export を使用。`,"codexAuth.importBtn":`インポート`,"codexAuth.importInvalidJson":`無効な JSON です`,"codexAuth.importMissingTokens":`JSON に access_token または refresh_token がありません`,"codexAuth.importMissingId":`アカウント ID は必須です`,"codexAuth.accountAdded":`アカウントをプールに追加しました`,"codexAuth.addPickDesc":`別の ChatGPT アカウントでログインしてプールに追加します。`,"codexAuth.oauthLogin":`OAuth ログイン`,"codexAuth.oauthDesc":`ブラウザで ChatGPT ログインを開きます`,"codexAuth.importAuthJson":`auth.json をインポート`,"codexAuth.importAuthJsonDesc":`別の Codex インストールまたは codex-auth export から`,"codexAuth.back":`戻る`,"codexAuth.oauthAlreadyInProgress":`ログインは既に進行中です。ブラウザで完了してください。`,"codexAuth.oauthWaiting":`ブラウザで ChatGPT ログインが完了するのを待機中...`,"codexAuth.oauthSubmittingCode":`コードを送信中…`,"codexAuth.oauthCodeSubmitted":`コードを送信しました — ログイン完了を待っています…`,"codexAuth.oauthStatusRetrying":`ログイン状態の確認中にネットワークまたはプロキシ エラーが発生しました — 再試行中…`,"codexAuth.oauthCancelled":`ログインはキャンセルされました。`,"codexAuth.loginFailed":`ログインに失敗しました`,"codexAuth.needsReauth":`再ログイン`,"codexAuth.reauthenticate":`再認証`,"codexAuth.tokenExpired":`トークンが期限切れ — このアカウントを再認証してください`,"codexAuth.mainTokenExpired":`トークンが期限切れ — Codex アプリログインから再度サインインしてください`,"codexAuth.emailCollision":`このアカウントはメインの Codex ログインと一致します。別のアカウントを使用してください。`,"codexAuth.resetCreditsTitle":`リセットクレジット`,"codexAuth.resetCreditsAvailable":`{count} 個のリセットクレジットが利用可能です。`,"codexAuth.resetCreditsDesc":`各クレジットは現在の時間別・週間使用量上限を即座にリセットします。`,"codexAuth.noResetCredits":`リセットクレジットはありません。`,"codexAuth.earnCreditsHint":`クレジットは毎月および紹介プログラム経由で獲得できます。`,"codexAuth.creditsExpireNote":`クレジットは獲得から 30 日で失効します。`,"codexAuth.useOneCredit":`1 クレジットを使用`,"codexAuth.confirmResetTitle":`リセットクレジットを使用しますか?`,"codexAuth.confirmResetDesc":`現在のレート制限を即座にリセットします。残り {count} クレジットです。`,"codexAuth.irreversible":`この操作は元に戻せません。`,"codexAuth.useCredit":`クレジットを使用`,"codexAuth.redeeming":`リセット中...`,"codexAuth.resetSuccess":`レート制限をリセットしました! 残り {remaining} クレジット。`,"codexAuth.resetSuccessGeneric":`レート制限をリセットしました!`,"codexAuth.resetAlreadyRedeemed":`このクレジットは既に引き換え済みです。クレジットは変わりません。`,"codexAuth.resetNothingToReset":`今リセットが必要なレート制限枠はありません。`,"codexAuth.resetNoCredit":`利用可能なリセットクレジットはありません。`,"codexAuth.resetError":`リセットクレジットの引き換えに失敗しました。もう一度お試しください。`,"codexAuth.fifoNote":`最も古いクレジットが先に使用されます。`,"codexAuth.confirmWhichCredit":`{date} のクレジットが使用されます。`,"codexAuth.creditNext":`次に使用`,"codexAuth.creditLabel":`クレジット #{n}`,"codexAuth.creditNextBadge":`次`,"codexAuth.creditGranted":`付与 {date}`,"codexAuth.creditExpires":`失効 {date} (残り {days}日)`,"api.title":`API アクセス`,"api.subtitle":`生成した API キーで外部アプリから opencodex プロキシに接続します。認証は {authHeader} ヘッダーで行い、エンドポイントごとに受け付けるヘッダーは下の表のとおりです。`,"api.endpointNote":`ベース URL を OpenAI 互換クライアントで使ってください。Responses と Chat Completions は /v1 配下で公開されます。`,"api.endpointsTitle":`エンドポイント`,"api.baseUrl":`ベース URL`,"api.responsesEndpoint":`Responses API`,"api.chatCompletionsEndpoint":`Chat Completions API`,"api.messagesEndpoint":`Messages API`,"api.modelsEndpoint":`Models API`,"api.authTitle":`認証`,"api.authBaseUrlNote":`クライアントにはベース URL を設定し、下のプロトコル別エンドポイントを選んでください。`,"api.authLoopback":`ループバック (127.0.0.1 または ::1) は認証を省略します。リモートでは生成した ocx_ キーまたは OPENCODEX_API_AUTH_TOKEN が必要です。`,"api.modelsTitle":`外部モデルカタログ`,"api.modelsCount":`{count} 件が利用可能`,"api.modelsSearch":`モデルを検索`,"api.modelsSubtitle":`これらの ID を /v1/models と選択したプロトコルで使用してください。`,"api.modelsLoading":`モデルを読み込み中…`,"api.modelsLoadFailed":`外部モデルカタログを読み込めませんでした。`,"api.modelsEmpty":`外部から呼び出せるモデルはまだありません。`,"api.modelsNoMatch":`「{query}」に一致するモデルはありません。`,"api.colModel":`モデル`,"api.colSource":`ソース`,"api.colProtocols":`プロトコル`,"api.copyModelId":`ID をコピー`,"api.modelCopied":`コピーしました`,"api.testModel":`テスト`,"api.testingModel":`テスト中…`,"api.testSucceeded":`OK`,"api.testFailed":`失敗`,"api.protocolResponses":`Responses`,"api.protocolChatCompletions":`Chat Completions`,"api.protocolMessages":`Messages`,"api.sourceNative":`ChatGPT プール`,"api.sourceCombo":`コンボ`,"api.sourceCustom":`カスタム`,"api.usageResponsesTitle":`Responses の例`,"api.usageChatTitle":`Chat Completions の例`,"api.usageMessagesTitle":`Messages の例`,"api.newKeyTitle":`新しいキーを作成しました`,"api.newKeyNote":`今すぐこのキーをコピーしてください — 再表示されません。`,"api.copy":`コピー`,"api.copied":`コピーしました`,"api.dismiss":`閉じる`,"api.generateTitle":`キーを生成`,"api.keyNamePlaceholder":`キー名(任意)`,"api.generate":`生成`,"api.generating":`作成中…`,"api.activeKeys":`アクティブなキー ({count})`,"api.activeKeysLoading":`有効なキー`,"api.noKeys":`まだ API キーがありません。上で生成してください。`,"api.workspace.sections":`API セクション`,"api.section.keys":`キー`,"api.section.connect":`接続`,"api.section.endpoints":`エンドポイント`,"api.section.models":`モデル`,"api.section.examples":`例`,"api.workspace.details":`APIキーの詳細`,"api.workspace.keyDetails":`キーの詳細`,"api.workspace.keyPrefix":`キーのプレフィックス`,"api.workspace.deleteKey":`キーを削除`,"api.workspace.deleteConfirm":`このキーを削除しますか?この操作は元に戻せません。`,"api.workspace.usageExamples":`使用例`,"api.copyUrlHint":`クリックして URL をコピー`,"api.urlCopied":`URL をコピーしました`,"api.copyExampleHint":`クリックして例をコピー`,"api.exampleCopied":`例をコピーしました`,"api.colName":`名前`,"api.colKey":`キー`,"api.colCreated":`作成日`,"api.confirm":`確認`,"api.deleteAria":`API キーを削除`,"api.usageSampleInput":`こんにちは、世界!`,"api.clientConfig.title":`クライアント設定`,"api.clientConfig.rowsLabel":`クライアントを接続`,"api.clientConfig.details":`詳細`,"api.clientConfig.detailsAria":`{client} 設定の詳細`,"api.clientConfig.copyAria":`{client} 設定 JSON をコピー`,"api.clientConfig.downloadAria":`{client} 設定をダウンロード`,"api.clientConfig.rowMeta":`{destination} · モデル {count} 件`,"api.clientConfig.rowError":`{client} の設定を生成できませんでした。`,"api.clientConfig.copiedAnnounceClient":`{client} の設定 JSON をクリップボードにコピーしました。`,"api.clientConfig.clientOpencode":`OpenCode`,"api.clientConfig.clientPi":`Pi`,"api.clientConfig.copy":`JSON をコピー`,"api.clientConfig.download":`ダウンロード`,"api.clientConfig.loading":`クライアント設定を生成中…`,"api.clientConfig.jsonLabel":`{client} 設定 JSON`,"api.clientConfig.destination":`配置先ファイル`,"api.clientConfig.envHint":`起動前にキーを設定`,"api.clientConfig.mergeWarning":`配置先ファイルにマージしてください。置き換えると既存のプロバイダーや MCP 設定が失われます。`,"api.clientConfig.modelCount":`{count} 件のモデルを書き出しました`,"api.clientConfig.missingLimits":`{total} 件中 {count} 件のモデルにコンテキスト上限がないため、クライアント側の既定値が使われます。`,"api.clientConfig.noKeyYet":`{env} に対応するキーがまだありません。ループバック外で使う前に上でキーを発行してください。`,"api.clientConfig.loadFailed":`モデル一覧を読み取れなかったため、クライアント設定を生成できませんでした。`,"api.clientConfig.copiedAnnounce":`クライアント設定 JSON をクリップボードにコピーしました。`,"api.clientConfig.copyFailed":`クライアント設定 JSON をコピーできませんでした。`,"api.clientConfig.downloadedAnnounce":`{filename} をダウンロードしました。まだ何も変わっていません。{destination} に自分でマージしてください。`,"api.clientConfig.whereDisclosure":`このファイルの置き場所`,"api.clientConfig.whereBody":`上のパスはグローバル設定の場所です。作業ディレクトリのプロジェクト設定ファイルが優先され、キーは設定に書かれた環境変数から読み込まれ、このファイルには保存されません。`,"api.keysLoadFailed":`APIキーを読み込めませんでした。`,"api.createFailed":`APIキーを作成できませんでした。`,"api.deleteFailed":`APIキーを削除できませんでした。`,"api.auth.endpoint":`エンドポイント`,"api.auth.required":`必須`,"api.auth.accepted":`利用可`,"api.auth.rejected":`不可`,"api.auth.testProtocol":`{protocol} をテスト`,"api.auth.testNeedsFreshKey":`認証付きテストを実行するには、キーを新しく作成し、一度だけ表示される値を画面に残したままにしてください。`,"api.key.name":`キー名`,"api.key.rename":`名前を変更`,"api.key.saveName":`名前を保存`,"api.key.renaming":`保存中…`,"api.key.renameFailed":`名前を変更できませんでした。入力内容はそのまま残しています。`,"api.key.deleting":`削除中…`,"api.key.copyFailed":`キーをコピーできませんでした。このパネルを閉じる前に手動で選択してコピーしてください。`,"api.attribution.title":`キー別の使用状況`,"api.attribution.requests7d":`直近 7 日のリクエスト`,"api.attribution.totalRequests":`集計済みリクエスト総数`,"api.attribution.totalRequestsAvailable":`利用可能な履歴のリクエスト`,"api.attribution.sinceAvailable":`利用可能な集計開始日`,"api.attribution.lastUsed":`最終使用`,"api.attribution.since":`集計開始`,"api.attribution.neverUsed":`集計開始以降は未使用`,"api.attribution.unavailable":`使用状況なし`,"api.attribution.unavailableDetail":`まだ集計された使用状況がありません。集計開始前のリクエストは遡って割り当てられません。`,"api.attribution.ambiguous":`2 つのキーが同じ ID を共有しているため、どちらの使用状況か判別できません。設定ファイルでキーごとに一意の ID を指定してください。`,"api.attribution.railAmbiguous":`ID 重複`,"nav.claude":`Claude`,"claude.subtitle":`Claude Code 内で GPT、Gemini などのモデルを使用します。`,"claude.pageTitle":`Claude Code`,"claude.workspace.settings":`設定`,"claude.enabledLabel":`Claude 接続`,"claude.enabledHint":`オフにすると Claude Code はこのプロキシを使用できません。`,"claude.authMode":`認証モード`,"claude.authModeHint":`サブスクリプションは Claude アカウントが必要、プロキシは Anthropic アカウント不要で動作します`,"claude.authModeSubscription":`サブスクリプション(Claude アカウント)`,"claude.authModeProxy":`プロキシ(アカウント不要)`,"claude.authModeAuto":`自動 (Claude 認証を検出)`,"claude.effectiveMode.label":`次回起動時に適用`,"claude.effectiveMode.manual":`手動: {mode}`,"claude.effectiveMode.autoPresent":`自動: サブスクリプション — {source} で Claude 認証を検出`,"claude.effectiveMode.autoAbsent":`自動: プロキシモード — Claude 認証が見つかりません`,"claude.effectiveMode.autoUnknown":`自動: サブスクリプション — 認証を確認できませんでした`,"claude.effectiveMode.admissionKey":`このプロキシの API キーは引き続き送信されます。`,"claude.authSource.claude-json-oauth":`Claude アカウント`,"claude.authSource.claude-credentials-file":`認証情報ファイル`,"claude.authSource.macos-keychain":`macOS キーチェーン`,"claude.authSource.exported-env":`環境変数`,"claude.authSource.unknown":`検出された認証情報`,"claude.systemEnv":`自動接続`,"claude.systemEnvDesc":`オンにすると、任意のターミナルで claude を実行すると自動的にプロキシ経由になります。`,"claude.systemEnvUnsupported":`自動接続は macOS でのみ利用できます。このシステムでは {cmd} で Claude を起動してください。`,"claude.systemEnvWarn":`⚠ これを有効化するにはターミナルアプリを完全に終了して再起動する必要があります。推奨されません。`,"claude.fastMode":`高速モード(OpenAI)`,"claude.fastModeDesc":`OpenAI モデルの service_tier を制御します。オン = 優先(高速)。オフ = デフォルト。自動 = パススルー(クライアントが決定)。`,"claude.fastAuto":`自動`,"claude.fastOn":`オン`,"claude.fastOff":`オフ`,"claude.autoContext":`大きなコンテキストを自動で使用`,"claude.autoContextDesc":`1M マーキングがどこまで及ぶかを制御します。オン: 200k トークンを超えるすべてのモデル(GPT モデルなど)に大型コンテキスト行を付けます。オフ: 真の 1M モデルのみに付けます。`,"claude.autoContextInert":`設定ファイルにレガシーのコンテキストサイズ値(maxContextTokens)が存在するため無効です。再び有効化するにはそれを削除してください。`,"claude.autoCompactWindow":`自動要約ポイント`,"claude.autoCompactDefault":`350k(デフォルト)`,"claude.autoCompactWindowDesc":`チャットがこのポイントに達すると古いメッセージが要約されます。各モデル自身の上限を超えることはないので、200k モデルは影響を受けません。`,"claude.autoCompactWindowWarn":`これを変更すると GPT モデルが壊れる可能性があります — モデルの実際の上限より高く設定すると、要約が働く前にチャットがエラーになります。`,"claude.injectAgents":`サブエージェントを自動登録`,"claude.injectAgentsDesc":`サブエージェントタブで選んだモデル(と現在のデフォルトモデル)をディスパッチ可能な Claude Code エージェント(ocx-*)として登録します。次回セッションから適用されます。`,"claude.webSearchSidecar":`ウェブ検索サイドカーの上書き`,"claude.webSearchSidecarHint":`Claude Code リクエストのメインウェブ検索サイドカーを上書きします。`,"claude.visionSidecar":`ビジョンサイドカーの上書き`,"claude.visionSidecarHint":`Claude Code リクエストのメインビジョンサイドカーを上書きします。`,"claude.useMainSetting":`メイン設定を使用`,"claude.sidecarModelPlaceholder":`メイン設定のモデル`,"claude.quickstart":`はじめる`,"claude.quickstartHint":`{cmd} はプロキシ経由で Claude Code を開きます。あなたの claude.ai ログインはそのまま有効です。`,"claude.manualEnv":`手動セットアップ(高度)`,"claude.smallFastModel":`バックグラウンドヘルパーモデル`,"claude.smallFastModelHint":`チャットの要約やトピック検出のようなバックグラウンド作業に Claude Code が使うモデルです。haiku サブエージェントエイリアスもこれを使います。空 = Claude デフォルト(Haiku)。`,"claude.smallFastModelAccurateHint":`チャットの要約やトピック検出など、Claude Code がバックグラウンド処理に使うモデルです。サブエージェントの haiku エイリアスもこのモデルを使います。`,"claude.smallFastModelUnsetOption":`Claude Code に選択させる(ネイティブモデル)`,"claude.smallFastModelNativeWarning":`未設定の場合、OpenCodex はヘルパーモデルの上書きを設定しません。Claude Code がネイティブの Sonnet モデルを使用し、ネイティブプロバイダーで料金が発生する可能性があります。`,"claude.slotUnset":`Claude デフォルトを使用`,"claude.modelMap":`モデルの傍受`,"claude.modelMapHint":`特定モデルへのリクエストを傍受し、選んだモデルに再ルーティングします。デフォルトは空 — ルールを追加するまで何も起きません。`,"claude.mapFrom":`元のモデル(例: claude-sonnet-4-5)`,"claude.mapTo":`差し替え先(例: gemini/gemini-3-pro)`,"claude.addMapping":`ルールを追加`,"claude.removeMapping":`ルールを削除`,"claude.aliases":`利用可能なモデル`,"claude.aliasesHint":`Claude Code の /model メニューに表示されるモデル。`,"claude.aliasProviderOther":`その他`,"claude.loading":`読み込み中…`,"claude.loadFail":`Claude 設定の読み込みに失敗しました`,"claude.saved":`保存しました。`,"claude.saveFailed":`保存に失敗しました`,"claude.networkError":`ネットワークエラー — プロキシは起動していますか?`,"claude.toggleAria":`Claude 接続を切り替え`,"claude.none":`なし`,"claude.tabsLabel":`Claude クライアント`,"claude.tabCode":`Code`,"claude.tabDesktop":`Desktop`,"claudeDesktop.title":`Claude Desktop`,"claudeDesktop.subtitle":`各 Claude モデルファミリーをポート {port} の利用可能なモデルへルーティングします。`,"claudeDesktop.importJson":`JSON をインポート`,"claudeDesktop.exportJson":`JSON をエクスポート`,"claudeDesktop.loading":`Claude Desktop プロファイルを読み込み中…`,"claudeDesktop.loadFail":`Claude Desktop プロファイルの読み込みに失敗しました。`,"claudeDesktop.retry":`再試行`,"claudeDesktop.saveFailed":`Claude Desktop プロファイルの保存に失敗しました。`,"claudeDesktop.applyFailed":`プロファイルは保存されましたが、適用できませんでした。`,"claudeDesktop.updateFailed":`Claude Desktop の更新に失敗しました。`,"claudeDesktop.savedApplied":`プロファイルを保存し、Claude Desktop に適用しました。`,"claudeDesktop.savedAppliedAnnounce":`Claude Desktop プロファイルを保存して適用しました。`,"claudeDesktop.saved":`プロファイルを保存しました。`,"claudeDesktop.savedAnnounce":`Claude Desktop プロファイルを保存しました。`,"claudeDesktop.exported":`プロファイルを JSON としてエクスポートしました。`,"claudeDesktop.importExpected":`バージョン 1 の Claude Desktop プロファイルが必要です。`,"claudeDesktop.importReady":`JSON をインポートしました。ドラフトを確認して保存・適用してください。`,"claudeDesktop.importedAnnounce":`プロファイル JSON をインポートしました。未保存の変更を確認できます。`,"claudeDesktop.importInvalid":`選択されたファイルは有効なプロファイルではありません。`,"claudeDesktop.importFailed":`インポートに失敗しました。{error}`,"claudeDesktop.moved":`{route} を {family} に移動しました。`,"claudeDesktop.unsaved":`未保存の変更`,"claudeDesktop.upToDate":`プロファイルは最新です`,"claudeDesktop.saving":`保存中…`,"claudeDesktop.applying":`適用中…`,"claudeDesktop.saveApply":`保存して適用`,"claudeDesktop.emptyTitle":`利用可能なモデルがありません`,"claudeDesktop.emptyHint":`プロバイダーを追加または有効化してから、Claude Desktop ルートを割り当ててください。`,"claudeDesktop.assignmentsLabel":`Claude モデルファミリーの割り当て`,"claudeDesktop.family.opus":`Opus`,"claudeDesktop.family.fable":`Fable`,"claudeDesktop.family.sonnet":`Sonnet`,"claudeDesktop.family.haiku":`Haiku`,"claudeDesktop.modelCountOne":`{count} モデル`,"claudeDesktop.modelCountMany":`{count} モデル`,"claudeDesktop.chooseDefault":`デフォルトを選択`,"claudeDesktop.temporaryDefault":`一時的なデフォルト`,"claudeDesktop.laneEmpty":`ここにモデルをドロップするか、移動コントロールを使用してください。`,"claudeDesktop.laneNoMatch":`検索に一致するモデルはこのファミリーにありません。`,"nav.grok":`Grok`,"grok.title":`Grok Build`,"grok.subtitle":`opencodex が Grok 設定に登録したモデルです。`,"grok.loading":`Grok の状態を読み込み中…`,"grok.loadFail":`Grok 設定を読み取れませんでした。`,"grok.notConfiguredTitle":`Grok Build が未設定です`,"grok.notConfiguredHint":`Grok をインストールしてプロキシを再起動すると、opencodex が管理ブロックを次の場所に書き込みます:`,"grok.endpoint":`エンドポイント`,"grok.colModel":`モデル`,"grok.colAlias":`Grok エイリアス`,"grok.colContext":`コンテキスト`,"grok.groupNative":`ネイティブモデル`,"grok.groupRouted":`ルーティングモデル`,"grok.enabledCount":`{total} 件中 {on} 件を登録`,"grok.saved":`選択を保存しました。`,"grok.savedApplied":`選択を保存し、Grok 設定に反映しました。`,"grok.saveFailed":`Grok の選択を保存できませんでした。`,"grok.applyFailed":`選択は保存しましたが、Grok 設定を更新できませんでした。`,"grok.applySkipped":`選択は保存しましたが、Grok 設定は変更されませんでした。`,"grok.saveApply":`保存して適用`,"grok.saving":`保存中…`,"grok.applying":`適用中…`,"grok.unsaved":`未保存の変更`,"grok.upToDate":`選択は最新です`,"grok.toggleModel":`{id} を Grok に登録`,"claudeDesktop.available":`利用可能`,"claudeDesktop.defaultBadge":`既定`,"claudeDesktop.supports1m":`1M`,"claudeDesktop.unavailable":`利用不可`,"claudeDesktop.contextM":`{n}M コンテキスト`,"claudeDesktop.contextK":`{n}k コンテキスト`,"claudeDesktop.contextUnknown":`コンテキスト不明`,"claudeDesktop.alias":`エイリアス`,"claudeDesktop.useAsDefault":`{family} のデフォルトに設定`,"claudeDesktop.moveTo":`移動先`,"claudeDesktop.move":`移動`,"claudeDesktop.status.applied":`Desktop に適用済み`,"claudeDesktop.status.stale":`設定が古くなっています — 再適用してください`,"claudeDesktop.status.notApplied":`未適用`,"claudeDesktop.status.notActiveProfile":`Desktop は別のプロファイルを使用中 — 再適用してください`,"claudeDesktop.health.lastRequest":`最終リクエスト`,"claudeDesktop.health.stats":`{count} リクエスト / {errors} エラー`,"claudeDesktop.effort.supported":`effort`,"claudeDesktop.effort.displayOnly":`effort (表示のみ)`,"cws.loading":`コンボを読み込み中…`,"cws.loadFailed":`コンボを読み込めませんでした。`,"cws.saveFailed":`コンボを保存できませんでした。`,"cws.removeFailed":`コンボを削除できませんでした。`,"cws.saved":`コンボを保存しました。`,"cws.created":`{model} を作成しました。`,"cws.removed":`combo/{id} を削除しました。`,"cws.add":`コンボを追加`,"cws.addTitle":`コンボを追加`,"cws.addSubtitle":`プロバイダー全体にファンアウトする仮想モデルを作成します。クライアントは combo/<id> をリクエストします。`,"cws.create":`コンボを作成`,"cws.railAria":`コンボ一覧`,"cws.searchPlaceholder":`コンボやターゲットを検索…`,"cws.noSearchResults":`検索に一致するコンボがありません。`,"cws.group.failover":`フェイルオーバー`,"cws.group.roundRobin":`ラウンドロビン`,"cws.targetCount":`{count} ターゲット`,"cws.targetCountOne":`1 ターゲット`,"cws.overviewTitle":`コンボ`,"cws.overviewBlurb":`プロバイダー/モデルターゲット間でフェイルオーバーする、または決定論的で滑らかな重み付きラウンドロビンを使う仮想モデル。`,"cws.count.total":`合計`,"cws.count.failover":`フェイルオーバー`,"cws.count.roundRobin":`ラウンドロビン`,"cws.howTitle":`仕組み`,"cws.howBody":`Codex に combo/<id> を要求します。OpenCodex はターゲットを選び、再試行可能な上流の失敗時のみホップします。利用可能なターゲットが残っていない場合、グローバルなデフォルトプロバイダーを使わずにフェイルクローズします。`,"cws.attentionTitle":`要対応`,"cws.attention.empty":`ターゲットが設定されていません`,"cws.attention.few":`ターゲットが 1 つだけ — フェイルオーバーのホップ先がありません`,"cws.attention.catalogOmitted":`モデルカタログにありません — メンバー能力が不完全または非互換です(context window / メタデータ不足、または modality 交差が空)。エイリアス指定のルーティングは動作します`,"cws.emptyTitle":`最初のコンボを作成`,"cws.empty.createDesc":`仮想モデルに名前を付け、2 つ以上のバックエンドをつなぎます。`,"cws.backToAll":`すべてのコンボに戻る`,"cws.allCombos":`すべてのコンボ`,"cws.copyModel":`ID をコピー`,"cws.copied":`コピーしました`,"cws.renamed":`{from} を {to} に変更しました。`,"cws.tab.config":`設定`,"cws.tab.about":`概要`,"cws.strategy":`ストラテジー`,"cws.strategy.failover":`フェイルオーバー`,"cws.strategy.roundRobin":`ラウンドロビン`,"cws.strategy.failoverHint":`ターゲットを順に試します。最初が再試行可能なエラー(レート制限、障害、サブスクリプションゲート)で失敗した場合、次へホップします。`,"cws.strategy.roundRobinHint":`重みで決定論的にトラフィックを分散します。選んだターゲットを成功リクエストのバッチ分保持し、次へ進みます。`,"cws.field.id":`コンボ ID`,"cws.field.idHint":`クライアントは {model} をリクエストします`,"cws.field.idInternalHint":`コンボの内部 ID。作成後も変更できます。`,"cws.field.idHintEdit":`ID を変更するとコンボの名前が変更されます。クライアントは {model} をリクエストします。`,"cws.field.alias":`公開モデル名`,"cws.field.aliasPlaceholder":`deepseek-v4-flash または vendor/model`,"cws.field.aliasHint":`任意。プレフィックスなしの名前、vendor/model のようなカスタムプレフィックスを指定するか、空欄のままにすると combo/<id> を使用します。`,"cws.field.stickyLimit":`ローテーション前の固定成功数`,"cws.field.stickyLimitHint":`重み付きセレクタが進む前に、選んだターゲットをこの回数の成功リクエスト分保持します。`,"cws.field.defaultEffort":`デフォルトの推論`,"cws.field.defaultEffortNone":`なし(ターゲットのデフォルト)`,"cws.field.defaultEffortHint":`クライアントが推論負荷を省略した場合のみ使用されます。選択肢は選択ターゲットが広告する負荷の交差です。`,"cws.field.defaultEffortUnsupported":`この負荷はターゲット共通の階段にありません — リクエスト時に無視またはスナップされます。`,"cws.field.defaultEffortUnsupportedOption":`交差に含まれない`,"cws.targets":`ターゲット`,"cws.targets.failoverHint":`順序が重要 — 最初がプライマリです。`,"cws.targets.roundRobinHint":`重みが決定論的な相対選択を制御し、順序がローテーションリングの同点を解消します。`,"cws.target.provider":`プロバイダー`,"cws.target.model":`モデル`,"cws.target.weight":`重み`,"cws.target.pickProvider":`プロバイダーを選択…`,"cws.target.pickProviderFirst":`最初にプロバイダーを選択…`,"cws.target.pickModel":`モデルを選択…`,"cws.target.noModels":`このプロバイダーにモデルはありません`,"cws.target.modelPlaceholder":`モデル ID`,"cws.target.add":`ターゲットを追加`,"cws.target.drag":`ドラッグで並べ替え`,"cws.target.moveUp":`上へ移動`,"cws.target.moveDown":`下へ移動`,"cws.aboutTitle":`ランタイム`,"cws.aboutBody":`失敗したターゲットは Retry-After を尊重して短時間クールダウンします。無効またはコンテキストエラーはホップしません。各ターゲットは自身の能力に推論負荷を適応させます; 枯渇したコンボはフェイルクローズします。ログと使用量は順序付きの物理試行と試行ごとの使用量を保持します。`,"cws.removeConfirmTitle":`{model} を削除しますか?`,"cws.removeConfirmDesc":`これで仮想モデルが設定と Codex カタログから削除されます。プロバイダーは削除されません。`,"cws.unsavedTitle":`未保存の変更`,"cws.unsavedDesc":`このコンボへの編集を破棄して続行しますか?`,"cws.keepEditing":`編集を続ける`,"cws.err.missingId":`コンボ ID は必須です。`,"cws.err.invalidId":`ID は英字または数字で始まり、英数字、ドット、アンダースコア、ハイフンのみ使用できます(最大 64)。`,"cws.err.duplicateId":`この ID のコンボはすでに存在します。`,"cws.err.invalidAlias":`エイリアスには英字、数字、ドット、アンダースコア、ハイフンを使用でき、スラッシュ区切りは 1 つまでです。`,"cws.err.aliasReservedNamespace":`エイリアスに予約済みの "combo/" 名前空間は使用できません。`,"cws.err.aliasNativeFamily":`OpenAI ネイティブファミリー(gpt-*、o1-*、o3-*、o4-*、codex-*)のプレフィックスなしエイリアスは使用できません。`,"cws.err.duplicateAlias":`別のコンボがすでにこのエイリアスを使用しています。`,"cws.err.noTargets":`少なくとも 1 つのターゲットを追加してください。`,"cws.err.incompleteTarget":`各ターゲットにはプロバイダーとモデルが必要です。`,"cws.target.disabled":`{name}(無効)`,"cws.err.reservedNamespace":`combo という物理プロバイダーは、コンボ作成前に名前を変更する必要があります。`,"cws.err.providerCollision":`コンボ ID が設定されたプロバイダー名と衝突しています。`,"cws.err.unknownProvider":`各ターゲットは設定済みプロバイダーを使用する必要があります。`,"cws.err.duplicateTarget":`同じプロバイダー/モデルターゲットは一度しか使用できません。`,"cws.err.invalidStickyLimit":`固定成功数は 1 から 100 の整数にしてください。`,"cws.err.invalidWeight":`各ラウンドロビン重みは 1 から 10000 の整数にしてください。`,"cws.err.noEnabledTarget":`少なくとも 1 つのターゲットは有効なプロバイダーを使用する必要があります。`,"prov.editAlias":`Edit alias`,"prov.aliasPrompt":`Display name (leave empty to clear)`,"prov.aliasSaved":`Alias saved`,"prov.aliasSaveFailed":`Could not save alias`,"prov.accountId":`ID`,"models.customAdd":`Add custom model`,"models.customAddTitle":`Add custom model — {provider}`,"models.customEditTitle":`Edit custom model — {provider}`,"models.customAdded":`Custom model added`,"models.customUpdated":`Custom model updated`,"models.customDeleted":`Custom model deleted`,"models.customSaveFailed":`Failed to save custom model`,"models.customSaving":`Saving…`,"models.customAddBtn":`Add`,"models.customEditBtn":`Update`,"models.customEdit":`Edit`,"models.customDelete":`Delete`,"models.customDeleteConfirm":`Delete the {name} model?`,"models.customBadge":`Custom`,"models.customSummary":`{count} custom`,"models.customFieldModelId":`Model ID (endpoint slug)`,"models.customFieldModelIdPlaceholder":`e.g. qwen4-max-preview`,"models.customFieldDisplayName":`Display name (optional)`,"models.customFieldDisplayNamePlaceholder":`e.g. Qwen 4 Max Preview`,"models.customFieldContext":`Context window`,"models.customFieldModalities":`Input modalities`,"models.tipProvider":`Provider`,"models.tipContext":`Context`,"models.tipModalities":`Modalities`,"models.tipStatus":`Status`,"models.tipActive":`Active`,"models.tipDisabled":`Disabled`,"pws.estimatedCost":`Estimated cost`,"pws.costDisclaimer":`API list-price estimate, not an actual charge.`,"pws.modelBreakdown":`Model breakdown`,"pws.col.model":`Model`,"pws.col.cost":`Est. cost`,"pws.col.tokens":`Tokens`,"pws.col.requests":`Req.`,"pws.col.share":`Share`,"pws.tokenInput":`Input`,"pws.tokenOutput":`Output`,"dash.injectionManage":`設定を開く`,"sub.settings":`設定`,"sub.sections":`サブエージェントのセクション`,"sub.delegation.model":`最初に呼ぶモデル`,"sub.delegation.modelHint":`Codex が作業を任せるとき、最初に呼ぶモデルです。上のおすすめが呼べる候補で、ここで選んだものがその中の第一候補になります。`,"dash.syncModelsHint":`接続済みのプロバイダーをもとに Codex のモデルカタログを書き直します。`,"dash.syncRun":`今すぐ同期`}},Ue=[{code:`en`,name:`English`,htmlLang:`en`},{code:`de`,name:`Deutsch`,htmlLang:`de`},{code:`ko`,name:`한국어`,htmlLang:`ko`},{code:`zh`,name:`中文`,htmlLang:`zh-CN`},{code:`ru`,name:`Русский`,htmlLang:`ru`},{code:`ja`,name:`日本語`,htmlLang:`ja`}],We=`ocx-lang`;function Ge(){try{let e=localStorage.getItem(We);if(e===`en`||e===`de`||e===`ko`||e===`zh`||e===`ru`||e===`ja`)return e}catch{}let e=typeof navigator<`u`?navigator.language.toLowerCase():`en`;return e.startsWith(`de`)?`de`:e.startsWith(`ko`)?`ko`:e.startsWith(`zh`)?`zh`:e.startsWith(`ru`)?`ru`:e.startsWith(`ja`)?`ja`:`en`}var Ke=(0,_.createContext)(null);function qe(e,t){if(!t)return e;let n=e;for(let e of Object.keys(t))n=n.split(`{${e}}`).join(String(t[e]));return n}function X(){let e=(0,_.useContext)(Ke);if(!e)throw Error(`useI18n must be used within LanguageProvider`);return e}function Z(){return X().t}function Je({children:e}){let[t,n]=(0,_.useState)(Ge);(0,_.useEffect)(()=>{let e=Ue.find(e=>e.code===t)??Ue[0];document.documentElement.lang=e.htmlLang;try{localStorage.setItem(`ocx-lang`,t)}catch{}},[t]);let r=(0,_.useCallback)((e,n)=>qe(He[t][e]??Ve[e]??e,n),[t]),i=(0,_.useMemo)(()=>({locale:t,setLocale:n,t:r}),[t,r]);return(0,J.jsx)(Ke.Provider,{value:i,children:e})}function Ye({k:e,cmd:t,vars:n}){let{t:r}=X(),[i,a=``]=r(e,n).split(`{cmd}`);return(0,J.jsxs)(J.Fragment,{children:[i,(0,J.jsx)(`code`,{className:`chip`,children:t}),a]})}function Xe(e){return e.replace(/^#\/?/,``)}function Ze(e,t=window){let n=Xe(e);if(Xe(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function Qe(e,t=window){let n=Xe(e);Xe(t.location.hash)!==n&&(t.location.hash=n)}var $e=m(),et=4,tt=8,nt=8,rt=280,it=120,at=160,ot=12;function st(){return typeof window<`u`?window.innerHeight:800}function ct(){return typeof window<`u`?window.innerWidth:1024}function lt(e,{align:t=`left`,placement:n=`below`,menuHeight:r=rt}={}){let i=Math.min(Math.max(r,it),rt),a=st(),o=ct();if(n===`right`){let t=a-e.top-nt,n=e.top-nt,r=i+tt>t&&n>t,s=Math.max(nt,Math.min(e.right+ot,o-at-nt));return r?{position:`fixed`,left:s,bottom:a-e.top+tt,minWidth:at,maxHeight:Math.max(it,Math.min(rt,e.top-nt-et))}:{position:`fixed`,top:e.top,left:s,minWidth:at,maxHeight:Math.max(it,Math.min(rt,a-e.top-nt))}}let s=Math.max(e.width,0),c=a-e.bottom-nt,l=e.top-nt;if(i+et>c&&l>c){let n={position:`fixed`,bottom:a-e.top+tt,minWidth:s,maxHeight:Math.max(0,Math.min(rt,l-et))};return t===`right`?n.right=o-e.right:n.left=Math.max(nt,Math.min(e.left,o-nt-s)),n}let u={position:`fixed`,top:e.bottom+et,minWidth:s,maxHeight:Math.max(0,Math.min(rt,c-et))};return t===`right`?u.right=o-e.right:u.left=Math.max(nt,Math.min(e.left,o-nt-s)),u}function ut({on:e,onClick:t,disabled:n,label:r}){return(0,J.jsx)(`button`,{type:`button`,className:`switch${e?` on`:``}`,onClick:t,disabled:n,"aria-pressed":e,"aria-label":r??(e?`enabled`:`disabled`),children:(0,J.jsx)(`span`,{className:`knob`})})}function dt({tone:e,children:t}){return(0,J.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,J.jsx)(de,{}):(0,J.jsx)(ve,{}),(0,J.jsx)(`span`,{children:t})]})}function ft({value:e,options:t,onChange:n,disabled:r,label:i,id:a,style:o,align:s,placement:c,dropdownStyle:l,portal:u=!0}){let d=(0,_.useId)(),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=(0,_.useRef)(null),S=(0,_.useCallback)(e=>`${d}-${e}`,[d]),C=t.find(t=>t.value===e),w=t.length===0?0:Math.max(0,t.findIndex(t=>t.value===e)),T=!f||t.length===0?w:Math.min(m??w,t.length-1),E=(0,_.useCallback)((e=!1)=>{p(!1),h(null),e&&b.current?.focus()},[]),D=(0,_.useCallback)(e=>{r||t.length===0||(h(Math.max(0,Math.min(t.length-1,e))),p(!0))},[r,t.length]),O=(0,_.useCallback)(e=>{if(!u)return;let t=b.current;t&&v(lt(t.getBoundingClientRect(),{align:s,placement:c,menuHeight:e}))},[s,c,u]);(0,_.useEffect)(()=>{if(!f)return;let e=e=>{let t=e.target;y.current?.contains(t)||x.current?.contains(t)||E()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[E,f]),(0,_.useLayoutEffect)(()=>{if(!f||!u)return;O();let e=()=>O(x.current?.offsetHeight);return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[f,t.length,u,O]),(0,_.useLayoutEffect)(()=>{if(!f||!u||!x.current||!b.current)return;let e=x.current.offsetHeight;if(!e)return;let t=lt(b.current.getBoundingClientRect(),{align:s,placement:c,menuHeight:e});v(e=>e?.top===t.top&&e?.bottom===t.bottom&&e?.maxHeight===t.maxHeight?e:t)},[s,f,t.length,c,u]),(0,_.useLayoutEffect)(()=>{!f||!x.current||x.current.querySelector(`[id="${S(T)}"]`)?.scrollIntoView({block:`nearest`})},[T,f,S]);let k=e=>{let r=t[e];r&&(n(r.value),E(!0))},A=e=>{if(!r)switch(e.key){case`ArrowDown`:e.preventDefault(),D(f?Math.min(t.length-1,T+1):w);break;case`ArrowUp`:e.preventDefault(),D(f?Math.max(0,T-1):w);break;case`Home`:e.preventDefault(),D(0);break;case`End`:e.preventDefault(),D(t.length-1);break;case`Enter`:case` `:e.preventDefault(),f?k(T):D(w);break;case`Escape`:f&&(e.preventDefault(),E(!0));break;case`Tab`:if(f){let e=t[T];e&&n(e.value),p(!1)}break;default:break}},j=f&&t[T]?S(T):void 0,M=f?(0,J.jsx)(`div`,{ref:x,id:d,className:`select-dropdown${u?` select-dropdown-portal`:``}${!u&&s===`right`?` select-dropdown-right`:``}${!u&&c===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":i,style:u?{...g,zIndex:60,...l}:l,children:t.map((t,n)=>(0,J.jsx)(`button`,{id:S(n),type:`button`,role:`option`,tabIndex:-1,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}${n===T?` select-option-active`:``}`,onMouseEnter:()=>h(n),onClick:()=>k(n),children:t.label},t.value))}):null;return(0,J.jsxs)(`div`,{ref:y,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...o},children:[(0,J.jsxs)(`button`,{ref:b,id:a,type:`button`,role:`combobox`,className:`select-trigger`,onClick:()=>{r||(f?E():D(w))},onKeyDown:A,disabled:r,"aria-haspopup":`listbox`,"aria-expanded":f,"aria-controls":f?d:void 0,"aria-activedescendant":j,"aria-label":i,children:[(0,J.jsx)(`span`,{children:C?.label??e}),(0,J.jsx)(we,{style:{width:12,height:12,color:`var(--muted)`,transform:f?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),u?M&&(0,$e.createPortal)(M,document.body):M]})}function pt({icon:e,title:t,children:n,className:r,style:i}){return(0,J.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,J.jsx)(`div`,{className:`title`,children:t}),n&&(0,J.jsx)(`div`,{className:`text-control`,children:n})]})}function mt({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,_.useState)(!1),o=(0,_.useId)(),s=(0,_.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,_.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,J.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,J.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}async function ht(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 gt(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function Q(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=gt(await e.json(),t)}catch{}throw Error(n)}return ht(e)}async function _t(e){if(!e.ok)return null;try{return await ht(e)}catch{return null}}var vt=`dashboard/update`;function yt(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function bt(){return window.location.hash.replace(/^#\/?/,``)===vt}function xt(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function St(e,t){let n=await Q(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var Ct=[`low`,`medium`,`high`,`xhigh`];function wt(e){return e?.includes(`-preview.`)?`preview`:`latest`}function Tt(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`);default:return t(`dash.updateReason.unknown`)}}function Et(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 Dt(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),n}function Ot(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 kt(e,t){return e.find(e=>e.id===t)?.provider===`anthropic`?`anthropic`:`openai`}var At=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{At=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{At=!1},{capture:!0,passive:!0}));function jt(e){if(e){if(At){e.focus({preventScroll:!0});return}try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function Mt(e,t){let n=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let r=n.current;if(r){if(e){r.open||r.showModal();return}r.open&&r.close(),jt(t.current)}},[e,t]),(0,_.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),jt(t.current)},[t]),n}var Nt=[`gpt-5.4-mini`,`gpt-5.6-luna`];function Pt(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length>0?t:Nt}function Ft(e){return Pt(e).join(`, `)}function It(e){return Pt(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function Lt(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}=e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.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,J.jsxs)(`div`,{className:`modal-card`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,J.jsx)(fe,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,J.jsxs)(`div`,{className:`update-row`,children:[(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,J.jsx)(ft,{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,J.jsx)(pt,{className:`update-empty`,icon:(0,J.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,J.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,J.jsx)(ve,{}),(0,J.jsx)(`span`,{children:c})]}),l&&!s&&(0,J.jsxs)(`div`,{className:`update-box`,children:[(0,J.jsxs)(`div`,{className:`spread`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,J.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,J.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,J.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),(0,J.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,J.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,J.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,J.jsx)(ve,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,J.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,J.jsx)(ve,{}),` `,t(`dash.updateUnavailable`),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,J.jsx)(me,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,J.jsxs)(`div`,{className:`update-recheck`,children:[(0,J.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:Tt(l.reason,t)})}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,J.jsx)(me,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,J.jsxs)(`div`,{className:`spread update-restart`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,J.jsx)(`span`,{className:`knob`})})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,J.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,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,J.jsx)(fe,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,J.jsx)(`div`,{style:{marginTop:12},children:(0,J.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,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,J.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,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,J.jsx)(fe,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,J.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,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,J.jsx)(fe,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:Ft(C?.sourceModels)})}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]})]})}function Rt({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,J.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,J.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,J.jsx)(pt,{title:e(`dash.noModels`)}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,J.jsx)(be,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,J.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,J.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,J.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([e,t])=>{let n=r.trim().toLowerCase()!==``||o.has(e);return(0,J.jsxs)(`div`,{className:`dash-model-group`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`dash-model-head`,onClick:()=>s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),"aria-expanded":n,children:[(0,J.jsx)(we,{width:12,height:12,style:{transform:n?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`font-semibold`,children:e}),(0,J.jsx)(`span`,{className:`count`,children:t.length})]}),n&&(0,J.jsx)(`div`,{className:`dash-model-chips`,children:t.map(e=>(0,J.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},e)})})]})]})}var zt={ko:[{v:0x2386f26fc10000,s:`경`},{v:0xe8d4a51000,s:`조`},{v:1e8,s:`억`},{v:1e4,s:`만`}],zh:[{v:0x2386f26fc10000,s:`京`},{v:0xe8d4a51000,s:`兆`},{v:1e8,s:`亿`},{v:1e4,s:`万`}]};function Bt(e){return e.replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Vt(e,t){let n=zt[t];if(n){for(let t of n)if(e>=t.v)return`${Bt((e/t.v).toFixed(1))}${t.s}`;return String(e)}return e<1e4?String(e):e<1e6?`${Bt((e/1e3).toFixed(1))}K`:e<1e9?`${Bt((e/1e6).toFixed(1))}M`:e<0xe8d4a51000?`${Bt((e/1e9).toFixed(1))}B`:`${Bt((e/0xe8d4a51000).toFixed(1))}T`}var Ht={en:{day:`d`,hour:`h`,minute:`m`,second:`s`},de:{day:`T`,hour:`Std`,minute:`Min`,second:`Sek`},ko:{day:`일`,hour:`시간`,minute:`분`,second:`초`},zh:{day:`天`,hour:`小时`,minute:`分钟`,second:`秒`},ru:{day:`д`,hour:`ч`,minute:`мин`,second:`с`},ja:{day:`日`,hour:`時間`,minute:`分`,second:`秒`}};function Ut(e,t){let n=Math.max(0,Math.floor(e)),r=Ht[t]??Ht.en;if(n<300)return`${n}${r.second}`;let i=Math.floor(n/60);if(i<60)return`${i}${r.minute}`;let a=Math.floor(i/60);if(a<24){let e=i%60;return e>0?`${a}${r.hour} ${e}${r.minute}`:`${a}${r.hour}`}let o=Math.floor(a/24),s=a%24;return s>0?`${o}${r.day} ${s}${r.hour}`:`${o}${r.day}`}function Wt({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}){let m=Z(),h=t?.status===`ok`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[m(`dash.multiAgent`),(0,J.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":m(`dash.multiAgent`),"aria-haspopup":`dialog`,"aria-controls":`multi-agent-help-dialog`,"aria-expanded":d,children:(0,J.jsx)(ye,{width:14,height:14,"aria-hidden":`true`})})]}),(0,J.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,J.jsx)(`div`,{role:`radiogroup`,"aria-label":m(`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,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":c===e,className:`btn btn-sm text-caption${c===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,minWidth:36,padding:`5px 10px`,border:`none`,background:c===e?void 0:`transparent`,color:c===e?void 0:`var(--muted)`},disabled:l,onClick:()=>void p(e),children:m(`models.v2Mode_${e}`)},e))})})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:m(`dash.status`)}),(0,J.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:h?`var(--green)`:`var(--red)`},children:[(0,J.jsx)(`span`,{className:`dot ${h?`dot-green`:`dot-red`}`}),m(h?`dash.online`:`dash.offline`)]})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:m(`dash.version`)}),(0,J.jsx)(`div`,{className:`value mono`,children:t?.version??`—`})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:m(`dash.uptime`)}),(0,J.jsx)(`div`,{className:`value mono`,children:t?Ut(t.uptime,e):`—`})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:m(`dash.providers`)}),(0,J.jsx)(`div`,{className:`value`,children:n.length})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":i||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:m(`dash.tokens30d`)}),(0,J.jsx)(`div`,{className:`value mono`,children:r&&r.summary.requests>0?Vt(r.summary.totalTokens,e):`—`}),(0,J.jsx)(`div`,{className:`muted text-label dash-stat-coverage`,children:r&&r.summary.requests>0?m(`dash.coverage`).replace(`{pct}`,`${Math.round(r.summary.coverageRatio*100)}%`):`\xA0`})]})]}),(0,J.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,J.jsxs)(`a`,{className:`startup-health-bar`,href:`#startup`,children:[(0,J.jsx)(`span`,{className:`dot ${o===`error`?`dot-red`:o===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`startup-health-bar__summary`,children:m(o===`error`?`startup.error`:o===`at-risk`?`startup.summary.atRisk`:o===`protected`?`startup.summary.protected`:`startup.summary.native`)})]}):(0,J.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`dot dot-amber`}),(0,J.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),s.length>0&&(0,J.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,J.jsx)(ve,{}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:m(`dash.projectConfigTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:m(`dash.projectConfigHint`)}),(0,J.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,J.jsxs)(`li`,{style:{marginBottom:8},children:[(0,J.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,J.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}function Gt(){return typeof document<`u`&&document.visibilityState===`hidden`}function Kt(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function qt(e){if(typeof window<`u`&&typeof window.clearInterval==`function`){window.clearInterval(e);return}clearInterval(e)}function Jt(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=Kt(o,t))},c=()=>{i!==null&&(qt(i),i=null)},l=()=>{if(r){if(Gt()){c();return}o(),s()}};return r&&Gt()||s(),r&&typeof document<`u`&&document.addEventListener(`visibilitychange`,l),n?.immediate&&o(),()=>{a=!0,c(),r&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,l)}}var Yt=new Map;function Xt(e,t){let n=`${e}:${t}`,r=Yt.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),Yt.set(n,r)),r}var Zt=new Map;function Qt(e){let t=Zt.get(e);return t||(t=new Intl.NumberFormat(e),Zt.set(e,t)),t}function $t(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`${Xt(t,r===0?0:1).format(i)} ${n[r]}`}function en(e,t){return!Number.isFinite(e)||e<0?`—`:Ut(e/1e3,t)}function tn(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function nn(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 rn(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:(tn(n)-tn(t))/r*36e5}function an({label:e,value:t,sub:n,tone:r}){return(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:e}),(0,J.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,J.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function on({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,J.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,J.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,J.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,J.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,J.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:$t(e,r),t!==null&&(0,J.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,$t(t,r)]})]})]}),(0,J.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,J.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,J.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var sn=60,cn=1500,ln=12e4;function un({apiBase:e}){let{locale:t,t:n}=X(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(`idle`),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null);(0,_.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||f(r.protection===`none`)}catch{}})(),()=>{t=!0}},[e]),(0,_.useEffect)(()=>{let t=!1,n=!1,r=null,a=async()=>{if(n)return;n=!0;let a=y(1e4);r=a;try{let n=await fetch(`${e}/api/system/memory`,{signal:a.signal});if(!n.ok)throw Error(`memory unavailable`);let r=await n.json();if(t)return;i(r),o(!1),m(typeof r.activeTurnCount==`number`),r.isDraining&&s===`idle`&&c(`draining`),(s===`draining`||s===`reconnecting`)&&h!=null&&typeof r.pid==`number`&&r.pid!==h&&!r.isDraining&&(c(`idle`),g(null),u(null))}catch{if(t)return;s===`draining`||s===`reconnecting`?c(`reconnecting`):o(!0)}finally{a.clear(),r===a&&(r=null),n=!1}};a();let l=Jt(()=>void a(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),l()}},[e,s,h]),(0,_.useEffect)(()=>{if(s!==`reconnecting`)return;let t=!1,r=!1,i=null,a=Date.now(),o=()=>{if(r||t)return;r=!0;let o=y(5e3);i=o,fetch(`${e}/healthz`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=ln&&(c(`error`),u(n(`dash.mem.restartFailed`)));return}let r=h==null;if(h!=null)try{let t=await e.json();r=typeof t.pid==`number`&&t.pid!==h}catch{r=!0}if(!t){if(r){c(`idle`),g(null),u(null);return}Date.now()-a>=ln&&(c(`error`),u(n(`dash.mem.restartFailed`)))}}).catch(()=>{t||Date.now()-a>=ln&&(c(`error`),u(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let l=setInterval(o,cn);return()=>{t=!0,i?.controller.abort(),i?.clear(),clearInterval(l)}},[e,s,h,n]);let v=()=>{let t=[n(`dash.mem.restartConfirm`,{count:r?.activeTurnCount??0,seconds:sn})];d&&t.push(n(`dash.mem.restartNoSupervisor`)),window.confirm(t.join(`
46
46
 
47
- `))&&(async()=>{u(null),g(typeof r?.pid==`number`?r.pid:null),c(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{c(`error`),g(null),u(n(`dash.mem.restartFailed`))}})()};if(a&&!r&&s===`idle`)return(0,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(le,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let b=r?.watchdog?rn(r.watchdog.samples):null,x=r?r.observedBytes??r.watchdog?.observedBytes??tn(r):null,S=r?nn(r):null,C=(()=>{let e=r?.watchdog?.warnThresholdBytes;if(b===null||b<=0||x===null||!e)return;let t=e-x;if(t<=0)return`danger`;let n=t/b;if(n<=1)return`danger`;if(n<=8)return`warn`})(),w=r?.responseState,T=r?.activeTurnCount,E=s===`draining`||s===`reconnecting`;return(0,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`mem-head`,children:[(0,J.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,J.jsx)(le,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,J.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,J.jsxs)(`span`,{className:`mem-inflight`,children:[(0,J.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,J.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof T==`number`?Qt(t).format(T):`—`})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:E,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,J.jsx)(on,{observedBytes:x,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:S,locale:t,t:n}),(0,J.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,J.jsx)(an,{label:n(`dash.mem.rss`),value:r?$t(r.rss,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.jsHeap`),value:r?$t(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:$t(r.heapTotal,t)}):void 0}),(0,J.jsx)(an,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?$t(r.jscHeap.heapSize,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.growth`),value:b===null?`—`:`${b>=0?`+`:`−`}${$t(Math.abs(b),t)}${n(`dash.mem.perHour`)}`,tone:C})]}),(0,J.jsxs)(`details`,{style:{marginTop:10},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(an,{label:n(`dash.mem.observed`),value:x===null?`—`:`${$t(x,t)} (${S})`}),(0,J.jsx)(an,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:$t(r.external,t)}),(0,J.jsx)(an,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:$t(r.arrayBuffers,t)})]}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(an,{label:n(`dash.mem.storeEntries`),value:w?Qt(t).format(w.count):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.storeTotal`),value:w?$t(w.totalBytes,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.storeLargest`),value:w?$t(w.largestBytes,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.storeOldest`),value:w?w.count===0?`—`:en(w.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,J.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,J.jsx)(an,{label:n(`dash.mem.threshold`),value:$t(r.watchdog.warnThresholdBytes,t)}),(0,J.jsx)(an,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,J.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof T==`number`?T:0})}),s===`reconnecting`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,J.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function dn({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,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`injection-head`,children:[(0,J.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,J.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,J.jsx)(ye,{width:13,height:13,"aria-hidden":`true`})})]}),(0,J.jsx)(ft,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...Ct.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await St(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`)}),(0,J.jsx)(ft,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...Ct.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await St(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`)})]})})}function fn({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsx)(ft,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:`${e.provider} / ${e.model}`}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`)}),n&&i.length>0&&(0,J.jsx)(ft,{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`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Qe(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function pn({d:e}){let{t,runSync:n,syncing:r,updateTriggerRef:i,openUpdateDialog:a,updateLoading:o,updateOpen:s,syncResult:c,syncError:l,updateJob:u,reconnecting:d}=e;return(0,J.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,J.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,J.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:n,disabled:r,children:[(0,J.jsx)(me,{}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,J.jsx)(`button`,{ref:i,type:`button`,className:`maintenance-update-anchor`,onClick:a,disabled:o,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":s,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]})]}),c&&(0,J.jsxs)(`div`,{className:`notice ${c.nativeSubagentDefaultsWarning?`notice-warn`:`notice-ok`} maintenance-notice`,role:`status`,children:[c.nativeSubagentDefaultsWarning?(0,J.jsx)(ve,{}):(0,J.jsx)(me,{}),(0,J.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,J.jsxs)(J.Fragment,{children:[` `,(0,J.jsx)(Ye,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]})]}),l&&(0,J.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`status`,children:[(0,J.jsx)(ve,{}),(0,J.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})})]}),u&&(0,J.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,J.jsx)(ve,{}):(0,J.jsx)(me,{}),(0,J.jsxs)(`span`,{children:[Et(u.status,t),u.latestVersion?` ${u.currentVersion} -> ${u.latestVersion}.`:``,d?` ${t(`dash.updateReconnecting`)}`:``,u.error?` ${u.error}`:``]})]})]})}function mn({d:e}){let{t,settings:n,settingsSaving:r,toggleCodexAutoStart:i,sidecar:a,sidecarSaving:o,sidecarModels:s,models:c,saveSidecar:l,shadowCall:u,shadowCallSaving:d,shadowCallHelpTriggerRef:f,shadowCallHelpOpen:p,setShadowCallHelpOpen:m,saveShadowCall:h}=e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`spread`,children:[(0,J.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${n?.codexAutoStart??!0?`on`:``}`,onClick:i,disabled:!n||r,"aria-label":t(`dash.codexAutoStart`),"aria-pressed":n?.codexAutoStart??!0,children:(0,J.jsx)(`span`,{className:`knob`})})]})}),(0,J.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,J.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,J.jsx)(ft,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({webSearch:{model:e,backend:kt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,J.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,J.jsx)(ft,{value:a?.vision.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({vision:{model:e,backend:kt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]})]}),(0,J.jsx)(`div`,{className:`panel`,"aria-busy":!u||void 0,children:(0,J.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,J.jsx)(`button`,{ref:f,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:()=>m(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":p,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,J.jsx)(ye,{width:13,height:13,"aria-hidden":`true`})}),(0,J.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${It(u?.sourceModels)}`})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`switch ${u?.enabled?`on`:``}`,onClick:()=>h({enabled:!u?.enabled}),disabled:!u||d,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":u?.enabled??!1,children:(0,J.jsx)(`span`,{className:`knob`})}),(0,J.jsx)(ft,{value:u?.model??``,options:[{value:``,label:`—`},...c.map(e=>({value:e.id,label:`${e.provider}/${e.id}`}))],onChange:e=>{h({model:e})},disabled:!u||d||!u?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function hn(e){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dn,{apiBase:e.apiBase,d:e}),(0,J.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,J.jsx)(fn,{apiBase:e.apiBase,d:e}),(0,J.jsx)(pn,{d:e})]}),(0,J.jsx)(mn,{d:e}),(0,J.jsx)(un,{apiBase:e.apiBase})]})}function gn(e){return(0,J.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,J.jsx)(Wt,{...e}),(0,J.jsx)(hn,{...e})]})}function _n({t:e,providers:t}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,J.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,J.jsx)(pt,{title:(0,J.jsx)(Ye,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:e(`dash.col.name`)}),(0,J.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,J.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,J.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,J.jsx)(`tbody`,{children:t.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`font-semibold`,children:e.name}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`span`,{className:`chip`,children:e.adapter})}),(0,J.jsx)(`td`,{className:`muted mono text-label`,children:e.baseUrl}),(0,J.jsx)(`td`,{className:`muted`,children:e.defaultModel??`—`})]},e.name))})]})})]})}function vn(e){try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function yn(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function bn(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function xn(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Sn(e,t){return{request:++e.current,mutation:t.current}}var Cn=2e3;function wn(e){let t=e.status;return t===`native`||t===`protected`||t===`at-risk`?t:null}function Tn(e){return e?e.stale&&e.status!==`error`:!1}function En(e,t){return!t||e!==null&&e!==`error`?e:t.status}var Dn=3e4;function On(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function kn(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function An(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=wn(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(kn(e,t))throw e;return{status:`error`,stale:!1}}}async function jn(e,t){try{return(await _t(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function Mn(e,t){return St(await fetch(`${e}/api/models`,{signal:t}))}async function Nn(e,t){return St(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Pn(e,t,n){let{request:r,mutation:i}=Sn(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 St(a),c;try{if(o.ok){let e=await o.json();xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{xn({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 Fn(e,t,n){let{request:r,mutation:i}=Sn(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await St(await fetch(`${e}/api/settings`,{signal:t})),o,s;return xn({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 In(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`};let r=await n.json();return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?{maMode:r.multiAgentMode}:{maMode:`default`}}catch(e){if(kn(e,t))throw e;return{maMode:`default`}}}async function Ln(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await St(n),providers:await St(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function Rn(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={...On(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 zn=`ocx.dash.controls.v1:`,Bn=`ocx.dash.overview.v1:`,Vn=`ocx.dash.usage30d.v1:`,Hn=`ocx.dash.startup.v1:`,Un=`ocx.dash.maMode.v1:`;function Wn(e){return`${zn}${e}`}function Gn(e){let{locale:t,t:n}=X(),[r,i]=(0,_.useState)(yt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>vn(Wn(e)),[e]),u=(0,_.useMemo)(()=>vn(`${Bn}${e}`),[e]),d=(0,_.useMemo)(()=>vn(`${Vn}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=vn(`${Hn}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>vn(`${Un}${e}`),[e]),[m,h]=(0,_.useState)(()=>u?.health??null),[g,v]=(0,_.useState)(()=>f),[y,b]=(0,_.useState)(()=>u?.providers??[]),[x,S]=(0,_.useState)([]),[C,w]=(0,_.useState)(()=>l?.settings??null),[T,E]=(0,_.useState)(()=>l?.sidecar??null),[D,O]=(0,_.useState)(()=>l?.shadowCall??null),[k,A]=(0,_.useState)(()=>d),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(!1),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(()=>p??`default`),[U,W]=(0,_.useState)(!1),[G,ee]=(0,_.useState)(!1),[q,te]=(0,_.useState)(!1),[J,Y]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(``),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)([]),[ce,le]=(0,_.useState)([]),[ue,de]=(0,_.useState)(!1),[fe,pe]=(0,_.useState)(!0),[me,he]=(0,_.useState)(!1),[ge,_e]=(0,_.useState)(``),[ve,ye]=(0,_.useState)(``),[be,xe]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)(null),[Ee,De]=(0,_.useState)([]),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)(`latest`),[Me,Ne]=(0,_.useState)(!0),[Pe,Fe]=(0,_.useState)(!1),Ie=(0,_.useRef)(0),Le=(0,_.useRef)(null),Re=(0,_.useRef)(0),ze=(0,_.useRef)(0),Be=(0,_.useRef)(0),Ve=(0,_.useRef)(!1),He=(0,_.useRef)(0),Ue=(0,_.useRef)(0),We=(0,_.useRef)(!1),[Ge,Ke]=(0,_.useState)(null),[qe,Z]=(0,_.useState)(null),[Je,Ye]=(0,_.useState)(null),[Xe,Qe]=(0,_.useState)(!1),[$e,et]=(0,_.useState)(!1),tt=(0,_.useRef)(null),nt=(0,_.useRef)(null),rt=(0,_.useRef)(null),it=(0,_.useRef)(null),at=Mt(q,tt),ot=Mt(Oe,nt),st=Mt(G,rt),ct=Mt(J,it);(0,_.useEffect)(()=>{let e=()=>i(yt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)},[]);let lt=(0,_.useRef)(f),ut=(0,_.useRef)(0),dt=(0,_.useRef)({settingsRequestEpochRef:ze,settingsMutationEpochRef:Be,settingsMutationInFlightRef:Ve,shadowCallRequestEpochRef:He,shadowCallMutationEpochRef:Ue,shadowCallMutationInFlightRef:We}).current,ft=K(`dashboard-startup-health:${e}`,[e],t=>An(e,t),{pollMs:3e4}),pt=Tn(ft.data),mt=ft.refresh;(0,_.useEffect)(()=>{if(!pt)return;let e=window.setTimeout(()=>{mt()},Cn);return()=>window.clearTimeout(e)},[pt,mt]);let ht=K(`dashboard-overview:${e}`,[e],t=>Ln(e,t),{pollMs:5e3}),gt=m!==null||ht.data!==void 0,Q=K(`dashboard-ma-mode:${e}`,[e],t=>In(e,t),{pollMs:5e3}),_t=K(`dashboard-sidecars:${e}`,[e],async t=>{let n=ut.current;return{...await Pn(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),vt=K(`dashboard-settings:${e}`,[e],async t=>{let n=ut.current;return{...await Fn(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),xt=K(`dashboard-multi-agent:${e}`,[e],t=>Rn(e,t),{pollMs:5e3,enabled:gt}),Ct=K(`dashboard-usage:${e}`,[e],t=>Nn(e,t),{pollMs:6e4,enabled:gt,deadlineMs:6e4}),Tt=K(`dashboard-diagnostics:${e}`,[e],t=>jn(e,t),{pollMs:Dn,enabled:gt}),Et=K(`dashboard-models:${e}`,[e,$e],t=>Mn(e,t),{enabled:gt&&!$e});(0,_.useEffect)(()=>{if(ft.data!==void 0){let t=ft.data;ut.current+=1,v(t.status),lt.current=t.status,t.status!==`error`&&!t.stale&&yn(`${Hn}${e}`,t.status)}},[ft.data,e]),(0,_.useEffect)(()=>{let t=ht.data;t&&(t.health&&(h(t.health),b(t.providers),yn(`${Bn}${e}`,{health:t.health,providers:t.providers})),et(t.error))},[ht.data,e]),(0,_.useEffect)(()=>{Q.data!==void 0&&(H(Q.data.maMode),yn(`${Un}${e}`,Q.data.maMode))},[Q.data,e]);let kt=Q.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=xt.data;e&&(e.injection&&(pe(e.injection.multiAgentGuidanceEnabled),he(e.injection.syncCodexSubagentDefaults),re(e.injection.injectionModel),ae(e.injection.injectionEffort),se(e.injection.injectionEfforts),le(e.injection.injectionAvailable)),e.effortCaps&&(_e(e.effortCaps.effortCap),ye(e.effortCaps.subagentEffortCap)))},[xt.data]),(0,_.useEffect)(()=>{let t=_t.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=vn(Wn(e))??{};yn(Wn(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[_t.data,e]),(0,_.useEffect)(()=>{let t=vt.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===ut.current){let n=En(lt.current,t.startupHealthSeed);v(n),lt.current=n,n&&yn(`${Hn}${e}`,n)}if(t.settings!==void 0){let n=vn(Wn(e))??{};yn(Wn(e),{...n,settings:t.settings})}}},[vt.data,e]),(0,_.useEffect)(()=>{Ct.data!==void 0&&(A(Ct.data),yn(`${Vn}${e}`,Ct.data))},[Ct.data,e]),(0,_.useEffect)(()=>{Tt.data&&De(Tt.data)},[Tt.data]),(0,_.useEffect)(()=>{Et.data&&S(Et.data),I(Et.loading)},[Et.data,Et.loading]),(0,_.useEffect)(()=>()=>{ze.current+=1,He.current+=1},[]);let At=K(Je?.id&&Je.restart?`update-job:${e}:${Je.id}`:`update-job:idle:${e}`,[e,Je?.id,Je?.restart,Je?.latestVersion],async t=>{if(!Je?.id||!Je.restart)return{reconnecting:!1};let n=Je.latestVersion;try{let r=await St(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Je.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await St(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:!!(Je?.id&&Je.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=At.data;e&&(`job`in e&&e.job&&Ye(e.job),Qe(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[At.data]);let jt=(0,_.useMemo)(()=>{let e={};for(let t of x)(e[t.provider]??=[]).push(t);return Object.entries(e).sort(([e],[t])=>e.localeCompare(t))},[x]),Nt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return jt;let t=[];for(let[n,r]of jt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[jt,a]),Pt=(0,_.useMemo)(()=>{let e=Ot(x);for(let t of[T?.webSearch.model,T?.vision.model])t&&!e.some(e=>e.value===t)&&e.unshift({value:t,label:t});return e},[x,T]),Ft=async t=>{if(!T||j)return;let n=T,r={webSearch:Dt(T.webSearch,t.webSearch),vision:Dt(T.vision,t.vision)};M(!0),E(r);try{let n=await St(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);E({webSearch:n.webSearch,vision:n.vision});let r=vn(Wn(e))??{};yn(Wn(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision}})}catch{E(n)}finally{M(!1)}};async function It(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),We.current=!0,O(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`);Ue.current+=1}catch{O(n)}finally{We.current=!1,P(!1)}}let Lt=async t=>{if(!(U||V===t)){W(!0);try{(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})})).ok&&(H(t),yn(`${Un}${e}`,t))}catch{}finally{W(!1)}}},Rt=async t=>{if(!ue){de(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await St(await fetch(`${e}/api/injection-model`)),r=On(n);pe(r.multiAgentGuidanceEnabled),he(r.syncCodexSubagentDefaults),re(r.injectionModel),ae(r.injectionEffort),Array.isArray(n.efforts)&&se(n.efforts),Array.isArray(n.available)&&le(n.available)}catch{}finally{de(!1)}}},zt=async()=>{if(!C||L)return;let t=!C.codexAutoStart;R(!0),Ve.current=!0,w({...C,codexAutoStart:t});try{let n=await St(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Be.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),et(!0)}finally{Ve.current=!1,R(!1)}},Bt=async()=>{if(!z){B(!0),Ce(null),Te(null);try{let t=await St(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Ce(t),t.projectConfigGrouped&&De(t.projectConfigGrouped)}catch(e){Te(e instanceof Error?e.message:String(e))}finally{B(!1)}}},Vt=async(t,n=!1)=>{n&&(Ie.current=0),Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);let r=++Re.current;Fe(!0),Z(null),Ke(null);try{let n=await St(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Re.current)return;if(Ke(n),n.reason===`latest_unavailable`&&Ie.current<2){let e=++Ie.current;Le.current=window.setTimeout(()=>{r===Re.current&&(Le.current=null,Vt(t))},800*e);return}n.reason!==`latest_unavailable`&&(Ie.current=0),Fe(!1)}catch(e){if(r!==Re.current)return;Z(e instanceof Error?e.message:String(e)),Fe(!1)}},Ht=()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Fe(!1),ke(!1)},Ut=()=>{let e=wt(m?.version);je(e),Ne(!0),ke(!0),Vt(e,!0)},Wt=e=>{je(e),Vt(e,!0)},Gt=(0,_.useRef)(Ut);return(0,_.useEffect)(()=>{Gt.current=Ut}),(0,_.useEffect)(()=>{let e=()=>{bt()&&(Ze(`dashboard`),Gt.current())},t=bt()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:t,t:n,selectedSection:r,setSelectedSection:i,modelQuery:a,setModelQuery:o,expandedProviders:s,setExpandedProviders:c,health:m,startupHealth:g,providers:y,models:x,settings:C,sidecar:T,shadowCall:D,usage30d:k,usageLoading:Ct.loading&&!k,healthLoading:ht.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:F,settingsSaving:L,syncing:z,maMode:V,maModeResolved:kt,maBusy:U,setMaHelpOpen:ee,maHelpOpen:G,effortCapHelpOpen:q,setEffortCapHelpOpen:te,shadowCallHelpOpen:J,setShadowCallHelpOpen:Y,injectionModel:ne,injectionEffort:ie,injectionEfforts:oe,injectionAvailable:ce,injectionSaving:ue,multiAgentGuidanceEnabled:fe,syncCodexSubagentDefaults:me,saveInjection:Rt,effortCap:ge,subagentEffortCap:ve,effortCapSaving:be,setEffortCap:_e,setSubagentEffortCap:ye,setEffortCapSaving:xe,syncResult:Se,syncError:we,projectConfigWarnings:Ee,updateOpen:Oe,updateChannel:Ae,setUpdateRestart:Ne,updateRestart:Me,updateLoading:Pe,updateCheck:Ge,updateError:qe,updateJob:Je,reconnecting:Xe,error:$e,effortCapHelpTriggerRef:tt,updateTriggerRef:nt,maHelpTriggerRef:rt,shadowCallHelpTriggerRef:it,effortCapHelpDialogRef:at,updateDialogRef:ot,maHelpDialogRef:st,shadowCallHelpDialogRef:ct,filteredGroups:Nt,sidecarModels:Pt,saveSidecar:Ft,saveShadowCall:It,switchMaMode:Lt,toggleCodexAutoStart:zt,runSync:Bt,fetchUpdateCheck:Vt,closeUpdateDialog:Ht,openUpdateDialog:Ut,changeUpdateChannel:Wt,runUpdate:async()=>{if(Ge?.canUpdate){Z(null);try{let t=await St(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Ae,restart:Me})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);Ye(t.job),Qe(!1),Ht()}catch(e){Z(e instanceof Error?e.message:String(e))}}}}}function Kn(e){Qe(xt(e))}function qn({apiBase:e}){let t=Gn(e),{t:n,error:r,selectedSection:i,providers:a,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}=t;if(r)return(0,J.jsx)(pt,{style:{marginTop:40},icon:(0,J.jsx)(ve,{}),title:(0,J.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,J.jsx)(Ye,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,J.jsx)(gn,{...t}),m=(0,J.jsx)(_n,{t:n,providers:a}),h=(0,J.jsx)(Rt,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,J.jsx)(Lt,{...t}),_=[{id:`overview`,label:n(`dash.workspace.overview`),body:p},{id:`providers`,label:n(`dash.activeProviders`),body:m},{id:`models`,label:n(`dash.availableModels`),body:h}],v=_.find(e=>e.id===i)??_[0],y=Kn,b=e=>{let t=_.findIndex(e=>e.id===i),n=-1;if(e.key===`ArrowRight`?n=(t+1)%_.length:e.key===`ArrowLeft`?n=(t-1+_.length)%_.length:e.key===`Home`?n=0:e.key===`End`&&(n=_.length-1),n<0)return;e.preventDefault();let r=_[n];y(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,J.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":i===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>y(e.id),onKeyDown:b,children:e.label},e.id))}),(0,J.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${v.id}`,"aria-labelledby":`dashboard-tab-${v.id}`,tabIndex:0,children:v.body}),g]})}var Jn=`https://chatgpt.com/backend-api/codex`,Yn=`openai`;function Xn(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 Zn(e){try{let t=new URL(e).hostname.replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`}catch{return!1}}function Qn(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||Zn(e.baseUrl)||e.hasApiKey===!0}function $n(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Xn(e.baseUrl)===Jn}function er(e,t){return e===Yn&&$n(t)}function tr(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||Zn(e.baseUrl)}function nr(e,t){return er(e,t)?`accounts`:tr(t)?`free`:`paid`}function rr(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??nr(e.name,e);switch(t){case`az`:return n.sort(r);case`za`:return n.sort((e,t)=>r(t,e));case`free-paid`:return n.sort((e,t)=>(i(e)===`free`?0:1)-(i(t)===`free`?0:1)||r(e,t));case`paid-free`:return n.sort((e,t)=>(i(e)===`free`)-+(i(t)===`free`)||r(e,t));case`accounts-first`:return n.sort((e,t)=>{let n=e=>{let t=i(e);return t===`accounts`?0:t===`free`?1:2};return n(e)-n(t)||r(e,t)});default:return n}}function ir(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}Qn(a)?t.push({name:i,...a,tier:nr(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function ar(e,t){let n=new Set(Object.entries(t).filter(([,e])=>e).map(([e])=>e));if(n.size===0)return e;let r=e=>e.map(e=>n.has(e.name)?{...e,activeNeedsReauth:!0}:e);return{ready:r(e.ready),needsSetup:r(e.needsSetup),disabled:e.disabled}}function or(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:Qn(e)?`ready`:`needs-setup`}function sr(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!er(`openai`,t)||!$n(n))return e;let r={...e};return delete r.chatgpt,r}function cr(e){return e.authMode===`local`||Zn(e.baseUrl)}var lr=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function ur(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(cr(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return lr.some(e=>n.includes(e))?`selfHosted`:`cloud`}function dr(e){if(!e||typeof e!=`object`)return{};let t=e.available;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))Array.isArray(r)&&(n[e]=r.filter(e=>typeof e==`string`));return n}function fr(e){if(!e||typeof e!=`object`)return{};let t=e.liveModelCounts;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))typeof r!=`number`||!Number.isFinite(r)||r<0||(n[e]=Math.floor(r));return n}function pr(e){if(!e||typeof e!=`object`)return{};let t=e.selected;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))Array.isArray(r)&&(n[e]=r.filter(e=>typeof e==`string`));return n}function mr(e){let t={};for(let[n,r]of Object.entries(dr(e)))t[n]=r.length;return t}function hr(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 gr={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function _r(e,t,n){let r=typeof t==`object`&&t?t:gr,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 vr(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 yr(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 br(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function xr(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 Sr(e,t=`en`){return xr(e,t)}function Cr(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var wr={anthropic:`claude-color.svg`,"anthropic-apikey":`claude-color.svg`,"azure-openai":`openai.svg`,chatgpt:`openai.svg`,"cloudflare-ai-gateway":`cloudflare-ai-gateway-color.svg`,"cloudflare-workers-ai":`cloudflare-ai-gateway-color.svg`,cursor:`cursor-color.svg`,deepseek:`deepseek-color.svg`,firepass:`firepass-color.svg`,fireworks:`fireworks-color.svg`,github:`github-copilot-color.svg`,"github-copilot":`copilot-color.svg`,"gitlab-duo":`gitlab-duo-color.svg`,google:`gemini-color.svg`,"google-antigravity":`antigravity-color.svg`,"google-vertex":`gemini-color.svg`,groq:`groq-color.svg`,huggingface:`huggingface-color.svg`,kimi:`kimi-color.svg`,"kimi-code":`kimi-color.svg`,kiro:`kiro-color.svg`,"lm-studio":`lm-studio-color.svg`,mistral:`mistral-color.svg`,moonshot:`moonshot-color.svg`,nvidia:`nvidia-color.svg`,ollama:`ollama-color.svg`,"ollama-cloud":`ollama-color.svg`,openai:`openai.svg`,"openai-apikey":`openai.svg`,"opencode-free":`opencode.svg`,"opencode-go":`opencode.svg`,"opencode-zen":`opencode.svg`,openrouter:`openrouter-color.svg`,qianfan:`qianfan-color.svg`,alibaba:`alibaba-color.svg`,"alibaba-token-plan":`alibaba-color.svg`,"alibaba-token-plan-intl":`alibaba-color.svg`,"qwen-cloud":`qwen-portal-color.svg`,"vercel-ai-gateway":`vercel-ai-gateway-color.svg`,vllm:`vllm-color.svg`,xai:`grok-color.svg`,"mimo-free":`xiaomi-color.svg`,xiaomi:`xiaomi-color.svg`},Tr={anthropic:`Anthropic Claude`,"anthropic-apikey":`Anthropic Claude`,chatgpt:`ChatGPT`,openai:`OpenAI (Codex login)`,"openai-apikey":`OpenAI API`,"azure-openai":`Azure OpenAI`,"cloudflare-ai-gateway":`Cloudflare AI Gateway`,"cloudflare-workers-ai":`Cloudflare Workers AI`,nvidia:`NVIDIA NIM`,ollama:`Ollama`,"ollama-cloud":`Ollama Cloud`,xai:`xAI Grok`,"mimo-free":`MiMo Free`,xiaomi:`Xiaomi`,cursor:`Cursor`,deepseek:`DeepSeek`,github:`GitHub`,"github-copilot":`GitHub Copilot`,"gitlab-duo":`GitLab Duo`,openrouter:`OpenRouter`,"opencode-go":`OpenCode Go`,"opencode-free":`OpenCode Free`,"opencode-zen":`OpenCode Zen`,mistral:`Mistral`,groq:`Groq`,alibaba:`Alibaba Coding Plan`,"alibaba-token-plan":`Alibaba Token Plan`,"alibaba-token-plan-intl":`Alibaba Token Plan (Intl)`,kimi:`Kimi`,"kimi-code":`Kimi`,moonshot:`Moonshot`,google:`Google`,"google-vertex":`Google Vertex`,"lm-studio":`LM Studio`,huggingface:`Hugging Face`,"qwen-cloud":`Qwen Cloud`,siliconflow:`SiliconFlow`,"tencent-coding-plan":`Tencent Cloud Coding Plan`,"vercel-ai-gateway":`Vercel AI Gateway`,vllm:`vLLM`,litellm:`LiteLLM`},Er={volcengine:`provider.name.volcengine`,"volcengine-coding-plan":`provider.name.volcengineCodingPlan`,"volcengine-agent-plan":`provider.name.volcengineAgentPlan`},Dr=new Set([...Object.keys(Tr),...Object.keys(Er)]);function Or(e){return wr[e.toLowerCase()]}function kr(e,t){let n=Or(e);return n?`/provider-icons/${n}`:void 0}function Ar(e,t){let n=e.toLowerCase(),r=Er[n];return r?t(r):Tr[n]?Tr[n]:e===n&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)?e.split(`-`).map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(` `):e}function jr(e){return Dr.has(e.toLowerCase())}function Mr(e,t){let n=or(e);return n===`disabled`?t(`prov.disabledBadge`):n===`ready`?t(`pws.status.ready`):`activeNeedsReauth`in e&&e.activeNeedsReauth?t(`pws.status.needsAttention`):t(`pws.status.needsSetup`)}function Nr(e,t){switch(e.authMode){case`oauth`:return t(`modal.badge.oauth`);case`forward`:return t(`pws.auth.chatgptPassthrough`);case`local`:return t(`modal.badge.local`);case`key`:return t(`modal.badge.apiKey`);default:return e.authMode??(e.keyOptional?t(`pws.auth.noKey`):t(`modal.badge.apiKey`))}}function Pr(e){let t=or(e);return t===`disabled`?`providers-workspace-rail-status providers-workspace-rail-status--inactive`:t===`ready`?`providers-workspace-rail-status providers-workspace-rail-status--active`:`providers-workspace-rail-status providers-workspace-rail-status--warning`}function Fr({name:e,adapter:t,baseUrl:n,cls:r}){let i=kr(e,{adapter:t,baseUrl:n});return(0,J.jsx)(`span`,{className:r,children:i?(0,J.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`}):(0,J.jsx)(re,{"aria-hidden":`true`})})}function Ir({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Z(),l=tr(e),u=cr(e),d=Mr(e,c),f=Ar(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,J.jsxs)(`button`,{type:`button`,className:`providers-workspace-rail-row${t?` providers-workspace-rail-row--selected`:``}`,onClick:o,role:`option`,"aria-selected":t,tabIndex:n?0:-1,"aria-label":c(`pws.rail.selectAria`,{name:p,status:d,suffix:m}),title:p,onFocus:s,children:[(0,J.jsx)(Fr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,J.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,J.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,J.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,J.jsx)(ze,{width:17,height:17,"aria-hidden":`true`})}),(0,J.jsx)(`span`,{className:Pr(e),title:d,"aria-hidden":`true`})]})]})}function Lr(e){let t=e?.aggregation;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;if(n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`)return null;let r=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,i=r(n.includedAccounts),a=r(n.excludedAccounts),o=r(n.unknownPlanAccounts);if(i===void 0||a===void 0||o===void 0)return null;let s=n.presentation===`effective-account-fallback`||n.presentation===`coverage-only`?n.presentation:`aggregate`,c=[n.fiveHour,n.weekly,n.monthly,...Array.isArray(n.customWindows)?n.customWindows:[]].filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)).map(e=>({at:r(e.nextRecoveryAt),percent:r(e.nextRecoveryPercent)})).filter(e=>e.at!==void 0).sort((e,t)=>e.at-t.at)[0];return{presentation:s,includedAccounts:i,excludedAccounts:a,unknownPlanAccounts:o,...c?{nextRecoveryAt:c.at}:{},...c?.percent===void 0?{}:{nextRecoveryPercent:c.percent}}}function Rr(e){let t=e?.quota;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t,r=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,i=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||r(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...r(t.resetAt)===void 0?{}:{resetAt:t.resetAt},...typeof t.valueLabel==`string`&&t.valueLabel.trim()?{valueLabel:t.valueLabel}:{},...Array.isArray(t.segments)?{segments:t.segments.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||r(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...r(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]})}:{}}]}):[],a={...r(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...r(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...r(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...r(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...r(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...r(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...i.length>0?{customWindows:i}:{},updatedAt:r(n.updatedAt)??e?.updatedAt??Date.now()};return a.fiveHourPercent!==void 0||a.weeklyPercent!==void 0||a.monthlyPercent!==void 0||(a.customWindows?.length??0)>0?a:null}function zr(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Br(e,t,n,r,i,a){let o=r&&r.length>0?r:t?[t]:[],s=[...new Set([...a?e:o,...i])],c=n.trim().toLowerCase();return c?s.filter(e=>e.toLowerCase().includes(c)):s}function Vr(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function Hr(e,t){return!e||!Vr(t)?e:{...e.monthlyPercent===void 0?{}:{monthlyPercent:e.monthlyPercent},...e.monthlyResetAt===void 0?{}:{monthlyResetAt:e.monthlyResetAt},...e.resetCredits===void 0?{}:{resetCredits:e.resetCredits},updatedAt:e.updatedAt}}function Ur(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function Wr(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 Gr(e,t,n){let r=Hr(e,t);if(!r)return[];let i=[];typeof r.fiveHourPercent==`number`&&i.push({rank:0,row:{label:n(`codexAuth.fiveHour`),limitLabel:n(`quota.fiveHourLimit`),percent:r.fiveHourPercent,resetAt:r.fiveHourResetAt}}),typeof r.weeklyPercent==`number`&&i.push({rank:1,row:{label:n(`codexAuth.weekly`),limitLabel:n(`quota.weeklyLimit`),percent:r.weeklyPercent,resetAt:r.weeklyResetAt}}),typeof r.monthlyPercent==`number`&&i.push({rank:4,row:{label:n(`codexAuth.monthly`),limitLabel:n(`quota.monthlyLimit`),percent:r.monthlyPercent,resetAt:r.monthlyResetAt}});for(let e of r.customWindows??[]){let t=Wr(e.label,n);i.push({rank:Ur(e.label),row:{label:t,limitLabel:t,percent:e.percent,resetAt:e.resetAt,...e.valueLabel===void 0?{}:{valueLabel:e.valueLabel},...e.segments!==void 0&&e.segments.length>0?{segments:e.segments}:{}}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function Kr(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 t.length?Math.max(...t):-1}function qr(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;default:return e}}function Jr(e){return e>=99.5}function Yr(e,t){return t>0&&e>=t}function Xr(e,t){return Yr(e,t)||Jr(e)?`bar-warn`:`bar-green`}function Zr(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Qr(e){return{"--bar-scale":String(Zr(e)/100)}}function $r({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1}){let{locale:s}=X(),c=Gr(e,t,r);return c.length===0?o?a===`stacked`?(0,J.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,J.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,J.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`})]},t)),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,J.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:c.map(e=>(0,J.jsx)(ii,{row:e,threshold:n,t:r,locale:s},e.limitLabel))}):(0,J.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:c.map(e=>e.segments!==void 0&&e.segments.length>0?(0,J.jsx)(ni,{row:e,threshold:n,t:r,locale:s},e.label):e.valueLabel===void 0?(0,J.jsx)(ei,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:s},e.label):(0,J.jsx)(ti,{label:e.label,value:e.valueLabel},e.label))})}function ei({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Jr(t),s=Yr(t,r),c=Xr(t,r),l=ai(n,i,a);return(0,J.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,J.jsx)(`span`,{className:`quota-label`,children:e}),(0,J.jsx)(`span`,{className:`quota-reset-label`,children:i(`codexAuth.resets`)}),(0,J.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,J.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,J.jsx)(`div`,{className:`bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${c}`,style:Qr(t)})}),(0,J.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):void 0,children:[s&&(0,J.jsx)(ve,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function ti({label:e,value:t}){return(0,J.jsxs)(`div`,{className:`quota-row quota-row--value`,children:[(0,J.jsx)(`span`,{className:`quota-label`,children:e}),(0,J.jsx)(`span`,{className:`quota-val`,children:t})]})}function ni({row:e,threshold:t,t:n,locale:r}){return(0,J.jsx)(`div`,{className:`quota-row quota-row--segments`,children:(0,J.jsx)(`div`,{className:`quota-segments`,children:(e.segments??[]).map(e=>(0,J.jsx)(ri,{segment:e,threshold:t,t:n,locale:r},e.label))})})}function ri({segment:e,threshold:t,t:n,locale:r}){let i=Yr(e.percent,t),a=Xr(e.percent,t),o=oi(e.resetAt,n,r);return(0,J.jsxs)(`div`,{className:`quota-segment`,children:[(0,J.jsxs)(`span`,{className:`quota-segment-head`,children:[(0,J.jsxs)(`span`,{className:`quota-segment-title`,children:[e.label,o?(0,J.jsxs)(`span`,{className:`quota-segment-reset`,children:[` · `,o]}):null]}),(0,J.jsxs)(`span`,{className:`quota-segment-val${i?` quota-segment-val--warn`:``}`,children:[Math.round(e.percent),`%`]})]}),(0,J.jsx)(`div`,{className:`bar quota-segment-bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${a}`,style:Qr(e.percent)})})]})}function ii({row:e,threshold:t,t:n,locale:r}){if(e.segments!==void 0&&e.segments.length>0)return(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--segments`,children:[(0,J.jsx)(`div`,{className:`quota-stacked-head`,children:(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel})}),(0,J.jsx)(`div`,{className:`quota-segments`,children:(e.segments??[]).map(e=>(0,J.jsx)(ri,{segment:e,threshold:t,t:n,locale:r},e.label))})]});if(e.valueLabel!==void 0)return(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--value`,children:[(0,J.jsx)(`div`,{className:`quota-stacked-head`,children:(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel})}),(0,J.jsx)(`div`,{className:`quota-stacked-bar-row`,children:(0,J.jsx)(`span`,{className:`quota-stacked-used`,children:e.valueLabel})})]});let i=Jr(e.percent),a=Yr(e.percent,t),o=Xr(e.percent,t),s=oi(e.resetAt,n,r);return(0,J.jsxs)(`div`,{className:`quota-stacked-row${a?` quota-stacked-row--warn`:``}${i?` quota-stacked-row--exhausted`:``}`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),(0,J.jsx)(`span`,{className:`quota-stacked-reset muted`,children:s})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${o}`,style:Qr(e.percent)})}),(0,J.jsx)(`span`,{className:`quota-stacked-used${a?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),i&&(0,J.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,J.jsx)(ve,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function ai(e,t,n){if(typeof e!=`number`||!Number.isFinite(e))return{day:``,time:``};let r=e<1e10?e*1e3:e,i=new Date(r),a=new Date,o=qr(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 oi(e,t,n=`en`,r=Date.now()){if(typeof e!=`number`||!Number.isFinite(e))return``;let i=e<1e10?e*1e3:e,a=new Date(i),o=qr(n),s=new Intl.DateTimeFormat(o,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(a),c=new Date(r),l=new Date(c.getFullYear(),c.getMonth(),c.getDate()).getTime(),u=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),d=Math.round((u-l)/864e5);if(d===1)return t(`quota.resetsTomorrow`,{time:s});let f=a.getFullYear()!==c.getFullYear(),p=new Intl.DateTimeFormat(o,{day:`numeric`,month:`short`,...f?{year:`numeric`}:{}}).format(a);if(i<=r)return t(`quota.resetsAt`,{date:p,time:s,when:`${p}, ${s}`});let m=Math.round((i-r)/6e4);if(m<60)return t(`quota.resetsRelativeMinutes`,{n:Math.max(1,m)});let h=Math.round(m/60);return h<12&&d===0?t(`quota.resetsRelativeHours`,{n:Math.max(1,h)}):d===0?t(`quota.resetsToday`,{time:s}):t(`quota.resetsAt`,{date:p,time:s,when:`${p}, ${s}`})}function si({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=Z(),{locale:c}=X(),l=vr(s),u=(0,_.useMemo)(()=>[...e.ready,...e.needsSetup,...e.disabled],[e]),d=(0,_.useMemo)(()=>new Set(u.map(e=>e.name)),[u]),f=(0,_.useMemo)(()=>yr(e,{}),[e]),p=f.length,m=(0,_.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),h=e.ready.length-m,g=e.needsSetup.length+m,v=(0,_.useMemo)(()=>{let e=[];for(let n of u){let r=t[n.name],i=r?Rr(r):null;r&&i&&e.push({item:n,report:r,urgency:Kr(i)})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[u,t]),y=(0,_.useMemo)(()=>{let e={};for(let[t,r]of Object.entries(n))d.has(t)&&(e[t]=r);return hr(e).slice(0,4)},[n,d]),b=e=>{let t=br(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,J.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,J.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,J.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,J.jsx)(ci,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,J.jsx)(ci,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,J.jsx)(ci,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,J.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,J.jsx)(ve,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,J.jsx)(Fr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ar(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,J.jsx)(we,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Fr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ar(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:(()=>{let e=Lr(t);if(!e)return s(`pws.dashboard.checkedAgo`,{time:_r(t.updatedAt,l)});let n=s(`pws.capacity.coverage`,{included:e.includedAccounts,total:e.includedAccounts+e.excludedAccounts}),r=e.nextRecoveryAt?s(`pws.capacity.nextRecovery`,{time:_r(e.nextRecoveryAt,l)}):``;return`${s(`pws.capacity.estimate`)} · ${n}${r?` · ${r}`:``}`})()})]}),(0,J.jsx)(we,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)($r,{quota:Rr(t),threshold:80,t:s,layout:`stacked`,pending:i&&!t.quota})})]},e.name))}):i?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)($r,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Fr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ar(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:xr(e.requests,c)})}),(0,J.jsx)(we,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function ci({count:e,label:t,tone:n}){return(0,J.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,J.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function li({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Z(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,J.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,J.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,J.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,J.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,J.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,J.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,J.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var ui=[{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 di({providers:e,apiBase:t,defaultProvider:n,selectedName:r,onSelect:i,onRemoveProvider:a,onAddProvider:o,onEditConfig:s,jsonEditor:c,jsonSaving:l=!1,modelsRefreshToken:u=0,activeAccountNeedsReauth:d,quotaRefreshEpoch:f=0,quotaForceRefresh:p=!1,detail:m}){let h=Z(),[g,v]=(0,_.useState)(``),[b,x]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[S,C]=(0,_.useState)({free:!0,paid:!0}),[w,T]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[E,D]=(0,_.useState)(`az`),[O,k]=(0,_.useState)(!1),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)({}),[P,F]=(0,_.useState)({}),[I,L]=(0,_.useState)({}),[R,z]=(0,_.useState)({}),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(!1),W=`ocx.providers.quotas.v1:${t}`,G=`ocx.providers.usage.v1:${t}`,[ee,K]=(0,_.useState)(()=>vn(G)?.totals??{}),[q,te]=(0,_.useState)(()=>vn(G)?.models??{}),[Y,ne]=(0,_.useState)(()=>vn(W)??{}),[re,ie]=(0,_.useState)(()=>!vn(G)),[ae,oe]=(0,_.useState)(()=>!vn(W)),[se,ce]=(0,_.useState)(0),le=(0,_.useRef)(null),ue=(0,_.useMemo)(()=>ar(ir(sr(e)),d??{}),[e,d]),de=(0,_.useCallback)(()=>{ce(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{V(!0),(async()=>{try{let n=await Q(await fetch(`${t}/api/selected-models`));if(e)return;N(mr(n)),F(dr(n)),L(fr(n)),z(pr(n)),U(!1)}catch{if(e)return;U(!0)}finally{e||V(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,se]),(0,_.useEffect)(()=>{let e=!1,n=null,r=window.setTimeout(()=>{vn(G)||ie(!0);let r=y(6e4);n=r,fetch(`${t}/api/usage?range=30d`,{signal:r.signal}).then(e=>_t(e)).then(t=>{if(e||!t)return;let n={};for(let e of t.providers??[])n[e.provider]={requests:e.requests,totalTokens:e.totalTokens};K(n);let r={};for(let e of t.models??[]){let t=e.provider;r[t]||(r[t]=[]),r[t].push({model:e.model,...e.resolvedModel?{resolvedModel:e.resolvedModel}:{},requests:e.requests,totalTokens:e.totalTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens,shareRatio:e.shareRatio,...e.estimatedCostUsd===void 0?{}:{estimatedCostUsd:e.estimatedCostUsd}})}te(r),yn(G,{totals:n,models:r})}).catch(()=>{}).finally(()=>{r.clear(),n===r&&(n=null),e||ie(!1)})},0);return()=>{e=!0,window.clearTimeout(r),n?.controller.abort(),n?.clear()}},[t,G]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{vn(W)||oe(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>_t(e)).then(t=>{e||!t||ne(e=>{let n={...e};for(let e of t.reports??[])e?.provider&&(n[e.provider]={label:e.label,source:e.source,updatedAt:typeof e.updatedAt==`number`?e.updatedAt:Date.now(),quota:e.quota});return yn(W,n),n})}).catch(()=>{}).finally(()=>{e||oe(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,W]),(0,_.useEffect)(()=>{if(!O)return;let e=e=>{le.current&&!le.current.contains(e.target)&&k(!1)},t=e=>{e.key===`Escape`&&k(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[O]);let fe=(0,_.useMemo)(()=>[...ue.ready,...ue.needsSetup,...ue.disabled],[ue]),pe=(0,_.useMemo)(()=>fe.filter(tr).length,[fe]),me=fe.length-pe,he=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of fe)e[ur(t)]+=1;return e},[fe]),ge=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>rr(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=tr(t);return!(n&&!S.free||!n&&!S.paid||!w[ur(t)])}),E);return{ready:b.ready?t(ue.ready):[],needsSetup:b.needsSetup?t(ue.needsSetup):[],disabled:b.disabled?t(ue.disabled):[]}},[ue,g,b,S,w,E]),ve=!b.ready||!b.needsSetup||!b.disabled||!S.free||!S.paid||!w.cloud||!w.local||!w.selfHosted||!w.login||E!==`az`,ye=()=>{x({ready:!0,needsSetup:!0,disabled:!0}),C({free:!0,paid:!0}),T({cloud:!0,local:!0,selfHosted:!0,login:!0}),D(`az`)},xe=(0,_.useMemo)(()=>r?fe.find(e=>e.name===r)??null:null,[r,fe]),Se=(0,_.useMemo)(()=>{let e=new Map;for(let t of fe){let n=Ar(t.name,h);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},[fe,h]);if(fe.length===0)return(0,J.jsx)(fi,{onAddProvider:o});let Ce=[{key:`ready`,label:h(`pws.status.ready`),count:ue.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:ue.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:ue.disabled.length}],we=[{id:`ready`,label:h(`pws.status.ready`),count:ge.ready.length,ariaLabel:h(`pws.groupReady`,{count:ge.ready.length}),items:ge.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:ge.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:ge.needsSetup.length}),items:ge.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:ge.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:ge.disabled.length}),items:ge.disabled}],Te=we.flatMap(e=>e.items.map(e=>e.name)),Ee=A&&Te.includes(A)?A:r&&Te.includes(r)?r:Te[0]??null;return(0,J.jsx)(`div`,{className:`pws-shell-container`,children:(0,J.jsxs)(`div`,{className:`pws-root`,children:[(0,J.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,J.jsxs)(`div`,{className:`pws-search-row`,children:[(0,J.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,J.jsx)(be,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:h(`pws.searchPlaceholder`),value:g,onChange:e=>v(e.target.value),"aria-label":h(`pws.searchPlaceholder`)})]}),(0,J.jsxs)(`div`,{className:`pws-filter-wrap`,ref:le,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ve||O?` pws-filter-btn--active`:``}`,onClick:()=>k(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":O,"aria-controls":`pws-provider-filters`,children:[(0,J.jsx)(Be,{width:18,height:18,"aria-hidden":`true`}),ve&&(0,J.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),O&&(0,J.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,J.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),Ce.map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:b[e],onChange:()=>x(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:S.free,onChange:()=>C(e=>({...e,free:!e.free}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:pe})]}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:S.paid,onChange:()=>C(e=>({...e,paid:!e.paid}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:me})]}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:he.cloud},{key:`local`,label:h(`pws.type.local`),count:he.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:he.selfHosted},{key:`login`,label:h(`pws.type.login`),count:he.login}].map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:w[e],onChange:()=>T(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,J.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:ui.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`pws-sort-btn${E===e.id?` pws-sort-btn--active`:``}`,onClick:()=>D(e.id),"aria-pressed":E===e.id,children:h(e.labelKey)},e.id))}),(0,J.jsx)(`div`,{className:`pws-filter-footer`,children:(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:ye,disabled:!ve,children:h(`pws.resetAll`)})})]})]})]}),(0,J.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":h(`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(ge).every(e=>e.length===0)&&(0,J.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:ve?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),we.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,J.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,J.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,J.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,J.jsx)(Ir,{item:e,selected:r===e.name,tabbable:Ee===e.name,modelCount:M[e.name],isDefault:n===e.name,showConfigId:Se.has(Ar(e.name,h)),onClick:()=>i(e.name),onFocus:()=>j(e.name)}),a&&(0,J.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),a(e.name)},title:h(`pws.removeConfirmTitle`),children:(0,J.jsx)(_e,{width:14,height:14})})]},e.name))]},e))]})]}),(0,J.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,J.jsx)(li,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):xe?m?.(xe,{usageTotals:ee[xe.name],modelUsage:q[xe.name],quotaReport:Y[xe.name],availableModels:P[xe.name]??[],hasLiveModels:(I[xe.name]??0)>0,selectedModels:R[xe.name]??[],modelsLoading:B,modelsLoadFailed:H,onRetryModels:de})??(0,J.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,J.jsx)(`h3`,{children:Ar(xe.name,h)}),(0,J.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,J.jsx)(si,{sections:ue,quotaReports:Y,usageTotals:ee,usageLoading:re,quotasLoading:ae,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function fi({onAddProvider:e}){let t=Z();return(0,J.jsx)(`div`,{className:`pws-empty-root`,children:(0,J.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,J.jsx)(`div`,{"aria-hidden":`true`,children:(0,J.jsx)(ie,{style:{width:64,height:64}})}),(0,J.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,J.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Fe,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(ke,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Oe,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function pi(e){if(er(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||cr(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0;return!(t===`key`||n||t===``)||e.keyOptional===!0&&!n?null:`api-keys`}function mi(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 hi({item:e,usageTotals:t,quotaReport:n,oauthEmail:r,apiBase:i,connectionIdentity:a,onEditSettings:o,onViewUsage:s,onUpdateProvider:c,onReauthenticate:l,onCancelLogin:u,reauthBusy:d=!1,accountPanel:f}){let p=Z(),{locale:m}=X(),h=vr(p),g=or(e),v=!!e.activeNeedsReauth,y=p(g===`ready`?`pws.status.connected`:g===`needs-setup`?v?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),b=t?.requests,x=t?.totalTokens,S=Rr(n),C=JSON.stringify([i??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,a??null]),[w,T]=(0,_.useState)(null),E=(0,_.useRef)(null),D=w?.key===C&&w.testing,O=w?.key===C?w.result:null;(0,_.useEffect)(()=>()=>{E.current?.key===C&&(E.current.controller.abort(),E.current=null)},[C]);let k=(0,_.useCallback)(async()=>{if(!i)return;E.current?.controller.abort();let t=new AbortController;E.current={key:C,controller:t},T({key:C,testing:!0,result:null});try{let n=await Q(await fetch(`${i}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),p(`pws.connectionFailed`));if(!n)throw Error(p(`pws.connectionFailed`));t.signal.aborted||T({key:C,testing:!1,result:n})}catch(e){t.signal.aborted||T({key:C,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:p(`pws.connectionFailed`)}})}finally{E.current?.controller===t&&(E.current=null)}},[i,C,e.name,p]),A=O?.applicable===!1?`not-applicable`:O?.ok===!0?`ok`:`failed`,j=O?.applicable===!1?p(`pws.connectionNotApplicable`):O?.ok===!0?O.message||p(`pws.connectionOk`):O?.error||p(`pws.connectionFailed`);return(0,J.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,J.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.connection`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.connection`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`dash.status`)}),(0,J.jsxs)(`dd`,{className:g===`ready`?`pws-status-ok`:`pws-status-warn`,children:[g===`ready`?(0,J.jsx)(de,{style:{width:13,height:13},"aria-hidden":`true`}):(0,J.jsx)(ve,{style:{width:13,height:13},"aria-hidden":`true`}),y]})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.baseUrl`)}),(0,J.jsx)(`dd`,{children:(0,J.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.auth`)}),(0,J.jsx)(`dd`,{children:r?`${Nr(e,p)} · ${r}`:Nr(e,p)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.defaultModel`)}),(0,J.jsx)(`dd`,{children:e.defaultModel??(0,J.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.note`)}),(0,J.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),i&&(0,J.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:()=>void k(),children:p(D?`pws.testing`:`pws.testConnection`)}),O&&(0,J.jsx)(`span`,{role:`status`,className:A===`ok`?`pws-status-ok`:A===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":A,children:j})]}),o&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:o,children:p(`pws.editSettings`)})]}),f?(0,J.jsx)(`section`,{className:`pws-section`,"aria-label":p(`pws.availableAccounts`),children:f}):(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.authSummary`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.authSummary`)}),v?(0,J.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,J.jsx)(ve,{style:{width:14,height:14},"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:p(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?p(`pws.attention.reauthForward`):p(`pws.attention.reauth`)]}),l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:d,onClick:()=>l(),children:p(d?`prov.waitingBrowser`:`pws.reauthenticate`)}),d&&u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>u(),children:p(`common.cancel`)})]})]}):(0,J.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,J.jsx)(`span`,{className:`pws-auth-dot`}),(0,J.jsx)(`span`,{children:e.authMode===`forward`?p(`pws.passthrough`):e.authMode===`oauth`?r?p(`pws.loggedInAs`,{email:r}):p(`pws.notLoggedIn`):e.hasApiKey?p(`pws.apiKeyConfigured`):Nr(e,p)})]})]})]}),(0,J.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.statsAria`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.statsTitle`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[typeof b==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalRequests`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:xr(b,m)})]}),typeof x==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalTokens`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:Sr(x,m)})]}),n&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?zr(n.source):void 0,children:_r(n.updatedAt,h)})]}),typeof b!=`number`&&typeof x!=`number`&&!n&&(0,J.jsx)(`div`,{className:`muted`,children:p(`pws.usageUnavailable`)})]}),s&&(0,J.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:s,children:[p(`pws.viewUsage`),` →`]}),S&&(0,J.jsx)(`div`,{className:`muted pws-stats-note`,children:p(`pws.stats.quotaTracked`)})]}),(0,J.jsx)(gi,{item:e,onUpdateProvider:c})]})]})}function gi({item:e,onUpdateProvider:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.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,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.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,J.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,J.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function _i({item:e,apiBase:t,availableModels:n,hasLiveModels:r,selectedModels:i,modelsLoading:a=!1,modelsLoadFailed:o=!1,needsReauth:s=!1,onRetryModels:c,onOpenAccounts:l}){let u=Z(),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(``),[S,C]=(0,_.useState)([]),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(null),M=(0,_.useRef)(null),N=(0,_.useMemo)(()=>new Set(i),[i]),P=(0,_.useMemo)(()=>e.models??[],[e.models]),F=p.trim(),I=!w||!F||F.includes(`/`)||n.includes(F)||S.includes(F)||P.includes(F)||e.defaultModel===F,L=(0,_.useMemo)(()=>Br(n,e.defaultModel,d,P,S,r),[n,e.defaultModel,d,P,S,r]);(0,_.useEffect)(()=>{let n=!0;return(async()=>{try{let r=await fetch(`${t}/api/custom-models`);if(!r.ok)throw Error();let i=await r.json();if(!Array.isArray(i))throw Error(`Invalid custom model list`);if(!n)return;C(i.flatMap(t=>{if(!t||typeof t!=`object`)return[];let n=t;return n.provider===e.name&&typeof n.modelId==`string`?[n.modelId]:[]})),D(!1),y(``),T(!0)}catch{if(!n)return;C([]),T(!1),D(!0),y(u(`models.networkError`))}})(),()=>{n=!1}},[t,e.name,u,O]);let R=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let z=async e=>{try{await navigator.clipboard.writeText(e),j(e),M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{j(t=>t===e?null:t),M.current=null},1200)}catch{}},B=async()=>{if(!(I||h)){g(!0),y(``),x(``);try{(await fetch(`${t}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,modelId:F})})).ok?(C(e=>e.includes(F)?e:[...e,F]),m(``),x(u(`models.customAdded`)),c?.()):y(u(`models.customSaveFailed`))}catch{y(u(`models.networkError`))}finally{g(!1)}}},V=n.length===0&&P.length===0&&S.length===0&&!e.defaultModel,H=n.length===0&&P.length>0,U=L.length>300,W=U?L.slice(0,300):L;return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-section-head`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),L.length>0&&(0,J.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:L.length})})]}),s&&(0,J.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),H&&!s&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,J.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,J.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,J.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&B()},placeholder:u(`models.customFieldModelIdPlaceholder`),"aria-label":u(`models.customAdd`),disabled:h}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{B()},disabled:h||I,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,J.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,J.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:R,style:{marginLeft:8},children:u(`common.retry`)})]}),!V&&(0,J.jsx)(`input`,{type:`search`,className:`input pws-model-search`,placeholder:u(`pws.modelSearchPlaceholder`),value:d,onChange:e=>f(e.target.value),"aria-label":u(`pws.modelSearchPlaceholder`)}),a&&V?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&V?(0,J.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):V?(0,J.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):L.length===0?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,J.jsx)(`ul`,{className:`pws-model-list`,children:W.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,J.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,J.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:()=>{z(t)},title:t,"aria-label":u(A===t?`pws.modelCopied`:`pws.copyModelId`),children:(0,J.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,J.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,J.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),U&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(L.length)})})]})}function vi({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=Z(),{locale:a}=X(),o=vr(i),s=t?.requests!==void 0,c=Rr(n),[l,u]=(0,_.useState)(null),d=(0,_.useMemo)(()=>r?.length?r.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[r]),f=(0,_.useMemo)(()=>{if(!d.length)return;let e=0,t=!1;for(let n of d)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[d]);return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Cr(f,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:xr(t?.requests,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:Sr(t?.totalTokens,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,J.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`pws-model-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`pws.col.model`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,J.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,J.jsxs)(_.Fragment,{children:[(0,J.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,J.jsx)(`td`,{className:`mono`,children:(0,J.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,J.jsx)(`td`,{className:`num mono`,children:Cr(e.estimatedCostUsd,a)}),(0,J.jsx)(`td`,{className:`num mono`,children:Sr(e.totalTokens,a)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`pws-share-bar`,children:(0,J.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,J.jsx)(`tr`,{className:`pws-model-detail`,children:(0,J.jsx)(`td`,{colSpan:5,children:(0,J.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Sr(e.inputTokens,a)]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Sr(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($r,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,J.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,J.jsx)(`dd`,{children:zr(n.source)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{children:_r(n?.updatedAt,o)})]})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function yi(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function bi(e){return yi(e)??`account-…`}function xi(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Si(e){let t=xi(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function Ci(e){return e===`reauth_required`}function wi(e){return!!e?.needsReauth||Ci(e?.health?.status)}function Ti(e){return e===`cooldown`}function Ei(e){return e===`warning`||e===`reauth_required`}function Di(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`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 Oi(e,t){let n=Di(t);return n?e(n):null}function ki(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):bi(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===`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 Ai(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return ji(e)}function ji(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 Mi(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var Ni=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function Pi(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-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};case`oauth-code-submitted`:return{...e,error:``,manualCode:``,manualCodeState:`waiting`,statusTone:`ok`,statusNotice:``};default:return e}}function Fi({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,J.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:a(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,J.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,J.jsx)(Fe,{width:20}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,J.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var Ii=2500;function Li(){let[e,t]=(0,_.useState)(null),n=(0,_.useRef)(null),r=(0,_.useRef)(0),i=(0,_.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,_.useEffect)(()=>i,[i]),{outcomeFor:(0,_.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,_.useCallback)((e,a)=>{let o=++r.current;Ai(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)},Ii))})},[i])}}function Ri({url:e}){let t=Z(),{outcomeFor:n,copy:r}=Li();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,J.jsxs)(`div`,{className:`login-url-block`,children:[(0,J.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,J.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,J.jsx)(je,{style:{width:13,height:13},"aria-hidden":`true`}),(0,J.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,J.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,J.jsx)(De,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function zi({reauthAccountId:e,authUrl:t,manualCode:n,manualCodeBusy:r,manualCodeWaiting:i,statusNotice:a,statusTone:o,flowId:s,error:c,onManualCodeChange:l,onSubmitManualCode:u,onClose:d}){let f=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,J.jsx)(Ri,{url:t}),(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,marginTop:12},children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:f(`prov.pasteRedirectHint`)}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,J.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:n,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),u())},placeholder:f(`prov.pasteRedirect`),"aria-label":f(`prov.pasteRedirect`),disabled:r||i,className:`input text-label`,style:{flex:1}}),(0,J.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,disabled:r||i||!n.trim()||!s,onClick:u,children:f(r?`codexAuth.oauthSubmittingCode`:`prov.pasteSubmit`)})]})]}),a&&(0,J.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,J.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,J.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}function Bi({apiBase:e,reauthAccountId:t,ui:n,dispatch:r,t:i}){let a=(0,_.useRef)(!0),o=(0,_.useRef)(0),s=(0,_.useRef)(!1),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(n.manualCodeState),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(()=>{}),g=(0,_.useRef)(()=>{}),v=n.manualCodeState===`submitting`,b=n.manualCodeState===`waiting`;(0,_.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,_.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let x=(0,_.useCallback)(()=>{c.current&&=(c.current(),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),S=(0,_.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),C=(0,_.useCallback)(async()=>{S();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-auth-url`,authUrl:``}),x(),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,S,r,x]);(0,_.useEffect)(()=>(a.current=!0,()=>{S(),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}),x(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,S,r,x]);let w=(0,_.useCallback)((e,t)=>{h.current=e,g.current=t},[]),T=(0,_.useCallback)(()=>{n.step===`oauth-waiting`&&C(),g.current()},[n.step,C]),E=(0,_.useCallback)(async n=>{S(),d.current=null,r({type:`set-flow-id`,flowId:null});let m=new AbortController;p.current?.abort(),p.current=m,r({type:`reset-oauth-start`}),o.current=0;try{let p=t??n?.trim()??``,_=()=>fetch(`${e}/api/codex-auth/login`,{signal:m.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{id:t,reauth:!0}:p?{id:p}:{})}),v=await _();if(!a.current)return;if(v.status===409){if(await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),!a.current||m.signal.aborted)return;if(v=await _(),v.status===409){r({type:`set-error`,error:i(`codexAuth.oauthAlreadyInProgress`)});return}}let b=await Q(v,i(`modal.networkError`));if(!a.current||!b)return;if(b.url){d.current=b.flowId??null,r({type:`set-flow-id`,flowId:b.flowId??null}),r({type:`set-auth-url`,authUrl:b.url}),r({type:`set-step`,step:`oauth-waiting`}),x();let n=b.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`,v=new AbortController;u.current=v,c.current=Jt(async()=>{if(s.current||v.signal.aborted)return;s.current=!0;let e=y(1e4),n=AbortSignal.any([v.signal,e.signal]);try{let e=await _t(await fetch(_,{signal:n}));if(!a.current||v.signal.aborted)return;if(!e){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`}),e.status===`done`){if(x(),S(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(),g.current()}else(e.status===`error`||e.status===`expired`)&&(x(),S(),d.current=null,r({type:`set-flow-id`,flowId:null}),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:e.error??i(`codexAuth.loginFailed`)})))}catch(e){if(!a.current||v.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{e.clear(),s.current=!1}},2e3),l.current=setTimeout(()=>{c.current&&(S(),C(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},3e5)}b.error&&!b.url&&r({type:`set-error`,error:b.error})}catch(e){a.current&&!(e instanceof Error&&e.name===`AbortError`)&&r({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[e,C,S,r,t,x,i]);return(0,_.useEffect)(()=>{if(!t){m.current=null;return}m.current!==t&&(m.current=t,E())},[t,E]),{manualCodeBusy:v,manualCodeWaiting:b,bindCallbacks:w,closeModal:T,startOAuth:E,submitManualCode:(0,_.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(!(!t||!s||v||b)){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,b,i,n.manualCode])}}function Vi({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Z(),[a,o]=(0,_.useReducer)(Pi,r,Ni),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=Bi({apiBase:e,reauthAccountId:r,ui:a,dispatch:o,t:i});(0,_.useEffect)(()=>{d(n,t)},[d,n,t]),(0,_.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,_.useCallback)(e=>{e.preventDefault(),f()},[f]);return(0,J.jsx)(`dialog`,{ref:c,"aria-label":i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`),className:`modal-overlay`,onCancel:h,children:(0,J.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,J.jsx)(Fi,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{p(a.id)},onClose:f}),a.step===`oauth-waiting`&&(0,J.jsx)(zi,{reauthAccountId:r,authUrl:a.authUrl,manualCode:a.manualCode,manualCodeBusy:l,manualCodeWaiting:u,statusNotice:a.statusNotice,statusTone:a.statusTone,flowId:a.flowId,error:a.error,onManualCodeChange:e=>o({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{m()},onClose:f})]})})}var Hi=1e4;function Ui(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Wi(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Gi(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Ki(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function qi(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Ji(e,t,n){if(e<=0){let t=Gi(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Wi(t)??Gi(0,n)}}async function Yi(e,t,n=(e,t)=>fetch(e,t),r=Hi){if(!Number.isInteger(t)||t<0||t>100)return!1;try{return(await n(`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({threshold:t}),signal:AbortSignal.timeout(r)})).ok}catch{return!1}}var Xi=3e4,Zi=new Map;function Qi(e,t=!0){let n=Zi.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),[a,o]=(0,_.useState)(()=>n?.activeId??null),[s,c]=(0,_.useState)(()=>n==null?`loading`:`ready`),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(0),[v,b]=(0,_.useState)(()=>n!=null),[x,S]=(0,_.useState)(0),C=(0,_.useRef)(new Set),w=(0,_.useRef)(null),T=(0,_.useRef)(0),E=(0,_.useRef)(null),D=(0,_.useRef)(new Set),O=(0,_.useRef)(null),k=(0,_.useRef)(null),A=(0,_.useRef)(!!n?.accounts.length),j=(0,_.useRef)(n!=null),M=(0,_.useRef)(null),N=(0,_.useCallback)(e=>(D.current.add(e),()=>{D.current.delete(e)}),[]),P=(0,_.useCallback)(()=>qi(O.current?.value),[]),F=(0,_.useCallback)(()=>O.current?.value,[]),I=(0,_.useCallback)(async(t=!1)=>{let n=++T.current,r=y(2e4);g(e=>e+1);try{let a=[...D.current],s=new Map;for(let e of a)s.set(e,e.beginActiveRead());!t&&!j.current&&c(`loading`);let l=null,u,d=(async()=>{try{let a=await fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`,{signal:r.signal});if(!a.ok)throw Error(`account load failed`);let o=await a.json();return T.current===n&&(l=o.accounts??[],i(l),A.current=l.length>0,j.current=!0,c(`ready`)),!0}catch{return!1}})(),f=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`,{signal:r.signal});if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(T.current===n){let e=i.activeCodexAccountId??null,t=E.current;t&&e!==t.id||(E.current=null,u=e,o(e)),O.current={value:i};for(let e of a)e.acceptActiveRead(i,s.get(e))}return!0}catch{if(T.current===n)for(let e of a)e.rejectActiveRead();return!1}})(),[p,m]=await Promise.all([d,f]);if(T.current!==n)return!1;if(p){c(`ready`),j.current=!0;let t=Zi.get(e);return Zi.set(e,{accounts:l??t?.accounts??[],activeId:u===void 0?t?.activeId??null:u}),m}return j.current||c(`error`),!1}finally{r.clear(),g(e=>Math.max(0,e-1)),b(!0)}},[e]);(0,_.useEffect)(()=>{t&&w.current!==e&&(w.current=e,Promise.resolve().then(()=>{I()}))},[e,t,I]);let L=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!L||x>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{I(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,L,x,I]),(0,_.useEffect)(()=>{if(!(!t||x>0))return Jt(()=>{I()},Xi)},[t,I,x]);let R=(0,_.useCallback)(()=>{let e={};return C.current.add(e),S(C.current.size),e},[]),z=(0,_.useCallback)(e=>{C.current.delete(e)&&S(C.current.size)},[]),B=(0,_.useCallback)(async t=>{if(k.current)return{ok:!1,reason:`busy`};k.current=t??`__main__`,u(t??`__main__`);try{let n=await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t})});if(!n.ok)throw Error(`account switch failed`);let r=(await n.json().catch(()=>({}))).activeCodexAccountId??t;return E.current={id:r??null},o(r??null),I(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{k.current=null,u(null)}},[e,I]),V=(0,_.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 I(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,I]),H=(0,_.useCallback)(async(t,n)=>{if(M.current)return{ok:!1,reason:`busy`};M.current={accountId:t},f(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(()=>({})),s=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(s,`activeCodexAccountId`)){let e=s.activeCodexAccountId??null;E.current={id:e},o(e)}return I(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{M.current=null,f(null)}},[e,I]),U=(0,_.useCallback)(async()=>{if(M.current)return{ok:!1,reason:`busy`};M.current=`bulk`,m(!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;E.current={id:e},o(e)}return I(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{M.current=null,m(!1)}},[e,I]),W=(0,_.useCallback)(async t=>{try{return(await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(await I(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,I]),G=(0,_.useCallback)(async()=>await I()?{ok:!0}:{ok:!1,reason:`reload`},[I]),ee=a&&a!==`__main__`?r.find(e=>e.id===a):null,K=r.find(e=>e.isMain),q=ee??K,te=!q?.paused&&wi(q);return{accounts:r,activeId:a,loadState:s,refreshing:h>0,initialLoading:!v,switchingId:l,pauseUpdatingId:d,pausingExhausted:p,activeNeedsReauth:te,load:I,switchAccount:B,setAccountPaused:H,pauseExhaustedAccounts:U,saveAlias:V,removeAccount:W,syncAfterAccountAdded:G,pauseRefresh:R,resumeRefresh:z,subscribeLoadObserver:N,readLastThreshold:P,readLastActive:F}}function $i(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 ea({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,J.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,J.jsx)(xe,{width:10,height:10,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,J.jsx)(Se,{width:10,height:10,"aria-hidden":`true`})})]})}var ta={quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function na({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=Z(),m=(0,_.useRef)(!1),h=e>0,g=ta[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,J.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,J.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,J.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,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,J.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&&!v&&l()}},children:[a&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,J.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(ea,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s($i(t,1,1,100))},onDecrement:()=>{c(!0),s($i(t,-1,1,100))}})]})]}),(0,J.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,J.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:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,J.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,J.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var ra=[`quota`,`round-robin`,`fill-first`],ia=`quota`,aa=new Set(ra);function oa(e){return typeof e==`string`&&aa.has(e)?e:ia}function sa(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function ca(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function la(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};try{let r=await n(`${e}/api/codex-auth/pool-strategy`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t.strategy===void 0?{}:{strategy:t.strategy},...t.stickyLimit===void 0?{}:{stickyLimit:t.stickyLimit}})});if(!r.ok)return{ok:!1};let i=await r.json();return{ok:!0,strategy:oa(i.accountPoolStrategy??t.strategy),stickyLimit:sa(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var ua={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},da={quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function fa({strategy:e,stickyDraft:t,disabled:n=!1,strategySelectId:r=`account-pool-strategy`,stickyInputId:i=`account-pool-sticky-limit`,onStrategyChange:a,onStickyDraftChange:o,onStickyCommit:s}){let c=Z(),l=ra.map(e=>({value:e,label:c(ua[e])}));return(0,J.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(da[e])}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.unboundDefinition`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,J.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{id:i,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,disabled:n,"aria-label":c(`accountPool.stickyLimitAria`),onChange:e=>o(e.target.value),onBlur:()=>s(),onKeyDown:e=>{e.nativeEvent.isComposing||n||e.key===`Enter`&&(e.preventDefault(),s())}}),(0,J.jsx)(ea,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=$i(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=$i(t,-1,1,100);o(e),s(e)}})]})})]})]})}function pa(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:oa(t.accountPoolStrategy),stickyLimit:sa(t.accountPoolStickyLimit)}}function ma({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Z(),[a,o]=(0,_.useState)(ia),[s,c]=(0,_.useState)(1),[l,u]=(0,_.useState)(`1`),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(!1),y=(0,_.useRef)(0),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),w=(0,_.useCallback)(e=>{let t=oa(e.accountPoolStrategy),n=sa(e.accountPoolStickyLimit);o(t),r?.(t),c(n),u(String(n)),p.current=!0,f(!0),x(!1),C(null)},[r]),T=(0,_.useCallback)(e=>{let t=pa(e);t&&w({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[w]),E=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(g.current){v.current=!0;return}w(n)}catch{g.current||x(!0)}},[e,w]),D=(0,_.useCallback)(()=>{v.current&&(v.current=!1,queueMicrotask(()=>{if(g.current){v.current=!0;return}E()}))},[E]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>y.current,acceptActiveRead:(e,t)=>{if(t===y.current){if(g.current){v.current=!0;return}T(e)}},rejectActiveRead:()=>{p.current||x(!0)}});return!g.current&&n&&T(n()),e},[t,T,n]),(0,_.useEffect)(()=>{!n||t||g.current||T(n())},[n,T,t]),(0,_.useEffect)(()=>{t||E()},[E,t]);let O=(0,_.useCallback)(async t=>{if(g.current)return;let n=a,l=s;t.strategy!==void 0&&(o(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(c(t.stickyLimit),u(String(t.stickyLimit))),g.current=!0,h(!0),C(null),y.current+=1;let d=await la(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,J.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,J.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,J.jsx)(fa,{strategy:a,stickyDraft:l,disabled:k,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{k||e===a||O({strategy:e})},onStickyDraftChange:u,onStickyCommit:e=>{if(k)return;let t=ca(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function ha(e,t){let[n,r]=(0,_.useState)(80),[i,a]=(0,_.useState)(`80`),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(80),h=(0,_.useRef)(!1),g=(0,_.useRef)(80),v=(0,_.useRef)(!1),y=(0,_.useRef)(!1),b=(0,_.useRef)(!1),x=(0,_.useRef)(0),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useCallback)(e=>{m.current=e,h.current=!0,s(!0),r(e),e>0&&(g.current=e),a(String(e>0?e:g.current))},[]),T=(0,_.useCallback)(e=>{if(v.current||y.current){S.current=e;return}S.current=null,w(e)},[w]),E=(0,_.useCallback)(()=>{let e=S.current;return e===null?!1:(S.current=null,w(e),!0)},[w]),D=(0,_.useCallback)(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null),p(null)},[]),O=(0,_.useCallback)((e,t)=>{C.current!==null&&window.clearTimeout(C.current),p({tone:t?`err`:`ok`,message:e}),C.current=window.setTimeout(()=>{p(null),C.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{C.current!==null&&window.clearTimeout(C.current)},[]);let k=(0,_.useCallback)(()=>(h.current||l(!1),x.current),[]),A=(0,_.useCallback)((e,t)=>{l(!1);let n=qi(e),r=Ki(v.current,y.current,t,x.current);r===`defer`?S.current=Ui(n):r===`apply`&&T(Ui(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(Ui(qi(e))))},[w]),M=(0,_.useCallback)(()=>{h.current||l(!0)},[]),N=(0,_.useCallback)(async(n,r,i=!0)=>{if(y.current)return!1;y.current=!0,v.current=!1,D(),d(!0),x.current+=1;try{let a=await Yi(e,n);return x.current+=1,a?(S.current=null,w(n),i&&O(t.updated,!1)):(E()||w(r),O(t.updateFailed,!0)),a}finally{y.current=!1,d(!1)}},[e,w,D,t.updateFailed,t.updated,E,O]),P=(0,_.useCallback)(()=>{v.current=!1;let e=m.current;E()||a(String(e>0?e:g.current)),O(t.invalid,!0)},[t.invalid,E,O]),F=(0,_.useCallback)(()=>{v.current=!1,b.current=!0,D();let e=m.current;E()||a(String(e>0?e:g.current))},[D,E]),I=(0,_.useCallback)(async()=>{if(b.current)return b.current=!1,!0;if(!h.current||y.current)return!1;let e=m.current;v.current=!1;let t=Wi(i);return t===null?(P(),!1):t===e?(E()||a(String(t)),!0):N(t,e)},[i,E,P,N]),L=(0,_.useCallback)(async()=>{if(!h.current||y.current)return!1;let e=m.current;v.current=!1;let t=Ji(e,i,g.current),n=await N(t.threshold,e);return n?(g.current=t.lastEnabled,t.threshold===0&&a(String(t.lastEnabled)),n):!1},[i,N]);return{threshold:n,draft:i,hydrated:o,saving:u,loadError:c,feedback:f,beginServerRead:k,acceptServerRead:A,hydrateServerValue:j,rejectServerRead:M,setDraft:(0,_.useCallback)(e=>{h.current&&(v.current=!0,b.current=!1,D(),a(e))},[D]),setEditing:(0,_.useCallback)(e=>{v.current=e},[]),commit:I,cancel:F,toggle:L,retry:(0,_.useCallback)(()=>{l(!1),D()},[D])}}var ga=new Map;function _a(e,t){return`${e??``}\0${JSON.stringify(t)}`}function va(e,t){let n=_a(e,t??{}),r=ga.get(n);return r||(r=new Intl.NumberFormat(e,t),ga.set(n,r)),r}var ya={month:`short`,day:`numeric`,year:`numeric`},ba={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},xa=new Map;function Sa(e,t){let n=_a(e,t),r=xa.get(n);return r||(r=new Intl.DateTimeFormat(e,t),xa.set(n,r)),r}function Ca(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Sa(t,ya).format(n)}function wa(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Sa(t,ba).format(n)}function Ta(e,t){return!Number.isFinite(e)||e<0?`—`:`~${va(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function Ea(e,t){return Ca(e,t)}function Da(e,t){return wa(e,t)}function Oa(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function ka({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=Oa(n),s=o<=7;return(0,J.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,J.jsxs)(`div`,{className:`credit-item-head`,children:[(0,J.jsx)(Ae,{width:13}),(0,J.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,J.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,J.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,J.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:Ea(t,i)})}),(0,J.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:Da(n,i),days:String(o)})})]})]})}function Aa({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Ae,{width:12}),`0`]}):r===void 0?null:(0,J.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,J.jsx)(Ae,{width:12}),r]})}function ja({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;return(0,J.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${Math.max(r.length,i.length,a.length)}ch`},children:o})}function Ma({pool:e,activeId:t,accountModeState:n,switchActionLabel:r,threshold:i,onOpenReset:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onReauth:u,onEditAlias:d,onRemove:f,onCopyDoctor:p,doctorCopyOutcomeFor:m}){let h=Z(),g=e=>!e.paused&&t===e.id;return(0,J.jsx)(J.Fragment,{children:e.map(e=>{let t=e.health?.status,_=!!e.needsReauth||Ci(t),v=Ti(t),y=Oi(h,e.health),b=ki(h,`codex`,e.id,e.health);return(0,J.jsxs)(`div`,{className:`card ${g(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${_?`dot-amber`:g(e)?`dot-blue`:`dot-muted`}`}),(0,J.jsx)(`strong`,{children:e.alias??e.email}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:h(`codexAuth.pausedHint`),children:h(`codexAuth.paused`)}),(0,J.jsx)(Aa,{t:h,account:e,onClick:()=>a(e)}),y&&(0,J.jsx)(`span`,{className:Si(t),children:y}),_&&!y&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:h(`codexAuth.needsReauth`)}),g(e)&&!_&&!v&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:h(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!g(e)&&!_&&!v&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),_&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>u(e.id),children:h(`codexAuth.reauthenticate`)}),p&&Ei(t)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>p(e.id),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Mi(h,m?.(e.id))})}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?h(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${h(`codexAuth.resume`)}. ${h(`codexAuth.pausedHint`)}`:h(`codexAuth.pause`),children:[e.paused?(0,J.jsx)(ge,{width:14}):(0,J.jsx)(he,{width:14}),(0,J.jsx)(ja,{t:h,paused:e.paused,saving:c===e.id})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void d(e),children:h(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger card-right`,"aria-label":`${h(`common.remove`)} — ${e.email}`,title:`${h(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),f(e.id)},children:(0,J.jsx)(fe,{width:14})})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,h(`prov.accountId`),`: `,bi(e.id)]}),b&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:b}),v&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:h(`pws.healthCooldownHint`)}),_?(0,J.jsx)(`div`,{className:`card-sub faint`,children:h(`codexAuth.tokenExpired`)}):!v&&(0,J.jsx)($r,{quota:e.quota,plan:e.plan,threshold:i,t:h,pending:e.quota==null})]},e.id)})})}function Na({onReauth:e}){let t=Z();return(0,J.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(ve,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function Pa({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,onCancel:i,onConfirm:a}){let o=Z(),s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?o(`codexAuth.preparePoolTitle`):e.id===`__main__`?o(`codexAuth.switchBack`):o(`codexAuth.switchTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?o(`codexAuth.preparePoolDesc`):e.id===`__main__`?o(`codexAuth.switchBackDesc`):o(`codexAuth.switchDesc`)}),(0,J.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,J.jsx)(`strong`,{children:e.id===`__main__`?t||o(`codexAuth.codexApp`):e.email}),e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,J.jsxs)(`div`,{className:`notice-warn`,children:[(0,J.jsx)(ve,{width:14}),` `,o(`codexAuth.cacheWarning`)]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`codexAuth.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r,onClick:a,children:o(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function Fa({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=X(),d=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,J.jsx)(`div`,{className:`confirm-icon`,children:(0,J.jsx)(ve,{width:22})}),(0,J.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:Ea(n[0].granted_at,l)})}),(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,J.jsx)(Ae,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,J.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,J.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,J.jsx)(ka,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,J.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function Ia({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onOpenReset:u,onCopyDoctor:d,doctorCopyOutcomeFor:f}){let p=e(`codexAuth.codexApp`),m=t?.id??`__main__`,h={id:`__main__`,email:t?.email||p,plan:t?.plan,isMain:!0,paused:t?.paused??!1,hasCredential:!0,quota:t?.quota??null},g=!!t?.needsReauth||Ci(t?.health?.status),_=Ti(t?.health?.status),v=Oi(e,t?.health),y=t?ki(e,`codex`,m,t.health):null;return(0,J.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${g?`dot-amber`:`dot-green`}`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,J.jsx)(Aa,{t:e,account:{...t,id:`__main__`},onClick:()=>u({...t,id:`__main__`})}),t?.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),v&&(0,J.jsx)(`span`,{className:Si(t?.health?.status),children:v}),g&&!v&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,J.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&!n&&!g&&!_&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(h),children:a}),d&&Ei(t?.health?.status)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>d(m),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Mi(e,f?.(m))})}),t&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(h),disabled:l,title:t.paused?e(`codexAuth.pausedHint`):void 0,"aria-label":t.paused?`${e(`codexAuth.resume`)}. ${e(`codexAuth.pausedHint`)}`:e(`codexAuth.pause`),children:[t.paused?(0,J.jsx)(ge,{width:14}):(0,J.jsx)(he,{width:14}),(0,J.jsx)(ja,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(ke,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),y&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:y}),_&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),g?(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!_&&(0,J.jsx)($r,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function La({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,J.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,J.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,J.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,J.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,J.jsx)(he,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,J.jsx)(me,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function Ra({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,J.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,J.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot dot-muted`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Ae,{width:12}),`0`]}),(0,J.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(he,{width:14}),` `,e(`codexAuth.pause`)]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(ke,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,J.jsx)($r,{quota:null,threshold:0,t:e,pending:!0})]}),(0,J.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(pe,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,J.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,J.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,J.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function za(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Ba(e,t,n,r){try{let i=await _t(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:za(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`)}}}var Va=`ocx doctor`;function Ha({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a}){let o=Z(),s=ha(e,{updated:o(`codexAuth.autoSwitchUpdated`),updateFailed:o(`codexAuth.autoSwitchUpdateFailed`),invalid:o(`codexAuth.autoSwitchThresholdInvalid`)}),[c,l]=(0,_.useState)(null),{beginServerRead:u,acceptServerRead:d,rejectServerRead:f,hydrateServerValue:p}=s,m=Qi(e,!a),h=a??m,{accounts:g,activeId:v,loadState:y,switchingId:b,pauseUpdatingId:x,pausingExhausted:S,load:C}=h,[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(null),P=(0,_.useRef)(null),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(null),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(null),[G,ee]=(0,_.useState)(!1),K=Li(),q=(0,_.useCallback)((e,t=!1)=>{P.current&&clearTimeout(P.current),j(e),N(t?`err`:`ok`),P.current=setTimeout(()=>{j(null),N(null),P.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{P.current&&clearTimeout(P.current)},[]);let te=(0,_.useCallback)(e=>{K.copy(Va,e)},[K]),{subscribeLoadObserver:Y,readLastThreshold:ne}=h;(0,_.useEffect)(()=>Y({beginActiveRead:u,acceptActiveRead:d,rejectActiveRead:f}),[Y,u,d,f]),(0,_.useEffect)(()=>{let e=ne();e!==void 0&&p(e)},[ne,p]),(0,_.useEffect)(()=>{if(!E)return;let e=h.pauseRefresh();return()=>h.resumeRefresh(e)},[h,E]);let re=v&&v!==`__main__`?g.find(e=>e.id===v):null,ie=!re?.paused&&wi(re);(0,_.useEffect)(()=>{i?.(ie)},[ie,i]);let ae=(0,_.useCallback)(e=>{k(e),D(!0)},[]),oe=(0,_.useCallback)(()=>{D(!1),k(null)},[]),se=(0,_.useCallback)(()=>{h.syncAfterAccountAdded(),q(o(`codexAuth.accountAdded`)),oe()},[oe,h,q,o]),ce=async e=>{let n=await h.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;q(o(`codexAuth.switchFailed`),!0);return}T(null);let r=n.activeId,i=r&&r!==`__main__`?g.find(e=>e.id===r)?.email??o(`pws.accountOrdinal`,{count:`1`}):o(`codexAuth.mainAccount`);q(o(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},le=async e=>{let t=window.prompt(o(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await h.saveAlias(e.id,t);q(o(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),!n.ok)},ue=async e=>{let t=!e.paused,n=await h.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(T(t=>t?.id===e.id?null:t),q(o(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),!n.ok))},de=async e=>{let t=g.find(t=>t.id===e)?.email??o(`pws.accountOrdinal`,{count:`1`});window.confirm(o(`codexAuth.removeConfirm`,{id:t}))&&((await h.removeAccount(e)).ok||q(o(`codexAuth.removeFailed`),!0))},fe=async()=>{I(!0);try{let e=await C(!0);q(o(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),!e)}finally{I(!1)}},me=async()=>{let e=await h.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||q(e.ok?e.pausedCount>0?o(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):o(`codexAuth.pauseExhaustedNone`):o(`codexAuth.pauseExhaustedFailed`),!e.ok)},he=async t=>{R(t),B(!1),W(null),ee(!0);try{let n=await _t(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));n&&W((n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime()))}catch{}finally{ee(!1)}},ge=async t=>{H(!0);try{let n=await Ba(e,t,o,C);n.close&&(R(null),B(!1)),n.toast&&q(n.toast,!n.ok)}finally{H(!1)}},_e=g.find(e=>e.isMain),ve=g.filter(e=>!e.isMain),ye=!_e?.paused&&(!v||v===`__main__`),be=o(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),xe=x!==null||S,Se=s.threshold??0;return(0,J.jsxs)(`div`,{children:[(0,J.jsx)(La,{t:o,embedded:r,refreshingQuota:F,actionFeedback:A,actionFeedbackTone:M,pausingExhausted:S,pauseBusy:xe,onRefresh:()=>{fe()},onPauseExhausted:()=>{me()}}),n,(0,J.jsx)(Ra,{t:o,loadState:y,accountsCount:g.length,onRetry:()=>{C()}}),!(y===`loading`&&g.length===0)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Ia,{t:o,main:_e,isMainActive:ye,accountModeState:t,threshold:Se,switchActionLabel:be,onSwitch:T,onTogglePause:ue,pauseUpdatingId:x,pauseBusy:xe,onOpenReset:he,onCopyDoctor:te,doctorCopyOutcomeFor:K.outcomeFor}),(0,J.jsxs)(`div`,{className:`section-sep`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:o(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>D(!0),children:[(0,J.jsx)(pe,{width:14}),` `,o(`codexAuth.add`)]})]}),ie&&re&&(0,J.jsx)(Na,{onReauth:()=>ae(re.id)}),ve.length===0&&(0,J.jsx)(pt,{title:o(`codexAuth.noPool`)}),(0,J.jsx)(Ma,{pool:ve,activeId:v,accountModeState:t,switchActionLabel:be,threshold:Se,onOpenReset:he,onSwitch:T,onTogglePause:ue,pauseUpdatingId:x,pauseBusy:xe,onReauth:ae,onEditAlias:le,onRemove:de,onCopyDoctor:te,doctorCopyOutcomeFor:K.outcomeFor})]}),c!==null&&(0,J.jsx)(na,{threshold:s.threshold,draft:s.draft,strategy:c,hydrated:s.hydrated,saving:s.saving,loadError:s.loadError,feedback:s.feedback,onDraftChange:s.setDraft,onEditingChange:s.setEditing,onCommit:s.commit,onCancel:s.cancel,onToggle:s.toggle,onRetry:()=>{s.retry(),C()}}),(0,J.jsx)(ma,{apiBase:e,subscribeLoadObserver:h.subscribeLoadObserver,readLastActive:h.readLastActive,onStrategyResolved:l}),w&&(0,J.jsx)(Pa,{confirm:w,mainEmail:_e?.email,accountModeState:t,switchingId:b,onCancel:()=>T(null),onConfirm:()=>{ce(w.id===`__main__`?`__main__`:w.id)}}),L&&(0,J.jsx)(Fa,{resetPopup:L,resetConfirm:z,creditDetails:U,creditDetailsLoading:G,redeeming:V,onClose:()=>{R(null),B(!1),W(null)},onShowConfirm:()=>B(!0),onCancelConfirm:()=>B(!1),onRedeem:()=>{ge(L.id)}}),E&&(0,J.jsx)(Vi,{apiBase:e,reauthAccountId:O??void 0,onClose:oe,onAdded:se})]})}function Ua({apiBase:e,accountCount:t}){let n=Z(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(`80`),[s,c]=(0,_.useState)(`1`),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let t=!1,n=new AbortController;return Promise.resolve().then(()=>fetch(`${e}/api/oauth/accounts/pool?provider=anthropic`,{signal:n.signal})).then(e=>{if(!e.ok)throw Error(`load`);return e.json()}).then(e=>{if(t)return;let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=sa(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:oa(e.strategy),stickyLimit:r}),o(String(n)),c(String(r)),m(!1)}).catch(()=>{t||n.signal.aborted||m(!0)}),()=>{t=!0,n.abort()}},[e]);let h=(0,_.useCallback)(async t=>{let a=r;i({enabled:t.enabled,threshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit}),u(!0),f(null);try{let n=await fetch(`${e}/api/oauth/accounts/pool`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:`anthropic`,enabled:t.enabled,autoSwitchThreshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit})});if(!n.ok)throw Error(`save`);let r=await n.json().catch(()=>null),a=oa(r?.strategy??t.strategy),s=sa(r?.stickyLimit??t.stickyLimit);i({enabled:t.enabled,threshold:t.threshold,strategy:a,stickyLimit:s}),o(String(t.threshold)),c(String(s))}catch{f(n(`anthropicPool.saveFailed`)),a&&(i(a),o(String(a.threshold)),c(String(a.stickyLimit)))}finally{u(!1)}},[e,r,n]),g=r?.enabled===!0,v=r?.threshold??80,y=r?.strategy??`quota`,b=r?.stickyLimit??1,x=r===null&&!p,S=x||l||p||!g&&t<2;return(0,J.jsxs)(`div`,{className:`card`,style:{marginTop:12},"aria-busy":x||l,children:[(0,J.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,J.jsxs)(`div`,{style:{flex:1},children:[(0,J.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:p?n(`anthropicPool.loadFailed`):x?n(`common.loading`):g?n(`anthropicPool.enabledDesc`,{threshold:v}):n(`anthropicPool.disabledDesc`)})]}),(0,J.jsxs)(`label`,{className:`toggle`,style:{display:`inline-flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:g,disabled:S,onChange:e=>{let t=e.target.checked;h({enabled:t,threshold:v,strategy:y,stickyLimit:b})}}),(0,J.jsx)(`span`,{children:n(g?`anthropicPool.on`:`anthropicPool.off`)})]})]}),(0,J.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:10,padding:`8px 10px`,border:`1px solid var(--border, #c9a227)`,borderRadius:6,background:`color-mix(in srgb, var(--warn, #c9a227) 12%, transparent)`},children:n(`anthropicPool.experimentalWarning`)}),t<2&&(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`field`,style:{display:`block`,marginTop:12},children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:a,disabled:l,"aria-label":n(`anthropicPool.thresholdAria`),onChange:e=>o(e.target.value),onBlur:()=>{let e=Number(a);if(!Number.isInteger(e)||e<0||e>100){o(String(v)),f(n(`anthropicPool.thresholdInvalid`));return}e!==v&&h({enabled:!0,threshold:e,strategy:y,stickyLimit:b})}}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,J.jsx)(fa,{strategy:y,stickyDraft:s,disabled:l,strategySelectId:`anthropic-pool-strategy`,stickyInputId:`anthropic-pool-sticky-limit`,onStrategyChange:e=>{e!==y&&h({enabled:!0,threshold:v,strategy:e,stickyLimit:b})},onStickyDraftChange:c,onStickyCommit:e=>{let t=ca(e??s);if(t===null){c(String(b)),f(n(`accountPool.stickyLimitInvalid`));return}if(t===b){c(String(t));return}h({enabled:!0,threshold:v,strategy:y,stickyLimit:t})}})]}),d&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}var Wa=`ocx doctor`,Ga=4e3,Ka=[],qa=[];function Ja({item:e,apiBase:t,oauth:n,accounts:r=Ka,keys:i=qa,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d}){let f=Z(),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(!1),S=Li(),C=Li();(0,_.useEffect)(()=>{if(r.length===0){x(!1);return}if(!r.some(e=>e.quota==null&&!e.quotaUnavailable)){x(!1);return}x(!0);let e=window.setTimeout(()=>x(!1),Ga);return()=>window.clearTimeout(e)},[r]);let w=pi({...e,hasApiKey:e.hasApiKey||i.length>0}),T=w===`oauth-accounts`,E=w===`api-keys`;if(w===`codex-accounts`)return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(`pws.availableAccounts`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:f(`pws.availableAccounts`)}),(0,J.jsx)(`div`,{className:`pwi-auth-body`,children:(0,J.jsx)(Ha,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!w||!l)return null;let D=c?.provider===e.name?c:null,O=D?.deviceCode??``,k=S.outcomeFor(O),A=f(k===`copied`?`prov.codeCopied`:k===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),j=r.length>0||n?.loggedIn===!0,M=r.find(e=>e.active&&e.needsReauth),N=!!M,P=async()=>{let t=h.trim();if(t){y(!0);try{await l.onAddApiKey(e.name,t)&&(g(``),m(!1))}finally{y(!1)}}};return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(T?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:f(T?`pws.availableAccounts`:`pws.apiKeys`)}),(0,J.jsxs)(`div`,{className:`pwi-auth-body`,children:[T&&(0,J.jsxs)(J.Fragment,{children:[e.name===`anthropic`&&(0,J.jsx)(Ua,{apiBase:t,accountCount:r.length}),(0,J.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${N?`pwi-auth-dot--warn`:j?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`pwi-auth-status-text`,children:j?r.length>0?f(`pws.loggedInTitle`):n?.email??f(`pws.loggedInTitle`):n?.error||f(`pws.notLoggedInTitle`)}),(0,J.jsxs)(`span`,{className:`pwi-auth-actions`,children:[M&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,M.id),children:f(`pws.reauthenticate`)}),j?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:f(`prov.logout`)}):(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,J.jsx)(ke,{style:{width:13,height:13},"aria-hidden":`true`}),f(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),s&&D&&(0,J.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,J.jsx)(`div`,{className:`pwi-auth-wait-title`,children:f(`prov.waitingBrowser`)}),D.deviceCode&&(0,J.jsxs)(`div`,{className:`pwi-device-code-wrap`,children:[(0,J.jsx)(`span`,{children:f(`prov.deviceCode`)}),(0,J.jsx)(`code`,{className:`pwi-device-code`,children:D.deviceCode}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>S.copy(O,O),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:A})})]}),(0,J.jsx)(Ri,{url:D.url??``}),l.onCancelLogin&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onCancelLogin?.(e.name),children:f(`common.cancel`)})]})]}),a===`loading`&&r.length===0&&(0,J.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),f(`pws.accountsLoading`)]}),a===`error`&&(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:f(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:f(`pws.retryAccounts`)})]}),r.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=mi(r,t,f),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||Ci(a),u=Ei(a),d=Ti(a),p=bi(t.id),m=Oi(f,t.health),h=ki(f,e.name,t.id,t.health);return(0,J.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,J.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!d&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${f(`pws.accountCurrent`)}`:``}`,disabled:!!(c||d||o&&!i),children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${c?`pwi-auth-dot--warn`:t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${f(`prov.accountId`)}: ${p}`].filter(Boolean).join(` · `)}),h&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:h}),d&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:f(`pws.healthCooldownHint`)})]}),m&&(0,J.jsx)(`span`,{className:Si(a),children:m}),c&&!m&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:f(`pws.reauth`)}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)}),i&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:f(`pws.accountSwitching`)})]}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s||!!o,onClick:()=>void l.onReauth(e.name,t.id),children:f(`pws.reauthenticate`)}),u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{C.copy(Wa,t.id)},children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Mi(f,C.outcomeFor(t.id))})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`oauth`,t.id,t.alias),children:f(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${f(`common.remove`)} — ${n}`,title:`${f(`common.remove`)} — ${n}`,disabled:!!o,onClick:()=>void l.onRemoveAccount(e.name,t),children:(0,J.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||b&&t.quota==null)&&(0,J.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,J.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:f(`pws.accountQuotaUnavailable`)}):(0,J.jsx)($r,{quota:t.quota??null,plan:null,threshold:80,t:f,layout:`stacked`,pending:t.quota==null})})]},t.id)})}),a===`ready`&&j&&r.length===0&&(0,J.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:f(`pws.noAccounts`)}),j&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>void l.onLogin(e.name,!0),disabled:s||!!o,children:f(`pws.addAccount`)})]}),E&&(0,J.jsxs)(J.Fragment,{children:[i.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,J.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,J.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,f(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`api-key`,t.id,t.label),children:f(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${f(`common.remove`)} — ${t.label??t.masked}`,title:`${f(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void l.onRemoveApiKey(e.name,t),children:(0,J.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),p?(0,J.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,J.jsx)(`input`,{className:`input`,type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:v}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void P(),disabled:v||!h.trim(),children:f(v?`pws.saving`:`pws.addKey`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m(!1),g(``)},children:f(`common.cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>m(!0),children:f(`pws.addKey`)})]})]})]})}function Ya(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 Xa(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 Za(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Qa=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],$a=[];function $({item:e,availableModels:t=$a,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Z(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),[c,l]=(0,_.useState)(e.adapter),[u,d]=(0,_.useState)(e.baseUrl),[f,p]=(0,_.useState)(e.defaultModel??``),[m,h]=(0,_.useState)(s),[g,v]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[y,b]=(0,_.useState)(e.note??``),[x,S]=(0,_.useState)(e.allowPrivateNetwork??!1),[C,w]=(0,_.useState)(e.liveModels!==!1),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(),[j,M]=(0,_.useState)(n?`loading`:`idle`),[N,P]=(0,_.useState)(()=>`custom`);(0,_.useEffect)(()=>{l(e.adapter),d(e.baseUrl),p(e.defaultModel??``),h(String(e.authMode??(e.keyOptional?`local`:`key`))),v(e.apiKeyTransport??`x-api-key`),b(e.note??``),S(e.allowPrivateNetwork??!1),w(e.liveModels!==!1),O(null),queueMicrotask(()=>P(Xa(k,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,e.liveModels,k]),(0,_.useEffect)(()=>{if(!n)return;let t=!1,r=e.name,i=e.baseUrl;return fetch(`${n}/api/provider-presets`).then(e=>_t(e)).then(e=>{if(t)return;if(!e){A(void 0),M(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;A(n),M(`ready`),P(Xa(n,i))}).catch(()=>{t||(A(void 0),M(`error`))}),()=>{t=!0}},[n,e.name]);let F=c.trim()!==e.adapter||u.trim()!==e.baseUrl||f.trim()!==(e.defaultModel??``)||m!==String(e.authMode??(e.keyOptional?`local`:`key`))||c.trim()===`anthropic`&&m===`key`&&g!==(e.apiKeyTransport??`x-api-key`)||y.trim()!==(e.note??``)||x!==(e.allowPrivateNetwork??!1)||C!==(e.liveModels!==!1);(0,_.useEffect)(()=>(i?.(F),()=>i?.(!1)),[F,i]);let I=(0,_.useMemo)(()=>{let n=new Set(t);return f.trim()&&n.add(f.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,f,e.defaultModel]),L=(0,_.useMemo)(()=>{let e=[...Qa];return c&&!e.includes(c)&&e.unshift(c),e},[c]),R=jr(e.name),z=j===`ready`&&!!(k&&k.length>0),B=c.trim()===`anthropic`&&m===`key`,V=R&&j!==`error`,H=async()=>{if(!r)return O({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;let t=z?Za(k,N,u):u.trim();if(!c.trim()||!t)return O({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;E(!0),O(null);try{let n={adapter:c.trim(),baseUrl:t,defaultModel:f.trim(),authMode:m,note:y.trim(),allowPrivateNetwork:x};C!==(e.liveModels!==!1)&&(n.liveModels=C),B?n.apiKeyTransport=g:e.apiKeyTransport!==void 0&&(n.apiKeyTransport=``);let i=await r(e.name,n);return O(i.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:i.error||o(`prov.saveFailed`)}),i.ok}finally{E(!1)}},U=(0,_.useRef)(H);(0,_.useEffect)(()=>{U.current=H}),(0,_.useEffect)(()=>{if(a)return a(()=>U.current()),()=>a(null)},[a]);let W=()=>{l(e.adapter),d(e.baseUrl),p(e.defaultModel??``),h(s),v(e.apiKeyTransport??`x-api-key`),b(e.note??``),S(e.allowPrivateNetwork??!1),w(e.liveModels!==!1),O(null),P(Xa(k,e.baseUrl))},G=(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,J.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,J.jsx)(ke,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,J.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),R?(0,J.jsx)(`input`,{className:`input`,value:c,readOnly:!0,disabled:!0}):(0,J.jsx)(`select`,{className:`input`,value:c,onChange:e=>l(e.target.value),children:L.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})]}),z?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,J.jsx)(`select`,{className:`input`,value:N,onChange:e=>{let t=e.target.value;P(t),d(Ya(k,t,u))},children:k.map(e=>(0,J.jsx)(`option`,{value:e.id,children:G(e.id,e.label)},e.id))})]}),N===`custom`&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),readOnly:V,disabled:V})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),I.length>0?(0,J.jsxs)(`select`,{className:`input`,value:f,onChange:e=>p(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),I.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}):(0,J.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),R?(0,J.jsx)(`input`,{className:`input`,value:Nr(e,o),readOnly:!0,disabled:!0}):(0,J.jsxs)(`select`,{className:`input`,value:m,onChange:e=>h(e.target.value),children:[(0,J.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,J.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,J.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,J.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),B&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,J.jsxs)(`select`,{className:`input`,value:g,onChange:e=>v(e.target.value),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,J.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:y,onChange:e=>b(e.target.value),rows:2})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,J.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),F&&(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,J.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:W,disabled:T,children:o(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void H(),disabled:T,children:o(T?`pws.saving`:`pws.saveSettings`)})]})]}),D&&(0,J.jsx)(`div`,{className:D.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:D.text})]})}function eo({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Z();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,J.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function to({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Z();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,J.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function no({item:e,usageTotals:t,modelUsage:n,quotaReport:r,availableModels:i,hasLiveModels:a,selectedModels:o,modelsLoading:s,modelsLoadFailed:c,onRetryModels:l,oauthEmail:u,onDeselect:d,apiBase:f,oauth:p,accounts:m,accountLoadState:h,switchingAccountId:g,keys:v,busyProvider:y,loginHint:b,authHandlers:x,onCodexActiveNeedsReauthChange:S,codexController:C,onUpdateProvider:w,isDefault:T,onRemoveProvider:E,onSetDisabled:D,onSetDefault:O}){let k=Z(),[A,j]=(0,_.useState)(`overview`),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)(!1),R=(0,_.useRef)(null),z=(0,_.useCallback)(e=>{R.current=e},[]),B=e.disabled===!0,V=(0,_.useMemo)(()=>tr(e),[e]),H=(0,_.useMemo)(()=>cr(e),[e]),U=(0,_.useMemo)(()=>pi(e),[e]),W=JSON.stringify([C?.activeId??``,m?.find(e=>e.active)?.id??``,v?.find(e=>e.active)?.id??``,p?.loggedIn===void 0?``:String(p.loggedIn),p?.needsReauth===void 0?``:String(p.needsReauth),u??``]),G=(0,_.useMemo)(()=>[{id:`overview`,label:k(`pws.tab.overview`)},{id:`models`,label:k(`pws.tab.models`)},{id:`usage`,label:k(`pws.tab.usage`)},...U?[{id:`accounts`,label:k(U===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:k(`pws.tab.settings`)}],[U,k]),ee=(0,_.useCallback)(e=>{if(M&&A===`settings`&&e!==`settings`){F(e);return}j(e)},[A,M]),K=(0,_.useCallback)(()=>{if(M&&A===`settings`){F(`deselect`);return}d()},[M,A,d]),q=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%G.length;else if(e.key===`ArrowLeft`)n=(t-1+G.length)%G.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=G.length-1;else return;e.preventDefault(),ee(G[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ee,G]),te=`pws-tab-${A}`,Y=`pws-panel-${A}`;return(0,J.jsxs)(`div`,{className:`pws-detail`,children:[(0,J.jsx)(`div`,{className:`pws-detail-head`,children:(0,J.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:K,children:[(0,J.jsx)(we,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),k(`pws.allProviders`)]})}),(0,J.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,J.jsx)(Fr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,J.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,J.jsxs)(`h2`,{className:`pws-detail-title`,children:[Ar(e.name,k),H&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:k(`modal.badge.local`)}),!H&&V&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:k(`modal.badge.free`)})]})}),(0,J.jsxs)(`div`,{className:`pws-detail-actions`,children:[!T&&!B&&O&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>O(e.name),children:k(`prov.setDefault`)}),E&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>E(e.name),"aria-label":k(`pws.removeConfirmTitle`),title:k(`pws.removeConfirmTitle`),children:(0,J.jsx)(_e,{style:{width:15,height:15},"aria-hidden":`true`})}),D&&(0,J.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,J.jsx)(`span`,{className:`pws-detail-toggle-label`,children:k(`pws.enabledLabel`)}),(0,J.jsx)(ut,{on:!B,onClick:()=>D(e.name,!B),disabled:T,label:k(`pws.enabledLabel`)})]})]})]}),(0,J.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:G.map((e,t)=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":A===e.id,tabIndex:A===e.id?0:-1,className:`pws-detail-tab${A===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ee(e.id),onKeyDown:e=>q(e,t),children:e.label},e.id))}),(0,J.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:Y,"aria-labelledby":te,tabIndex:0,children:[A===`overview`&&(0,J.jsx)(hi,{accountPanel:U?(0,J.jsx)(Ja,{item:e,apiBase:f,oauth:p,accounts:m,keys:v,accountLoadState:h,switchingAccountId:g,busy:y===e.name,loginHint:b,authHandlers:x,onCodexActiveNeedsReauthChange:S,codexController:C}):void 0,item:e,apiBase:f,connectionIdentity:W,usageTotals:t,quotaReport:r,oauthEmail:u,onEditSettings:()=>ee(`settings`),onViewUsage:()=>ee(`usage`),onUpdateProvider:w,reauthBusy:y===e.name,onCancelLogin:x?.onCancelLogin?()=>void x.onCancelLogin?.(e.name):void 0,onReauthenticate:e.activeNeedsReauth?()=>{if(e.authMode===`oauth`){let t=m??[],n=t.find(e=>e.active&&e.needsReauth)??t.find(e=>e.needsReauth);x?.onReauth(e.name,n?.id);return}ee(`accounts`)}:void 0}),A===`models`&&(0,J.jsx)(_i,{item:e,apiBase:f,availableModels:i,hasLiveModels:a,selectedModels:o,modelsLoading:s,modelsLoadFailed:c,needsReauth:(m??[]).some(e=>e.active&&e.needsReauth)||p?.needsReauth===!0,onRetryModels:l,onOpenAccounts:U?()=>ee(`accounts`):void 0},e.name),A===`usage`&&(0,J.jsx)(vi,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),A===`accounts`&&(0,J.jsx)(Ja,{item:e,apiBase:f,oauth:p,accounts:m,keys:v,accountLoadState:h,switchingAccountId:g,busy:y===e.name,loginHint:b,authHandlers:x,onCodexActiveNeedsReauthChange:S,codexController:C}),A===`settings`&&(0,J.jsx)($,{item:e,apiBase:f,availableModels:i,onUpdateProvider:w,onDirtyChange:N,onRegisterSave:z},e.name)]}),P&&(0,J.jsx)(to,{saving:I,onCancel:()=>{I||F(null)},onDiscard:()=>{if(I)return;let e=P;F(null),N(!1),e===`deselect`?d():j(e)},onSave:()=>{(async()=>{if(!I){L(!0);try{if(!(await R.current?.()??!1))return;let e=P;F(null),N(!1),e===`deselect`?d():e&&j(e)}finally{L(!1)}}})()}})]})}var ro=`https://chatgpt.com/backend-api/codex`;function io(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 ao(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 oo(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||io(e.baseUrl)!==ro?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function so(e){return e.id===`openai`}function co(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function lo(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),t}function uo(e,t){return so(e)?fo(e):{name:t.name.trim(),provider:lo(t)}}function fo(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var po=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function mo(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 po(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new po(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new po(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(fo(i))})).ok)throw new po(`codexAuth.enableOpenaiFailed`)}var ho=new Set([`anthropic`,`google-antigravity`]),go=new Set([`github-copilot`,`cursor`]);function _o(e){let t=e.trim().toLowerCase();return ho.has(t)?`high`:go.has(t)?`elevated`:null}function vo(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function yo(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function bo(e,t=!1){let n={};for(let[t,r]of Object.entries(e))wi(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function xo(e){let{apiBase:t,t:n,config:r,aliveRef:i,notify:a,fetchConfig:o,fetchOauth:s,fetchProviderQuotas:c,codexActiveNeedsReauth:l}=e,[u,d]=(0,_.useState)({}),[f,p]=(0,_.useState)({}),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)({}),[y,b]=(0,_.useState)({}),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(``),T=(0,_.useRef)({}),E=(0,_.useRef)(null),D=(0,_.useRef)(null),O=(0,_.useRef)(null),k=(0,_.useCallback)(async e=>{let n=[...new Set(e)];return p(e=>{let t={...e};for(let e of n)t[e]=`loading`;return t}),(await Promise.all(n.map(async e=>{let n=(T.current[e]??0)+1;T.current[e]=n;try{let r=await fetch(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`);if(!r.ok)throw Error(String(r.status));let a=await r.json();return!i.current||T.current[e]!==n?!0:(d(t=>({...t,[e]:{activeAccountId:a.activeAccountId??null,accounts:a.accounts??[]}})),p(t=>({...t,[e]:`ready`})),(async()=>{try{let r=await fetch(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}&quota=1`);if(!r.ok)return;let o=await r.json();if(!i.current||T.current[e]!==n)return;d(t=>({...t,[e]:{activeAccountId:o.activeAccountId??a.activeAccountId??null,accounts:o.accounts??a.accounts??[]}}))}catch{}})(),!0)}catch{return!i.current||T.current[e]!==n?!0:(p(t=>({...t,[e]:`error`})),!1)}}))).every(Boolean)},[i,t]),A=(0,_.useCallback)(async e=>{let n=await Promise.all(e.map(async e=>[e,(await fetch(`${t}/api/providers/keys?name=${encodeURIComponent(e)}`).then(async e=>{if(!e.ok)throw Error(String(e.status));return e.json()}).catch(()=>null))?.keys??[]]));b(Object.fromEntries(n))},[t]),j=async(e,r)=>{if(r.active||r.needsReauth||O.current)return;let o={provider:e,accountId:r.id};O.current=o,h(o);let l=mi(u[e]?.accounts??[r],r,n);try{if(!(await fetch(`${t}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:r.id})})).ok){a(n(`prov.accountSwitchFail`),!1);return}let i=await k([e]);if(await Promise.all([s(),c(!0)]),!i){a(n(`pws.accountsLoadFailed`),!1);return}a(n(`prov.accountSwitched`,{email:l}),!0)}catch{a(n(`prov.accountSwitchFail`),!1)}finally{O.current?.provider===o.provider&&O.current.accountId===o.accountId&&(O.current=null,i.current&&h(null))}},M=async(e,r)=>{if(r.active)return;let i=await fetch(`${t}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:r.id})});i.ok?(a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),A(Object.keys(y)),c(!0)):a((await i.json().catch(()=>({}))).error||n(`prov.keySwitchFail`),!1)},N=async(e,r)=>{window.confirm(n(`prov.keyRemoveConfirm`,{key:r.label??r.masked}))&&(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),A(Object.keys(y)),o(),c(!0))},P=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})});return r.ok?(a(n(`prov.keyAdded`,{name:e}),!0),S(null),await Promise.all([A(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),o(),c(!0)]),!0):(a((await r.json().catch(()=>({}))).error||n(`prov.keyAddFail`),!1),!1)}catch{return a(n(`prov.keyAddFail`),!1),!1}},F=async e=>{await P(e,C)&&w(``)},I=async(e,r,i,o)=>{let s=window.prompt(n(`prov.aliasPrompt`),o??``);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){a((await l.json().catch(()=>({}))).error||n(`prov.aliasSaveFailed`),!1);return}r===`oauth`?await k([e]):await A(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),a(n(`prov.aliasSaved`),!0)},L=async(e,r)=>{let i=mi(u[e]?.accounts??[r],r,n);if(window.confirm(n(`prov.accountRemoveConfirm`,{email:i})))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 k([e]),await Promise.all([s(),c(!0)])}catch{a(n(`prov.accountRemoveFail`,{email:i}),!1)}},R=(0,_.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[r]);(0,_.useEffect)(()=>{if(R.length===0)return;let e=R.join(`,`);E.current!==e&&(E.current=e,Promise.resolve().then(()=>{k(R)}))},[k,R]);let z=(0,_.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[r]);return(0,_.useEffect)(()=>{if(z.length===0)return;let e=z.join(`,`);D.current!==e&&(D.current=e,Promise.resolve().then(()=>{A(z)}))},[A,z]),{accountSets:u,accountLoadStates:f,switchingAccount:m,openAccounts:g,keyPools:y,addingKeyFor:x,newKeyValue:C,setAccountSets:d,setAccountLoadStates:p,setSwitchingAccount:h,setOpenAccounts:v,setKeyPools:b,setAddingKeyFor:S,setNewKeyValue:w,fetchAccountSets:k,fetchKeyPools:A,switchAccount:j,switchApiKey:M,removeApiKey:N,addApiKeyValue:P,addApiKey:F,editCredentialAlias:I,removeAccount:L,oauthCardProviders:R,keyCardProviders:z,activeAccountNeedsReauth:(0,_.useMemo)(()=>bo(u,l),[u,l])}}function So(e){let{apiBase:t,config:n,notify:r,fetchConfig:i,fetchProviderQuotas:a,onSaved:o,t:s}=e,[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),x=(0,_.useRef)(!1);(0,_.useEffect)(()=>{n&&!x.current&&d(JSON.stringify(n,null,2))},[n]);let S=(0,_.useCallback)(async()=>{v(!0);try{let e=JSON.parse(u),n=await fetch(`${t}/api/config`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});return n.ok?(r(s(`prov.saved`),!0),l(!1),p(!1),x.current=!1,b(!1),h(JSON.stringify(e,null,2)),i(),a(!0),o(),!0):(r((await n.json().catch(()=>({}))).error||s(`prov.saveFailed`),!1),!1)}catch{return r(s(`prov.invalidJson`),!1),!1}finally{v(!1)}},[t,u,i,a,r,o,s]),C=(0,_.useCallback)(()=>{let e=n?JSON.stringify(n,null,2):u;h(e),d(e),b(!1),p(!0),x.current=!0},[n,u]),w=(0,_.useCallback)(()=>{b(!1),p(!1),x.current=!1;let e=n?JSON.stringify(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:y,jsonEditorOpenRef:x,saveConfig:S,openJsonEditor:C,discardJsonEditor:w,requestCloseJsonEditor:(0,_.useCallback)(()=>{if(f&&u!==m){b(!0);return}w()},[w,u,m,f]),restoreJsonEditor:(0,_.useCallback)(()=>{d(m)},[m]),jsonIsDirty:f&&u!==m,setJsonLeaveOpen:b}}var Co={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},wo=e=>Co[e]??e;function To({apiBase:e,t,aliveRef:n,oauthLoginGenerationRef:r,accountSets:i,setBusy:a,setStatus:o,setLoginInfo:s,setOauthStatus:c,notify:l,fetchConfig:u,fetchOauth:d,fetchAccountSets:f,fetchProviderQuotas:p,bumpModelsRefresh:m}){return{cancelLoginOAuth:(0,_.useCallback)(async i=>{let o=(r.current.get(i)??0)+1;r.current.set(i,o);try{await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:i})})}catch{}n.current&&(r.current.get(i)===o&&(a(e=>e===i?null:e),s(e=>e?.provider===i?null:e)),l(t(`prov.loginCancelled`,{provider:wo(i)}),!1))},[n,e,l,r,a,s,t]),loginOAuth:async(d,h=!1,g)=>{let _=(r.current.get(d)??0)+1;r.current.set(d,_);let v=_,y=g?.trim()||void 0;a(d),o(``),s(null);try{let a=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:d,...h||y?{addAccount:!0}:{},...y?{accountId:y,reauth:!0}:{}})});if(r.current.get(d)!==v||!n.current)return;if(!a.ok){l((await a.json().catch(()=>({}))).error||t(`prov.loginFailStart`,{provider:wo(d)}),!1);return}let o=await a.json();(o.url||o.instructions||o.deviceCode)&&s({provider:d,url:o.url,instructions:o.instructions,deviceCode:o.deviceCode});let g=i[d]?.accounts.length??0,_=!1;for(let a=0;a<150&&n.current&&r.current.get(d)===v;a++){if(await new Promise(e=>setTimeout(e,2e3)),r.current.get(d)!==v||!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${d}`).catch(()=>null),o=a?await _t(a)??null:null;if(o){if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:wo(d)}):t(`prov.loginError`,{provider:wo(d),error:o.error}),!1),s(null),_=!0;break}if(h||y?(o.accounts?.length??0)>g||o.done===!0:o.loggedIn||o.done===!0){c(e=>({...e,[d]:o}));let e=y?o.accounts?.find(e=>e.id===y):o.accounts?.find(e=>e.active)??o.accounts?.find(e=>e.id===o.activeAccountId);if(y&&!e){l(t(`prov.loginError`,{provider:wo(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),_=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:wo(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),_=!0;break}l(t(`prov.loginOk`,{provider:wo(d),cmd:`ocx sync`}),!0),s(null),u();let n=Object.keys(i);f(new Set(n).has(d)?n:[...n,d]),p(!0),m(),_=!0;break}}}!_&&r.current.get(d)===v&&n.current&&(await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:d})}).catch(()=>{}),l(t(`prov.loginTimeout`,{provider:wo(d)}),!1),s(null))}catch{r.current.get(d)===v&&l(t(`prov.loginRequestFail`,{provider:wo(d)}),!1)}finally{n.current&&r.current.get(d)===v&&a(null)}},logoutOAuth:async n=>{try{if(!(await fetch(`${e}/api/oauth/logout?provider=${encodeURIComponent(n)}`,{method:`POST`})).ok){l(t(`prov.logoutFail`,{provider:wo(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:wo(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:wo(n)}),!1)}}}}async function Eo(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function Do(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 Oo({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l}){let u=(0,_.useCallback)(async e=>{a(e)},[a]),d=(0,_.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;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(Do(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]),f=(0,_.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 Eo(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),p=(0,_.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)});return i.ok?(await s(),{ok:!0}):{ok:!1,error:await Eo(i,t(`prov.updateFail`))}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,t]);return{removeProvider:u,confirmRemoveProvider:d,setProviderDisabled:f,setDefaultProvider:(0,_.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(Do(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:p}}function ko({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await Q(await fetch(`${e}/api/config`));n(t??null),s&&t&&yn(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await Q(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 _t(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function Ao({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Z(),a=(0,_.useId)(),o=(0,_.useId)(),s=(0,_.useRef)(null),c=(0,_.useRef)(!1),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(!1),p=_o(e);(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]);let m=(0,_.useCallback)(e=>{e.preventDefault(),n()},[n]);if(!p)return null;let h=e.trim().toLowerCase(),g=h===`anthropic`?`oauthTos.anthropicBody`:yo(p),v=h===`anthropic`||h===`google-antigravity`;return(0,J.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,J.jsx)(`h3`,{id:a,children:i(vo(p),{provider:t})}),(0,J.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,J.jsx)(ve,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,J.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,J.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,J.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function jo(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function Mo(e){return nr(e.id,jo(e))}function No(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[Mo(n)].push(n);return t}function Po(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}var Fo={},Io=[],Lo={};function Ro({presets:e,usageRank:t=Fo,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=Io,accountStatus:s=Lo,busyProvider:c=null,onLogin:l,onCancelLogin:u,onLogout:d}){let f=Z(),[p,m]=(0,_.useState)(r),[h,g]=(0,_.useState)(``),v=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),y=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return v.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)})},[v,t]),b=(0,_.useMemo)(()=>No(y),[y])[p],x=(0,_.useMemo)(()=>Po(b,h),[b,h]),S=e=>{let t=e.codexAccountMode===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.pool`)}):e.auth===`oauth`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.oauth`)}):e.auth===`forward`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.codexLogin`)}):e.auth===`local`?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:f(`modal.badge.local`)}):e.keyOptional?null:(0,J.jsx)(`span`,{className:`badge badge-muted`,children:f(`modal.badge.apiKey`)});return(0,J.jsxs)(J.Fragment,{children:[(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.free`)}):null,t]})};return(0,J.jsxs)(`div`,{className:`provider-catalog`,children:[(0,J.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":p===e,className:`provider-catalog-tab${p===e?` active`:``}`,onClick:()=>{m(e),g(``)},children:f(e===`accounts`?`modal.tab.accounts`:e===`free`?`modal.tab.free`:`modal.tab.paid`)},e))}),p===`accounts`&&(0,J.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:f(`modal.accountsHint`)}),(0,J.jsx)(`input`,{className:`input provider-catalog-search`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.search`)}),(0,J.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&x.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.catalogLoading`)}),p!==`accounts`&&x.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsxs)(`div`,{className:`sub`,children:[(0,J.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:S(e)})]},e.id)),p!==`accounts`&&!n&&x.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.noMatch`)}),p===`accounts`&&o.map(e=>{let t=s[e.id],n=c===e.id,r=!!t?.loggedIn,i=r?t?.email??e.statusLabel??f(`modal.accountLoggedIn`):t?.error??e.statusLabel??f(`modal.accountLoggedOut`);return(0,J.jsxs)(`div`,{className:`list-row provider-catalog-account-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsx)(`div`,{className:`sub`,children:i})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,J.jsxs)(J.Fragment,{children:[r&&(0,J.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-auth`,children:f(`modal.accountManage`)}),l&&(0,J.jsx)(`button`,{type:`button`,className:r?`btn btn-ghost`:`btn btn-primary`,disabled:n,onClick:()=>{n||l(e.id)},children:f(n?`codexAuth.enablingOpenai`:r?`modal.accountAdd`:`modal.accountLogin`)})]}):r?d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(e.id),children:f(`modal.accountLogout`)}):n?u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:f(`common.cancel`)}):l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>l(e.id),children:f(`modal.accountLogin`)})})]},e.id)}),p===`accounts`&&o.length===0&&!n&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.noMatch`)})]}),(0,J.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,J.jsx)(`div`,{style:{flex:1}}),p!==`accounts`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:f(`modal.notListed`)})]})]})}function zo({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,manualCode:o,manualCodeBusy:s,manualCodeMsg:c,manualCodeOk:l,onRequestLogin:u,onUseApiKeyInstead:d,onManualCodeChange:f,onSubmitManualCode:p,onBack:m}){let h=Z();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,J.jsx)(`div`,{className:`muted text-control`,children:e.note??h(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>u(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,J.jsx)(ke,{}),n?h(`modal.waitingBrowser`):h(`modal.logInWith`,{label:e.label})]}):(0,J.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:h(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,J.jsx)(Ri,{url:a}),n&&(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:h(`prov.pasteRedirectHint`)}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,J.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:o,onChange:e=>f(e.target.value),onKeyDown:t=>{t.key===`Enter`&&e.oauthProvider&&(t.preventDefault(),p(e.oauthProvider))},placeholder:h(`prov.pasteRedirect`),"aria-label":h(`prov.pasteRedirect`),disabled:s,className:`input text-label`,style:{flex:1}}),(0,J.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,disabled:s||!o.trim()||!e.oauthProvider,onClick:()=>e.oauthProvider&&p(e.oauthProvider),children:h(s?`prov.pasteSubmitting`:`prov.pasteSubmit`)})]}),c&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:l?`var(--accent-hover)`:`var(--amber)`},children:c})]}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:d,children:h(`modal.useApiKeyInstead`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}function Bo({label:e,children:t}){return(0,J.jsxs)(`label`,{style:{display:`block`},children:[(0,J.jsx)(`span`,{className:`field-label`,children:e}),t]})}function Vo({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=Z();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,J.jsxs)(`details`,{className:`setup-guide`,children:[(0,J.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,J.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,J.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,J.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,J.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,J.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,J.jsx)(Bo,{label:h(`modal.providerName`),children:(0,J.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Bo,{label:h(`modal.adapter`),children:(0,J.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>u({...t,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Bo,{label:h(`modal.endpoint`),children:(0,J.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:Ya(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,J.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,J.jsx)(Bo,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,J.jsx)(Bo,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,J.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,J.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,J.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,J.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,J.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`)}):e.keyOptional?(0,J.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,J.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,J.jsxs)(J.Fragment,{children:[e.dashboardUrl&&(0,J.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,J.jsx)(Oe,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,J.jsx)(De,{style:{width:13,height:13}})]}),(0,J.jsx)(Bo,{label:h(`modal.apiKey`),children:(0,J.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,J.jsx)(Bo,{label:h(`modal.apiKeyTransport`),children:(0,J.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,J.jsx)(Bo,{label:h(`modal.defaultModel`),children:(0,J.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,J.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Ho=2e3;function Uo({apiBase:e,t,aliveRef:n,onAdded:r}){return{loginOAuth:(0,_.useCallback)(async(i,a)=>{let{setOauthBusy:o,setOauthMsg:s,setOauthMsgTone:c,setOauthUrl:l,setManualCode:u,setManualCodeMsg:d,setManualCodeOk:f}=a;o(!0),s(``),c(`ok`),l(``,i),u(``),d(``),f(!0);try{let a=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:i})});if(!n.current)return;if(!a.ok){let e=await a.json().catch(()=>({}));c(`warn`),s(e.error===`unknown oauth provider`?t(`modal.oauthComingSoonShort`):e.error||t(`modal.loginFailStart`));return}let o=await a.json();o.url?(l(o.url,i),s(t(`modal.waitingLogin`))):s(o.instructions||t(`modal.loggingIn`));for(let a=0;a<100;a++){if(await new Promise(e=>setTimeout(e,Ho)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await _t(a):null;if(!n.current)return;if(o?.error){c(`warn`),s(t(`modal.loginError`,{error:o.error}));return}if(o?.loggedIn){r(i);return}}c(`warn`),s(t(`modal.loginTimeout`))}catch{n.current&&(c(`warn`),s(t(`modal.networkError`)))}finally{n.current&&o(!1)}},[n,e,r,t]),submitManualCode:(0,_.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 Wo(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:``,oauthUrlProvider:null,manualCode:``,manualCodeBusy:!1,manualCodeMsg:``,manualCodeOk:!0,endpointChoice:`custom`,oauthTosPending:null}}function Go(e,t){switch(t.type){case`choose-preset`:return{...e,preset:t.preset,form:t.form,endpointChoice:t.endpointChoice,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`back`:return{...e,preset:null,form:null,endpointChoice:`custom`,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,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,oauthUrlProvider:t.providerId}: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:``,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function Ko({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:c,onAccountLogin:l,onAccountCancelLogin:u,onAccountLogout:d,onOpen:f}){let p=Z(),m=(0,_.useMemo)(()=>[{id:`custom`,label:p(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[p]),[h,g]=(0,_.useReducer)(Go,a,e=>Wo(e,p(`modal.customProvider`))),v=(0,_.useRef)(!0),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=K(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),S=K(`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}),C=K(`add-provider-usage:${e}`,[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)return{};let r=await n.json(),i={};for(let e of r.providers??[])i[e.provider]=e.requests;return i},{deadlineMs:6e4}),w=x.data??[],T=S.data??m,E=S.loading,D=C.data??{},{preset:O,form:k,saving:A,error:j,oauthBusy:M,oauthMsg:N,oauthMsgTone:P,oauthUrl:F,oauthUrlProvider:I,manualCode:L,manualCodeBusy:R,manualCodeMsg:z,manualCodeOk:B,endpointChoice:V,oauthTosPending:H}=h;(0,_.useEffect)(()=>{v.current=!0,y.current=document.activeElement,f?.();let e=b.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()=>{v.current=!1,y.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!H&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,H]);let U=e=>{let t=co(e);return t?p(t):e.note},W=e=>{let t=Xa(e.baseUrlChoices,e.baseUrl);g({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?Ya(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},G=async()=>{if(!k)return;let t=O?so(O):!1,n=O?.baseUrlChoices?.length?Za(O.baseUrlChoices,V,k.baseUrl):k.baseUrl.trim();if(!t&&!k.name.trim()){g({type:`set-error`,error:p(`modal.nameRequired`)});return}if(!t&&!n){g({type:`set-error`,error:p(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){g({type:`set-error`,error:p(`modal.baseUrlPlaceholderError`)});return}let i={...k,baseUrl:n},a;try{a=uo(O??{id:`custom`},i)}catch{g({type:`set-error`,error:p(`modal.invalidPreset`)});return}g({type:`set-saving`,saving:!0}),g({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){g({type:`set-error`,error:(await t.json().catch(()=>({}))).error||p(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{g({type:`set-error`,error:p(`modal.networkError`)})}finally{g({type:`set-saving`,saving:!1})}},{loginOAuth:ee,submitManualCode:q}=Uo({apiBase:e,t:p,aliveRef:v,onAdded:r}),te={setOauthBusy:e=>g({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>g({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>g({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t)=>g({type:`set-oauth-url`,url:e,providerId:t}),setManualCode:e=>g({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>g({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>g({type:`set-manual-code-msg`,msg:z,ok:e})},Y=k?t.includes(k.name.trim())&&k.name.trim()!==``:!1,ne=e=>{if(!M){if(_o(e)){g({type:`set-oauth-tos-pending`,providerId:e});return}ee(e,te)}},re=e=>{q(e,L,R,{setManualCodeBusy:e=>g({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>g({type:`set-manual-code`,code:e}),setManualCodeOk:e=>g({type:`set-manual-code-msg`,msg:z,ok:e}),setManualCodeMsg:e=>g({type:`set-manual-code-msg`,msg:e})})},ie=O?.id===`custom`,ae=k?.authMode===`local`,oe=O?so(O):!1;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":p(`modal.add`),className:`modal-overlay`,onClick:n,children:(0,J.jsxs)(`div`,{ref:b,className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:O?p(`modal.addNamed`,{label:O.label}):p(`modal.add`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":p(`common.close`),onClick:n,children:(0,J.jsx)(fe,{})})]}),O?k&&(O.auth===`oauth`&&k.authMode===`oauth`?(0,J.jsx)(zo,{preset:O,oauthSupported:w,oauthBusy:M,oauthMsg:N,oauthMsgTone:P,oauthUrl:I===O.oauthProvider?F:``,manualCode:L,manualCodeBusy:R,manualCodeMsg:z,manualCodeOk:B,onRequestLogin:ne,onUseApiKeyInstead:()=>{g({type:`use-api-key-instead`,form:{...k,authMode:`key`}})},onManualCodeChange:e=>g({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{re(e)},onBack:()=>g({type:`back`})}):(0,J.jsx)(Vo,{preset:O,form:k,endpointChoice:V,error:j,saving:A,dup:Y,isCustom:ie,isLocal:ae,isReservedForward:oe,presetDescription:U,onFormChange:e=>g({type:`set-form`,form:e}),onEndpointChoiceChange:e=>g({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{G()},onUseOauthLogin:()=>g({type:`use-oauth-login`,form:{...k,authMode:`oauth`}}),onBack:()=>g({type:`back`})})):(0,J.jsx)(Ro,{presets:T,usageRank:D,presetsLoading:E,initialTier:i,onSelectPreset:e=>W(e),onSelectCustom:()=>W(m[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:l,onCancelLogin:u,onLogout:d})]})}),H&&(0,J.jsx)(Ao,{providerId:H,providerLabel:O?.label??H,onCancel:()=>g({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=H;e&&(g({type:`set-oauth-tos-pending`,providerId:null}),ee(e,te))}},H)]})}function qo({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,removeConfirmName:s,removeDefaultProvider:c,codexLoginOpen:l,jsonLeaveOpen:u,jsonSaving:d,oauthTosPending:f,onCloseAdd:p,onAdded:m,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onOpenAdd:v,onCloseCodexLogin:y,onCodexAdded:b,onCancelRemove:x,onConfirmRemove:S,onCancelJsonLeave:C,onDiscardJson:w,onSaveJson:T,onCancelOauthTos:E,onContinueOauthTos:D}){return(0,J.jsxs)(J.Fragment,{children:[n&&(0,J.jsx)(Ko,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:p,onAdded:m,accountRows:a,accountStatus:o,accountBusy:i,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onOpen:v}),l&&(0,J.jsx)(Vi,{apiBase:e,onClose:y,onAdded:b}),s&&(0,J.jsx)(eo,{providerName:s,defaultProviderName:c,onCancel:x,onConfirm:S}),u&&C&&w&&T&&(0,J.jsx)(to,{saving:d??!1,onCancel:C,onDiscard:w,onSave:T}),f&&(0,J.jsx)(Ao,{providerId:f.provider,providerLabel:wo(f.provider),onCancel:E,onContinue:D},`${f.provider}:${f.addAccount?`add`:`login`}`)]})}function Jo(e,t,n){return[...ao(e.providers).map(e=>({id:e,label:Ar(e,n),kind:`codex`,href:`#codex-auth`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:wo(e),kind:`oauth`}))]}function Yo(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 Xo({apiBase:e}){let t=Z(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>vn(n)),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)({}),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(null),M=(0,_.useRef)(!0),N=(0,_.useRef)(null),P=(0,_.useRef)(!1),F=(0,_.useRef)(new Map),I=(0,_.useCallback)((e,t=!0)=>{c(e),u(t)},[]);(0,_.useEffect)(()=>(M.current=!0,()=>{M.current=!1}),[]),K(`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(`add-provider-usage:${e}`,[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)return{};let r=await n.json(),i={};for(let e of r.providers??[])i[e.provider]=e.requests;return i},{deadlineMs:6e4});let[L,R]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:z,fetchOauth:B,fetchProviderQuotas:V}=ko({apiBase:e,t,setConfig:i,setOauthProviders:f,setOauthStatus:m,notify:I,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{R(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),H=Qi(e),U=H.activeNeedsReauth,W=(0,_.useMemo)(()=>{let e=H.accounts;if(e.length===0&&H.loadState===`loading`)return p;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{...p,openai:{loggedIn:i,...a?{email:a}:{},...U?{needsReauth:!0}:{}}}},[p,H.accounts,H.loadState,U]),{accountSets:G,accountLoadStates:ee,switchingAccount:q,keyPools:te,fetchAccountSets:Y,switchAccount:ne,switchApiKey:re,removeApiKey:ie,addApiKeyValue:ae,editCredentialAlias:oe,removeAccount:se,activeAccountNeedsReauth:ce}=xo({apiBase:e,t,config:r,oauthStatus:W,aliveRef:M,notify:I,fetchConfig:z,fetchOauth:B,fetchProviderQuotas:V,codexActiveNeedsReauth:U}),{draft:le,setDraft:ue,jsonEditorOpen:de,jsonSaving:fe,jsonLeaveOpen:me,saveConfig:he,openJsonEditor:ge,discardJsonEditor:_e,requestCloseJsonEditor:ve,restoreJsonEditor:ye,jsonIsDirty:be,setJsonLeaveOpen:xe}=So({apiBase:e,config:r,notify:I,fetchConfig:z,fetchProviderQuotas:V,onSaved:()=>k(e=>e+1),t});(0,_.useEffect)(()=>{N.current!==e&&(N.current=e,Promise.resolve().then(()=>{z(),B()}))},[e,z,B]);let Se=()=>k(e=>e+1),{cancelLoginOAuth:Ce,loginOAuth:we,logoutOAuth:Te}=To({apiBase:e,t,aliveRef:M,oauthLoginGenerationRef:F,accountSets:G,setBusy:g,setStatus:c,setLoginInfo:y,setOauthStatus:m,notify:I,fetchConfig:z,fetchOauth:B,fetchAccountSets:Y,fetchProviderQuotas:V,bumpModelsRefresh:Se}),{removeProvider:Ee,confirmRemoveProvider:De,setProviderDisabled:Oe,setDefaultProvider:ke,updateProvider:Ae}=Oo({apiBase:e,t,removeBusyRef:P,workspaceSelected:b,setWorkspaceSelected:x,setRemoveConfirmName:T,notify:I,fetchConfig:z,fetchOauth:B,fetchProviderQuotas:V}),je=(e,t=!1)=>{if(h!==e){if(_o(e)){j({provider:e,addAccount:t});return}we(e,t)}};if(!r)return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,J.jsx)(dt,{tone:`err`,children:s}):(0,J.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,J.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`providers-workspace-main`,children:(0,J.jsxs)(`p`,{className:`muted`,children:[(0,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let Me=Jo(r,d,t),Ne=Yo(r,W),Pe=e=>r.providers[e]?.authMode===`forward`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.providers`)}),(0,J.jsx)(`div`,{className:`row`,children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,J.jsx)(pe,{}),t(`prov.add`)]})})]}),s&&(0,J.jsx)(dt,{tone:l?`ok`:`err`,children:s}),(0,J.jsx)(di,{onRemoveProvider:Ee,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:b,onSelect:x,onAddProvider:e=>{C(e??null),o(!0)},onEditConfig:ge,jsonEditor:{open:de,draft:le,isDirty:be,onDraftChange:ue,onSave:()=>he(),onClose:ve,onRestore:ye},jsonSaving:fe,modelsRefreshToken:O,activeAccountNeedsReauth:ce,quotaRefreshEpoch:L.epoch,quotaForceRefresh:L.force,detail:(t,n)=>{let i=Ne[t.name]??p[t.name];return(0,J.jsx)(no,{item:t,usageTotals:n.usageTotals,modelUsage:n.modelUsage,quotaReport:n.quotaReport,availableModels:n.availableModels,hasLiveModels:n.hasLiveModels,selectedModels:n.selectedModels,modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:i?.email,onDeselect:()=>x(null),apiBase:e,oauth:i,accounts:G[t.name]?.accounts??[],keys:te[t.name]??[],accountLoadState:ee[t.name]??(t.authMode===`oauth`?`idle`:`ready`),switchingAccountId:q?.provider===t.name?q.accountId:null,busyProvider:h,loginHint:v,authHandlers:{onLogin:je,onCancelLogin:Ce,onLogout:Te,onReauth:(e,t)=>we(e,!0,t),onSwitchAccount:ne,onRemoveAccount:se,onRetryAccounts:async e=>{await Y([e])},onAddApiKey:ae,onSwitchApiKey:re,onRemoveApiKey:ie,onEditAlias:oe},isDefault:t.name===r.defaultProvider,onRemoveProvider:Ee,onSetDisabled:Oe,onSetDefault:e=>{ke(e)},onUpdateProvider:Ae,codexController:H},t.name)}}),(0,J.jsx)(qo,{apiBase:e,config:r,adding:a,addIntent:S,busy:h,addModalAccountRows:Me,accountLoginStatus:Ne,removeConfirmName:w,removeDefaultProvider:w===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==w&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:E,jsonLeaveOpen:me,jsonSaving:fe,oauthTosPending:A,onCloseAdd:()=>{h&&Ce(h),o(!1),C(null)},onAdded:e=>{o(!1),C(null),I(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),z(),B(),V(!0),Se()},onAccountLogin:async n=>{if(n===`openai`){if(h===`openai`)return;let n=r.providers.openai,i=oo(n);if(i===`invalid`){I(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){g(`openai`);try{await mo(e,i),await z()}catch(e){e instanceof po?I(t(e.i18nKey),!1):I(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{M.current&&g(e=>e===`openai`?null:e)}}D(!0);return}if(Pe(n)){D(!0);return}(r.providers[n]?.authMode===`oauth`||d.includes(n))&&je(n)},onAccountCancelLogin:e=>{Ce(e)},onAccountLogout:e=>{Te(e)},onOpenAdd:B,onCloseCodexLogin:()=>D(!1),onCodexAdded:()=>{D(!1),I(t(`prov.loginOk`,{provider:Ar(`openai`,t),cmd:`ocx sync`}),!0),z(),B(),V(!0),Se()},onCancelRemove:()=>T(null),onConfirmRemove:()=>{De(w)},onCancelJsonLeave:()=>{fe||xe(!1)},onDiscardJson:_e,onSaveJson:()=>{he()},onCancelOauthTos:()=>j(null),onContinueOauthTos:()=>{let e=A;e&&(j(null),we(e.provider,e.addAccount))}})]})}var Zo={"gpt-5.6-sol":Me,"gpt-5.6-terra":Fe,"gpt-5.6-luna":Ne},Qo={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function $o(e){return e.slice(e.lastIndexOf(`/`)+1)}function es(e){return Zo[e]??Zo[$o(e)]??null}function ts(e){let t=es(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:Qo,"aria-hidden":!0}),e):e}var ns=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function rs(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...ns];let r=new Set(ns),i=null;for(let e of n){let n=`${e.provider.trim()}/${e.model.trim()}`,a=t.get(n),o=a===void 0?[]:a.filter(e=>r.has(e));if(i===null)i=o;else{let e=new Set(o);i=i.filter(t=>e.has(t))}}let a=new Set(i??[]);return ns.filter(e=>a.has(e))}var is=0;function as(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++is}`}}var os=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,ss=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,cs=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function ls(e){return os.test(e.trim())}function us(e){return`combo/${e.trim()}`}function ds(e,t){return(typeof t==`string`?t.trim():``)||us(e)}function fs(e){return typeof e==`string`&&e.trim()?e.trim():null}function ps(e){return e===`round-robin`?`round-robin`:`failover`}function ms(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function hs(e){return typeof e==`string`&&ns.includes(e)?e:null}function gs(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function _s(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=gs(t.weight);a.push(as(i===void 0?{provider:n,model:r}:{provider:n,model:r,weight:i}))}n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():ds(r,fs(t.alias)),alias:fs(t.alias),strategy:ps(t.strategy),stickyLimit:ms(t.stickyLimit),defaultEffort:hs(t.defaultEffort),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function vs(e){let t=[],n=[];for(let r of e)r.strategy===`round-robin`?n.push(r):t.push(r);return{failover:t,roundRobin:n}}function ys(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 bs(e,t={}){let n=[],r=t.cataloguedComboIds;for(let t of e)t.targets.length===0?n.push({id:t.id,model:t.model,reason:`empty-targets`}):t.targets.length<2&&n.push({id:t.id,model:t.model,reason:`few-targets`}),r&&t.targets.length>0&&!r.has(t.id)&&n.push({id:t.id,model:t.model,reason:`catalog-omitted`});return n}function xs(e,t){return e.id!==t.id||e.alias!==t.alias||e.strategy!==t.strategy||e.stickyLimit!==t.stickyLimit||e.defaultEffort!==t.defaultEffort||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)})}function Ss(e,t={}){return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},combo:{targets:e.targets.map(t=>e.strategy===`round-robin`?{provider:t.provider.trim(),model:t.model.trim(),weight:t.weight??1}:{provider:t.provider.trim(),model:t.model.trim()}),strategy:e.strategy,defaultEffort:e.defaultEffort,...e.strategy===`round-robin`?{stickyLimit:e.stickyLimit}:{},...e.alias&&e.alias.trim()?{alias:e.alias.trim()}:{}}}}function Cs(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!ls(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()??``;if(r){if(!ss.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&cs.test(r))return`aliasNativeFamily`;if((t.existingAliases??[]).includes(r))return`duplicateAlias`}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`}let i=new Set;for(let t of e.targets){let e=`${t.provider.trim()}/${t.model.trim()}`;if(i.has(e))return`duplicateTarget`;i.add(e)}if(e.strategy===`round-robin`){if(!Number.isInteger(e.stickyLimit)||e.stickyLimit<1||e.stickyLimit>100)return`invalidStickyLimit`;for(let t of e.targets){let e=t.weight??1;if(!Number.isInteger(e)||e<1||e>1e4)return`invalidWeight`}}return e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function ws(e=``){return{id:e,model:e?us(e):`combo/`,alias:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,targets:[as()]}}function Ts(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 Es(e,t,n,r){let{isEmpty:i,...a}=r,o=K(e,t,n,a);return{...o,state:Ts(o,i,r.enabled!==!1)}}function Ds({className:e,style:t}){return(0,J.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function Os({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,J.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,J.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,J.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,J.jsx)(Ds,{})},t))]})}function ks({children:e,busy:t=!0,live:n=!0,className:r}){return(0,J.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,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:e})]})}function As(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),liveModels:n?.liveModels!==!1,configuredModels:n?.models??[],discovery:n?.discovery}}).sort((e,t)=>e.native===t.native?e.provider.localeCompare(t.provider):e.native?-1:1)}function js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ms(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Ns(e){if(!js(e))throw Error(`invalid selected models response`);let t=e.selected;if(!js(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ms(t)]))}async function Ps(e,t=fetch){let n=await t(`${e}/api/selected-models`);if(!n.ok)throw Error(`selected models HTTP ${n.status}`);return Ns(await n.json())}function Fs(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Is(e,t,n,r,i){return Fs(e,t,n,r)&&!i}async function Ls(e,t,n,r,i,a=fetch){return a(`${e}/api/model-visibility`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope:t,provider:n,targets:r,enabled:i})})}function Rs(e,t){return e===t}function zs(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`)}}var Bs=Array.from({length:18},(e,t)=>1e5+t*5e4),Vs=new Set(Bs),Hs=`custom`,Us=[4,8,16,32,64,128,256,500,1e3],Ws=new Set(Us),Gs=`ocx-models-collapsed:v2`,Ks=`ocx-models-combos-open:v1`;function qs(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function Js(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ys(e,t,n){let r=[];for(let i of e){let e=t.has(i.id)||t.has(i.namespaced);Is(n,i.provider,i.id,i.native===!0,e)&&r.push({value:i.namespaced,label:i.namespaced})}return r}function Xs(e=localStorage){try{let t=e.getItem(Gs);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 Zs(e,t=localStorage){try{t.setItem(Gs,JSON.stringify([...e]))}catch{}}function Qs(e=localStorage){try{return(e.getItem(`ocx-models-combos-open:v1`)??e.getItem(`ocx-models-combos-open`))===`1`}catch{return!1}}function $s(e,t=localStorage){try{t.setItem(Ks,e?`1`:`0`)}catch{}}function ec({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Z(),i=e&&t?.status===`failed`?t:void 0;return(0,J.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,J.jsx)(ye,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,J.jsxs)(`span`,{children:[i&&n&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${zs(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,J.jsx)(`a`,{href:`#providers`,children:r(`models.openProviderSettings`)})]})]})}function tc(e){return Array.isArray(e)?_s({combos:e}):null}function nc({apiBase:e}){let t=Z(),n=`ocx.models.catalog.v1:${e}`,r=(0,_.useMemo)(()=>vn(n),[n]),[i,a]=(0,_.useState)(()=>r?.models??[]),[o,s]=(0,_.useState)(()=>r?.providers??[]),[c,l]=(0,_.useState)(()=>new Set(r?.disabled??[])),[u,d]=(0,_.useState)(()=>r?.selectedModels??null),[f,p]=(0,_.useState)({}),[m,h]=(0,_.useState)({}),[g,v]=(0,_.useState)(()=>r?.contextCaps??{}),[b,x]=(0,_.useState)(()=>r?.contextCapValue??35e4),[S,C]=(0,_.useState)(``),[w,T]=(0,_.useState)(!1),E=Xs(),[D,O]=(0,_.useState)(()=>E??new Set),k=(0,_.useRef)(E===null),[A,j]=(0,_.useState)(``),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(!1),I=(0,_.useRef)(!1),L=(0,_.useRef)(0),R=(0,_.useRef)(!1),[z,B]=(0,_.useState)(null),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(``),G=(0,_.useRef)(!1),[ee,K]=(0,_.useState)(``),[te,Y]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(!1),[ae,oe]=(0,_.useState)(!1),[se,ce]=(0,_.useState)(`add`),[le,ue]=(0,_.useState)(``),[de,fe]=(0,_.useState)(``),[pe,me]=(0,_.useState)(``),[he,ge]=(0,_.useState)(``),[_e,ve]=(0,_.useState)(``),[be,xe]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)([`text`]),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)(``),[ke,Ae]=(0,_.useState)(null),je=(0,_.useRef)(null),[Me,Ne]=(0,_.useState)(null),[Pe,Fe]=(0,_.useState)(!1),Ie=`ocx.models.combos.v1:${e}`,Re=(0,_.useMemo)(()=>{let t=tc(vn(Ie));return t===null?tc(vn(`ocx.combos.workspace.v1:${e}`)?.combos):t},[e,Ie]),ze=Es(`models-combos:${e}`,[e],async t=>{let n=_s(await Q(await fetch(`${e}/api/combos`,{signal:t})));return yn(Ie,n),n},{isEmpty:()=>!1,initialData:Re??void 0}),Be=ze.state,Ve=Be.data??Re,He=Be.showError,[Ue,We]=(0,_.useState)(Qs),[Ge,Ke]=(0,_.useState)(null),qe=()=>{let e=!Ue;$s(e),We(e)};(0,_.useEffect)(()=>()=>{je.current&&clearTimeout(je.current)},[]);let X=(0,_.useMemo)(()=>Ys(i,c,u??{}),[i,c,u]),Je=(0,_.useCallback)(async()=>{let t=y(15e3);try{let n=await _t(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&Ne(n)}catch{}finally{t.clear()}},[e]),Ye=(0,_.useCallback)(async()=>{if(G.current)return;let t=y(15e3);try{let n=await fetch(`${e}/api/v2`,{signal:t.signal});if(!(n.headers.get(`content-type`)??``).includes(`application/json`)){B(null);return}let r=await _t(n);if(!r||typeof r.enabled!=`boolean`){B(null);return}B({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`})}catch{B(null)}finally{t.clear()}},[e]),Xe=(0,_.useCallback)(async t=>{let[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}),Ps(e,(e,n)=>fetch(e,{...n,signal:t}))]),[s,c,l]=await Promise.all([Q(r),Q(i),Q(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=Js(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??{},contextCapValue:f};return yn(n,p),p},[e,n]),Ze=(0,_.useCallback)(e=>{let t=As(e.models,e.providers);Ke(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),a(e.models),s(e.providers),l(new Set(e.disabled)),d(e.selectedModels),x(e.contextCapValue),v(e.contextCaps)},[]),Qe=Es(n,[e],async e=>{let t=await Xe(e);if(e.aborted)throw Error(`models request aborted`);return Ze(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:r??void 0,deadlineMs:6e4}),$e=Qe.state,et=(0,_.useCallback)(async(e=!1)=>{if(R.current&&!e)return!1;R.current=!0;let t=++L.current;try{let e=await Xe(new AbortController().signal);return Rs(t,L.current)?(Ze(e),q(n,e),!0):!1}catch{return!1}finally{Rs(t,L.current)&&(R.current=!1)}},[Ze,n,Xe]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{Je(),Ye()},0),t=Jt(()=>{G.current||Ye()},1e4);return()=>{window.clearTimeout(e),t()}},[Je,Ye]);let tt=(0,_.useMemo)(()=>As(i,o),[i,o]);(0,_.useEffect)(()=>{if(!k.current||tt.length===0)return;k.current=!1;let e=new Set(tt.map(e=>e.provider));O(e),Zs(e)},[tt]);let nt=(0,_.useMemo)(()=>u?i.filter(e=>Is(u,e.provider,e.id,e.native===!0,c.has(e.namespaced))).length:0,[c,i,u]),rt=async(n,r,i,a)=>{++L.current,F(!0),I.current=!0,j(``);let o=null;try{(await Ls(e,n,r,i,a)).ok||(o=`models.saveFailed`)}catch{o=`models.networkError`}finally{let e=await et(!0);o?(N(!1),j(t(o))):e&&(N(!0),j(t(`models.applied`))),F(!1),I.current=!1}},it=async n=>{F(!0),I.current=!0,j(``);let r=g[n]!==b;try{let i=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,enabled:r})});try{v((await Q(i,t(`models.capSaveFailed`)))?.caps??{}),N(!0),j(t(`models.capApplied`)),await et(!0)}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{F(!1),I.current=!1}},at=e=>{O(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Zs(n),n})},ot=e=>{O(()=>{let t=e?new Set(tt.map(e=>e.provider)):new Set;return Zs(t),t})},st=async n=>{F(!0),I.current=!0,j(``);try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{let e=await Q(r,t(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&x(e.value),v(e?.caps??{}),N(!0),j(t(`models.capApplied`)),await et(!0)}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{F(!1),I.current=!1}},ct=e=>{!Number.isFinite(e)||e<=0||st({value:Math.floor(e)})},lt=e=>{if(e===`custom`){T(!0),C(String(b));return}T(!1);let t=Number(e);Number.isFinite(t)&&t>0&&t!==b&&ct(t)},ht=()=>{let e=Number(S.replace(/[_,\s]/g,``));if(!Number.isFinite(e)||e<=0){N(!1),j(t(`models.capSaveFailed`));return}T(!1),ct(e)},gt=(0,_.useMemo)(()=>{let e=tt.filter(e=>!e.native&&e.rows.length>0);return e.length>0&&e.every(e=>g[e.provider]===b)},[tt,g,b]),vt=()=>{st({setAll:!gt})},yt=async t=>{if(!(!Me||Pe)){Fe(!0),Ne({...Me,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Fe(!1)}}},bt=async n=>{if(!(!z||G.current)&&z.multiAgentMode!==n){H(!0),G.current=!0,W(``),j(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:n})});try{let e=await Q(r,t(`models.saveFailed`));Ye(),N(!0),j(t(`models.v2Applied`)),W((e?.warnings??[]).join(` `))}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{H(!1),G.current=!1}}},xt=async n=>{if(!(!z||G.current)){if(!Number.isInteger(n)||n<1){N(!1),j(t(`models.v2ThreadsInvalid`));return}if(z.maxConcurrentThreadsPerSession!==n){H(!0),G.current=!0,W(``),j(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await Q(r,t(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){N(!1),j(t(`models.saveFailed`));return}B({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`}),N(!0),j(t(`models.v2ThreadsApplied`)),Y(!1)}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{H(!1),G.current=!1}}}},St=e=>{if(e===`custom`){Y(!0),K(String(z?.maxConcurrentThreadsPerSession??``));return}Y(!1),xt(Number(e))},Ct=(e,t)=>{je.current&&clearTimeout(je.current),je.current=setTimeout(()=>{Ae({namespaced:e,rect:t.getBoundingClientRect()})},300)},wt=(e,t)=>{je.current&&clearTimeout(je.current),Ae({namespaced:e,rect:t.getBoundingClientRect()})},Tt=()=>{je.current&&clearTimeout(je.current),je.current=setTimeout(()=>Ae(null),120)},Et=()=>{je.current&&clearTimeout(je.current)},Dt=async(n,r,i,a,o)=>{Ee(!0),Oe(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,modelId:r,displayName:i,contextWindow:a,inputModalities:o})});try{await Q(s,t(`models.customSaveFailed`)),oe(!1),N(!0),j(t(`models.customAdded`)),await et(!0)}catch(e){Oe(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Oe(t(`models.networkError`))}finally{Ee(!1)}},Ot=async(n,r)=>{Ee(!0),Oe(``);try{let i=await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});try{await Q(i,t(`models.customSaveFailed`)),oe(!1),N(!0),j(t(`models.customUpdated`)),await et(!0)}catch(e){Oe(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Oe(t(`models.networkError`))}finally{Ee(!1)}},kt=async n=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`DELETE`})).ok?(N(!0),j(t(`models.customDeleted`)),await et(!0)):(N(!1),j(t(`models.customSaveFailed`)))}catch{N(!1),j(t(`models.networkError`))}},At=$e.data??r;if($e.showSkeleton&&!At)return(0,J.jsx)(Os,{label:t(`models.loading`),rows:5});if($e.kind===`failed-cold`)return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:$e.error instanceof Error?$e.error.message:t(`models.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Qe.refresh(),children:t(`common.retry`)})]});let jt=u??{},Mt=e=>{let{provider:n,rows:r,native:i,liveModels:a,discovery:o}=e,s=D.has(n),l=e=>Is(jt,n,e.id,e.native===!0,c.has(e.namespaced)),u=r.filter(l).length,d=g[n]===b,_=i,v=a&&o?.status===`failed`?o:void 0,y=(f[n]??``).trim().toLowerCase(),x=y?r.filter(e=>e.id.toLowerCase().includes(y)):r,S=x.toSorted((e,t)=>Number(!l(e))-Number(!l(t))),C=m[n]??60,w=S.slice(0,C),T=x.length-w.length,E=r.length>0,O=!E||r.every(l),k=!E||r.every(e=>!l(e)),A=e=>{E&&rt(`provider`,n,r.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,J.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,J.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>at(n),"aria-expanded":!s,style:{flex:1,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,J.jsx)(we,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,J.jsx)(`span`,{className:`text-body font-semibold`,children:n}),_&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.nativeGroupLabel`)}),v&&(0,J.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:zs(t,v),children:t(`models.discoveryFailedBadge`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:u,total:r.length})})]}),(0,J.jsxs)(`div`,{className:`row models-provider-actions`,children:[!_&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),ce(`add`),ue(n),fe(``),me(``),ge(``),ve(``),xe(!1),Ce([`text`]),Oe(``),oe(!0)},"aria-label":t(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:P||O,onClick:()=>A(!0),children:t(`models.allOn`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:P||k,onClick:()=>A(!1),children:t(`models.allOff`)}),!_&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ut,{on:d,onClick:()=>it(n),disabled:P,label:t(`models.capValue`,{value:qs(b)})}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.capValue`,{value:qs(b)})})]})]})]}),!s&&(0,J.jsxs)(`div`,{className:`models-provider-body`,children:[_&&(0,J.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:t(`models.nativeHint`)}),r.length===0&&(0,J.jsx)(ec,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>60/2&&(0,J.jsx)(`input`,{className:`input`,placeholder:t(`models.search`),value:f[n]??``,onChange:e=>p(t=>({...t,[n]:e.target.value})),"aria-label":t(`models.search`)}),w.map(e=>{let r=!l(e);return(0,J.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Ct(e.namespaced,t.currentTarget),onMouseLeave:Tt,onFocus:t=>wt(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||Ae(null)},children:[(0,J.jsxs)(`div`,{className:`row models-model-row`,children:[(0,J.jsx)(ut,{on:!r,onClick:()=>void rt(`models`,n,[{id:e.id,native:e.native===!0}],r),disabled:P,label:e.native?e.id:e.namespaced}),(0,J.jsx)(`code`,{className:`mono text-control`,style:{color:r?`var(--faint)`:`var(--text)`,textDecoration:r?`line-through`:`none`},children:e.native?ts(e.id):e.namespaced}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.customBadge`)}),e.contextCapped&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.contextCappedValue`,{value:qs(e.contextCap??b)})})]}),ke?.namespaced===e.namespaced&&(()=>{let n=ke.rect,i=n.bottom+4,a=i+360>window.innerHeight;return(0,J.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${a?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:n.left+24,...a?{bottom:window.innerHeight-n.top+4}:{top:i}},onMouseEnter:Et,onMouseLeave:Tt,children:[(0,J.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,J.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:t(`models.customBadge`)}),(0,J.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipProvider`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:e.provider}),(e.contextWindow||e.contextCap)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipContext`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:qs(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipModalities`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipStatus`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:t(r?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,J.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{ce(`edit`),ue(e.provider),fe(e.customId),me(e.id),ge(e.displayName??``),ve(e.contextWindow?String(e.contextWindow):``),xe(!1),Ce(e.inputModalities??[`text`]),Oe(``),oe(!0),Ae(null)},children:t(`models.customEdit`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{window.confirm(t(`models.customDeleteConfirm`,{name:e.displayName??e.id}))&&kt(e.customId),Ae(null)},children:t(`models.customDelete`)})]})]})})()]},e.namespaced)}),T>0&&(0,J.jsx)(`button`,{type:`button`,onClick:()=>h(e=>({...e,[n]:C+60})),className:`btn btn-ghost btn-sm models-show-more`,children:t(`models.showMore`,{n:T})})]})]},n)},Nt=Ge?tt.filter(e=>e.provider===Ge):tt,Pt=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`models-control-top-row`,children:[(0,J.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!Me||void 0,children:[(0,J.jsxs)(`span`,{className:`models-shadow-label`,children:[t(`models.shadowCallIntercept`),` `,(0,J.jsx)(mt,{content:t(`models.shadowCallInterceptHint`,{models:Ft(Me?.sourceModels)}),side:`top`,maxWidth:320,children:(0,J.jsx)(`span`,{style:{cursor:`help`},"aria-label":t(`models.shadowCallInterceptHint`,{models:Ft(Me?.sourceModels)}),children:`ⓘ`})})]}),(0,J.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:t(`models.shadowCallOriginal`,{models:It(Me?.sourceModels)})}),(0,J.jsx)(ut,{on:Me?.enabled??!1,onClick:()=>void yt({enabled:!Me?.enabled}),disabled:!Me||Pe,label:t(`models.shadowCallIntercept`)}),(0,J.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,J.jsx)(ft,{value:Me?.model??``,options:[{value:``,label:`—`},...X],onChange:e=>{Ne(t=>t&&{...t,model:e}),yt({model:e})},disabled:!Me||Pe||!Me.enabled,label:t(`models.shadowCallIntercept`)})})]}),z&&(0,J.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2Label`)}),(0,J.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":t(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(z.multiAgentMode??`default`)===e,className:`btn btn-sm${(z.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(z.multiAgentMode??`default`)===e?void 0:`transparent`,color:(z.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:V,onClick:()=>void bt(e),children:t(`models.v2Mode_${e}`)},e))}),(0,J.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)`},onClick:()=>re(!0),"aria-label":t(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,J.jsx)(ye,{width:14,height:14,"aria-hidden":`true`})})]})]}),z&&(z.enabled||z.agentsMaxThreadsConflict||U)&&(0,J.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[z.enabled&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2ThreadsLabel`)}),(0,J.jsx)(ft,{value:te?`custom`:z.maxConcurrentThreadsPerSession!==null&&z.maxConcurrentThreadsPerSession!==void 0?Ws.has(z.maxConcurrentThreadsPerSession)?String(z.maxConcurrentThreadsPerSession):`custom`:``,options:[...z.maxConcurrentThreadsPerSession===null||z.maxConcurrentThreadsPerSession===void 0?[{value:``,label:t(`models.v2ThreadsDefault`)}]:[],...z.maxConcurrentThreadsPerSession!==null&&z.maxConcurrentThreadsPerSession!==void 0&&!Ws.has(z.maxConcurrentThreadsPerSession)&&!te?[{value:`custom`,label:String(z.maxConcurrentThreadsPerSession)}]:[],...Us.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:t(`models.custom`)}],onChange:e=>St(e),disabled:V,label:t(`models.v2ThreadsLabel`)}),te&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:ee,onChange:e=>K(e.target.value),onKeyDown:e=>{e.key===`Enter`&&xt(Number(ee.replace(/[_,\s]/g,``)))},disabled:V,"aria-label":t(`models.v2ThreadsLabel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:V,onClick:()=>{xt(Number(ee.replace(/[_,\s]/g,``)))},children:t(`models.v2ThreadsApply`)})]})]}),z.enabled&&z.agentsMaxThreadsConflict&&(0,J.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:t(`models.v2Conflict`)}),U&&(0,J.jsx)(`span`,{className:`muted text-label`,children:U})]}),(0,J.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`models.contextCapLabel`)}),(0,J.jsx)(ft,{value:w?Hs:Vs.has(b)?String(b):Hs,options:[...!Vs.has(b)&&!w?[{value:String(b),label:qs(b)}]:[],...Bs.map(e=>({value:String(e),label:qs(e)})),{value:Hs,label:t(`models.custom`)}],onChange:e=>lt(e),disabled:P,label:t(`models.contextCapLabel`)}),w&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:t(`models.customPlaceholder`),value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ht()},disabled:P,"aria-label":t(`models.customPlaceholder`)}),(0,J.jsx)(`button`,{type:`button`,onClick:ht,disabled:P,className:`btn btn-ghost btn-sm`,children:t(`models.customApply`)})]}),(0,J.jsx)(ut,{on:gt,onClick:vt,disabled:P,label:t(`models.setAll`)}),(0,J.jsx)(`span`,{className:`muted text-label leading-body`,children:t(`models.setAllHint`,{value:qs(b)})})]}),(()=>{let e=i.filter(e=>e.custom).length;return e===0?null:(0,J.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:t(`models.customSummary`,{count:e})})})})(),(0,J.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,J.jsx)(ye,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:t(`models.orderHint`)})]})]}),Lt=(0,J.jsxs)(J.Fragment,{children:[Ve===null&&!He&&(0,J.jsx)(`div`,{className:`card models-combos-card`,"aria-busy":`true`,children:(0,J.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,J.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),(0,J.jsx)(`span`,{className:`muted text-label`,children:t(`common.loading`)})]}),(0,J.jsx)(`a`,{className:`btn btn-sm`,href:`#combos`,style:{flexShrink:0,visibility:`hidden`},tabIndex:-1,"aria-hidden":`true`,children:t(`models.combosSetup`)})]})}),Ve===null&&He&&(0,J.jsx)(`div`,{className:`card models-combos-card`,children:(0,J.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,J.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),(0,J.jsx)(`span`,{className:`muted text-label`,role:`alert`,children:t(`models.loadFail`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{flexShrink:0},onClick:()=>ze.refresh(),children:t(`common.retry`)})]})}),Ve!==null&&Ve.length===0&&(0,J.jsx)(`div`,{className:`card models-combos-card`,children:(0,J.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,J.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),He?(0,J.jsx)(`span`,{className:`muted text-label`,role:`alert`,children:t(`models.loadFail`)}):(0,J.jsx)(`span`,{className:`muted text-label`,children:t(`models.combosEmpty`)})]}),He?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{flexShrink:0},onClick:()=>ze.refresh(),children:t(`common.retry`)}):(0,J.jsx)(`a`,{className:`btn btn-sm`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]})}),Ve!==null&&Ve.length>0&&(0,J.jsxs)(`div`,{className:`card models-combos-card`,children:[(0,J.jsxs)(`div`,{className:`row group-head models-field-row${Ue?` open`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`row models-field-row`,"aria-expanded":Ue,onClick:qe,style:{flex:1,background:`none`,border:`none`,padding:0,cursor:`pointer`,font:`inherit`,color:`inherit`,textAlign:`left`,minWidth:0},children:[(0,J.jsx)(we,{style:{width:14,height:14,color:`var(--muted)`,flexShrink:0,transform:Ue?`rotate(90deg)`:`none`,transition:`transform .12s`}}),(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.combosActive`,{count:Ve.length})}),He&&(0,J.jsx)(`span`,{className:`muted text-label`,role:`alert`,children:t(`models.loadFail`)})]}),He?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{flexShrink:0},onClick:()=>ze.refresh(),children:t(`common.retry`)}):(0,J.jsx)(`a`,{className:`btn btn-sm btn-ghost`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]}),Ue&&(0,J.jsxs)(`div`,{children:[Ve.map(e=>(0,J.jsxs)(`div`,{className:`row models-combo-row`,children:[(0,J.jsx)(`span`,{className:`mono leading-ui`,children:e.model}),(0,J.jsxs)(`span`,{className:`muted text-label`,children:[e.strategy,` · `,e.targets.length]})]},e.id)),(0,J.jsxs)(`a`,{className:`row muted models-combos-add`,href:`#combos`,children:[`+ `,t(`models.combosAdd`)]})]})]})]}),Rt=(0,J.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ot(!0),disabled:P,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ot(!1),disabled:P,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),zt=(0,J.jsx)(J.Fragment,{children:tt.length===0&&(0,J.jsx)(pt,{icon:(0,J.jsx)(ie,{}),title:t(`models.noRouted`),children:t(`models.noRoutedHint`)})}),Bt=(0,J.jsxs)(J.Fragment,{children:[ne&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.v2Label`),onClick:()=>re(!1),onKeyDown:e=>{e.key===`Escape`&&re(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:t(`models.v2Label`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>re(!1),"aria-label":t(`common.close`),children:`×`})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,J.jsx)(`div`,{className:`models-help-link`,children:(0,J.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,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>re(!1),children:t(`common.ok`)})})]})}),ae&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.customAdd`),onClick:()=>{Te||oe(!1)},onKeyDown:e=>{e.key===`Escape`&&!Te&&oe(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:t(se===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:le})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>oe(!1),disabled:Te,"aria-label":t(`common.close`),children:`×`})]}),De&&(0,J.jsx)(dt,{tone:`err`,children:De}),(0,J.jsxs)(`div`,{className:`models-field-stack`,children:[(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldModelId`),(0,J.jsx)(`input`,{className:`input`,value:pe,onChange:e=>me(e.target.value),disabled:Te,placeholder:t(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldDisplayName`),(0,J.jsx)(`input`,{className:`input`,value:he,onChange:e=>ge(e.target.value),disabled:Te,placeholder:t(`models.customFieldDisplayNamePlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldContext`),(0,J.jsxs)(`div`,{className:`row models-field-row`,children:[(0,J.jsx)(ft,{value:be?`custom`:_e,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:t(`models.custom`)}],onChange:e=>{if(e===`custom`){xe(!0);return}xe(!1),ve(e)},disabled:Te,label:t(`models.customFieldContext`)}),be&&(0,J.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:_e,onChange:e=>ve(e.target.value),disabled:Te,placeholder:t(`models.customPlaceholder`),"aria-label":t(`models.customFieldContext`)})]})]}),(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[t(`models.customFieldModalities`),(0,J.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:Se.includes(e),onChange:t=>{Ce(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Te}),(0,J.jsx)(`span`,{className:`text-control`,children:e})]},e))})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>oe(!1),disabled:Te,children:t(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Te||!pe.trim(),onClick:()=>{let e=pe.trim(),t=he.trim(),n=_e?Number(_e.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;se===`add`?Dt(le,e,t||void 0,r,Se.length>0?Se:void 0):Ot(de,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:Se})},children:t(Te?`models.customSaving`:se===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]});return(0,J.jsxs)(`div`,{className:`models-workspace-shell`,children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.models`)}),(0,J.jsx)(`div`,{className:`row`,children:(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:nt,total:i.length})})})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`models.subtitle`)}),A&&(0,J.jsx)(dt,{tone:M?`ok`:`err`,children:A}),$e.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`models.loadFail`)}),(0,J.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":$e.refreshing||void 0,children:[(0,J.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":t(`nav.models`),children:[(0,J.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-title`,children:t(`models.workspace.providers`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-count`,children:tt.length})]}),(0,J.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ge===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ke(null),"aria-current":Ge===null?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:t(`models.workspace.allProviders`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:nt,total:i.length})})]}),tt.map(e=>{let{provider:n,rows:r}=e,i=r.filter(e=>Is(jt,n,e.id,e.native===!0,c.has(e.namespaced))).length;return(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ge===n?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ke(n),"aria-current":Ge===n?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:n}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:i,total:r.length})})]},n)})]})]}),(0,J.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":t(`models.workspace.mainAria`),children:[Pt,Lt,Rt,(0,J.jsx)(`div`,{className:`models-provider-list`,children:Nt.map(e=>Mt(e))}),tt.length===0&&zt]})]}),Bt]})}function rc(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function ic(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function ac(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 oc(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||ac(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 sc({value:e,onChange:t,disabled:n}){let r=Z();return(0,J.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:[[`failover`,`cws.strategy.failover`],[`round-robin`,`cws.strategy.roundRobin`]].map(([i,a])=>(0,J.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(a)},i))})}function cc({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Z(),o=i??ns,s=t!==null&&!o.includes(t);return(0,J.jsxs)(J.Fragment,{children:[(0,J.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,J.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,J.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),s?(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function lc({targets:e,strategy:t,providers:n,models:r,onChange:i}){let a=Z(),o=rc(n),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(null),d=(t,n)=>{i(e.map((e,r)=>r===t?{...e,...n}:e))},f=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[a]=r.splice(t,1);r.splice(n,0,a),i(r)};return(0,J.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((p,m)=>{let h=n.find(e=>e.name===p.provider),g=h&&!o.some(e=>e.name===p.provider)?[...o,h]:o,_=oc(r,p.provider,n),v=p.model&&!_.includes(p.model)?[p.model,..._]:_,y=!p.provider;return(0,J.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`?`cwi-target-row--failover`:``,s===m?`cwi-target-row--dragging`:``,l===m&&s!==null&&s!==m?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{s!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,l!==m&&u(m))},onDrop:e=>{e.preventDefault(),s!==null&&f(s,m),c(null),u(null)},onDragEnd:()=>{c(null),u(null)},children:[(0,J.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":a(`cws.target.drag`),title:a(`cws.target.drag`),onDragStart:e=>{c(m),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(m))},children:(0,J.jsx)(Re,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:m===0,"aria-label":a(`cws.target.moveUp`),onClick:()=>f(m,m-1),children:(0,J.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:m===e.length-1,"aria-label":a(`cws.target.moveDown`),onClick:()=>f(m,m+1),children:(0,J.jsx)(Se,{width:14,height:14,"aria-hidden":`true`})})]}),(0,J.jsxs)(`select`,{className:`input`,value:p.provider,"aria-label":a(`cws.target.provider`),onChange:e=>{let t=e.target.value;d(m,{provider:t,model:oc(r,t,n)[0]??``})},children:[(0,J.jsx)(`option`,{value:``,children:a(`cws.target.pickProvider`)}),g.map(e=>(0,J.jsx)(`option`,{value:e.name,children:e.disabled?a(`cws.target.disabled`,{name:e.name}):e.name},e.name))]}),(0,J.jsxs)(`select`,{className:`input`,value:p.model,disabled:y,"aria-label":a(`cws.target.model`),onChange:e=>d(m,{model:e.target.value}),children:[(0,J.jsx)(`option`,{value:``,children:y?a(`cws.target.pickProviderFirst`):v.length===0?a(`cws.target.noModels`):a(`cws.target.pickModel`)}),v.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),t===`round-robin`&&(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:p.weight??1,"aria-label":a(`cws.target.weight`),onChange:e=>{let t=ic(e.target.value,1,1e4);t!==void 0&&d(m,{weight:t})}}),(0,J.jsx)(`div`,{className:`cwi-target-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>i(e.filter((e,t)=>t!==m)),"aria-label":a(`common.remove`),children:(0,J.jsx)(_e,{width:14,height:14})})})]},p.clientKey??`${p.provider}:${p.model}`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>i([...e,as()]),children:[(0,J.jsx)(pe,{width:14,height:14}),` `,a(`cws.target.add`)]})]})}function uc({existingIds:e,existingAliases:t,providerMap:n,providers:r,models:i,onClose:a,onSubmit:o}){let s=Z(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(()=>ws()),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(``),h=(0,_.useMemo)(()=>{let e=new Map;for(let t of i)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[i]),g=(0,_.useMemo)(()=>rs(l.targets,h),[l.targets,h]);(0,_.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let v=(0,_.useCallback)(()=>{d||a()},[d,a]),y=(0,_.useCallback)(e=>{e.preventDefault(),v()},[v]),b=async()=>{let r=Cs(l,{existingIds:e,existingAliases:t,isCreate:!0,providers:n});if(r){m(s(`cws.err.${r}`));return}f(!0),m(``);let i=l.id.trim(),a=l.alias?.trim()||null;try{let e=await o({...l,id:i,alias:a,model:ds(i,a)});if(!e.ok){m(e.error||s(`cws.saveFailed`));return}}finally{f(!1)}};return(0,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:y,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:v}),(0,J.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,J.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:s(`cws.addTitle`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:d,"aria-label":s(`common.close`),children:(0,J.jsx)(fe,{width:16,height:16})})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:s(`cws.addSubtitle`)}),p&&(0,J.jsx)(dt,{tone:`err`,children:p}),(0,J.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-id`,children:s(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:l.id,disabled:d,onChange:e=>u(t=>({...t,id:e.target.value,model:ds(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idInternalHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:s(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:l.alias??``,placeholder:s(`cws.field.aliasPlaceholder`),disabled:d,onChange:e=>u(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:ds(t.id,e.target.value)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.aliasHint`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idHint`,{model:l.id.trim()?ds(l.id,l.alias):`…`})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:s(`cws.strategy`)}),(0,J.jsx)(sc,{value:l.strategy,disabled:d,onChange:e=>u(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:l.strategy===`failover`?s(`cws.strategy.failoverHint`):s(`cws.strategy.roundRobinHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:s(`cws.field.defaultEffort`)}),(0,J.jsx)(cc,{id:`cwi-new-effort`,value:l.defaultEffort,disabled:d,allowedEfforts:g,onChange:e=>u(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.defaultEffortHint`)})]}),l.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:s(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:l.stickyLimit,disabled:d,onChange:e=>{let t=ic(e.target.value,1,100);t!==void 0&&u(e=>({...e,stickyLimit:t}))}}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.stickyLimitHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:s(`cws.targets`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:l.strategy===`failover`?s(`cws.targets.failoverHint`):s(`cws.targets.roundRobinHint`)}),(0,J.jsx)(lc,{targets:l.targets,strategy:l.strategy,providers:r,models:i,onChange:e=>u(t=>({...t,targets:e}))})]})]}),(0,J.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,disabled:d,children:s(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{b()},disabled:d,children:s(d?`common.saving`:`cws.create`)})]})]})]})}function dc({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providers:a,models:o,onBack:s,onSaved:c,onRequestRemove:l,onSave:u,onDirtyChange:d}){let f=Z(),[p,m]=(0,_.useState)(`config`),[h,g]=(0,_.useState)(e),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(!1),w=!xs(h,e),T=`${e.id}:${e.alias??``}:${e.strategy}:${e.stickyLimit}:${e.defaultEffort}:${e.targets.map(e=>`${e.provider}/${e.model}:${e.weight??1}`).join(`,`)}`,E=(0,_.useMemo)(()=>{let e=new Map;for(let t of o)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[o]),D=(0,_.useMemo)(()=>rs(h.targets,E),[h.targets,E]),O=(0,_.useCallback)(t=>{let n=t(h);g(n),d(!xs(n,e))},[h,e,d]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{g(e),x(null),m(`config`),d(!1)},0);return()=>window.clearTimeout(t)},[T]);let k=async()=>{try{await navigator.clipboard.writeText(e.model),C(!0),window.setTimeout(()=>C(!1),1200)}catch{}},A=async()=>{let a=Cs(h,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){x({ok:!1,text:f(`cws.err.${a}`)});return}y(!0);let o=h.id.trim(),s=h.alias?.trim()||null,l={...h,id:o,alias:s,model:ds(o,s)},d=!t&&o!==e.id?e.id:void 0;try{let e=await u(l,t,d);if(!e.ok){x({ok:!1,text:e.error||f(`cws.saveFailed`)});return}x({ok:!0,text:t?f(`cws.created`,{model:l.model}):f(`cws.saved`)}),c(l)}finally{y(!1)}},j=t?h.id.trim()?ds(h.id,h.alias):f(`cws.addTitle`):e.model;return(0,J.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[s&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:s,"aria-label":f(`cws.backToAll`),children:[(0,J.jsx)(we,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),f(`cws.allCombos`)]}),(0,J.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:j}),!t&&(0,J.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{k()},title:f(`cws.copyModel`),children:f(S?`cws.copied`:`cws.copyModel`)}),(0,J.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&l&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,J.jsx)(_e,{width:14,height:14}),` `,f(`common.remove`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!w||v,onClick:()=>{A()},children:f(v?`common.saving`:t?`cws.create`:`common.save`)})]})]}),b&&(0,J.jsx)(dt,{tone:b.ok?`ok`:`err`,children:b.text}),(0,J.jsxs)(`div`,{className:`combos-workspace-tabs`,role:`tablist`,children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":p===`config`,className:`combos-workspace-tab${p===`config`?` combos-workspace-tab--active`:``}`,onClick:()=>m(`config`),children:f(`cws.tab.config`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":p===`about`,className:`combos-workspace-tab${p===`about`?` combos-workspace-tab--active`:``}`,onClick:()=>m(`about`),children:f(`cws.tab.about`)})]}),(0,J.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,children:p===`config`?(0,J.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:f(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:h.id,disabled:v,onChange:e=>O(t=>({...t,id:e.target.value,model:ds(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:t?f(`cws.field.idInternalHint`):f(`cws.field.idHintEdit`,{model:ds(h.id,h.alias)})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:f(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:h.alias??``,placeholder:us(h.id.trim()||`…`),disabled:v,onChange:e=>O(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:ds(t.id,e.target.value)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.aliasHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,J.jsx)(sc,{value:h.strategy,disabled:v,onChange:e=>O(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:h.strategy===`failover`?f(`cws.strategy.failoverHint`):f(`cws.strategy.roundRobinHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-effort`,children:f(`cws.field.defaultEffort`)}),(0,J.jsx)(cc,{id:`cwi-effort`,value:h.defaultEffort,disabled:v,allowedEfforts:D,onChange:e=>O(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),h.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-sticky`,children:f(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:h.stickyLimit,disabled:v,onChange:e=>{let t=ic(e.target.value,1,100);t!==void 0&&O(e=>({...e,stickyLimit:t}))}})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:h.strategy===`failover`?f(`cws.targets.failoverHint`):f(`cws.targets.roundRobinHint`)}),(0,J.jsx)(lc,{targets:h.targets,strategy:h.strategy,providers:a,models:o,onChange:e=>O(t=>({...t,targets:e}))})]})]}):(0,J.jsxs)(`section`,{className:`pwi-section`,children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:f(`cws.aboutTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0},children:f(`cws.aboutBody`)})]})})]})}function fc({model:e,onCancel:t,onConfirm:n}){let r=Z(),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,J.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,J.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function pc({onKeep:e,onDiscard:t}){let n=Z(),r=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,J.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,J.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function mc(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:`cws.attention.few`)}function hc({combos:e,cataloguedComboIds:t,onSelect:n,onAdd:r}){let i=Z(),a=vs(e),o=bs(e,{cataloguedComboIds:t});return(0,J.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,J.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:i(`cws.overviewTitle`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,children:[(0,J.jsx)(pe,{width:14,height:14}),` `,i(`cws.add`)]})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:i(`cws.overviewBlurb`)}),(0,J.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:e.length}),(0,J.jsx)(`span`,{children:i(`cws.count.total`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:a.failover.length}),(0,J.jsx)(`span`,{children:i(`cws.count.failover`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:a.roundRobin.length}),(0,J.jsx)(`span`,{children:i(`cws.count.roundRobin`)})]})]}),(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.howTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.howTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0},children:i(`cws.howBody`)})]}),o.length>0&&(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.attentionTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.attentionTitle`)}),(0,J.jsx)(`div`,{className:`cwi-attention-list`,children:o.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>n(e.id),children:[(0,J.jsx)(ve,{width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`code`,{className:`chip`,children:e.model}),(0,J.jsx)(`span`,{className:`muted`,children:mc(e.reason,i)}),(0,J.jsx)(we,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function gc({combos:e,providers:t,models:n,cataloguedComboIds:r,loading:i,onRefresh:a,onSave:o,onRemove:s,onAdd:c,adding:l,onCloseAdd:u,onCreated:d}){let f=Z(),p=(0,_.useMemo)(()=>Object.fromEntries(t.map(e=>[e.name,{disabled:e.disabled}])),[t]),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(void 0),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),T=(0,_.useMemo)(()=>ws(),[]),E=(0,_.useMemo)(()=>ys(e,m),[e,m]),D=(0,_.useMemo)(()=>vs(E),[E]),O=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),k=g&&e.some(e=>e.id===g)?g:null,A=e.find(e=>e.id===k)??null,j=A&&C?.id===A.id?C:A,[M,N]=(0,_.useState)(!1),P=[],F=[];if(j)for(let t of e)t.id!==j.id&&(P.push(t.id),t.alias&&F.push(t.alias));let I=(0,_.useCallback)(e=>{if(e!==k){if(!M){v(e),w(null);return}b(e)}},[k,M]),L=()=>{y!==void 0&&(v(y),w(null),N(!1),b(void 0))},R=()=>b(void 0),z=y!==void 0&&M,B=!i&&e.length===0;return(0,J.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":f(`cws.railAria`),children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`combos-workspace-rail-title`,children:f(`nav.combos`)}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(B){document.getElementById(`cwi-edit-id`)?.focus();return}c()},"aria-label":f(`cws.add`),children:[(0,J.jsx)(pe,{width:14,height:14}),` `,f(`cws.add`)]})]}),(0,J.jsx)(`div`,{className:`cwi-search-row`,children:(0,J.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,J.jsx)(be,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,J.jsx)(`input`,{className:`input cwi-search-input`,value:m,onChange:e=>h(e.target.value),placeholder:f(`cws.searchPlaceholder`),"aria-label":f(`cws.searchPlaceholder`)})]})}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-list`,children:E.length===0&&e.length>0?(0,J.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:f(`cws.noSearchResults`)}):(0,J.jsx)(J.Fragment,{children:[[`failover`,D.failover,`cws.group.failover`],[`round-robin`,D.roundRobin,`cws.group.roundRobin`]].map(([e,t,n])=>t.length>0?(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,J.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),f(n),(0,J.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${k===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>I(e.id),"aria-current":k===e.id?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,J.jsx)(Le,{width:16,height:16})}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?f(`cws.targetCountOne`):f(`cws.targetCount`,{count:e.targets.length})}),(0,J.jsx)(we,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,J.jsx)(`div`,{className:`combos-workspace-main`,children:j?(0,J.jsx)(dc,{baseline:j,otherIds:P,otherAliases:F,providerMap:p,providers:t,models:n,onBack:()=>I(null),onSaved:e=>{N(!1),e.id===j.id?w(e):(v(e.id),w(null)),a()},onRequestRemove:()=>S(j.id),onSave:o,onDirtyChange:N},j.id):B?(0,J.jsx)(dc,{baseline:T,isCreate:!0,otherIds:[],otherAliases:[],providerMap:p,providers:t,models:n,onSaved:e=>{N(!1),v(e.id),w(e),d(e.id)},onSave:o,onDirtyChange:N},`first-combo`):(0,J.jsx)(hc,{combos:e,cataloguedComboIds:r,onSelect:e=>I(e),onAdd:c})}),l&&!B&&(0,J.jsx)(uc,{existingIds:e.map(e=>e.id),existingAliases:O,providerMap:p,providers:t,models:n,onClose:u,onSubmit:async e=>{let t=await o(e,!0);return t.ok&&(u(),d(e.id),v(e.id),w(null)),t}}),x&&(0,J.jsx)(fc,{model:e.find(e=>e.id===x)?.model??us(x),onCancel:()=>S(null),onConfirm:()=>{(async()=>{let e=await s(x);S(null),e.ok&&(k===x&&(v(null),w(null)),a())})()}}),z&&(0,J.jsx)(pc,{onKeep:R,onDiscard:L})]})}function _c(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function vc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function yc(e){return vn(e)}function bc({apiBase:e}){let t=Z(),n=`ocx.combos.workspace.v1:${e}`,r=yc(n),[i,a]=(0,_.useState)(``),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),u=(e,t)=>{a(e),s(t)};(0,_.useEffect)(()=>{if(!i||!o)return;let e=window.setTimeout(()=>{a(``),s(!1)},5e3);return()=>window.clearTimeout(e)},[i,o]);let d=(0,_.useCallback)(async()=>{let[t,r,i]=await Promise.all([fetch(`${e}/api/combos`),fetch(`${e}/api/config`),fetch(`${e}/api/models`)]);if(!t.ok||!r.ok||!i.ok)throw Error(`combo workspace load failed`);let a=await t.json(),o=await r.json(),s=await i.json(),c=Array.isArray(s)?s:Array.isArray(s?.models)?s.models:[],l=_s(a),u=o.providers??{},d=sr(u),f=Object.entries(u).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:!Object.hasOwn(d,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl})),p=[],m=new Set;for(let e of c){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`){m.add(r);continue}if(t.disabled===!0)continue;let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0;p.push({provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{}})}for(let[e,t]of Object.entries(u)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;!n||t.disabled||p.some(t=>t.provider===e&&t.id===n)||p.push({provider:e,id:n,namespaced:`${e}/${n}`})}let h={combos:l,providers:f,models:p,cataloguedComboIds:[...m]};return yn(n,h),h},[e,n]),f=Es(n,[e],d,{isEmpty:()=>!1}),{state:p}=f,m=p.data??r,h=m?.combos??[],g=m?.providers??[],v=m?.models??[],y=new Set(m?.cataloguedComboIds??[]);return p.showSkeleton&&!m?(0,J.jsx)(Os,{label:t(`cws.loading`),rows:5}):p.kind===`failed-cold`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:p.error instanceof Error?p.error.message:t(`cws.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,J.jsxs)(`div`,{className:`combos-workspace-shell`,children:[i&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)(dt,{tone:o?`ok`:`err`,children:i})}),p.showError&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)(dt,{tone:`err`,children:t(`cws.loadFailed`)})}),p.refreshing&&(0,J.jsx)(ks,{live:!p.showError,children:t(`cws.loading`)}),(0,J.jsx)(`div`,{className:`combos-workspace-shell-body`,children:(0,J.jsx)(gc,{combos:h,providers:g,models:v,cataloguedComboIds:y,loading:!1,onRefresh:()=>f.refresh(),onSave:async(n,r,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(Ss(n,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=_c(o);if(!a.ok||s||!vc(o)){let e=s||t(`cws.saveFailed`);return u(e,!1),{ok:!1,error:e}}return f.refresh(),u(i?t(`cws.renamed`,{from:us(i),to:n.model}):r?t(`cws.created`,{model:n.model}):t(`cws.saved`),!0),{ok:!0}}catch{let e=t(`cws.saveFailed`);return u(e,!1),{ok:!1,error:e}}},onRemove:async n=>{try{let r=await fetch(`${e}/api/combos?id=${encodeURIComponent(n)}`,{method:`DELETE`}),i=r.ok?await r.json():await r.json().catch(()=>null),a=_c(i);if(!r.ok||a||!vc(i)){let e=a||t(`cws.removeFailed`);return u(e,!1),{ok:!1,error:e}}return f.refresh(),u(t(`cws.removed`,{id:n}),!0),{ok:!0}}catch{let e=t(`cws.removeFailed`);return u(e,!1),{ok:!1,error:e}}},onAdd:()=>l(!0),adding:c,onCloseAdd:()=>l(!1),onCreated:()=>f.refresh()})})]})}var xc=`section`;function Sc(e,t){return[e,xc,t].join(`-`)}function Cc(e){return[e,xc,``].join(`-`)}var wc=1200;function Tc({scope:e,items:t,ariaLabel:n}){let[r,i]=(0,_.useState)(t[0]?.id??``),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useCallback)(()=>{a.current=null,o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),c=(0,_.useCallback)(()=>{s();let n=null,r=1/0;for(let i of t){let t=document.getElementById(Sc(e,i.id));if(!t)continue;let a=Math.abs(t.getBoundingClientRect().top-72);a<r&&(r=a,n=i.id)}n&&i(n)},[s,t,e]);(0,_.useEffect)(()=>()=>s(),[s]),(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(Sc(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=a.current;if(n){let r=document.getElementById(Sc(e,n));t.some(e=>e.isIntersecting&&e.target===r)&&(s(),i(n));return}let r=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!r)return;let o=r.target.id.slice(Cc(e).length);i(e=>e===o?e:o)},{rootMargin:`-72px 0px -60% 0px`,threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[s,t,e]);let l=t=>{let n=document.getElementById(Sc(e,t));n&&(a.current=t,o.current!==null&&clearTimeout(o.current),o.current=setTimeout(c,wc),i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,J.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,J.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":Sc(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>l(t.id),children:[t.label,t.meta?(0,J.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function Ec({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s}){let c=Z();return(0,J.jsxs)(`div`,{className:`swi-delegation`,children:[(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:c(`sub.delegation.model`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:c(`sub.delegation.modelHint`)})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,J.jsx)(ft,{value:e,options:[{value:``,label:c(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:`${e.provider} / ${e.model}`}))],onChange:e=>s({model:e||null,effort:t||null}),disabled:o,label:c(`dash.injectionLabel`)}),e&&n.length>0&&(0,J.jsx)(ft,{value:t,options:[{value:``,label:c(`dash.injectionEffortNone`)},...n.map(e=>({value:e,label:e}))],onChange:t=>s({model:e||null,effort:t||null}),disabled:o,label:c(`dash.injectionEffortLabel`)})]})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:c(`dash.syncCodexSubagentDefaults`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>s({syncCodexSubagentDefaults:!a}),disabled:o||!e,"aria-label":c(`dash.syncCodexSubagentDefaults`),"aria-pressed":a,children:(0,J.jsx)(`span`,{className:`knob`})})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:c(`dash.multiAgentGuidance`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.multiAgentGuidanceHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":c(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,J.jsx)(`span`,{className:`knob`})})]})]})}function Dc({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=Z(),[c,l]=(0,_.useState)(``),u=(0,_.useMemo)(()=>new Set(t),[t]),d=t.length>=5,f=(0,_.useMemo)(()=>{let t=c.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,c]);return(0,J.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,J.jsx)(Tc,{scope:`subagents`,items:(0,_.useMemo)(()=>[{id:`featured`,label:s(`sub.featured`),meta:`${t.length}/5`},{id:`models`,label:s(`sub.models`),meta:String(f.length)},{id:`settings`,label:s(`sub.settings`)}],[s,t.length,f.length]),ariaLabel:s(`sub.sections`)}),(0,J.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,J.jsxs)(`section`,{id:Sc(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,J.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,J.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,J.jsx)(ye,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:(0,J.jsx)(Ye,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,J.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,J.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,J.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,J.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,J.jsx)(`span`,{className:`swi-featured-name`,children:ts(e)}),(0,J.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,-1),disabled:n||a===0,"aria-label":s(`sub.moveUp`,{m:e}),children:(0,J.jsx)(xe,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,1),disabled:n||a===t.length-1,"aria-label":s(`sub.moveDown`,{m:e}),children:(0,J.jsx)(Se,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>r(e),disabled:n,"aria-label":s(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,J.jsx)(fe,{})})]})]},e))}),(0,J.jsx)(`div`,{className:`swi-save-row`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,J.jsxs)(`section`,{id:Sc(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,J.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,J.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,J.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,J.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,J.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,J.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:s(`sub.noModels`)}):f.map(e=>{let i=u.has(e),a=i?t.indexOf(e)+1:null,o=!i&&(d||n);return(0,J.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,J.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,J.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,J.jsx)(ae,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:ts(e)})]}),(0,J.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${i?` subagents-workspace-rail-toggle--on`:``}${o?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{o||r(e)},disabled:o,"aria-pressed":i,"aria-label":s(i?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:i?s(`sub.workspace.removeFromFeatured`,{m:e}):d?s(`sub.workspace.featuredFull`):s(`sub.workspace.addToFeatured`,{m:e}),children:i?(0,J.jsx)(de,{style:{width:14,height:14}}):(0,J.jsx)(pe,{style:{width:14,height:14}})})]},e)})})]})]}),(0,J.jsxs)(`section`,{id:Sc(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,J.jsx)(`div`,{className:`swi-featured-head`,children:(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,J.jsx)(Ec,{model:o.model,effort:o.effort,efforts:o.efforts,available:o.available,guidanceEnabled:o.guidanceEnabled,syncCodexDefaults:o.syncCodexDefaults,saving:o.saving,onSave:o.onSave})]})]})]})}function Oc(e){let[t,n]=(0,_.useState)(!1),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)([]),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useCallback)(e=>{let t=On(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,_.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await St(await fetch(`${e}/api/injection-model`));if(t)return;v(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,v]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,_.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`);v(await St(await fetch(`${e}/api/injection-model`)))}catch{}finally{i(!1)}}},[e,v,r])}}function kc(e){return vn(e)}function Ac({apiBase:e}){let t=Z(),n=`ocx.subagents.v1:${e}`,r=kc(n),[i,a]=(0,_.useState)(()=>r?.chosen??[]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),f=(0,_.useRef)(!1),p=Oc(e),m=(0,_.useCallback)(async r=>{let i=await Q(await fetch(`${e}/api/subagent-models`,{signal:r}),t(`sub.loadFail`));if(!i)throw Error(t(`sub.loadFail`));let o=i.available??[],s=new Set(o),c={available:o,chosen:(i.chosen??[]).filter(e=>s.has(e))};return a(c.chosen),yn(n,c),c},[e,n,t]),h=Es(n,[e],m,{isEmpty:()=>!1,initialData:r??void 0}),{state:g}=h,v=h.refresh,y=g.data??r,b=y?.available??[],x=e=>{u||(s(``),a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e]))},S=(e,t)=>{u||a(n=>{let r=[...n],i=e+t;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)})},C=async()=>{if(!(u||f.current)){f.current=!0,d(!0),s(``);try{let r=await Q(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:i})}),t(`sub.saveFailed`)),o=r?.applied??i;r?.applied&&a(r.applied),yn(n,{available:b,chosen:o}),l(!0),s(t(`sub.saved`,{n:o.length,cmd:`ocx sync`}))}catch(e){l(!1),s(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{f.current=!1,d(!1)}}};return g.showSkeleton&&!y?(0,J.jsx)(Os,{label:t(`sub.loading`),rows:4}):g.kind===`failed-cold`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:g.error instanceof Error?g.error.message:t(`sub.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,J.jsx)(dt,{tone:c?`ok`:`err`,children:o}),g.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`sub.loadFail`)}),(0,J.jsx)(Dc,{available:b,chosen:i,busy:u,onToggle:x,onMove:S,onSave:()=>{C()},delegation:{model:p.model,effort:p.effort,efforts:p.efforts,available:p.available,guidanceEnabled:p.guidanceEnabled,syncCodexDefaults:p.syncCodexDefaults,saving:p.saving,onSave:e=>{p.save(e)}}})]})}function jc(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 Mc(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 Nc(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Pc=(e,t)=>Math.abs(e-t)<1.01,Fc=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Ic,Lc=()=>{if(Ic!==void 0)return Ic;if(typeof navigator>`u`)return Ic=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Ic=!0;let e=navigator.maxTouchPoints;return Ic=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Rc=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},zc=e=>e,Bc=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},Vc=(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(Rc(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(Rc(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Hc={passive:!0},Uc=typeof window>`u`?!0:`onscrollend`in window,Wc=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Uc,o=0,s=a?null:Fc(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,Hc),a&&r.addEventListener(`scrollend`,u,Hc),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Gc=(e,t)=>Wc(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Kc=(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`]},qc=(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})},Jc=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:zc,rangeExtractor:Bc,onChange:()=>{},measureElement:Kc,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=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=Mc(()=>(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.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.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=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,!(!Lc()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Hc),e.addEventListener(`touchend`,n,Hc),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&&(Lc()&&(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;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.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=Mc(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(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}),{key:!1}),this.getMeasurements=Mc(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=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 l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=jc(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Mc(()=>[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=Mc(()=>{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=t-(this.itemSizeCache.get(i)??n);if(o!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,s=a?this.getTotalSize():0,c=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(i)||this.scrollDirection!==`backward`):this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,a?this.applyScrollAdjustment(this.getTotalSize()-s):c&&this.applyScrollAdjustment(o),this.notify(!1)}},this.getVirtualItems=Mc(()=>[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 Nc(t[Yc(0,t.length-1,r?e=>n[e*2]:e=>Nc(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`}={})=>{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`}={})=>{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){e!==0&&(Lc()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=e:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=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&&Pc(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()}},Yc=(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 Xc(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=Xc(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=Yc(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 Qc=typeof document<`u`?_.useLayoutEffect:_.useEffect;function $c({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=_.useReducer(e=>e+1,0)[1],a=_.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`}let r=!!e.options.horizontal,i=t.mode===`transform`,o=r?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let n of c){let a=n.start-s,c=e.elementsCache.get(n.key);c&&t.lastPositions.get(c)!==a&&(t.lastPositions.set(c,a),i?c.style.transform=r?`translate3d(${a}px, 0, 0)`:`translate3d(0, ${a}px, 0)`:c.style[o]=`${a}px`)}},s={...r,onChange:(t,n)=>{var s;let c=a.current,l=!0;if(c.enabled){o(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,$e.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[c]=_.useState(()=>{let e=new Jc(s);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 c.setOptions(s),Qc(()=>c._didMount(),[]),Qc(()=>c._willUpdate()),Qc(()=>{o(c)}),c}function el(e){return $c({observeElementRect:Vc,observeElementOffset:Gc,scrollToFn:qc,...e})}var tl=32;function nl(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function rl(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}async function il(e){let t=e.trim();if(t&&!rl(t)&&!(t.length>4096))return nl(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,tl)}function al(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r?!0:n!==void 0&&e===n:!1}var ol={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{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 本文を確認してください。`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{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 が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`}},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.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{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:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`}},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.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다.`},zh:{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 キーが不正とは限りません。`}},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.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{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 プロバイダー設定を確認してください。`}},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.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{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:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`}},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.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{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:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`}},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.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{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:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`}},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.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{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:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`}},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.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{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 がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`}},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.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{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:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`}},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.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{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 がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{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 回再試行し、繰り返す場合はプロキシログを確認してください。`}},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.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{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:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{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:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`}},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.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{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:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{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:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`}}},sl={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{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:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`}},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.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{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 または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`}}};function cl(e){return e===`de`||e===`ko`||e===`zh`||e===`ru`||e===`ja`?e:`en`}function ll(e,t){if(e<400)return null;let n=cl(t);return(ol[Math.trunc(e)]??(e<500?sl.client:sl.server))[n]}var ul=[`provider`,`usage`,`injection`];function dl(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function fl(e){return new Date(e).toLocaleTimeString()}function pl(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function ml(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function hl({entries:e}){let{t}=X();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,J.jsx)(`div`,{style:{overflowX:`auto`},children:(0,J.jsxs)(`table`,{className:`table text-label`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,J.jsx)(`th`,{children:`thinking`}),(0,J.jsx)(`th`,{children:`effort`}),(0,J.jsx)(`th`,{children:`beta`}),(0,J.jsx)(`th`,{children:`metadata`}),(0,J.jsx)(`th`,{children:`system`})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted mono`,children:fl(e.at)}),(0,J.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,J.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,J.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,J.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,J.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,J.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,J.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function gl({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=X();return e?n?r.length===0?(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,J.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,J.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,J.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${dl(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function _l({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=X();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=ml(e,n);return(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,J.jsx)(ut,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,J.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:i,children:o(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,J.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function vl({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=X();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,J.jsx)(`h2`,{children:o(`debug.title`)}),(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,J.jsx)(me,{}),` `,o(`debug.refresh`)]}),(0,J.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function yl(e){return`debug-settings:${e}`}function bl({apiBase:e,embedded:t,active:n=!0}){let{t:r}=X(),i=`ocx.debug.settings.v1:${e}`,a=vn(i),o=yl(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(`provider`),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useRef)(0),b=(0,_.useRef)(0),x=(0,_.useRef)(0),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),T=Es(o,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return yn(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),E=T.state,D=T.data??a??null,O=K(`debug-claude-inbound:${e}`,[e,D?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:n&&!!D?.claude}).data??[],k=el({count:d.length,getScrollElement:()=>C.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),A=(0,_.useCallback)(e=>pl(D,e),[D]);(0,_.useEffect)(()=>{if(!D||A(l))return;let e=ul.find(A);if(!e)return;let t=window.setTimeout(()=>u(e),0);return()=>window.clearTimeout(t)},[D,l,A]);let j=A(l),M=l===`provider`?`${e}/api/debug/logs`:l===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,N=(0,_.useCallback)(async(e,t)=>{let n=++x.current;if(!j){n===x.current&&(f([]),v.current=0);return}g(!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!==x.current)return;let a=await i.json();if(t?.aborted||n!==x.current||a.length===0)return;f(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===x.current&&g(!1)}},[M,j]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${l}:${j}`,r=w.current!==t;if(w.current=t,!r&&d.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&f([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),x.current+=1,i.abort()}},[n,e,l,j]);let P=(0,_.useRef)(!1),F=(0,_.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let e=y(1e4);N(!1,e.signal).finally(()=>{e.clear(),P.current=!1})});(0,_.useEffect)(()=>{if(!(!n||!p||!j))return Jt(()=>F(),1e3)},[n,p,j]),(0,_.useEffect)(()=>{p&&d.length>0&&k.scrollToIndex(d.length-1,{align:`end`})},[d,p,k]);let I=async t=>{let n=++b.current;c(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let a=await r.json();if(n!==b.current)return;yn(i,a),q(o,a)}catch{}},a=(S.current??Promise.resolve()).then(r,r);S.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===b.current&&c(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(vl,{embedded:t,refreshing:h,streamEnabled:j,follow:p,onRefresh:()=>void N(!0),onFollowChange:m}),!D&&E.showError?(0,J.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,J.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>T.refresh(),children:r(`common.retry`)})]}):E.showSkeleton&&!D?(0,J.jsx)(Os,{label:r(`debug.loading`),rows:3}):D?(0,J.jsx)(_l,{debug:D,debugBusy:s,stream:l,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()},onStreamChange:u}):null,D&&E.showError&&(0,J.jsx)(dt,{tone:`err`,children:r(`debug.loadFailed`)}),D?.claude&&(0,J.jsx)(hl,{entries:O}),(0,J.jsx)(gl,{debug:!!D,stream:l,streamEnabled:j,entries:d,scrollContainerRef:C,lineVirtualizer:k})]})}function xl(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function Sl(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function Cl(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),Sl(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),Sl(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function wl(e){return e.requestedSpeedLabel||void 0}function Tl(e,t){return t===`all`?!0:t===`claude`?e.surface===`claude`||e.surface===`claude-desktop`:t===`grok`?e.surface===`grok`:e.surface===void 0}function El(e){return`ocx.logs.list.v1:${e}`}function Dl(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`)return null;return e}function Ol(e){return e===`cursor`||e.startsWith(`cursor-`)}function kl(e,t){if(!e.usage)return;let n=Ml(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(Ol(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function Al(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 jl(e){let t=Al(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function Ml(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 Nl(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 Pl(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function Fl(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}`}function Il(e,t){if(!e||e.kind===`unavailable`||!Number.isFinite(e.estimate.cost.total)||e.estimate.cost.total<0)return`—`;let n=e.estimate.cost.total;return`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(n)}`}function Ll(e,t){return!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var Rl=3,zl={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`},Bl={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`};function Vl(e){return zl[e]}function Hl(e){return Bl[e]}function Ul(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function Wl(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Gl(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 Kl(e,t,n){let{date:r,time:i}=Gl(e,t,n);return`${r} ${i}`}function ql(e){return[`model=${e.model}`,e.resolvedModel?`resolved=${e.resolvedModel}`:void 0,e.requestedServiceTier?`requestedTier=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`configuredTier=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`responseTier=${e.responseServiceTier}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`supportsTier=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function Jl(e){let t=0,n=0,r=0,i=0;for(let a of e){let e=Al(a);if(e!==void 0&&(t+=e),a.usageStatus===`unsupported`){i+=1;continue}let o=a.displayMetrics?.cost,s=o?.kind===`value`?o.estimate.cost.total:void 0;if(s!==void 0&&Number.isFinite(s)&&s>=0){n+=s;continue}r+=1}return{requests:e.length,totalTokens:t,estimatedCostUsd:n,unpricedRequests:r,unmeteredRequests:i}}function Yl({apiBase:e}){let{t,locale:n}=X(),r=El(e),i=Dl(vn(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(`all`),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(),v=(0,_.useRef)(null),y=Ue.find(e=>e.code===n)?.htmlLang,[b,x]=(0,_.useState)();(0,_.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()&&x(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[S,C]=(0,_.useState)(xl),[w,T]=(0,_.useState)(()=>xl()===`debug`);(0,_.useEffect)(()=>{let e=()=>C(xl());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{S===`debug`&&T(!0)},[S]);let E=Sl,D=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/logs?limit=2000`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let i=await n.json(),a=Array.isArray(i)?i:i.logs??[];return yn(r,a),a},[e,r]),O=Es(r,[e],D,{isEmpty:e=>e.length===0,enabled:S===`logs`,pollMs:a?2e3:void 0,initialData:i??void 0}),k=O.state,A=k.data??i??[],j=O.refresh,M=!O.refreshing&&k.showError,N=!O.refreshing&&!k.showError&&k.data!==void 0,[P,F]=(0,_.useState)({error:null,count:0});N&&P.count!==0?F({error:null,count:0}):M&&P.error!==k.error&&F(e=>({error:k.error,count:e.count+1}));let I=P.count>=Rl||!a&&M,L=s?ll(s.status,n):null,R=p.trim();(0,_.useEffect)(()=>{let e=!1;if(!R){g(void 0);return}return il(R).then(t=>{e||g(t)}),()=>{e=!0}},[R]);let z=A.filter(e=>Tl(e,l)&&(!d||!!e.shadowCallRewrittenFrom)&&(!R||al(e.conversationId,R,h))),B=R?Jl(z):null,V=el({count:z.length,getScrollElement:()=>v.current,estimateSize:()=>44,overscan:15}),H=V.getVirtualItems(),U=H.length>0?H[0].start:0,W=H.length>0?V.getTotalSize()-H[H.length-1].end:0;return(0,J.jsxs)(`div`,{className:`logs-page`,children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.logs`)}),S===`logs`&&(0,J.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,J.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":S===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:S===`logs`?0:-1,className:`page-tab${S===`logs`?` page-tab--active`:``}`,onClick:()=>E(`logs`),onKeyDown:Cl,children:t(`logs.tabLogs`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":S===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:S===`debug`?0:-1,className:`page-tab${S===`debug`?` page-tab--active`:``}`,onClick:()=>E(`debug`),onKeyDown:Cl,children:t(`logs.tabDebug`)})]}),w&&(0,J.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:S!==`debug`,children:(0,J.jsx)(bl,{apiBase:e,embedded:!0,active:S===`debug`})}),(0,J.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:S!==`logs`,children:[(0,J.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,J.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,J.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm${l===e?` btn-primary`:` btn-ghost`}`,style:{background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},onClick:()=>u(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),t(`logs.filter.interceptedHelpersOnly`)]}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,J.jsx)(`input`,{type:`search`,className:`input mono`,value:p,onChange:e=>m(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),R&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>m(``),children:t(`logs.filter.conversation.clear`)})]}),B&&(0,J.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,J.jsxs)(dt,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:B.requests,tokens:Vt(B.totalTokens,y??n),cost:Ll(B.estimatedCostUsd,y)}),` `,(0,J.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),B.unpricedRequests+B.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:B.unpricedRequests,unmetered:B.unmeteredRequests})}`:``]})]})}),k.kind===`failed-cold`&&(0,J.jsxs)(dt,{tone:`err`,children:[k.error instanceof Error?`${t(`logs.loadError`)} ${k.error.message}`:t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j({forceLoading:!0}),disabled:k.refreshing,children:t(`common.retry`)})]}),I&&A.length>0&&(0,J.jsxs)(dt,{tone:`err`,children:[t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j({forceLoading:!0}),disabled:O.refreshing,children:t(`common.retry`)})]}),k.kind===`failed-cold`?null:k.showSkeleton&&A.length===0?(0,J.jsx)(Os,{label:t(`common.loading`),rows:6}):z.length===0?(0,J.jsx)(pt,{title:t(`logs.noRequests`)}):(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{ref:v,className:`tbl-wrap logs-table-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`logs.col.time`)}),(0,J.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,J.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,J.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,J.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,J.jsx)(`th`,{children:t(`logs.col.status`)}),(0,J.jsx)(`th`,{children:t(`logs.col.request`)}),(0,J.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,J.jsxs)(`tbody`,{children:[U>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:U}})}),H.map(e=>{let r=z[z.length-1-e.index],i=Pl(r),a=Gl(r.timestamp,y,b);return(0,J.jsxs)(`tr`,{"data-index":e.index,ref:V.measureElement,children:[(0,J.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:a.date}),(0,J.jsx)(`span`,{children:a.time})]})}),(0,J.jsx)(`td`,{className:`num mono log-col-tokens`,title:kl(r,t),children:(()=>{let e=jl(r),{read:i,write:a}=Ml(r);return e===void 0?(0,J.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,J.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,J.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Vt(e,n)]}),i!==void 0&&i>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Vt(i,n)]}),a!==void 0&&a>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Vt(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(Ol(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,J.jsx)(`td`,{className:`num mono log-col-rate`,children:Fl(r.displayMetrics?.tokPerSecond,y)}),(0,J.jsx)(`td`,{className:`num mono log-col-cost`,children:Il(r.displayMetrics?.cost,y)}),(0,J.jsx)(`td`,{className:`mono log-col-model`,title:ql(r),children:(0,J.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,J.jsx)(`span`,{children:ts(r.resolvedModel??r.model)}),r.shadowCallRewrittenFrom&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:t(`logs.badge.interceptedHelperTitle`),children:t(`logs.badge.interceptedHelper`,{model:r.shadowCallRewrittenFrom})}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),wl(r)&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:wl(r)})]})}),(0,J.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:Nl(r)}),i&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,J.jsx)(`td`,{className:`muted`,children:r.provider}),(0,J.jsx)(`td`,{children:(0,J.jsxs)(`span`,{className:`log-status-cell`,children:[(0,J.jsx)(`span`,{className:`mono font-semibold`,style:{color:Wl(r.status)},children:r.status}),(0,J.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>c(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,J.jsx)(`td`,{className:`muted mono`,children:(0,J.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,J.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),W>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:W}})})]})]})})}),s&&(0,J.jsx)(Zl,{detail:s,detailInfo:L,localeCode:n,localeTag:y,serverTimeZone:b,t,onClose:()=>c(null),onFilterConversation:e=>{m(e),c(null)}})]})]})}function Xl(e){let t=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function Zl({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Xl(!0),[l,u]=(0,_.useState)(!1),d=Ml(e),f=e.displayMetrics?.cost,p=Pl(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,J.jsx)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:(0,J.jsxs)(`div`,{className:`modal-card log-detail-card`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,J.jsx)(`span`,{className:`mono`,style:{color:Wl(e.status)},children:e.status}),t&&(0,J.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,J.jsx)(fe,{})})]}),t&&(0,J.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,J.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,J.jsx)(`span`,{className:`mono`,children:Kl(e.timestamp,r,i)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,J.jsx)(`span`,{className:`mono`,children:ts(e.resolvedModel??e.model)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,J.jsx)(`span`,{children:e.provider}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[Nl(e),p?` (${p})`:``]})]}),e.errorCode&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,J.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`span`,{className:`mono`,children:Fl(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Vl(e.displayMetrics.tokPerSecond.reason))})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,J.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.total,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.input,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.cacheRead,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.cacheWrite,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.output,r)}),f.estimate.price&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,J.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,J.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Ul(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,J.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,J.jsx)(`li`,{children:a(Hl(e))},e))})]}):(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,J.jsx)(`span`,{children:f?.kind===`unavailable`?a(Vl(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,J.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,J.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{className:`num`,children:`#`}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,J.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=Pl(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.join(`, `):void 0)??(t?.kind===`unavailable`?a(Vl(t.reason)):a(`logs.detail.attempt.completed`));return(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,J.jsxs)(`td`,{children:[(0,J.jsx)(`span`,{children:e.provider}),(0,J.jsx)(`br`,{}),(0,J.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[Nl(e),n?` (${n})`:``]})]}),i&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Ul(i.status))]})]})]}),(0,J.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`td`,{className:`num mono`,children:Fl(e.displayMetrics?.tokPerSecond,r)}),(0,J.jsx)(`td`,{className:`num mono`,children:Il(t,r)}),(0,J.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,J.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Vt(e.usage.inputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Vt(e.usage.outputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Vt(d.read,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Vt(d.write,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Vt(e.usage.reasoningOutputTokens,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,J.jsx)(`span`,{className:`mono`,children:jl(e)===void 0?`—`:Vt(jl(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:Vt(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,J.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,J.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,J.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})})}function Ql(e){return`${Math.round(e*100)}%`}function $l(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 eu(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 tu(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 nu(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function ru(e){let t=tu(e.map(e=>e.totalTokens)),n=new Map(e.map(e=>[e.date,e])),r=new Date;r.setHours(0,0,0,0);let i=new Date(r);i.setDate(i.getDate()-364),i.setDate(i.getDate()-i.getDay());let a=[],o=[],s=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],c=-4,l=-1,u=[],d=new Date(i);for(;d<=r;){let e=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,`0`)}-${String(d.getDate()).padStart(2,`0`)}`,r=d.getMonth();d.getDay()===0&&r!==l&&a.length-c>=4&&(o.push({label:s[r],col:a.length}),c=a.length,l=r);let i=n.get(e);u.push({date:e,requests:i?.requests??0,totalTokens:i?.totalTokens??0,level:i?nu(i.totalTokens,t):0,dayOfWeek:d.getDay()}),d.getDay()===6&&(a.push(u),u=[]),d.setDate(d.getDate()+1)}if(u.length>0){for(;u.length<7;)u.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:u.length});a.push(u)}return{weeks:a,months:o,buckets:t}}function iu({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,J.jsxs)(`div`,{className:`usage-filters`,children:[(0,J.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,J.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,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,J.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,J.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 au({summary:e,activeDays:t,locale:n,t:r}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Vt(e.totalTokens,n)})]}),(0,J.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Vt(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,J.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Vt(e.cacheCreationInputTokens??0,n)]})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Ql(e.coverageRatio)})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,J.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,J.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,J.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:Ta(e.estimatedCostUsd,n)}),(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function ou({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,J.jsx)(`div`,{className:`daybars`,role:`img`,"aria-label":n(`usage.section.heatmap`),children:e.map(e=>{let n=Math.round(e.totalTokens/a*100),o=e.date.slice(5);return(0,J.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,J.jsx)(`div`,{className:`daybar-track`,children:(0,J.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:$l(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,J.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,J.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,J.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,J.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:$l(e.model,e.provider)}}),(0,J.jsx)(`span`,{className:`daybar-tip-name`,children:ts(e.model)}),(0,J.jsx)(`span`,{className:`daybar-tip-val`,children:Vt(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,J.jsx)(`span`,{className:`daybar-count`,children:Vt(e.totalTokens,t)}),(0,J.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function su({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,_.useRef)(null),[o,s]=(0,_.useState)(null);return(0,_.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,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,J.jsx)(ou,{weekBars:n,locale:r,t:i}):(0,J.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,J.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,J.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,J.jsxs)(`div`,{className:`heatmap-body`,children:[(0,J.jsxs)(`div`,{className:`heatmap-days`,children:[(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,J.jsx)(`span`,{})]}),(0,J.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,J.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,J.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.currentTarget.getBoundingClientRect();s({weekIndex:t,dayIndex:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>s(e=>e?.weekIndex===t&&e.dayIndex===n?null:e)},e.date||`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),o&&(()=>{let e=t.weeks[o.weekIndex]?.[o.dayIndex];return e?.date?(0,J.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,J.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,J.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Vt(e.totalTokens,r)})}),(0,J.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,J.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,J.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,J.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,J.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function cu({title:e,titleId:t,children:n}){return(0,J.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,J.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function lu({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=(0,J.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`logs.col.model`)}),(0,J.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:ts(e.model)}),(0,J.jsx)(`td`,{className:`muted`,children:e.provider}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Vt(e.totalTokens,r)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,J.jsxs)(cu,{title:s,titleId:c,children:[(0,J.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function uu({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:e.provider}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Vt(e.totalTokens,t)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,J.jsx)(cu,{title:i,titleId:a,children:o}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,J.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function du({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,J.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,J.jsx)(cu,{title:r,titleId:i,children:a}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,J.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function fu({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,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(au,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,J.jsx)(su,{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,J.jsx)(lu,{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,J.jsx)(uu,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Ql(e.summary.coverageRatio):`—`,body:e?(0,J.jsx)(du,{summary:e.summary,t:u,workspace:!0}):null}];return(0,J.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,J.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,J.jsx)(Tc,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,J.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,J.jsx)(pt,{title:u(`usage.empty`)}):f.map(e=>(0,J.jsx)(`div`,{id:Sc(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var pu=new Map;function mu(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function hu(e,t,n){let r=mu(e,t,n);return pu.get(r)??vn(r)}function gu(e,t,n,r){let i=mu(e,t,n);pu.set(i,r),yn(i,r)}function _u({apiBase:e}){let{t,locale:n}=X(),[r,i]=(0,_.useState)(`30d`),[a,o]=(0,_.useState)(`all`),[s,c]=(0,_.useState)(``),l=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/usage?range=${r}&surface=${a}`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let i=await n.json();return gu(e,r,a,i),i},[e,r,a]),u=mu(e,r,a),d=hu(e,r,a),f=Es(u,[e,r,a],l,{isEmpty:()=>!1,initialData:d??void 0}),{state:p}=f,m=p.data??d??null,h=(0,_.useMemo)(()=>ru(m?.days??[]),[m?.days]),g=(0,_.useMemo)(()=>eu(m?.days??[]),[m?.days]),v=(0,_.useMemo)(()=>(m?.days??[]).filter(e=>e.requests>0).length,[m?.days]),y=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(m?.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)},[m?.models,s]),b=(0,_.useMemo)(()=>(m?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[m?.providers]);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,J.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,J.jsx)(iu,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),p.showSkeleton&&!m?(0,J.jsx)(Os,{label:t(`usage.loading`),rows:5}):p.kind===`failed-cold`?(0,J.jsxs)(dt,{tone:`err`,children:[p.error instanceof Error?`${t(`usage.loadError`)} ${p.error.message}`:t(`usage.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,J.jsxs)(J.Fragment,{children:[p.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`usage.loadError`)}),m?.historyTruncated&&(0,J.jsx)(dt,{tone:`ok`,children:t(`usage.historyTruncated`)}),(0,J.jsx)(fu,{data:m,heatmap:h,weekBars:g,activeDays:v,filteredModels:y,modelQuery:s,onModelQuery:c,sortedProviders:b,range:r,locale:n,t})]})]})}function vu(e,t){if(e<1024)return`${e} B`;let n=[`KB`,`MB`,`GB`,`TB`],r=e,i=-1;do r/=1024,i++;while(r>=1024&&i<n.length-1);return`${r.toLocaleString(t,{maximumFractionDigits:1})} ${n[i]}`}var yu={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 bu(e,t){let n=yu[e.key];return n?t(n):e.label}function xu(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function Su(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function Cu({report:e,locale:t}){let n=Z(),[r,i]=(0,_.useState)(null),a=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),o=a.find(e=>e.key===r)??null,s=(0,_.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,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,J.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":n(`storage.section.buckets`),children:[(0,J.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-title`,children:n(`storage.section.buckets`)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-count`,children:a.length})]}),(0,J.jsx)(`div`,{className:`storage-workspace-rail-list`,children:a.length===0?(0,J.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:n(`storage.empty`)}):a.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${r===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>i(t=>t===e.key?null:e.key),"aria-current":r===e.key?`true`:void 0,children:[(0,J.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-name`,children:bu(e,n)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-size`,children:vu(e.bytes,t)})]}),(0,J.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,n(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,J.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":o?bu(o,n):n(`storage.section.largest`),children:o?(0,J.jsxs)(`div`,{className:`stw-detail`,children:[(0,J.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>i(null),children:[(0,J.jsx)(we,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),n(`modal.back`)]})}),(0,J.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,J.jsx)(`h2`,{className:`stw-detail-title`,children:bu(o,n)}),(0,J.jsxs)(`dl`,{className:`stw-kv`,children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.size`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:vu(o.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.files`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:o.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.oldest`)}),(0,J.jsx)(`dd`,{children:xu(o.oldest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.newest`)}),(0,J.jsx)(`dd`,{children:xu(o.newest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:Su(o,t,n)})]})]}),(o.largest?.length??0)>0&&(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),o.largest.map(e=>(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:vu(e.bytes,t)})]},e.path))]})]})]}):(0,J.jsxs)(`div`,{className:`stw-overview`,children:[(0,J.jsxs)(`div`,{className:`stw-summary`,children:[(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.total`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:vu(e.total.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.files`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.home`)}),(0,J.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),s.length>0?(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),s.map(e=>{let r=c.get(e.bucketKey);return(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),r&&(0,J.jsx)(`span`,{className:`stw-file-bucket`,children:bu(r,n)}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:vu(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,J.jsxs)(`p`,{className:`stw-hint`,children:[(0,J.jsx)(ue,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),n(`storage.workspace.selectBucket`)]})]})})]})}var wu=1024**3,Tu=[10,25,50],Eu=(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 Du({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,_.useState)(25),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(null),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=(0,_.useRef)(!1),S=(0,_.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,_.useEffect)(()=>{x.current=f},[f]),(0,_.useEffect)(()=>{if(!c)return;b.current=document.activeElement,y.current?.focus();let e=e=>{e.key===`Escape`&&!x.current&&S()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),b.current?.focus()}},[c,S]);let C=(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`)}},w=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),T=async()=>{p(!0),v(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(C(e.error,n(`storage.cleanup.previewFailed`)))}s(await t.json()),l(!0)}catch(e){v(Eu(e,n(`storage.cleanup.previewFailed`)))}finally{p(!1)}},E=async()=>{if(o){p(!0),v(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`&&S(!0),Error(C(e.error,e.message,e.trashDir))}let a=await i.json();if(!a.ok)throw a.error===`stale_preview`&&S(!0),Error(C(a.error,a.message,a.trashDir));S(!0),h(n(u?`storage.cleanup.donePermanent`:`storage.cleanup.doneQuarantine`,{count:String(a.count),size:vu(a.bytes,t)})),r()}catch(e){v(Eu(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,J.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,J.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,J.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,J.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,J.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Tu.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:vu(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,J.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,J.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,J.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,J.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,J.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void E(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function Ou({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(null),g=(0,_.useRef)(!1);(0,_.useEffect)(()=>{g.current=o},[o]);let v=(0,_.useCallback)(()=>l(null),[]);(0,_.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&v()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,v]);let y=(0,_.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]),b=Es(`storage-trash:${e}`,[e,i],y,{isEmpty:e=>e.length===0}).state,x=b.data??[],S=(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`)}},C=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(S(e.error,e.message))}let a=await i.json();if(!a.ok)throw Error(S(a.error,a.message));v(),d(n(`storage.trash.done`,{count:String(a.count),size:vu(a.bytes,t)})),r()}catch(e){p(Eu(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},w=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},T=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:b.error instanceof Error?b.error.message:n(`storage.trash.listFailed`)}),b.refreshing&&!b.showSkeleton&&(0,J.jsx)(ks,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,J.jsx)(Os,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,J.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,J.jsx)(`th`,{})]})}),(0,J.jsx)(`tbody`,{children:x.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted`,children:w(e)}),(0,J.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,J.jsx)(`td`,{className:`num mono`,children:vu(e.bytes,t)}),(0,J.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,J.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:vu(c.bytes,t),id:c.id})}),f&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function ku(e){let{job:t,...n}=e;return n}function Au(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/wu*100)/100));return e.target.reduceToBytes===void 0?{policy:ku(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:ku(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/wu*100)/100))}}async function ju(e){await new Promise(t=>window.setTimeout(t,e))}function Mu({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=vn(i),o=(0,_.useRef)(!!a),[s,c]=(0,_.useState)(()=>a?.policy??null),[l,u]=(0,_.useState)(()=>!a),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>a?.targetMode??`percent`),[S,C]=(0,_.useState)(()=>a?.percent??`25`),[w,T]=(0,_.useState)(()=>a?.reduceGb??`4`),[E,D]=(0,_.useState)(()=>a?.thresholdGb??`5`),O=(0,_.useRef)(null),k=(0,_.useRef)(!1),A=(0,_.useRef)(!1),j=(0,_.useRef)(0),M=(0,_.useCallback)(e=>{let t=Au(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,yn(i,t),k.current=!1},[i]),N=(0,_.useCallback)(()=>{k.current=!0},[]),P=(0,_.useCallback)(e=>{A.current=e},[]),F=(0,_.useCallback)(async t=>{let r=++j.current;o.current||u(!0),y(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!==j.current||k.current||A.current)return;M(i)}catch{if(t?.aborted||r!==j.current)return;o.current||(c(null),y(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===j.current&&u(!1)}},[e,M,n]);(0,_.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{F(e.signal)},0);return()=>{window.clearTimeout(t),j.current+=1,e.abort()}},[F]),(0,_.useEffect)(()=>()=>{O.current?.abort(),O.current=null},[]);let I=()=>{if(!s)return null;let e=E.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(b===`reduce`){let e=w.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*wu)}}else{let e=Number(S);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*wu)},target:n,schedule:s.schedule,mode:s.mode}},L=async t=>{let r=I();if(!r){y(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),y(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){y(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){y(n(`storage.policy.saveFailed`));return}M(r.policy),g(n(`storage.policy.saved`))}catch{y(n(`storage.policy.saveFailed`))}finally{f(!1)}},R=async()=>{O.current?.abort();let i=new AbortController;O.current=i;let{signal:a}=i;m(!0),y(null),g(null);try{let i=I();if(!i){y(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){y(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){y(n(`storage.policy.saveFailed`));return}M(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&&M(e.policy),y(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&M(e.policy),e.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}y(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&M(l.policy),l.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){y(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await ju(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=ku(n),M(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&&M(p),!f){y(n(`storage.policy.runFailed`));return}f.skipped===`disabled`?g(n(`storage.policy.skippedDisabled`)):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`?y(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:vu(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:vu(f.freedBytes??0,t)})),r()):y(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;y(n(`storage.policy.runFailed`))}finally{O.current===i&&(O.current=null),a.aborted||m(!1)}},z=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,J.jsx)(`div`,{className:`storage-policy-enable`,children:(0,J.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,J.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 L({enabled:!s.enabled}),children:(0,J.jsx)(`span`,{className:`toggle-knob`})}),(0,J.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,J.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,J.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,J.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,J.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:E,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>P(!0),onChange:e=>{N(),D(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(ea,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D($i(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D($i(E,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,J.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:S,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>P(!0),onChange:e=>{N(),C(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(ea,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C($i(S,1,1,100))},onDecrement:()=>{N(),C($i(S,-1,1,100))}})]})]}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:w,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>P(!0),onChange:e=>{N(),T(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(ea,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T($i(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T($i(w,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,J.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;L({schedule:t})},children:[(0,J.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,J.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,J.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,J.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,J.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;L({mode:t})},children:[(0,J.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,J.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,J.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,J.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[z(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:vu(s.lastRun.freedBytes,t)})}`:``]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,J.jsx)(`span`,{className:`storage-policy-meta-value`,children:z(s.nextRun)})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,J.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,J.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function Nu({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,_.useState)(`policy`),u=(0,_.useRef)(null),d=(0,_.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,J.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,J.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,J.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,J.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,J.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,J.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,J.jsx)(Mu,{apiBase:e,locale:t,t:n,onDone:o}),(0,J.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,J.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,J.jsx)(Du,{apiBase:e,locale:t,t:n,onDone:o}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,J.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,J.jsx)(Ou,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function Pu({apiBase:e}){let{t,locale:n}=X(),r=`ocx.storage.report.v1:${e}`,i=vn(r),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(0),l=(0,_.useRef)(!1),[u,d]=(0,_.useState)({apiBase:e,settled:!1,hasEntries:!1}),f=(0,_.useCallback)(async n=>{try{let i=await fetch(`${e}/api/storage`,{signal:n});if(!i.ok)throw Error(t(`storage.error`));let a=await i.json();return yn(r,a),l.current&&(l.current=!1,o(t(`storage.rescanned`))),a}catch(e){throw l.current&&(l.current=!1,o(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,r,t]),p=Es(`storage-report:${e}`,[e],f,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),m=p.state,h=m.data??i,g=m.refreshing||m.showSkeleton&&!h,v=p.refresh,y=(0,_.useCallback)(()=>{o(null),l.current=!0,v(),c(e=>e+1)},[v]),b=(0,_.useCallback)(t=>{d({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=u.apiBase===e&&u.settled,S=u.apiBase===e&&u.hasEntries,C=h?.error!==void 0,w=!g&&!m.showError&&!C&&h.total.fileCount===0&&x&&!S,T=h?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!h&&!C,D=E&&(h.total.fileCount>0||!x||S);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,J.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,J.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,J.jsx)(me,{}),` `,t(`storage.refresh`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,J.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,J.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,J.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,J.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,J.jsx)(Os,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,J.jsxs)(J.Fragment,{children:[m.showError&&(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,J.jsx)(pt,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,J.jsx)(Cu,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,J.jsx)(ks,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,J.jsx)(Nu,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}function Fu(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 Iu({state:e,busy:t,onEnable:n}){let r=Z();return(0,J.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,J.jsxs)(`div`,{className:`row`,children:[(0,J.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===null?(0,J.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot openai-account-mode-banner__badge-slot--pending`,"aria-hidden":`true`,children:r(`codexAuth.accountModePool`)}):e===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===null&&(0,J.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc openai-account-mode-banner__desc--pending`,"aria-hidden":`true`,children:`\xA0`}),e===`pool`&&(0,J.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,J.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,J.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,J.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,J.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,J.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,J.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]})]})}function Lu(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 Ru({apiBase:e}){let t=Z(),n=`ocx.codex-auth.config.v1:${e}`,r=vn(n),[i,a]=(0,_.useState)(()=>r?.bannerState??null),[o,s]=(0,_.useState)(()=>r?.accountModeState??null),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(``),p=(0,_.useCallback)(async()=>{let t=y(15e3);try{let r=await fetch(`${e}/api/config`,{signal:t.signal});if(!r.ok)throw Error(String(r.status));let i=await r.json(),o=oo(Lu(i));if(o===`absent`||o===`disabled`||o===`invalid`){a(o);let e=o===`disabled`?`disabled`:`absent`;s(e),yn(n,{bannerState:o,accountModeState:e});return}let c=Fu(i);a(c),s(c),yn(n,{bannerState:c,accountModeState:c})}catch{}finally{t.clear()}},[e,n]);(0,_.useEffect)(()=>{c.current!==e&&(c.current=e,Promise.resolve().then(()=>{p()}));let t=Jt(()=>{p()},3e4);return()=>{t()}},[e,p]);let m=async()=>{u(!0),f(``);try{if(i!==`absent`&&i!==`disabled`)return;await mo(e,i),await p()}catch(e){e instanceof po?f(t(e.i18nKey)):f(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{u(!1)}};return(0,J.jsx)(Ha,{apiBase:e,accountModeState:o,banner:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Iu,{state:i,busy:l,onEnable:()=>{m()}}),d&&(0,J.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:d})]})})}function zu(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function Bu(e){let t=e.id.indexOf(`/`),n=typeof e.owned_by==`string`&&e.owned_by.trim()?e.owned_by.trim():void 0,r=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 Vu(e){return e.id}function Hu(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.ambiguous===!0?!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 Uu=new Set([`required`,`accepted`,`rejected`]);function Wu(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`&&Uu.has(t.bearer)&&Uu.has(t.dedicated)&&Uu.has(t.xApiKey)})}var Gu={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 Ku(e){let t=e||Gu.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 qu(e,t){let n=new Date(e);return!e||Number.isNaN(n.getTime())?`—`:n.toLocaleDateString(t)}function Ju({url:e}){return(0,J.jsx)(Yu,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,J.jsx)(`code`,{className:`api-code api-code-inline api-endpoint-url`,children:e})})}function Yu({text:e,hintKey:t,copiedKey:n,className:r,children:i}){let{t:a}=X(),o=(0,_.useId)(),s=(0,_.useRef)(null),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(null),h=c||u;(0,_.useEffect)(()=>()=>{m.current!==null&&window.clearTimeout(m.current)},[]),(0,_.useLayoutEffect)(()=>{if(!h)return;let e=()=>{let e=s.current;if(!e)return;let t=e.getBoundingClientRect();p({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)}},[h]);let g=()=>l(!0),v=()=>l(!1),y=async()=>{try{await navigator.clipboard.writeText(e),d(!0),m.current!==null&&window.clearTimeout(m.current),m.current=window.setTimeout(()=>d(!1),1500)}catch{d(!1)}},b=h&&f?(0,$e.createPortal)((0,J.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble api-copy-tip-fixed`,role:`tooltip`,style:{top:f.top,left:f.left},children:a(u?n:t)}),document.body):null;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,ref:s,className:`ocx-tooltip ${r}`,onMouseEnter:g,onMouseLeave:v,onFocus:g,onBlur:v,onClick:e=>{if(typeof window<`u`&&window.getSelection()?.toString())return;let t=e.target;if(t instanceof HTMLElement&&t!==e.currentTarget){let n=t.getBoundingClientRect();if(t.scrollHeight>t.clientHeight+1&&e.clientX>=n.right-16||t.scrollWidth>t.clientWidth+1&&e.clientY>=n.bottom-16)return}y()},onKeyDown:e=>{e.key===`Escape`&&v()},"aria-label":a(t),"aria-describedby":h?o:void 0,children:i}),b]})}function Xu({text:e}){return(0,J.jsx)(Yu,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,J.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}function Zu(e,t){return t(e===`required`?`api.auth.required`:e===`accepted`?`api.auth.accepted`:`api.auth.rejected`)}function Qu({endpoints:e,claudeCodeEnabled:t,authMatrix:n}){let{t:r}=X();return(0,J.jsxs)(`div`,{className:`panel api-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`api.endpointsTitle`)}),(0,J.jsxs)(`div`,{className:`api-endpoints`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.baseUrl`)}),(0,J.jsx)(Ju,{url:e.baseUrl})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.responsesEndpoint`)}),(0,J.jsx)(Ju,{url:e.responses})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.chatCompletionsEndpoint`)}),(0,J.jsx)(Ju,{url:e.chatCompletions})]}),t&&(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.messagesEndpoint`)}),(0,J.jsx)(Ju,{url:e.messages})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.modelsEndpoint`)}),(0,J.jsx)(Ju,{url:e.models})]})]}),(0,J.jsx)(`p`,{className:`muted small`,children:r(`api.endpointNote`)}),(0,J.jsxs)(`div`,{className:`api-auth-matrix-block`,children:[(0,J.jsx)(`h4`,{className:`api-auth-matrix-title`,children:r(`api.authTitle`)}),(0,J.jsx)(`div`,{className:`api-auth-matrix-scroll`,children:(0,J.jsxs)(`table`,{className:`api-auth-matrix`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:r(`api.auth.endpoint`)}),(0,J.jsx)(`th`,{children:(0,J.jsx)(`code`,{children:`Authorization: Bearer`})}),(0,J.jsx)(`th`,{children:(0,J.jsx)(`code`,{children:`x-opencodex-api-key`})}),(0,J.jsx)(`th`,{children:(0,J.jsx)(`code`,{children:`x-api-key`})})]})}),(0,J.jsx)(`tbody`,{children:n.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:(0,J.jsx)(`code`,{children:e.endpoint})}),(0,J.jsx)(`td`,{children:Zu(e.bearer,r)}),(0,J.jsx)(`td`,{children:Zu(e.dedicated,r)}),(0,J.jsx)(`td`,{children:Zu(e.xApiKey,r)})]},e.endpoint))})]})}),(0,J.jsx)(`p`,{className:`muted small`,children:r(`api.authLoopback`)}),(0,J.jsx)(`p`,{className:`muted small`,children:r(`api.authBaseUrlNote`)})]})]})}function $u({keys:e,keysLoading:t=!1,keysLoadFailed:n,newName:r,creating:i,newKey:a,copied:o,confirmDelete:s,localeTag:c,showKeyList:l=!0,onNewNameChange:u,onCreate:d,onDismissNewKey:f,onCopyKey:p,onConfirmDelete:m,onCancelDelete:h,onDelete:g}){let{t:_}=X();return(0,J.jsxs)(J.Fragment,{children:[a&&(0,J.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:_(`api.newKeyTitle`)}),(0,J.jsx)(`p`,{className:`muted small`,children:_(`api.newKeyNote`)}),(0,J.jsxs)(`div`,{className:`api-form-row`,children:[(0,J.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:a}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:p,children:o?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(de,{}),` `,_(`api.copied`)]}):_(`api.copy`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:f,children:_(`api.dismiss`)})]}),(0,J.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:_(`api.generateTitle`)}),(0,J.jsxs)(`div`,{className:`api-form-row`,children:[(0,J.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:_(`api.keyNamePlaceholder`),"aria-label":_(`api.keyNamePlaceholder`),value:r,maxLength:64,onChange:e=>u(e.target.value),className:`input`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:d,disabled:i,children:[(0,J.jsx)(pe,{}),` `,_(i?`api.generating`:`api.generate`)]})]})]}),l&&(0,J.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:t?_(`api.activeKeysLoading`):_(`api.activeKeys`,{count:e.length})}),t?(0,J.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":_(`common.loading`)}):e.length>0?(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:_(`api.colName`)}),(0,J.jsx)(`th`,{children:_(`api.colKey`)}),(0,J.jsx)(`th`,{children:_(`api.colCreated`)}),(0,J.jsx)(`th`,{})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:e.name}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`code`,{children:e.prefix})}),(0,J.jsx)(`td`,{children:qu(e.createdAt,c)}),(0,J.jsx)(`td`,{children:s===e.id?(0,J.jsxs)(`span`,{className:`api-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>g(e.id),children:_(`api.confirm`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:h,children:_(`common.cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":_(`api.deleteAria`),onClick:()=>m(e.id),children:(0,J.jsx)(fe,{})})})]},e.id))})]})}):n?(0,J.jsx)(`p`,{className:`muted`,children:_(`api.keysLoadFailed`)}):(0,J.jsx)(`p`,{className:`muted`,children:_(`api.noKeys`)})]})]})}function ed({filteredModels:e,modelsLoading:t,modelsRefreshing:n=!1,modelsLoadFailed:r,modelCount:i,hasModelData:a,modelQuery:o,copiedModelId:s,modelTests:c,claudeCodeEnabled:l,onModelQueryChange:u,onCopyModelId:d,onTestModel:f,onRetryModels:p,canTestModels:m,sourceLabel:h,protocolLabel:g}){let{t:_}=X();return(0,J.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,J.jsxs)(`div`,{className:`api-panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:_(`api.modelsTitle`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:_(`api.modelsCount`,{count:e.length})})]}),(0,J.jsx)(`p`,{className:`muted small`,children:_(`api.modelsSubtitle`)}),(0,J.jsx)(`input`,{type:`search`,className:`input`,value:o,onChange:e=>u(e.target.value),placeholder:_(`api.modelsSearch`),"aria-label":_(`api.modelsSearch`)}),r&&(0,J.jsxs)(`div`,{className:`api-models-error`,children:[(0,J.jsx)(`p`,{className:`muted small`,role:`alert`,children:_(`api.modelsLoadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:_(`common.retry`)})]}),n&&!t&&(0,J.jsx)(`p`,{className:`muted small`,"aria-live":`polite`,children:_(`api.modelsLoading`)}),t?(0,J.jsx)(Os,{label:_(`api.modelsLoading`),rows:3}):a?e.length===0?(0,J.jsx)(`p`,{className:`muted small api-models-empty`,children:i===0?_(`api.modelsEmpty`):_(`api.modelsNoMatch`,{query:o.trim()})}):(0,J.jsx)(`div`,{className:`api-models-scroll`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:_(`api.colModel`)}),(0,J.jsx)(`th`,{children:_(`api.colSource`)}),(0,J.jsx)(`th`,{children:_(`api.colProtocols`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>{let t=Vu(e),n=zu(l);return(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:(0,J.jsxs)(`div`,{className:`api-model-cell`,children:[(0,J.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,J.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,J.jsx)(`td`,{children:h(e)}),(0,J.jsx)(`td`,{children:(0,J.jsxs)(`div`,{className:`api-model-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{d(t)},children:_(s===t?`api.modelCopied`:`api.copyModelId`)}),n.map(n=>{let r=c[t]?.[n],i=r?.state??`idle`;return(0,J.jsxs)(`span`,{className:`api-model-test-chip`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:i===`testing`||!m,title:m?void 0:_(`api.auth.testNeedsFreshKey`),onClick:()=>{f(e,n)},children:_(`api.auth.testProtocol`,{protocol:g(n)})}),i!==`idle`&&(0,J.jsx)(`span`,{className:`api-test-note api-test-note--${i}`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:i===`testing`?_(`api.testingModel`):i===`ok`?_(`api.testSucceeded`):r?.detail??_(`api.testFailed`)})]},n)})]})})]},t)})})]})}):null]})}function td({endpoints:e,claudeCodeEnabled:t}){let{t:n}=X(),r=JSON.stringify(n(`api.usageSampleInput`)),i=`curl ${e.chatCompletions} \\
47
+ `))&&(async()=>{u(null),g(typeof r?.pid==`number`?r.pid:null),c(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{c(`error`),g(null),u(n(`dash.mem.restartFailed`))}})()};if(a&&!r&&s===`idle`)return(0,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(le,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let b=r?.watchdog?rn(r.watchdog.samples):null,x=r?r.observedBytes??r.watchdog?.observedBytes??tn(r):null,S=r?nn(r):null,C=(()=>{let e=r?.watchdog?.warnThresholdBytes;if(b===null||b<=0||x===null||!e)return;let t=e-x;if(t<=0)return`danger`;let n=t/b;if(n<=1)return`danger`;if(n<=8)return`warn`})(),w=r?.responseState,T=r?.activeTurnCount,E=s===`draining`||s===`reconnecting`;return(0,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`mem-head`,children:[(0,J.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,J.jsx)(le,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,J.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,J.jsxs)(`span`,{className:`mem-inflight`,children:[(0,J.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,J.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof T==`number`?Qt(t).format(T):`—`})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:E,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,J.jsx)(on,{observedBytes:x,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:S,locale:t,t:n}),(0,J.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,J.jsx)(an,{label:n(`dash.mem.rss`),value:r?$t(r.rss,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.jsHeap`),value:r?$t(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:$t(r.heapTotal,t)}):void 0}),(0,J.jsx)(an,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?$t(r.jscHeap.heapSize,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.growth`),value:b===null?`—`:`${b>=0?`+`:`−`}${$t(Math.abs(b),t)}${n(`dash.mem.perHour`)}`,tone:C})]}),(0,J.jsxs)(`details`,{style:{marginTop:10},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(an,{label:n(`dash.mem.observed`),value:x===null?`—`:`${$t(x,t)} (${S})`}),(0,J.jsx)(an,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:$t(r.external,t)}),(0,J.jsx)(an,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:$t(r.arrayBuffers,t)})]}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(an,{label:n(`dash.mem.storeEntries`),value:w?Qt(t).format(w.count):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.storeTotal`),value:w?$t(w.totalBytes,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.storeLargest`),value:w?$t(w.largestBytes,t):`—`}),(0,J.jsx)(an,{label:n(`dash.mem.storeOldest`),value:w?w.count===0?`—`:en(w.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,J.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,J.jsx)(an,{label:n(`dash.mem.threshold`),value:$t(r.watchdog.warnThresholdBytes,t)}),(0,J.jsx)(an,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,J.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof T==`number`?T:0})}),s===`reconnecting`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,J.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function dn({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,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`injection-head`,children:[(0,J.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,J.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,J.jsx)(ye,{width:13,height:13,"aria-hidden":`true`})})]}),(0,J.jsx)(ft,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...Ct.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await St(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`)}),(0,J.jsx)(ft,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...Ct.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await St(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`)})]})})}function fn({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsx)(ft,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:`${e.provider} / ${e.model}`}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`)}),n&&i.length>0&&(0,J.jsx)(ft,{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`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Qe(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function pn({d:e}){let{t,runSync:n,syncing:r,updateTriggerRef:i,openUpdateDialog:a,updateLoading:o,updateOpen:s,syncResult:c,syncError:l,updateJob:u,reconnecting:d}=e;return(0,J.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,J.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,J.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:n,disabled:r,children:[(0,J.jsx)(me,{}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,J.jsx)(`button`,{ref:i,type:`button`,className:`maintenance-update-anchor`,onClick:a,disabled:o,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":s,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]})]}),c&&(0,J.jsxs)(`div`,{className:`notice ${c.nativeSubagentDefaultsWarning?`notice-warn`:`notice-ok`} maintenance-notice`,role:`status`,children:[c.nativeSubagentDefaultsWarning?(0,J.jsx)(ve,{}):(0,J.jsx)(me,{}),(0,J.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,J.jsxs)(J.Fragment,{children:[` `,(0,J.jsx)(Ye,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]})]}),l&&(0,J.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`status`,children:[(0,J.jsx)(ve,{}),(0,J.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})})]}),u&&(0,J.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,J.jsx)(ve,{}):(0,J.jsx)(me,{}),(0,J.jsxs)(`span`,{children:[Et(u.status,t),u.latestVersion?` ${u.currentVersion} -> ${u.latestVersion}.`:``,d?` ${t(`dash.updateReconnecting`)}`:``,u.error?` ${u.error}`:``]})]})]})}function mn({d:e}){let{t,settings:n,settingsSaving:r,toggleCodexAutoStart:i,sidecar:a,sidecarSaving:o,sidecarModels:s,models:c,saveSidecar:l,shadowCall:u,shadowCallSaving:d,shadowCallHelpTriggerRef:f,shadowCallHelpOpen:p,setShadowCallHelpOpen:m,saveShadowCall:h}=e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`spread`,children:[(0,J.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${n?.codexAutoStart??!0?`on`:``}`,onClick:i,disabled:!n||r,"aria-label":t(`dash.codexAutoStart`),"aria-pressed":n?.codexAutoStart??!0,children:(0,J.jsx)(`span`,{className:`knob`})})]})}),(0,J.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,J.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,J.jsx)(ft,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({webSearch:{model:e,backend:kt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,J.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,J.jsx)(ft,{value:a?.vision.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({vision:{model:e,backend:kt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]})]}),(0,J.jsx)(`div`,{className:`panel`,"aria-busy":!u||void 0,children:(0,J.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,J.jsx)(`button`,{ref:f,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:()=>m(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":p,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,J.jsx)(ye,{width:13,height:13,"aria-hidden":`true`})}),(0,J.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${It(u?.sourceModels)}`})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`switch ${u?.enabled?`on`:``}`,onClick:()=>h({enabled:!u?.enabled}),disabled:!u||d,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":u?.enabled??!1,children:(0,J.jsx)(`span`,{className:`knob`})}),(0,J.jsx)(ft,{value:u?.model??``,options:[{value:``,label:`—`},...c.map(e=>({value:e.id,label:`${e.provider}/${e.id}`}))],onChange:e=>{h({model:e})},disabled:!u||d||!u?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function hn(e){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dn,{apiBase:e.apiBase,d:e}),(0,J.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,J.jsx)(fn,{apiBase:e.apiBase,d:e}),(0,J.jsx)(pn,{d:e})]}),(0,J.jsx)(mn,{d:e}),(0,J.jsx)(un,{apiBase:e.apiBase})]})}function gn(e){return(0,J.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,J.jsx)(Wt,{...e}),(0,J.jsx)(hn,{...e})]})}function _n({t:e,providers:t}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,J.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,J.jsx)(pt,{title:(0,J.jsx)(Ye,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:e(`dash.col.name`)}),(0,J.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,J.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,J.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,J.jsx)(`tbody`,{children:t.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`font-semibold`,children:e.name}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`span`,{className:`chip`,children:e.adapter})}),(0,J.jsx)(`td`,{className:`muted mono text-label`,children:e.baseUrl}),(0,J.jsx)(`td`,{className:`muted`,children:e.defaultModel??`—`})]},e.name))})]})})]})}function vn(e){try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function yn(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function bn(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function xn(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Sn(e,t){return{request:++e.current,mutation:t.current}}var Cn=2e3;function wn(e){let t=e.status;return t===`native`||t===`protected`||t===`at-risk`?t:null}function Tn(e){return e?e.stale&&e.status!==`error`:!1}function En(e,t){return!t||e!==null&&e!==`error`?e:t.status}var Dn=3e4;function On(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function kn(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function An(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=wn(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(kn(e,t))throw e;return{status:`error`,stale:!1}}}async function jn(e,t){try{return(await _t(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function Mn(e,t){return St(await fetch(`${e}/api/models`,{signal:t}))}async function Nn(e,t){return St(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Pn(e,t,n){let{request:r,mutation:i}=Sn(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 St(a),c;try{if(o.ok){let e=await o.json();xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{xn({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 Fn(e,t,n){let{request:r,mutation:i}=Sn(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await St(await fetch(`${e}/api/settings`,{signal:t})),o,s;return xn({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 In(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`};let r=await n.json();return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?{maMode:r.multiAgentMode}:{maMode:`default`}}catch(e){if(kn(e,t))throw e;return{maMode:`default`}}}async function Ln(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await St(n),providers:await St(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function Rn(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={...On(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 zn=`ocx.dash.controls.v1:`,Bn=`ocx.dash.overview.v1:`,Vn=`ocx.dash.usage30d.v1:`,Hn=`ocx.dash.startup.v1:`,Un=`ocx.dash.maMode.v1:`;function Wn(e){return`${zn}${e}`}function Gn(e){let{locale:t,t:n}=X(),[r,i]=(0,_.useState)(yt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>vn(Wn(e)),[e]),u=(0,_.useMemo)(()=>vn(`${Bn}${e}`),[e]),d=(0,_.useMemo)(()=>vn(`${Vn}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=vn(`${Hn}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>vn(`${Un}${e}`),[e]),[m,h]=(0,_.useState)(()=>u?.health??null),[g,v]=(0,_.useState)(()=>f),[y,b]=(0,_.useState)(()=>u?.providers??[]),[x,S]=(0,_.useState)([]),[C,w]=(0,_.useState)(()=>l?.settings??null),[T,E]=(0,_.useState)(()=>l?.sidecar??null),[D,O]=(0,_.useState)(()=>l?.shadowCall??null),[k,A]=(0,_.useState)(()=>d),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(!1),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(()=>p??`default`),[U,W]=(0,_.useState)(!1),[G,ee]=(0,_.useState)(!1),[q,te]=(0,_.useState)(!1),[J,Y]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(``),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)([]),[ce,le]=(0,_.useState)([]),[ue,de]=(0,_.useState)(!1),[fe,pe]=(0,_.useState)(!0),[me,he]=(0,_.useState)(!1),[ge,_e]=(0,_.useState)(``),[ve,ye]=(0,_.useState)(``),[be,xe]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)(null),[Ee,De]=(0,_.useState)([]),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)(`latest`),[Me,Ne]=(0,_.useState)(!0),[Pe,Fe]=(0,_.useState)(!1),Ie=(0,_.useRef)(0),Le=(0,_.useRef)(null),Re=(0,_.useRef)(0),ze=(0,_.useRef)(0),Be=(0,_.useRef)(0),Ve=(0,_.useRef)(!1),He=(0,_.useRef)(0),Ue=(0,_.useRef)(0),We=(0,_.useRef)(!1),[Ge,Ke]=(0,_.useState)(null),[qe,Z]=(0,_.useState)(null),[Je,Ye]=(0,_.useState)(null),[Xe,Qe]=(0,_.useState)(!1),[$e,et]=(0,_.useState)(!1),tt=(0,_.useRef)(null),nt=(0,_.useRef)(null),rt=(0,_.useRef)(null),it=(0,_.useRef)(null),at=Mt(q,tt),ot=Mt(Oe,nt),st=Mt(G,rt),ct=Mt(J,it);(0,_.useEffect)(()=>{let e=()=>i(yt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)},[]);let lt=(0,_.useRef)(f),ut=(0,_.useRef)(0),dt=(0,_.useRef)({settingsRequestEpochRef:ze,settingsMutationEpochRef:Be,settingsMutationInFlightRef:Ve,shadowCallRequestEpochRef:He,shadowCallMutationEpochRef:Ue,shadowCallMutationInFlightRef:We}).current,ft=K(`dashboard-startup-health:${e}`,[e],t=>An(e,t),{pollMs:3e4}),pt=Tn(ft.data),mt=ft.refresh;(0,_.useEffect)(()=>{if(!pt)return;let e=window.setTimeout(()=>{mt()},Cn);return()=>window.clearTimeout(e)},[pt,mt]);let ht=K(`dashboard-overview:${e}`,[e],t=>Ln(e,t),{pollMs:5e3}),gt=m!==null||ht.data!==void 0,Q=K(`dashboard-ma-mode:${e}`,[e],t=>In(e,t),{pollMs:5e3}),_t=K(`dashboard-sidecars:${e}`,[e],async t=>{let n=ut.current;return{...await Pn(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),vt=K(`dashboard-settings:${e}`,[e],async t=>{let n=ut.current;return{...await Fn(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),xt=K(`dashboard-multi-agent:${e}`,[e],t=>Rn(e,t),{pollMs:5e3,enabled:gt}),Ct=K(`dashboard-usage:${e}`,[e],t=>Nn(e,t),{pollMs:6e4,enabled:gt,deadlineMs:6e4}),Tt=K(`dashboard-diagnostics:${e}`,[e],t=>jn(e,t),{pollMs:Dn,enabled:gt}),Et=K(`dashboard-models:${e}`,[e,$e],t=>Mn(e,t),{enabled:gt&&!$e});(0,_.useEffect)(()=>{if(ft.data!==void 0){let t=ft.data;ut.current+=1,v(t.status),lt.current=t.status,t.status!==`error`&&!t.stale&&yn(`${Hn}${e}`,t.status)}},[ft.data,e]),(0,_.useEffect)(()=>{let t=ht.data;t&&(t.health&&(h(t.health),b(t.providers),yn(`${Bn}${e}`,{health:t.health,providers:t.providers})),et(t.error))},[ht.data,e]),(0,_.useEffect)(()=>{Q.data!==void 0&&(H(Q.data.maMode),yn(`${Un}${e}`,Q.data.maMode))},[Q.data,e]);let kt=Q.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=xt.data;e&&(e.injection&&(pe(e.injection.multiAgentGuidanceEnabled),he(e.injection.syncCodexSubagentDefaults),re(e.injection.injectionModel),ae(e.injection.injectionEffort),se(e.injection.injectionEfforts),le(e.injection.injectionAvailable)),e.effortCaps&&(_e(e.effortCaps.effortCap),ye(e.effortCaps.subagentEffortCap)))},[xt.data]),(0,_.useEffect)(()=>{let t=_t.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=vn(Wn(e))??{};yn(Wn(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[_t.data,e]),(0,_.useEffect)(()=>{let t=vt.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===ut.current){let n=En(lt.current,t.startupHealthSeed);v(n),lt.current=n,n&&yn(`${Hn}${e}`,n)}if(t.settings!==void 0){let n=vn(Wn(e))??{};yn(Wn(e),{...n,settings:t.settings})}}},[vt.data,e]),(0,_.useEffect)(()=>{Ct.data!==void 0&&(A(Ct.data),yn(`${Vn}${e}`,Ct.data))},[Ct.data,e]),(0,_.useEffect)(()=>{Tt.data&&De(Tt.data)},[Tt.data]),(0,_.useEffect)(()=>{Et.data&&S(Et.data),I(Et.loading)},[Et.data,Et.loading]),(0,_.useEffect)(()=>()=>{ze.current+=1,He.current+=1},[]);let At=K(Je?.id&&Je.restart?`update-job:${e}:${Je.id}`:`update-job:idle:${e}`,[e,Je?.id,Je?.restart,Je?.latestVersion],async t=>{if(!Je?.id||!Je.restart)return{reconnecting:!1};let n=Je.latestVersion;try{let r=await St(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Je.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await St(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:!!(Je?.id&&Je.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=At.data;e&&(`job`in e&&e.job&&Ye(e.job),Qe(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[At.data]);let jt=(0,_.useMemo)(()=>{let e={};for(let t of x)(e[t.provider]??=[]).push(t);return Object.entries(e).sort(([e],[t])=>e.localeCompare(t))},[x]),Nt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return jt;let t=[];for(let[n,r]of jt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[jt,a]),Pt=(0,_.useMemo)(()=>{let e=Ot(x);for(let t of[T?.webSearch.model,T?.vision.model])t&&!e.some(e=>e.value===t)&&e.unshift({value:t,label:t});return e},[x,T]),Ft=async t=>{if(!T||j)return;let n=T,r={webSearch:Dt(T.webSearch,t.webSearch),vision:Dt(T.vision,t.vision)};M(!0),E(r);try{let n=await St(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);E({webSearch:n.webSearch,vision:n.vision});let r=vn(Wn(e))??{};yn(Wn(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision}})}catch{E(n)}finally{M(!1)}};async function It(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),We.current=!0,O(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`);Ue.current+=1}catch{O(n)}finally{We.current=!1,P(!1)}}let Lt=async t=>{if(!(U||V===t)){W(!0);try{(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})})).ok&&(H(t),yn(`${Un}${e}`,t))}catch{}finally{W(!1)}}},Rt=async t=>{if(!ue){de(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await St(await fetch(`${e}/api/injection-model`)),r=On(n);pe(r.multiAgentGuidanceEnabled),he(r.syncCodexSubagentDefaults),re(r.injectionModel),ae(r.injectionEffort),Array.isArray(n.efforts)&&se(n.efforts),Array.isArray(n.available)&&le(n.available)}catch{}finally{de(!1)}}},zt=async()=>{if(!C||L)return;let t=!C.codexAutoStart;R(!0),Ve.current=!0,w({...C,codexAutoStart:t});try{let n=await St(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Be.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),et(!0)}finally{Ve.current=!1,R(!1)}},Bt=async()=>{if(!z){B(!0),Ce(null),Te(null);try{let t=await St(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Ce(t),t.projectConfigGrouped&&De(t.projectConfigGrouped)}catch(e){Te(e instanceof Error?e.message:String(e))}finally{B(!1)}}},Vt=async(t,n=!1)=>{n&&(Ie.current=0),Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);let r=++Re.current;Fe(!0),Z(null),Ke(null);try{let n=await St(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Re.current)return;if(Ke(n),n.reason===`latest_unavailable`&&Ie.current<2){let e=++Ie.current;Le.current=window.setTimeout(()=>{r===Re.current&&(Le.current=null,Vt(t))},800*e);return}n.reason!==`latest_unavailable`&&(Ie.current=0),Fe(!1)}catch(e){if(r!==Re.current)return;Z(e instanceof Error?e.message:String(e)),Fe(!1)}},Ht=()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Fe(!1),ke(!1)},Ut=()=>{let e=wt(m?.version);je(e),Ne(!0),ke(!0),Vt(e,!0)},Wt=e=>{je(e),Vt(e,!0)},Gt=(0,_.useRef)(Ut);return(0,_.useEffect)(()=>{Gt.current=Ut}),(0,_.useEffect)(()=>{let e=()=>{bt()&&(Ze(`dashboard`),Gt.current())},t=bt()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:t,t:n,selectedSection:r,setSelectedSection:i,modelQuery:a,setModelQuery:o,expandedProviders:s,setExpandedProviders:c,health:m,startupHealth:g,providers:y,models:x,settings:C,sidecar:T,shadowCall:D,usage30d:k,usageLoading:Ct.loading&&!k,healthLoading:ht.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:F,settingsSaving:L,syncing:z,maMode:V,maModeResolved:kt,maBusy:U,setMaHelpOpen:ee,maHelpOpen:G,effortCapHelpOpen:q,setEffortCapHelpOpen:te,shadowCallHelpOpen:J,setShadowCallHelpOpen:Y,injectionModel:ne,injectionEffort:ie,injectionEfforts:oe,injectionAvailable:ce,injectionSaving:ue,multiAgentGuidanceEnabled:fe,syncCodexSubagentDefaults:me,saveInjection:Rt,effortCap:ge,subagentEffortCap:ve,effortCapSaving:be,setEffortCap:_e,setSubagentEffortCap:ye,setEffortCapSaving:xe,syncResult:Se,syncError:we,projectConfigWarnings:Ee,updateOpen:Oe,updateChannel:Ae,setUpdateRestart:Ne,updateRestart:Me,updateLoading:Pe,updateCheck:Ge,updateError:qe,updateJob:Je,reconnecting:Xe,error:$e,effortCapHelpTriggerRef:tt,updateTriggerRef:nt,maHelpTriggerRef:rt,shadowCallHelpTriggerRef:it,effortCapHelpDialogRef:at,updateDialogRef:ot,maHelpDialogRef:st,shadowCallHelpDialogRef:ct,filteredGroups:Nt,sidecarModels:Pt,saveSidecar:Ft,saveShadowCall:It,switchMaMode:Lt,toggleCodexAutoStart:zt,runSync:Bt,fetchUpdateCheck:Vt,closeUpdateDialog:Ht,openUpdateDialog:Ut,changeUpdateChannel:Wt,runUpdate:async()=>{if(Ge?.canUpdate){Z(null);try{let t=await St(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Ae,restart:Me})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);Ye(t.job),Qe(!1),Ht()}catch(e){Z(e instanceof Error?e.message:String(e))}}}}}function Kn(e){Qe(xt(e))}function qn({apiBase:e}){let t=Gn(e),{t:n,error:r,selectedSection:i,providers:a,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}=t;if(r)return(0,J.jsx)(pt,{style:{marginTop:40},icon:(0,J.jsx)(ve,{}),title:(0,J.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,J.jsx)(Ye,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,J.jsx)(gn,{...t}),m=(0,J.jsx)(_n,{t:n,providers:a}),h=(0,J.jsx)(Rt,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,J.jsx)(Lt,{...t}),_=[{id:`overview`,label:n(`dash.workspace.overview`),body:p},{id:`providers`,label:n(`dash.activeProviders`),body:m},{id:`models`,label:n(`dash.availableModels`),body:h}],v=_.find(e=>e.id===i)??_[0],y=Kn,b=e=>{let t=_.findIndex(e=>e.id===i),n=-1;if(e.key===`ArrowRight`?n=(t+1)%_.length:e.key===`ArrowLeft`?n=(t-1+_.length)%_.length:e.key===`Home`?n=0:e.key===`End`&&(n=_.length-1),n<0)return;e.preventDefault();let r=_[n];y(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,J.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":i===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>y(e.id),onKeyDown:b,children:e.label},e.id))}),(0,J.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${v.id}`,"aria-labelledby":`dashboard-tab-${v.id}`,tabIndex:0,children:v.body}),g]})}var Jn=`https://chatgpt.com/backend-api/codex`,Yn=`openai`;function Xn(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 Zn(e){try{let t=new URL(e).hostname.replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`}catch{return!1}}function Qn(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||Zn(e.baseUrl)||e.hasApiKey===!0}function $n(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Xn(e.baseUrl)===Jn}function er(e,t){return e===Yn&&$n(t)}function tr(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||Zn(e.baseUrl)}function nr(e,t){return er(e,t)?`accounts`:tr(t)?`free`:`paid`}function rr(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??nr(e.name,e);switch(t){case`az`:return n.sort(r);case`za`:return n.sort((e,t)=>r(t,e));case`free-paid`:return n.sort((e,t)=>(i(e)===`free`?0:1)-(i(t)===`free`?0:1)||r(e,t));case`paid-free`:return n.sort((e,t)=>(i(e)===`free`)-+(i(t)===`free`)||r(e,t));case`accounts-first`:return n.sort((e,t)=>{let n=e=>{let t=i(e);return t===`accounts`?0:t===`free`?1:2};return n(e)-n(t)||r(e,t)});default:return n}}function ir(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}Qn(a)?t.push({name:i,...a,tier:nr(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function ar(e,t){let n=new Set(Object.entries(t).filter(([,e])=>e).map(([e])=>e));if(n.size===0)return e;let r=e=>e.map(e=>n.has(e.name)?{...e,activeNeedsReauth:!0}:e);return{ready:r(e.ready),needsSetup:r(e.needsSetup),disabled:e.disabled}}function or(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:Qn(e)?`ready`:`needs-setup`}function sr(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!er(`openai`,t)||!$n(n))return e;let r={...e};return delete r.chatgpt,r}function cr(e){return e.authMode===`local`||Zn(e.baseUrl)}var lr=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function ur(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(cr(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return lr.some(e=>n.includes(e))?`selfHosted`:`cloud`}function dr(e){if(!e||typeof e!=`object`)return{};let t=e.available;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))Array.isArray(r)&&(n[e]=r.filter(e=>typeof e==`string`));return n}function fr(e){if(!e||typeof e!=`object`)return{};let t=e.liveModelCounts;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))typeof r!=`number`||!Number.isFinite(r)||r<0||(n[e]=Math.floor(r));return n}function pr(e){if(!e||typeof e!=`object`)return{};let t=e.selected;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))Array.isArray(r)&&(n[e]=r.filter(e=>typeof e==`string`));return n}function mr(e){let t={};for(let[n,r]of Object.entries(dr(e)))t[n]=r.length;return t}function hr(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 gr={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function _r(e,t,n){let r=typeof t==`object`&&t?t:gr,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 vr(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 yr(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 br(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function xr(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 Sr(e,t=`en`){return xr(e,t)}function Cr(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var wr={anthropic:`claude-color.svg`,"anthropic-apikey":`claude-color.svg`,"azure-openai":`openai.svg`,chatgpt:`openai.svg`,"cloudflare-ai-gateway":`cloudflare-ai-gateway-color.svg`,"cloudflare-workers-ai":`cloudflare-ai-gateway-color.svg`,cursor:`cursor-color.svg`,deepseek:`deepseek-color.svg`,firepass:`firepass-color.svg`,fireworks:`fireworks-color.svg`,github:`github-copilot-color.svg`,"github-copilot":`copilot-color.svg`,"gitlab-duo":`gitlab-duo-color.svg`,google:`gemini-color.svg`,"google-antigravity":`antigravity-color.svg`,"google-vertex":`gemini-color.svg`,groq:`groq-color.svg`,huggingface:`huggingface-color.svg`,kimi:`kimi-color.svg`,"kimi-code":`kimi-color.svg`,kiro:`kiro-color.svg`,"lm-studio":`lm-studio-color.svg`,mistral:`mistral-color.svg`,moonshot:`moonshot-color.svg`,nvidia:`nvidia-color.svg`,ollama:`ollama-color.svg`,"ollama-cloud":`ollama-color.svg`,openai:`openai.svg`,"openai-apikey":`openai.svg`,"opencode-free":`opencode.svg`,"opencode-go":`opencode.svg`,"opencode-zen":`opencode.svg`,openrouter:`openrouter-color.svg`,qianfan:`qianfan-color.svg`,alibaba:`alibaba-color.svg`,"alibaba-token-plan":`alibaba-color.svg`,"alibaba-token-plan-intl":`alibaba-color.svg`,"qwen-cloud":`qwen-portal-color.svg`,"vercel-ai-gateway":`vercel-ai-gateway-color.svg`,vllm:`vllm-color.svg`,xai:`grok-color.svg`,"mimo-free":`xiaomi-color.svg`,xiaomi:`xiaomi-color.svg`},Tr={anthropic:`Anthropic Claude`,"anthropic-apikey":`Anthropic Claude`,chatgpt:`ChatGPT`,openai:`OpenAI (Codex login)`,"openai-apikey":`OpenAI API`,"azure-openai":`Azure OpenAI`,"cloudflare-ai-gateway":`Cloudflare AI Gateway`,"cloudflare-workers-ai":`Cloudflare Workers AI`,nvidia:`NVIDIA NIM`,ollama:`Ollama`,"ollama-cloud":`Ollama Cloud`,xai:`xAI Grok`,"mimo-free":`MiMo Free`,xiaomi:`Xiaomi`,cursor:`Cursor`,deepseek:`DeepSeek`,github:`GitHub`,"github-copilot":`GitHub Copilot`,"gitlab-duo":`GitLab Duo`,openrouter:`OpenRouter`,"opencode-go":`OpenCode Go`,"opencode-free":`OpenCode Free`,"opencode-zen":`OpenCode Zen`,mistral:`Mistral`,groq:`Groq`,alibaba:`Alibaba Coding Plan`,"alibaba-token-plan":`Alibaba Token Plan`,"alibaba-token-plan-intl":`Alibaba Token Plan (Intl)`,kimi:`Kimi`,"kimi-code":`Kimi`,moonshot:`Moonshot`,google:`Google`,"google-vertex":`Google Vertex`,"lm-studio":`LM Studio`,huggingface:`Hugging Face`,"qwen-cloud":`Qwen Cloud`,siliconflow:`SiliconFlow`,"tencent-coding-plan":`Tencent Cloud Coding Plan`,"vercel-ai-gateway":`Vercel AI Gateway`,vllm:`vLLM`,litellm:`LiteLLM`},Er={volcengine:`provider.name.volcengine`,"volcengine-coding-plan":`provider.name.volcengineCodingPlan`,"volcengine-agent-plan":`provider.name.volcengineAgentPlan`},Dr=new Set([...Object.keys(Tr),...Object.keys(Er)]);function Or(e){return wr[e.toLowerCase()]}function kr(e,t){let n=Or(e);return n?`/provider-icons/${n}`:void 0}function Ar(e,t){let n=e.toLowerCase(),r=Er[n];return r?t(r):Tr[n]?Tr[n]:e===n&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)?e.split(`-`).map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(` `):e}function jr(e){return Dr.has(e.toLowerCase())}function Mr(e,t){let n=or(e);return n===`disabled`?t(`prov.disabledBadge`):n===`ready`?t(`pws.status.ready`):`activeNeedsReauth`in e&&e.activeNeedsReauth?t(`pws.status.needsAttention`):t(`pws.status.needsSetup`)}function Nr(e,t){switch(e.authMode){case`oauth`:return t(`modal.badge.oauth`);case`forward`:return t(`pws.auth.chatgptPassthrough`);case`local`:return t(`modal.badge.local`);case`key`:return t(`modal.badge.apiKey`);default:return e.authMode??(e.keyOptional?t(`pws.auth.noKey`):t(`modal.badge.apiKey`))}}function Pr(e){let t=or(e);return t===`disabled`?`providers-workspace-rail-status providers-workspace-rail-status--inactive`:t===`ready`?`providers-workspace-rail-status providers-workspace-rail-status--active`:`providers-workspace-rail-status providers-workspace-rail-status--warning`}function Fr({name:e,adapter:t,baseUrl:n,cls:r}){let i=kr(e,{adapter:t,baseUrl:n});return(0,J.jsx)(`span`,{className:r,children:i?(0,J.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`}):(0,J.jsx)(re,{"aria-hidden":`true`})})}function Ir({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Z(),l=tr(e),u=cr(e),d=Mr(e,c),f=Ar(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,J.jsxs)(`button`,{type:`button`,className:`providers-workspace-rail-row${t?` providers-workspace-rail-row--selected`:``}`,onClick:o,role:`option`,"aria-selected":t,tabIndex:n?0:-1,"aria-label":c(`pws.rail.selectAria`,{name:p,status:d,suffix:m}),title:p,onFocus:s,children:[(0,J.jsx)(Fr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,J.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,J.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,J.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,J.jsx)(ze,{width:17,height:17,"aria-hidden":`true`})}),(0,J.jsx)(`span`,{className:Pr(e),title:d,"aria-hidden":`true`})]})]})}function Lr(e){let t=e?.aggregation;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;if(n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`)return null;let r=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,i=r(n.includedAccounts),a=r(n.excludedAccounts),o=r(n.unknownPlanAccounts);if(i===void 0||a===void 0||o===void 0)return null;let s=n.presentation===`effective-account-fallback`||n.presentation===`coverage-only`?n.presentation:`aggregate`,c=[n.fiveHour,n.weekly,n.monthly,...Array.isArray(n.customWindows)?n.customWindows:[]].filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)).map(e=>({at:r(e.nextRecoveryAt),percent:r(e.nextRecoveryPercent)})).filter(e=>e.at!==void 0).sort((e,t)=>e.at-t.at)[0];return{presentation:s,includedAccounts:i,excludedAccounts:a,unknownPlanAccounts:o,...c?{nextRecoveryAt:c.at}:{},...c?.percent===void 0?{}:{nextRecoveryPercent:c.percent}}}function Rr(e){let t=e?.quota;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t,r=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,i=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||r(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...r(t.resetAt)===void 0?{}:{resetAt:t.resetAt},...typeof t.valueLabel==`string`&&t.valueLabel.trim()?{valueLabel:t.valueLabel}:{},...Array.isArray(t.segments)?{segments:t.segments.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||r(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...r(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]})}:{}}]}):[],a={...r(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...r(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...r(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...r(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...r(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...r(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...i.length>0?{customWindows:i}:{},updatedAt:r(n.updatedAt)??e?.updatedAt??Date.now()};return a.fiveHourPercent!==void 0||a.weeklyPercent!==void 0||a.monthlyPercent!==void 0||(a.customWindows?.length??0)>0?a:null}function zr(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Br(e,t,n,r,i,a){let o=r&&r.length>0?r:t?[t]:[],s=[...new Set([...a?e:o,...i])],c=n.trim().toLowerCase();return c?s.filter(e=>e.toLowerCase().includes(c)):s}function Vr(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function Hr(e,t){return!e||!Vr(t)?e:{...e.monthlyPercent===void 0?{}:{monthlyPercent:e.monthlyPercent},...e.monthlyResetAt===void 0?{}:{monthlyResetAt:e.monthlyResetAt},...e.resetCredits===void 0?{}:{resetCredits:e.resetCredits},updatedAt:e.updatedAt}}function Ur(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function Wr(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 Gr(e,t,n){let r=Hr(e,t);if(!r)return[];let i=[];typeof r.fiveHourPercent==`number`&&i.push({rank:0,row:{label:n(`codexAuth.fiveHour`),limitLabel:n(`quota.fiveHourLimit`),percent:r.fiveHourPercent,resetAt:r.fiveHourResetAt}}),typeof r.weeklyPercent==`number`&&i.push({rank:1,row:{label:n(`codexAuth.weekly`),limitLabel:n(`quota.weeklyLimit`),percent:r.weeklyPercent,resetAt:r.weeklyResetAt}}),typeof r.monthlyPercent==`number`&&i.push({rank:4,row:{label:n(`codexAuth.monthly`),limitLabel:n(`quota.monthlyLimit`),percent:r.monthlyPercent,resetAt:r.monthlyResetAt}});for(let e of r.customWindows??[]){let t=Wr(e.label,n);i.push({rank:Ur(e.label),row:{label:t,limitLabel:t,percent:e.percent,resetAt:e.resetAt,...e.valueLabel===void 0?{}:{valueLabel:e.valueLabel},...e.segments!==void 0&&e.segments.length>0?{segments:e.segments}:{}}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function Kr(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 t.length?Math.max(...t):-1}function qr(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;default:return e}}function Jr(e){return e>=99.5}function Yr(e,t){return t>0&&e>=t}function Xr(e,t){return Yr(e,t)||Jr(e)?`bar-warn`:`bar-green`}function Zr(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Qr(e){return{"--bar-scale":String(Zr(e)/100)}}function $r({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1}){let{locale:s}=X(),c=Gr(e,t,r);return c.length===0?o?a===`stacked`?(0,J.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,J.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,J.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`})]},t)),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,J.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:c.map(e=>(0,J.jsx)(ii,{row:e,threshold:n,t:r,locale:s},e.limitLabel))}):(0,J.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:c.map(e=>e.segments!==void 0&&e.segments.length>0?(0,J.jsx)(ni,{row:e,threshold:n,t:r,locale:s},e.label):e.valueLabel===void 0?(0,J.jsx)(ei,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:s},e.label):(0,J.jsx)(ti,{label:e.label,value:e.valueLabel},e.label))})}function ei({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Jr(t),s=Yr(t,r),c=Xr(t,r),l=ai(n,i,a);return(0,J.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,J.jsx)(`span`,{className:`quota-label`,children:e}),(0,J.jsx)(`span`,{className:`quota-reset-label`,children:i(`codexAuth.resets`)}),(0,J.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,J.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,J.jsx)(`div`,{className:`bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${c}`,style:Qr(t)})}),(0,J.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):void 0,children:[s&&(0,J.jsx)(ve,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function ti({label:e,value:t}){return(0,J.jsxs)(`div`,{className:`quota-row quota-row--value`,children:[(0,J.jsx)(`span`,{className:`quota-label`,children:e}),(0,J.jsx)(`span`,{className:`quota-val`,children:t})]})}function ni({row:e,threshold:t,t:n,locale:r}){return(0,J.jsx)(`div`,{className:`quota-row quota-row--segments`,children:(0,J.jsx)(`div`,{className:`quota-segments`,children:(e.segments??[]).map(e=>(0,J.jsx)(ri,{segment:e,threshold:t,t:n,locale:r},e.label))})})}function ri({segment:e,threshold:t,t:n,locale:r}){let i=Yr(e.percent,t),a=Xr(e.percent,t),o=oi(e.resetAt,n,r);return(0,J.jsxs)(`div`,{className:`quota-segment`,children:[(0,J.jsxs)(`span`,{className:`quota-segment-head`,children:[(0,J.jsxs)(`span`,{className:`quota-segment-title`,children:[e.label,o?(0,J.jsxs)(`span`,{className:`quota-segment-reset`,children:[` · `,o]}):null]}),(0,J.jsxs)(`span`,{className:`quota-segment-val${i?` quota-segment-val--warn`:``}`,children:[Math.round(e.percent),`%`]})]}),(0,J.jsx)(`div`,{className:`bar quota-segment-bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${a}`,style:Qr(e.percent)})})]})}function ii({row:e,threshold:t,t:n,locale:r}){if(e.segments!==void 0&&e.segments.length>0)return(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--segments`,children:[(0,J.jsx)(`div`,{className:`quota-stacked-head`,children:(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel})}),(0,J.jsx)(`div`,{className:`quota-segments`,children:(e.segments??[]).map(e=>(0,J.jsx)(ri,{segment:e,threshold:t,t:n,locale:r},e.label))})]});if(e.valueLabel!==void 0)return(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--value`,children:[(0,J.jsx)(`div`,{className:`quota-stacked-head`,children:(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel})}),(0,J.jsx)(`div`,{className:`quota-stacked-bar-row`,children:(0,J.jsx)(`span`,{className:`quota-stacked-used`,children:e.valueLabel})})]});let i=Jr(e.percent),a=Yr(e.percent,t),o=Xr(e.percent,t),s=oi(e.resetAt,n,r);return(0,J.jsxs)(`div`,{className:`quota-stacked-row${a?` quota-stacked-row--warn`:``}${i?` quota-stacked-row--exhausted`:``}`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),(0,J.jsx)(`span`,{className:`quota-stacked-reset muted`,children:s})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${o}`,style:Qr(e.percent)})}),(0,J.jsx)(`span`,{className:`quota-stacked-used${a?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),i&&(0,J.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,J.jsx)(ve,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function ai(e,t,n){if(typeof e!=`number`||!Number.isFinite(e))return{day:``,time:``};let r=e<1e10?e*1e3:e,i=new Date(r),a=new Date,o=qr(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 oi(e,t,n=`en`,r=Date.now()){if(typeof e!=`number`||!Number.isFinite(e))return``;let i=e<1e10?e*1e3:e,a=new Date(i),o=qr(n),s=new Intl.DateTimeFormat(o,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(a),c=new Date(r),l=new Date(c.getFullYear(),c.getMonth(),c.getDate()).getTime(),u=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),d=Math.round((u-l)/864e5);if(d===1)return t(`quota.resetsTomorrow`,{time:s});let f=a.getFullYear()!==c.getFullYear(),p=new Intl.DateTimeFormat(o,{day:`numeric`,month:`short`,...f?{year:`numeric`}:{}}).format(a);if(i<=r)return t(`quota.resetsAt`,{date:p,time:s,when:`${p}, ${s}`});let m=Math.round((i-r)/6e4);if(m<60)return t(`quota.resetsRelativeMinutes`,{n:Math.max(1,m)});let h=Math.round(m/60);return h<12&&d===0?t(`quota.resetsRelativeHours`,{n:Math.max(1,h)}):d===0?t(`quota.resetsToday`,{time:s}):t(`quota.resetsAt`,{date:p,time:s,when:`${p}, ${s}`})}function si({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=Z(),{locale:c}=X(),l=vr(s),u=(0,_.useMemo)(()=>[...e.ready,...e.needsSetup,...e.disabled],[e]),d=(0,_.useMemo)(()=>new Set(u.map(e=>e.name)),[u]),f=(0,_.useMemo)(()=>yr(e,{}),[e]),p=f.length,m=(0,_.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),h=e.ready.length-m,g=e.needsSetup.length+m,v=(0,_.useMemo)(()=>{let e=[];for(let n of u){let r=t[n.name],i=r?Rr(r):null;r&&i&&e.push({item:n,report:r,urgency:Kr(i)})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[u,t]),y=(0,_.useMemo)(()=>{let e={};for(let[t,r]of Object.entries(n))d.has(t)&&(e[t]=r);return hr(e).slice(0,4)},[n,d]),b=e=>{let t=br(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,J.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,J.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,J.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,J.jsx)(ci,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,J.jsx)(ci,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,J.jsx)(ci,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,J.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,J.jsx)(ve,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,J.jsx)(Fr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ar(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,J.jsx)(we,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Fr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ar(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:(()=>{let e=Lr(t);if(!e)return s(`pws.dashboard.checkedAgo`,{time:_r(t.updatedAt,l)});let n=s(`pws.capacity.coverage`,{included:e.includedAccounts,total:e.includedAccounts+e.excludedAccounts}),r=e.nextRecoveryAt?s(`pws.capacity.nextRecovery`,{time:_r(e.nextRecoveryAt,l)}):``;return`${s(`pws.capacity.estimate`)} · ${n}${r?` · ${r}`:``}`})()})]}),(0,J.jsx)(we,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)($r,{quota:Rr(t),threshold:80,t:s,layout:`stacked`,pending:i&&!t.quota})})]},e.name))}):i?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)($r,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Fr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ar(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:xr(e.requests,c)})}),(0,J.jsx)(we,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function ci({count:e,label:t,tone:n}){return(0,J.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,J.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function li({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Z(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,J.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,J.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,J.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,J.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,J.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,J.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,J.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var ui=[{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 di({providers:e,apiBase:t,defaultProvider:n,selectedName:r,onSelect:i,onRemoveProvider:a,onAddProvider:o,onEditConfig:s,jsonEditor:c,jsonSaving:l=!1,modelsRefreshToken:u=0,activeAccountNeedsReauth:d,quotaRefreshEpoch:f=0,quotaForceRefresh:p=!1,detail:m}){let h=Z(),[g,v]=(0,_.useState)(``),[b,x]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[S,C]=(0,_.useState)({free:!0,paid:!0}),[w,T]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[E,D]=(0,_.useState)(`az`),[O,k]=(0,_.useState)(!1),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)({}),[P,F]=(0,_.useState)({}),[I,L]=(0,_.useState)({}),[R,z]=(0,_.useState)({}),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(!1),W=`ocx.providers.quotas.v1:${t}`,G=`ocx.providers.usage.v1:${t}`,[ee,K]=(0,_.useState)(()=>vn(G)?.totals??{}),[q,te]=(0,_.useState)(()=>vn(G)?.models??{}),[Y,ne]=(0,_.useState)(()=>vn(W)??{}),[re,ie]=(0,_.useState)(()=>!vn(G)),[ae,oe]=(0,_.useState)(()=>!vn(W)),[se,ce]=(0,_.useState)(0),le=(0,_.useRef)(null),ue=(0,_.useMemo)(()=>ar(ir(sr(e)),d??{}),[e,d]),de=(0,_.useCallback)(()=>{ce(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{V(!0),(async()=>{try{let n=await Q(await fetch(`${t}/api/selected-models`));if(e)return;N(mr(n)),F(dr(n)),L(fr(n)),z(pr(n)),U(!1)}catch{if(e)return;U(!0)}finally{e||V(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,se]),(0,_.useEffect)(()=>{let e=!1,n=null,r=window.setTimeout(()=>{vn(G)||ie(!0);let r=y(6e4);n=r,fetch(`${t}/api/usage?range=30d`,{signal:r.signal}).then(e=>_t(e)).then(t=>{if(e||!t)return;let n={};for(let e of t.providers??[])n[e.provider]={requests:e.requests,totalTokens:e.totalTokens};K(n);let r={};for(let e of t.models??[]){let t=e.provider;r[t]||(r[t]=[]),r[t].push({model:e.model,...e.resolvedModel?{resolvedModel:e.resolvedModel}:{},requests:e.requests,totalTokens:e.totalTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens,shareRatio:e.shareRatio,...e.estimatedCostUsd===void 0?{}:{estimatedCostUsd:e.estimatedCostUsd}})}te(r),yn(G,{totals:n,models:r})}).catch(()=>{}).finally(()=>{r.clear(),n===r&&(n=null),e||ie(!1)})},0);return()=>{e=!0,window.clearTimeout(r),n?.controller.abort(),n?.clear()}},[t,G]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{vn(W)||oe(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>_t(e)).then(t=>{e||!t||ne(e=>{let n={...e};for(let e of t.reports??[])e?.provider&&(n[e.provider]={label:e.label,source:e.source,updatedAt:typeof e.updatedAt==`number`?e.updatedAt:Date.now(),quota:e.quota});return yn(W,n),n})}).catch(()=>{}).finally(()=>{e||oe(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,W]),(0,_.useEffect)(()=>{if(!O)return;let e=e=>{le.current&&!le.current.contains(e.target)&&k(!1)},t=e=>{e.key===`Escape`&&k(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[O]);let fe=(0,_.useMemo)(()=>[...ue.ready,...ue.needsSetup,...ue.disabled],[ue]),pe=(0,_.useMemo)(()=>fe.filter(tr).length,[fe]),me=fe.length-pe,he=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of fe)e[ur(t)]+=1;return e},[fe]),ge=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>rr(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=tr(t);return!(n&&!S.free||!n&&!S.paid||!w[ur(t)])}),E);return{ready:b.ready?t(ue.ready):[],needsSetup:b.needsSetup?t(ue.needsSetup):[],disabled:b.disabled?t(ue.disabled):[]}},[ue,g,b,S,w,E]),ve=!b.ready||!b.needsSetup||!b.disabled||!S.free||!S.paid||!w.cloud||!w.local||!w.selfHosted||!w.login||E!==`az`,ye=()=>{x({ready:!0,needsSetup:!0,disabled:!0}),C({free:!0,paid:!0}),T({cloud:!0,local:!0,selfHosted:!0,login:!0}),D(`az`)},xe=(0,_.useMemo)(()=>r?fe.find(e=>e.name===r)??null:null,[r,fe]),Se=(0,_.useMemo)(()=>{let e=new Map;for(let t of fe){let n=Ar(t.name,h);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},[fe,h]);if(fe.length===0)return(0,J.jsx)(fi,{onAddProvider:o});let Ce=[{key:`ready`,label:h(`pws.status.ready`),count:ue.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:ue.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:ue.disabled.length}],we=[{id:`ready`,label:h(`pws.status.ready`),count:ge.ready.length,ariaLabel:h(`pws.groupReady`,{count:ge.ready.length}),items:ge.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:ge.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:ge.needsSetup.length}),items:ge.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:ge.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:ge.disabled.length}),items:ge.disabled}],Te=we.flatMap(e=>e.items.map(e=>e.name)),Ee=A&&Te.includes(A)?A:r&&Te.includes(r)?r:Te[0]??null;return(0,J.jsx)(`div`,{className:`pws-shell-container`,children:(0,J.jsxs)(`div`,{className:`pws-root`,children:[(0,J.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,J.jsxs)(`div`,{className:`pws-search-row`,children:[(0,J.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,J.jsx)(be,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:h(`pws.searchPlaceholder`),value:g,onChange:e=>v(e.target.value),"aria-label":h(`pws.searchPlaceholder`)})]}),(0,J.jsxs)(`div`,{className:`pws-filter-wrap`,ref:le,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ve||O?` pws-filter-btn--active`:``}`,onClick:()=>k(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":O,"aria-controls":`pws-provider-filters`,children:[(0,J.jsx)(Be,{width:18,height:18,"aria-hidden":`true`}),ve&&(0,J.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),O&&(0,J.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,J.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),Ce.map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:b[e],onChange:()=>x(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:S.free,onChange:()=>C(e=>({...e,free:!e.free}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:pe})]}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:S.paid,onChange:()=>C(e=>({...e,paid:!e.paid}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:me})]}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:he.cloud},{key:`local`,label:h(`pws.type.local`),count:he.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:he.selfHosted},{key:`login`,label:h(`pws.type.login`),count:he.login}].map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:w[e],onChange:()=>T(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,J.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:ui.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`pws-sort-btn${E===e.id?` pws-sort-btn--active`:``}`,onClick:()=>D(e.id),"aria-pressed":E===e.id,children:h(e.labelKey)},e.id))}),(0,J.jsx)(`div`,{className:`pws-filter-footer`,children:(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:ye,disabled:!ve,children:h(`pws.resetAll`)})})]})]})]}),(0,J.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":h(`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(ge).every(e=>e.length===0)&&(0,J.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:ve?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),we.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,J.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,J.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,J.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,J.jsx)(Ir,{item:e,selected:r===e.name,tabbable:Ee===e.name,modelCount:M[e.name],isDefault:n===e.name,showConfigId:Se.has(Ar(e.name,h)),onClick:()=>i(e.name),onFocus:()=>j(e.name)}),a&&(0,J.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),a(e.name)},title:h(`pws.removeConfirmTitle`),children:(0,J.jsx)(_e,{width:14,height:14})})]},e.name))]},e))]})]}),(0,J.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,J.jsx)(li,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):xe?m?.(xe,{usageTotals:ee[xe.name],modelUsage:q[xe.name],quotaReport:Y[xe.name],availableModels:P[xe.name]??[],hasLiveModels:(I[xe.name]??0)>0,selectedModels:R[xe.name]??[],modelsLoading:B,modelsLoadFailed:H,onRetryModels:de})??(0,J.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,J.jsx)(`h3`,{children:Ar(xe.name,h)}),(0,J.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,J.jsx)(si,{sections:ue,quotaReports:Y,usageTotals:ee,usageLoading:re,quotasLoading:ae,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function fi({onAddProvider:e}){let t=Z();return(0,J.jsx)(`div`,{className:`pws-empty-root`,children:(0,J.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,J.jsx)(`div`,{"aria-hidden":`true`,children:(0,J.jsx)(ie,{style:{width:64,height:64}})}),(0,J.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,J.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Fe,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(ke,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Oe,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function pi(e){if(er(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||cr(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0;return!(t===`key`||n||t===``)||e.keyOptional===!0&&!n?null:`api-keys`}function mi(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 hi({item:e,usageTotals:t,quotaReport:n,oauthEmail:r,apiBase:i,connectionIdentity:a,onEditSettings:o,onViewUsage:s,onUpdateProvider:c,onReauthenticate:l,onCancelLogin:u,reauthBusy:d=!1,accountPanel:f}){let p=Z(),{locale:m}=X(),h=vr(p),g=or(e),v=!!e.activeNeedsReauth,y=p(g===`ready`?`pws.status.connected`:g===`needs-setup`?v?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),b=t?.requests,x=t?.totalTokens,S=Rr(n),C=JSON.stringify([i??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,a??null]),[w,T]=(0,_.useState)(null),E=(0,_.useRef)(null),D=w?.key===C&&w.testing,O=w?.key===C?w.result:null;(0,_.useEffect)(()=>()=>{E.current?.key===C&&(E.current.controller.abort(),E.current=null)},[C]);let k=(0,_.useCallback)(async()=>{if(!i)return;E.current?.controller.abort();let t=new AbortController;E.current={key:C,controller:t},T({key:C,testing:!0,result:null});try{let n=await Q(await fetch(`${i}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),p(`pws.connectionFailed`));if(!n)throw Error(p(`pws.connectionFailed`));t.signal.aborted||T({key:C,testing:!1,result:n})}catch(e){t.signal.aborted||T({key:C,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:p(`pws.connectionFailed`)}})}finally{E.current?.controller===t&&(E.current=null)}},[i,C,e.name,p]),A=O?.applicable===!1?`not-applicable`:O?.ok===!0?`ok`:`failed`,j=O?.applicable===!1?p(`pws.connectionNotApplicable`):O?.ok===!0?O.message||p(`pws.connectionOk`):O?.error||p(`pws.connectionFailed`);return(0,J.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,J.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.connection`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.connection`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`dash.status`)}),(0,J.jsxs)(`dd`,{className:g===`ready`?`pws-status-ok`:`pws-status-warn`,children:[g===`ready`?(0,J.jsx)(de,{style:{width:13,height:13},"aria-hidden":`true`}):(0,J.jsx)(ve,{style:{width:13,height:13},"aria-hidden":`true`}),y]})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.baseUrl`)}),(0,J.jsx)(`dd`,{children:(0,J.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.auth`)}),(0,J.jsx)(`dd`,{children:r?`${Nr(e,p)} · ${r}`:Nr(e,p)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.defaultModel`)}),(0,J.jsx)(`dd`,{children:e.defaultModel??(0,J.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.note`)}),(0,J.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),i&&(0,J.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:()=>void k(),children:p(D?`pws.testing`:`pws.testConnection`)}),O&&(0,J.jsx)(`span`,{role:`status`,className:A===`ok`?`pws-status-ok`:A===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":A,children:j})]}),o&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:o,children:p(`pws.editSettings`)})]}),f?(0,J.jsx)(`section`,{className:`pws-section`,"aria-label":p(`pws.availableAccounts`),children:f}):(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.authSummary`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.authSummary`)}),v?(0,J.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,J.jsx)(ve,{style:{width:14,height:14},"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:p(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?p(`pws.attention.reauthForward`):p(`pws.attention.reauth`)]}),l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:d,onClick:()=>l(),children:p(d?`prov.waitingBrowser`:`pws.reauthenticate`)}),d&&u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>u(),children:p(`common.cancel`)})]})]}):(0,J.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,J.jsx)(`span`,{className:`pws-auth-dot`}),(0,J.jsx)(`span`,{children:e.authMode===`forward`?p(`pws.passthrough`):e.authMode===`oauth`?r?p(`pws.loggedInAs`,{email:r}):p(`pws.notLoggedIn`):e.hasApiKey?p(`pws.apiKeyConfigured`):Nr(e,p)})]})]})]}),(0,J.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.statsAria`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.statsTitle`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[typeof b==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalRequests`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:xr(b,m)})]}),typeof x==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalTokens`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:Sr(x,m)})]}),n&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?zr(n.source):void 0,children:_r(n.updatedAt,h)})]}),typeof b!=`number`&&typeof x!=`number`&&!n&&(0,J.jsx)(`div`,{className:`muted`,children:p(`pws.usageUnavailable`)})]}),s&&(0,J.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:s,children:[p(`pws.viewUsage`),` →`]}),S&&(0,J.jsx)(`div`,{className:`muted pws-stats-note`,children:p(`pws.stats.quotaTracked`)})]}),(0,J.jsx)(gi,{item:e,onUpdateProvider:c})]})]})}function gi({item:e,onUpdateProvider:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.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,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.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,J.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,J.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function _i({item:e,apiBase:t,availableModels:n,hasLiveModels:r,selectedModels:i,modelsLoading:a=!1,modelsLoadFailed:o=!1,needsReauth:s=!1,onRetryModels:c,onOpenAccounts:l}){let u=Z(),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(``),[S,C]=(0,_.useState)([]),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(null),M=(0,_.useRef)(null),N=(0,_.useMemo)(()=>new Set(i),[i]),P=(0,_.useMemo)(()=>e.models??[],[e.models]),F=p.trim(),I=!w||!F||F.includes(`/`)||n.includes(F)||S.includes(F)||P.includes(F)||e.defaultModel===F,L=(0,_.useMemo)(()=>Br(n,e.defaultModel,d,P,S,r),[n,e.defaultModel,d,P,S,r]);(0,_.useEffect)(()=>{let n=!0;return(async()=>{try{let r=await fetch(`${t}/api/custom-models`);if(!r.ok)throw Error();let i=await r.json();if(!Array.isArray(i))throw Error(`Invalid custom model list`);if(!n)return;C(i.flatMap(t=>{if(!t||typeof t!=`object`)return[];let n=t;return n.provider===e.name&&typeof n.modelId==`string`?[n.modelId]:[]})),D(!1),y(``),T(!0)}catch{if(!n)return;C([]),T(!1),D(!0),y(u(`models.networkError`))}})(),()=>{n=!1}},[t,e.name,u,O]);let R=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let z=async e=>{try{await navigator.clipboard.writeText(e),j(e),M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{j(t=>t===e?null:t),M.current=null},1200)}catch{}},B=async()=>{if(!(I||h)){g(!0),y(``),x(``);try{(await fetch(`${t}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,modelId:F})})).ok?(C(e=>e.includes(F)?e:[...e,F]),m(``),x(u(`models.customAdded`)),c?.()):y(u(`models.customSaveFailed`))}catch{y(u(`models.networkError`))}finally{g(!1)}}},V=n.length===0&&P.length===0&&S.length===0&&!e.defaultModel,H=n.length===0&&P.length>0,U=L.length>300,W=U?L.slice(0,300):L;return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-section-head`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),L.length>0&&(0,J.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:L.length})})]}),s&&(0,J.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),H&&!s&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,J.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,J.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,J.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&B()},placeholder:u(`models.customFieldModelIdPlaceholder`),"aria-label":u(`models.customAdd`),disabled:h}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{B()},disabled:h||I,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,J.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,J.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:R,style:{marginLeft:8},children:u(`common.retry`)})]}),!V&&(0,J.jsx)(`input`,{type:`search`,className:`input pws-model-search`,placeholder:u(`pws.modelSearchPlaceholder`),value:d,onChange:e=>f(e.target.value),"aria-label":u(`pws.modelSearchPlaceholder`)}),a&&V?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&V?(0,J.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):V?(0,J.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):L.length===0?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,J.jsx)(`ul`,{className:`pws-model-list`,children:W.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,J.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,J.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:()=>{z(t)},title:t,"aria-label":u(A===t?`pws.modelCopied`:`pws.copyModelId`),children:(0,J.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,J.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,J.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),U&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(L.length)})})]})}function vi({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=Z(),{locale:a}=X(),o=vr(i),s=t?.requests!==void 0,c=Rr(n),[l,u]=(0,_.useState)(null),d=(0,_.useMemo)(()=>r?.length?r.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[r]),f=(0,_.useMemo)(()=>{if(!d.length)return;let e=0,t=!1;for(let n of d)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[d]);return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Cr(f,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:xr(t?.requests,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:Sr(t?.totalTokens,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,J.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`pws-model-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`pws.col.model`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,J.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,J.jsxs)(_.Fragment,{children:[(0,J.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,J.jsx)(`td`,{className:`mono`,children:(0,J.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,J.jsx)(`td`,{className:`num mono`,children:Cr(e.estimatedCostUsd,a)}),(0,J.jsx)(`td`,{className:`num mono`,children:Sr(e.totalTokens,a)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`pws-share-bar`,children:(0,J.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,J.jsx)(`tr`,{className:`pws-model-detail`,children:(0,J.jsx)(`td`,{colSpan:5,children:(0,J.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Sr(e.inputTokens,a)]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Sr(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($r,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,J.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,J.jsx)(`dd`,{children:zr(n.source)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{children:_r(n?.updatedAt,o)})]})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function yi(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function bi(e){return yi(e)??`account-…`}function xi(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Si(e){let t=xi(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function Ci(e){return e===`reauth_required`}function wi(e){return!!e?.needsReauth||Ci(e?.health?.status)}function Ti(e){return e===`cooldown`}function Ei(e){return e===`warning`||e===`reauth_required`}function Di(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`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 Oi(e,t){let n=Di(t);return n?e(n):null}function ki(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):bi(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===`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 Ai(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return ji(e)}function ji(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 Mi(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var Ni=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function Pi(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-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};case`oauth-code-submitted`:return{...e,error:``,manualCode:``,manualCodeState:`waiting`,statusTone:`ok`,statusNotice:``};default:return e}}function Fi({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,J.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:a(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,J.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,J.jsx)(Fe,{width:20}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,J.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var Ii=2500;function Li(){let[e,t]=(0,_.useState)(null),n=(0,_.useRef)(null),r=(0,_.useRef)(0),i=(0,_.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,_.useEffect)(()=>i,[i]),{outcomeFor:(0,_.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,_.useCallback)((e,a)=>{let o=++r.current;Ai(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)},Ii))})},[i])}}function Ri({url:e}){let t=Z(),{outcomeFor:n,copy:r}=Li();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,J.jsxs)(`div`,{className:`login-url-block`,children:[(0,J.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,J.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,J.jsx)(je,{style:{width:13,height:13},"aria-hidden":`true`}),(0,J.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,J.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,J.jsx)(De,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function zi({reauthAccountId:e,authUrl:t,manualCode:n,manualCodeBusy:r,manualCodeWaiting:i,statusNotice:a,statusTone:o,flowId:s,error:c,onManualCodeChange:l,onSubmitManualCode:u,onClose:d}){let f=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,J.jsx)(Ri,{url:t}),(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,marginTop:12},children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:f(`prov.pasteRedirectHint`)}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,J.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:n,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),u())},placeholder:f(`prov.pasteRedirect`),"aria-label":f(`prov.pasteRedirect`),disabled:r||i,className:`input text-label`,style:{flex:1}}),(0,J.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,disabled:r||i||!n.trim()||!s,onClick:u,children:f(r?`codexAuth.oauthSubmittingCode`:`prov.pasteSubmit`)})]})]}),a&&(0,J.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,J.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,J.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}function Bi({apiBase:e,reauthAccountId:t,ui:n,dispatch:r,t:i}){let a=(0,_.useRef)(!0),o=(0,_.useRef)(0),s=(0,_.useRef)(!1),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(n.manualCodeState),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(()=>{}),g=(0,_.useRef)(()=>{}),v=n.manualCodeState===`submitting`,b=n.manualCodeState===`waiting`;(0,_.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,_.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let x=(0,_.useCallback)(()=>{c.current&&=(c.current(),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),S=(0,_.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),C=(0,_.useCallback)(async()=>{S();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-auth-url`,authUrl:``}),x(),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,S,r,x]);(0,_.useEffect)(()=>(a.current=!0,()=>{S(),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}),x(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,S,r,x]);let w=(0,_.useCallback)((e,t)=>{h.current=e,g.current=t},[]),T=(0,_.useCallback)(()=>{n.step===`oauth-waiting`&&C(),g.current()},[n.step,C]),E=(0,_.useCallback)(async n=>{S(),d.current=null,r({type:`set-flow-id`,flowId:null});let m=new AbortController;p.current?.abort(),p.current=m,r({type:`reset-oauth-start`}),o.current=0;try{let p=t??n?.trim()??``,_=()=>fetch(`${e}/api/codex-auth/login`,{signal:m.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{id:t,reauth:!0}:p?{id:p}:{})}),v=await _();if(!a.current)return;if(v.status===409){if(await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),!a.current||m.signal.aborted)return;if(v=await _(),v.status===409){r({type:`set-error`,error:i(`codexAuth.oauthAlreadyInProgress`)});return}}let b=await Q(v,i(`modal.networkError`));if(!a.current||!b)return;if(b.url){d.current=b.flowId??null,r({type:`set-flow-id`,flowId:b.flowId??null}),r({type:`set-auth-url`,authUrl:b.url}),r({type:`set-step`,step:`oauth-waiting`}),x();let n=b.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`,v=new AbortController;u.current=v,c.current=Jt(async()=>{if(s.current||v.signal.aborted)return;s.current=!0;let e=y(1e4),n=AbortSignal.any([v.signal,e.signal]);try{let e=await _t(await fetch(_,{signal:n}));if(!a.current||v.signal.aborted)return;if(!e){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`}),e.status===`done`){if(x(),S(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(),g.current()}else(e.status===`error`||e.status===`expired`)&&(x(),S(),d.current=null,r({type:`set-flow-id`,flowId:null}),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:e.error??i(`codexAuth.loginFailed`)})))}catch(e){if(!a.current||v.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{e.clear(),s.current=!1}},2e3),l.current=setTimeout(()=>{c.current&&(S(),C(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},3e5)}b.error&&!b.url&&r({type:`set-error`,error:b.error})}catch(e){a.current&&!(e instanceof Error&&e.name===`AbortError`)&&r({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[e,C,S,r,t,x,i]);return(0,_.useEffect)(()=>{if(!t){m.current=null;return}m.current!==t&&(m.current=t,E())},[t,E]),{manualCodeBusy:v,manualCodeWaiting:b,bindCallbacks:w,closeModal:T,startOAuth:E,submitManualCode:(0,_.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(!(!t||!s||v||b)){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,b,i,n.manualCode])}}function Vi({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Z(),[a,o]=(0,_.useReducer)(Pi,r,Ni),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=Bi({apiBase:e,reauthAccountId:r,ui:a,dispatch:o,t:i});(0,_.useEffect)(()=>{d(n,t)},[d,n,t]),(0,_.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,_.useCallback)(e=>{e.preventDefault(),f()},[f]);return(0,J.jsx)(`dialog`,{ref:c,"aria-label":i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`),className:`modal-overlay`,onCancel:h,children:(0,J.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,J.jsx)(Fi,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{p(a.id)},onClose:f}),a.step===`oauth-waiting`&&(0,J.jsx)(zi,{reauthAccountId:r,authUrl:a.authUrl,manualCode:a.manualCode,manualCodeBusy:l,manualCodeWaiting:u,statusNotice:a.statusNotice,statusTone:a.statusTone,flowId:a.flowId,error:a.error,onManualCodeChange:e=>o({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{m()},onClose:f})]})})}var Hi=1e4;function Ui(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Wi(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Gi(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Ki(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function qi(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Ji(e,t,n){if(e<=0){let t=Gi(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Wi(t)??Gi(0,n)}}async function Yi(e,t,n=(e,t)=>fetch(e,t),r=Hi){if(!Number.isInteger(t)||t<0||t>100)return!1;try{return(await n(`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({threshold:t}),signal:AbortSignal.timeout(r)})).ok}catch{return!1}}var Xi=3e4,Zi=new Map;function Qi(e,t=!0){let n=Zi.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),[a,o]=(0,_.useState)(()=>n?.activeId??null),[s,c]=(0,_.useState)(()=>n==null?`loading`:`ready`),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(0),[v,b]=(0,_.useState)(()=>n!=null),[x,S]=(0,_.useState)(0),C=(0,_.useRef)(new Set),w=(0,_.useRef)(null),T=(0,_.useRef)(0),E=(0,_.useRef)(null),D=(0,_.useRef)(new Set),O=(0,_.useRef)(null),k=(0,_.useRef)(null),A=(0,_.useRef)(!!n?.accounts.length),j=(0,_.useRef)(n!=null),M=(0,_.useRef)(null),N=(0,_.useCallback)(e=>(D.current.add(e),()=>{D.current.delete(e)}),[]),P=(0,_.useCallback)(()=>qi(O.current?.value),[]),F=(0,_.useCallback)(()=>O.current?.value,[]),I=(0,_.useCallback)(async(t=!1)=>{let n=++T.current,r=y(2e4);g(e=>e+1);try{let a=[...D.current],s=new Map;for(let e of a)s.set(e,e.beginActiveRead());!t&&!j.current&&c(`loading`);let l=null,u,d=(async()=>{try{let a=await fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`,{signal:r.signal});if(!a.ok)throw Error(`account load failed`);let o=await a.json();return T.current===n&&(l=o.accounts??[],i(l),A.current=l.length>0,j.current=!0,c(`ready`)),!0}catch{return!1}})(),f=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`,{signal:r.signal});if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(T.current===n){let e=i.activeCodexAccountId??null,t=E.current;t&&e!==t.id||(E.current=null,u=e,o(e)),O.current={value:i};for(let e of a)e.acceptActiveRead(i,s.get(e))}return!0}catch{if(T.current===n)for(let e of a)e.rejectActiveRead();return!1}})(),[p,m]=await Promise.all([d,f]);if(T.current!==n)return!1;if(p){c(`ready`),j.current=!0;let t=Zi.get(e);return Zi.set(e,{accounts:l??t?.accounts??[],activeId:u===void 0?t?.activeId??null:u}),m}return j.current||c(`error`),!1}finally{r.clear(),g(e=>Math.max(0,e-1)),b(!0)}},[e]);(0,_.useEffect)(()=>{t&&w.current!==e&&(w.current=e,Promise.resolve().then(()=>{I()}))},[e,t,I]);let L=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!L||x>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{I(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,L,x,I]),(0,_.useEffect)(()=>{if(!(!t||x>0))return Jt(()=>{I()},Xi)},[t,I,x]);let R=(0,_.useCallback)(()=>{let e={};return C.current.add(e),S(C.current.size),e},[]),z=(0,_.useCallback)(e=>{C.current.delete(e)&&S(C.current.size)},[]),B=(0,_.useCallback)(async t=>{if(k.current)return{ok:!1,reason:`busy`};k.current=t??`__main__`,u(t??`__main__`);try{let n=await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t})});if(!n.ok)throw Error(`account switch failed`);let r=(await n.json().catch(()=>({}))).activeCodexAccountId??t;return E.current={id:r??null},o(r??null),I(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{k.current=null,u(null)}},[e,I]),V=(0,_.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 I(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,I]),H=(0,_.useCallback)(async(t,n)=>{if(M.current)return{ok:!1,reason:`busy`};M.current={accountId:t},f(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(()=>({})),s=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(s,`activeCodexAccountId`)){let e=s.activeCodexAccountId??null;E.current={id:e},o(e)}return I(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{M.current=null,f(null)}},[e,I]),U=(0,_.useCallback)(async()=>{if(M.current)return{ok:!1,reason:`busy`};M.current=`bulk`,m(!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;E.current={id:e},o(e)}return I(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{M.current=null,m(!1)}},[e,I]),W=(0,_.useCallback)(async t=>{try{return(await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(await I(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,I]),G=(0,_.useCallback)(async()=>await I()?{ok:!0}:{ok:!1,reason:`reload`},[I]),ee=a&&a!==`__main__`?r.find(e=>e.id===a):null,K=r.find(e=>e.isMain),q=ee??K,te=!q?.paused&&wi(q);return{accounts:r,activeId:a,loadState:s,refreshing:h>0,initialLoading:!v,switchingId:l,pauseUpdatingId:d,pausingExhausted:p,activeNeedsReauth:te,load:I,switchAccount:B,setAccountPaused:H,pauseExhaustedAccounts:U,saveAlias:V,removeAccount:W,syncAfterAccountAdded:G,pauseRefresh:R,resumeRefresh:z,subscribeLoadObserver:N,readLastThreshold:P,readLastActive:F}}function $i(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 ea({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,J.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,J.jsx)(xe,{width:10,height:10,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,J.jsx)(Se,{width:10,height:10,"aria-hidden":`true`})})]})}var ta={quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function na({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=Z(),m=(0,_.useRef)(!1),h=e>0,g=ta[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,J.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,J.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,J.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,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,J.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&&!v&&l()}},children:[a&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,J.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(ea,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s($i(t,1,1,100))},onDecrement:()=>{c(!0),s($i(t,-1,1,100))}})]})]}),(0,J.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,J.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:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,J.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,J.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var ra=[`quota`,`round-robin`,`fill-first`],ia=`quota`,aa=new Set(ra);function oa(e){return typeof e==`string`&&aa.has(e)?e:ia}function sa(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function ca(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function la(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};try{let r=await n(`${e}/api/codex-auth/pool-strategy`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t.strategy===void 0?{}:{strategy:t.strategy},...t.stickyLimit===void 0?{}:{stickyLimit:t.stickyLimit}})});if(!r.ok)return{ok:!1};let i=await r.json();return{ok:!0,strategy:oa(i.accountPoolStrategy??t.strategy),stickyLimit:sa(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var ua={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},da={quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function fa({strategy:e,stickyDraft:t,disabled:n=!1,strategySelectId:r=`account-pool-strategy`,stickyInputId:i=`account-pool-sticky-limit`,onStrategyChange:a,onStickyDraftChange:o,onStickyCommit:s}){let c=Z(),l=ra.map(e=>({value:e,label:c(ua[e])}));return(0,J.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(da[e])}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.unboundDefinition`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,J.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{id:i,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,disabled:n,"aria-label":c(`accountPool.stickyLimitAria`),onChange:e=>o(e.target.value),onBlur:()=>s(),onKeyDown:e=>{e.nativeEvent.isComposing||n||e.key===`Enter`&&(e.preventDefault(),s())}}),(0,J.jsx)(ea,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=$i(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=$i(t,-1,1,100);o(e),s(e)}})]})})]})]})}function pa(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:oa(t.accountPoolStrategy),stickyLimit:sa(t.accountPoolStickyLimit)}}function ma({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Z(),[a,o]=(0,_.useState)(ia),[s,c]=(0,_.useState)(1),[l,u]=(0,_.useState)(`1`),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(!1),y=(0,_.useRef)(0),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),w=(0,_.useCallback)(e=>{let t=oa(e.accountPoolStrategy),n=sa(e.accountPoolStickyLimit);o(t),r?.(t),c(n),u(String(n)),p.current=!0,f(!0),x(!1),C(null)},[r]),T=(0,_.useCallback)(e=>{let t=pa(e);t&&w({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[w]),E=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(g.current){v.current=!0;return}w(n)}catch{g.current||x(!0)}},[e,w]),D=(0,_.useCallback)(()=>{v.current&&(v.current=!1,queueMicrotask(()=>{if(g.current){v.current=!0;return}E()}))},[E]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>y.current,acceptActiveRead:(e,t)=>{if(t===y.current){if(g.current){v.current=!0;return}T(e)}},rejectActiveRead:()=>{p.current||x(!0)}});return!g.current&&n&&T(n()),e},[t,T,n]),(0,_.useEffect)(()=>{!n||t||g.current||T(n())},[n,T,t]),(0,_.useEffect)(()=>{t||E()},[E,t]);let O=(0,_.useCallback)(async t=>{if(g.current)return;let n=a,l=s;t.strategy!==void 0&&(o(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(c(t.stickyLimit),u(String(t.stickyLimit))),g.current=!0,h(!0),C(null),y.current+=1;let d=await la(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,J.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,J.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,J.jsx)(fa,{strategy:a,stickyDraft:l,disabled:k,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{k||e===a||O({strategy:e})},onStickyDraftChange:u,onStickyCommit:e=>{if(k)return;let t=ca(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function ha(e,t){let[n,r]=(0,_.useState)(80),[i,a]=(0,_.useState)(`80`),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(80),h=(0,_.useRef)(!1),g=(0,_.useRef)(80),v=(0,_.useRef)(!1),y=(0,_.useRef)(!1),b=(0,_.useRef)(!1),x=(0,_.useRef)(0),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useCallback)(e=>{m.current=e,h.current=!0,s(!0),r(e),e>0&&(g.current=e),a(String(e>0?e:g.current))},[]),T=(0,_.useCallback)(e=>{if(v.current||y.current){S.current=e;return}S.current=null,w(e)},[w]),E=(0,_.useCallback)(()=>{let e=S.current;return e===null?!1:(S.current=null,w(e),!0)},[w]),D=(0,_.useCallback)(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null),p(null)},[]),O=(0,_.useCallback)((e,t)=>{C.current!==null&&window.clearTimeout(C.current),p({tone:t?`err`:`ok`,message:e}),C.current=window.setTimeout(()=>{p(null),C.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{C.current!==null&&window.clearTimeout(C.current)},[]);let k=(0,_.useCallback)(()=>(h.current||l(!1),x.current),[]),A=(0,_.useCallback)((e,t)=>{l(!1);let n=qi(e),r=Ki(v.current,y.current,t,x.current);r===`defer`?S.current=Ui(n):r===`apply`&&T(Ui(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(Ui(qi(e))))},[w]),M=(0,_.useCallback)(()=>{h.current||l(!0)},[]),N=(0,_.useCallback)(async(n,r,i=!0)=>{if(y.current)return!1;y.current=!0,v.current=!1,D(),d(!0),x.current+=1;try{let a=await Yi(e,n);return x.current+=1,a?(S.current=null,w(n),i&&O(t.updated,!1)):(E()||w(r),O(t.updateFailed,!0)),a}finally{y.current=!1,d(!1)}},[e,w,D,t.updateFailed,t.updated,E,O]),P=(0,_.useCallback)(()=>{v.current=!1;let e=m.current;E()||a(String(e>0?e:g.current)),O(t.invalid,!0)},[t.invalid,E,O]),F=(0,_.useCallback)(()=>{v.current=!1,b.current=!0,D();let e=m.current;E()||a(String(e>0?e:g.current))},[D,E]),I=(0,_.useCallback)(async()=>{if(b.current)return b.current=!1,!0;if(!h.current||y.current)return!1;let e=m.current;v.current=!1;let t=Wi(i);return t===null?(P(),!1):t===e?(E()||a(String(t)),!0):N(t,e)},[i,E,P,N]),L=(0,_.useCallback)(async()=>{if(!h.current||y.current)return!1;let e=m.current;v.current=!1;let t=Ji(e,i,g.current),n=await N(t.threshold,e);return n?(g.current=t.lastEnabled,t.threshold===0&&a(String(t.lastEnabled)),n):!1},[i,N]);return{threshold:n,draft:i,hydrated:o,saving:u,loadError:c,feedback:f,beginServerRead:k,acceptServerRead:A,hydrateServerValue:j,rejectServerRead:M,setDraft:(0,_.useCallback)(e=>{h.current&&(v.current=!0,b.current=!1,D(),a(e))},[D]),setEditing:(0,_.useCallback)(e=>{v.current=e},[]),commit:I,cancel:F,toggle:L,retry:(0,_.useCallback)(()=>{l(!1),D()},[D])}}var ga=new Map;function _a(e,t){return`${e??``}\0${JSON.stringify(t)}`}function va(e,t){let n=_a(e,t??{}),r=ga.get(n);return r||(r=new Intl.NumberFormat(e,t),ga.set(n,r)),r}var ya={month:`short`,day:`numeric`,year:`numeric`},ba={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},xa=new Map;function Sa(e,t){let n=_a(e,t),r=xa.get(n);return r||(r=new Intl.DateTimeFormat(e,t),xa.set(n,r)),r}function Ca(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Sa(t,ya).format(n)}function wa(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Sa(t,ba).format(n)}function Ta(e,t){return!Number.isFinite(e)||e<0?`—`:`~${va(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function Ea(e,t){return Ca(e,t)}function Da(e,t){return wa(e,t)}function Oa(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function ka({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=Oa(n),s=o<=7;return(0,J.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,J.jsxs)(`div`,{className:`credit-item-head`,children:[(0,J.jsx)(Ae,{width:13}),(0,J.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,J.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,J.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,J.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:Ea(t,i)})}),(0,J.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:Da(n,i),days:String(o)})})]})]})}function Aa({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Ae,{width:12}),`0`]}):r===void 0?null:(0,J.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,J.jsx)(Ae,{width:12}),r]})}function ja({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;return(0,J.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${Math.max(r.length,i.length,a.length)}ch`},children:o})}function Ma({pool:e,activeId:t,accountModeState:n,switchActionLabel:r,threshold:i,onOpenReset:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onReauth:u,onEditAlias:d,onRemove:f,onCopyDoctor:p,doctorCopyOutcomeFor:m}){let h=Z(),g=e=>!e.paused&&t===e.id;return(0,J.jsx)(J.Fragment,{children:e.map(e=>{let t=e.health?.status,_=!!e.needsReauth||Ci(t),v=Ti(t),y=Oi(h,e.health),b=ki(h,`codex`,e.id,e.health);return(0,J.jsxs)(`div`,{className:`card ${g(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${_?`dot-amber`:g(e)?`dot-blue`:`dot-muted`}`}),(0,J.jsx)(`strong`,{children:e.alias??e.email}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:h(`codexAuth.pausedHint`),children:h(`codexAuth.paused`)}),(0,J.jsx)(Aa,{t:h,account:e,onClick:()=>a(e)}),y&&(0,J.jsx)(`span`,{className:Si(t),children:y}),_&&!y&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:h(`codexAuth.needsReauth`)}),g(e)&&!_&&!v&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:h(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!g(e)&&!_&&!v&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),_&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>u(e.id),children:h(`codexAuth.reauthenticate`)}),p&&Ei(t)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>p(e.id),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Mi(h,m?.(e.id))})}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?h(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${h(`codexAuth.resume`)}. ${h(`codexAuth.pausedHint`)}`:h(`codexAuth.pause`),children:[e.paused?(0,J.jsx)(ge,{width:14}):(0,J.jsx)(he,{width:14}),(0,J.jsx)(ja,{t:h,paused:e.paused,saving:c===e.id})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void d(e),children:h(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger card-right`,"aria-label":`${h(`common.remove`)} — ${e.email}`,title:`${h(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),f(e.id)},children:(0,J.jsx)(fe,{width:14})})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,h(`prov.accountId`),`: `,bi(e.id)]}),b&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:b}),v&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:h(`pws.healthCooldownHint`)}),_?(0,J.jsx)(`div`,{className:`card-sub faint`,children:h(`codexAuth.tokenExpired`)}):!v&&(0,J.jsx)($r,{quota:e.quota,plan:e.plan,threshold:i,t:h,pending:e.quota==null})]},e.id)})})}function Na({onReauth:e}){let t=Z();return(0,J.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(ve,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function Pa({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,onCancel:i,onConfirm:a}){let o=Z(),s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?o(`codexAuth.preparePoolTitle`):e.id===`__main__`?o(`codexAuth.switchBack`):o(`codexAuth.switchTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?o(`codexAuth.preparePoolDesc`):e.id===`__main__`?o(`codexAuth.switchBackDesc`):o(`codexAuth.switchDesc`)}),(0,J.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,J.jsx)(`strong`,{children:e.id===`__main__`?t||o(`codexAuth.codexApp`):e.email}),e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,J.jsxs)(`div`,{className:`notice-warn`,children:[(0,J.jsx)(ve,{width:14}),` `,o(`codexAuth.cacheWarning`)]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`codexAuth.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r,onClick:a,children:o(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function Fa({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=X(),d=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,J.jsx)(`div`,{className:`confirm-icon`,children:(0,J.jsx)(ve,{width:22})}),(0,J.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:Ea(n[0].granted_at,l)})}),(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,J.jsx)(Ae,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,J.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,J.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,J.jsx)(ka,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,J.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function Ia({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onOpenReset:u,onCopyDoctor:d,doctorCopyOutcomeFor:f}){let p=e(`codexAuth.codexApp`),m=t?.id??`__main__`,h={id:`__main__`,email:t?.email||p,plan:t?.plan,isMain:!0,paused:t?.paused??!1,hasCredential:!0,quota:t?.quota??null},g=!!t?.needsReauth||Ci(t?.health?.status),_=Ti(t?.health?.status),v=Oi(e,t?.health),y=t?ki(e,`codex`,m,t.health):null;return(0,J.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${g?`dot-amber`:`dot-green`}`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,J.jsx)(Aa,{t:e,account:{...t,id:`__main__`},onClick:()=>u({...t,id:`__main__`})}),t?.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),v&&(0,J.jsx)(`span`,{className:Si(t?.health?.status),children:v}),g&&!v&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,J.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&!n&&!g&&!_&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(h),children:a}),d&&Ei(t?.health?.status)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>d(m),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Mi(e,f?.(m))})}),t&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(h),disabled:l,title:t.paused?e(`codexAuth.pausedHint`):void 0,"aria-label":t.paused?`${e(`codexAuth.resume`)}. ${e(`codexAuth.pausedHint`)}`:e(`codexAuth.pause`),children:[t.paused?(0,J.jsx)(ge,{width:14}):(0,J.jsx)(he,{width:14}),(0,J.jsx)(ja,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(ke,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),y&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:y}),_&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),g?(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!_&&(0,J.jsx)($r,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function La({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,J.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,J.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,J.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,J.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,J.jsx)(he,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,J.jsx)(me,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function Ra({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,J.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,J.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot dot-muted`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Ae,{width:12}),`0`]}),(0,J.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(he,{width:14}),` `,e(`codexAuth.pause`)]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(ke,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,J.jsx)($r,{quota:null,threshold:0,t:e,pending:!0})]}),(0,J.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(pe,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,J.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,J.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,J.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function za(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Ba(e,t,n,r){try{let i=await _t(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:za(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`)}}}var Va=`ocx doctor`;function Ha({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a}){let o=Z(),s=ha(e,{updated:o(`codexAuth.autoSwitchUpdated`),updateFailed:o(`codexAuth.autoSwitchUpdateFailed`),invalid:o(`codexAuth.autoSwitchThresholdInvalid`)}),[c,l]=(0,_.useState)(null),{beginServerRead:u,acceptServerRead:d,rejectServerRead:f,hydrateServerValue:p}=s,m=Qi(e,!a),h=a??m,{accounts:g,activeId:v,loadState:y,switchingId:b,pauseUpdatingId:x,pausingExhausted:S,load:C}=h,[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(null),P=(0,_.useRef)(null),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(null),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(null),[G,ee]=(0,_.useState)(!1),K=Li(),q=(0,_.useCallback)((e,t=!1)=>{P.current&&clearTimeout(P.current),j(e),N(t?`err`:`ok`),P.current=setTimeout(()=>{j(null),N(null),P.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{P.current&&clearTimeout(P.current)},[]);let te=(0,_.useCallback)(e=>{K.copy(Va,e)},[K]),{subscribeLoadObserver:Y,readLastThreshold:ne}=h;(0,_.useEffect)(()=>Y({beginActiveRead:u,acceptActiveRead:d,rejectActiveRead:f}),[Y,u,d,f]),(0,_.useEffect)(()=>{let e=ne();e!==void 0&&p(e)},[ne,p]),(0,_.useEffect)(()=>{if(!E)return;let e=h.pauseRefresh();return()=>h.resumeRefresh(e)},[h,E]);let re=v&&v!==`__main__`?g.find(e=>e.id===v):null,ie=!re?.paused&&wi(re);(0,_.useEffect)(()=>{i?.(ie)},[ie,i]);let ae=(0,_.useCallback)(e=>{k(e),D(!0)},[]),oe=(0,_.useCallback)(()=>{D(!1),k(null)},[]),se=(0,_.useCallback)(()=>{h.syncAfterAccountAdded(),q(o(`codexAuth.accountAdded`)),oe()},[oe,h,q,o]),ce=async e=>{let n=await h.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;q(o(`codexAuth.switchFailed`),!0);return}T(null);let r=n.activeId,i=r&&r!==`__main__`?g.find(e=>e.id===r)?.email??o(`pws.accountOrdinal`,{count:`1`}):o(`codexAuth.mainAccount`);q(o(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},le=async e=>{let t=window.prompt(o(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await h.saveAlias(e.id,t);q(o(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),!n.ok)},ue=async e=>{let t=!e.paused,n=await h.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(T(t=>t?.id===e.id?null:t),q(o(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),!n.ok))},de=async e=>{let t=g.find(t=>t.id===e)?.email??o(`pws.accountOrdinal`,{count:`1`});window.confirm(o(`codexAuth.removeConfirm`,{id:t}))&&((await h.removeAccount(e)).ok||q(o(`codexAuth.removeFailed`),!0))},fe=async()=>{I(!0);try{let e=await C(!0);q(o(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),!e)}finally{I(!1)}},me=async()=>{let e=await h.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||q(e.ok?e.pausedCount>0?o(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):o(`codexAuth.pauseExhaustedNone`):o(`codexAuth.pauseExhaustedFailed`),!e.ok)},he=async t=>{R(t),B(!1),W(null),ee(!0);try{let n=await _t(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));n&&W((n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime()))}catch{}finally{ee(!1)}},ge=async t=>{H(!0);try{let n=await Ba(e,t,o,C);n.close&&(R(null),B(!1)),n.toast&&q(n.toast,!n.ok)}finally{H(!1)}},_e=g.find(e=>e.isMain),ve=g.filter(e=>!e.isMain),ye=!_e?.paused&&(!v||v===`__main__`),be=o(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),xe=x!==null||S,Se=s.threshold??0;return(0,J.jsxs)(`div`,{children:[(0,J.jsx)(La,{t:o,embedded:r,refreshingQuota:F,actionFeedback:A,actionFeedbackTone:M,pausingExhausted:S,pauseBusy:xe,onRefresh:()=>{fe()},onPauseExhausted:()=>{me()}}),n,(0,J.jsx)(Ra,{t:o,loadState:y,accountsCount:g.length,onRetry:()=>{C()}}),!(y===`loading`&&g.length===0)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Ia,{t:o,main:_e,isMainActive:ye,accountModeState:t,threshold:Se,switchActionLabel:be,onSwitch:T,onTogglePause:ue,pauseUpdatingId:x,pauseBusy:xe,onOpenReset:he,onCopyDoctor:te,doctorCopyOutcomeFor:K.outcomeFor}),(0,J.jsxs)(`div`,{className:`section-sep`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:o(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>D(!0),children:[(0,J.jsx)(pe,{width:14}),` `,o(`codexAuth.add`)]})]}),ie&&re&&(0,J.jsx)(Na,{onReauth:()=>ae(re.id)}),ve.length===0&&(0,J.jsx)(pt,{title:o(`codexAuth.noPool`)}),(0,J.jsx)(Ma,{pool:ve,activeId:v,accountModeState:t,switchActionLabel:be,threshold:Se,onOpenReset:he,onSwitch:T,onTogglePause:ue,pauseUpdatingId:x,pauseBusy:xe,onReauth:ae,onEditAlias:le,onRemove:de,onCopyDoctor:te,doctorCopyOutcomeFor:K.outcomeFor})]}),c!==null&&(0,J.jsx)(na,{threshold:s.threshold,draft:s.draft,strategy:c,hydrated:s.hydrated,saving:s.saving,loadError:s.loadError,feedback:s.feedback,onDraftChange:s.setDraft,onEditingChange:s.setEditing,onCommit:s.commit,onCancel:s.cancel,onToggle:s.toggle,onRetry:()=>{s.retry(),C()}}),(0,J.jsx)(ma,{apiBase:e,subscribeLoadObserver:h.subscribeLoadObserver,readLastActive:h.readLastActive,onStrategyResolved:l}),w&&(0,J.jsx)(Pa,{confirm:w,mainEmail:_e?.email,accountModeState:t,switchingId:b,onCancel:()=>T(null),onConfirm:()=>{ce(w.id===`__main__`?`__main__`:w.id)}}),L&&(0,J.jsx)(Fa,{resetPopup:L,resetConfirm:z,creditDetails:U,creditDetailsLoading:G,redeeming:V,onClose:()=>{R(null),B(!1),W(null)},onShowConfirm:()=>B(!0),onCancelConfirm:()=>B(!1),onRedeem:()=>{ge(L.id)}}),E&&(0,J.jsx)(Vi,{apiBase:e,reauthAccountId:O??void 0,onClose:oe,onAdded:se})]})}function Ua({apiBase:e,accountCount:t}){let n=Z(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(`80`),[s,c]=(0,_.useState)(`1`),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let t=!1,n=new AbortController;return Promise.resolve().then(()=>fetch(`${e}/api/oauth/accounts/pool?provider=anthropic`,{signal:n.signal})).then(e=>{if(!e.ok)throw Error(`load`);return e.json()}).then(e=>{if(t)return;let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=sa(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:oa(e.strategy),stickyLimit:r}),o(String(n)),c(String(r)),m(!1)}).catch(()=>{t||n.signal.aborted||m(!0)}),()=>{t=!0,n.abort()}},[e]);let h=(0,_.useCallback)(async t=>{let a=r;i({enabled:t.enabled,threshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit}),u(!0),f(null);try{let n=await fetch(`${e}/api/oauth/accounts/pool`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:`anthropic`,enabled:t.enabled,autoSwitchThreshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit})});if(!n.ok)throw Error(`save`);let r=await n.json().catch(()=>null),a=oa(r?.strategy??t.strategy),s=sa(r?.stickyLimit??t.stickyLimit);i({enabled:t.enabled,threshold:t.threshold,strategy:a,stickyLimit:s}),o(String(t.threshold)),c(String(s))}catch{f(n(`anthropicPool.saveFailed`)),a&&(i(a),o(String(a.threshold)),c(String(a.stickyLimit)))}finally{u(!1)}},[e,r,n]),g=r?.enabled===!0,v=r?.threshold??80,y=r?.strategy??`quota`,b=r?.stickyLimit??1,x=r===null&&!p,S=x||l||p||!g&&t<2;return(0,J.jsxs)(`div`,{className:`card`,style:{marginTop:12},"aria-busy":x||l,children:[(0,J.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,J.jsxs)(`div`,{style:{flex:1},children:[(0,J.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:p?n(`anthropicPool.loadFailed`):x?n(`common.loading`):g?n(`anthropicPool.enabledDesc`,{threshold:v}):n(`anthropicPool.disabledDesc`)})]}),(0,J.jsxs)(`label`,{className:`toggle`,style:{display:`inline-flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:g,disabled:S,onChange:e=>{let t=e.target.checked;h({enabled:t,threshold:v,strategy:y,stickyLimit:b})}}),(0,J.jsx)(`span`,{children:n(g?`anthropicPool.on`:`anthropicPool.off`)})]})]}),(0,J.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:10,padding:`8px 10px`,border:`1px solid var(--border, #c9a227)`,borderRadius:6,background:`color-mix(in srgb, var(--warn, #c9a227) 12%, transparent)`},children:n(`anthropicPool.experimentalWarning`)}),t<2&&(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`field`,style:{display:`block`,marginTop:12},children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:a,disabled:l,"aria-label":n(`anthropicPool.thresholdAria`),onChange:e=>o(e.target.value),onBlur:()=>{let e=Number(a);if(!Number.isInteger(e)||e<0||e>100){o(String(v)),f(n(`anthropicPool.thresholdInvalid`));return}e!==v&&h({enabled:!0,threshold:e,strategy:y,stickyLimit:b})}}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,J.jsx)(fa,{strategy:y,stickyDraft:s,disabled:l,strategySelectId:`anthropic-pool-strategy`,stickyInputId:`anthropic-pool-sticky-limit`,onStrategyChange:e=>{e!==y&&h({enabled:!0,threshold:v,strategy:e,stickyLimit:b})},onStickyDraftChange:c,onStickyCommit:e=>{let t=ca(e??s);if(t===null){c(String(b)),f(n(`accountPool.stickyLimitInvalid`));return}if(t===b){c(String(t));return}h({enabled:!0,threshold:v,strategy:y,stickyLimit:t})}})]}),d&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}var Wa=`ocx doctor`,Ga=4e3,Ka=[],qa=[];function Ja({item:e,apiBase:t,oauth:n,accounts:r=Ka,keys:i=qa,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d}){let f=Z(),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(!1),S=Li(),C=Li();(0,_.useEffect)(()=>{if(r.length===0){x(!1);return}if(!r.some(e=>e.quota==null&&!e.quotaUnavailable)){x(!1);return}x(!0);let e=window.setTimeout(()=>x(!1),Ga);return()=>window.clearTimeout(e)},[r]);let w=pi({...e,hasApiKey:e.hasApiKey||i.length>0}),T=w===`oauth-accounts`,E=w===`api-keys`;if(w===`codex-accounts`)return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(`pws.availableAccounts`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:f(`pws.availableAccounts`)}),(0,J.jsx)(`div`,{className:`pwi-auth-body`,children:(0,J.jsx)(Ha,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!w||!l)return null;let D=c?.provider===e.name?c:null,O=D?.deviceCode??``,k=S.outcomeFor(O),A=f(k===`copied`?`prov.codeCopied`:k===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),j=r.length>0||n?.loggedIn===!0,M=r.find(e=>e.active&&e.needsReauth),N=!!M,P=async()=>{let t=h.trim();if(t){y(!0);try{await l.onAddApiKey(e.name,t)&&(g(``),m(!1))}finally{y(!1)}}};return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(T?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:f(T?`pws.availableAccounts`:`pws.apiKeys`)}),(0,J.jsxs)(`div`,{className:`pwi-auth-body`,children:[T&&(0,J.jsxs)(J.Fragment,{children:[e.name===`anthropic`&&(0,J.jsx)(Ua,{apiBase:t,accountCount:r.length}),(0,J.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${N?`pwi-auth-dot--warn`:j?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`pwi-auth-status-text`,children:j?r.length>0?f(`pws.loggedInTitle`):n?.email??f(`pws.loggedInTitle`):n?.error||f(`pws.notLoggedInTitle`)}),(0,J.jsxs)(`span`,{className:`pwi-auth-actions`,children:[M&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,M.id),children:f(`pws.reauthenticate`)}),j?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:f(`prov.logout`)}):(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,J.jsx)(ke,{style:{width:13,height:13},"aria-hidden":`true`}),f(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),s&&D&&(0,J.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,J.jsx)(`div`,{className:`pwi-auth-wait-title`,children:f(`prov.waitingBrowser`)}),D.deviceCode&&(0,J.jsxs)(`div`,{className:`pwi-device-code-wrap`,children:[(0,J.jsx)(`span`,{children:f(`prov.deviceCode`)}),(0,J.jsx)(`code`,{className:`pwi-device-code`,children:D.deviceCode}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>S.copy(O,O),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:A})})]}),(0,J.jsx)(Ri,{url:D.url??``}),l.onCancelLogin&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onCancelLogin?.(e.name),children:f(`common.cancel`)})]})]}),a===`loading`&&r.length===0&&(0,J.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),f(`pws.accountsLoading`)]}),a===`error`&&(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:f(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:f(`pws.retryAccounts`)})]}),r.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=mi(r,t,f),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||Ci(a),u=Ei(a),d=Ti(a),p=bi(t.id),m=Oi(f,t.health),h=ki(f,e.name,t.id,t.health);return(0,J.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,J.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!d&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${f(`pws.accountCurrent`)}`:``}`,disabled:!!(c||d||o&&!i),children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${c?`pwi-auth-dot--warn`:t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${f(`prov.accountId`)}: ${p}`].filter(Boolean).join(` · `)}),h&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:h}),d&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:f(`pws.healthCooldownHint`)})]}),m&&(0,J.jsx)(`span`,{className:Si(a),children:m}),c&&!m&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:f(`pws.reauth`)}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)}),i&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:f(`pws.accountSwitching`)})]}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s||!!o,onClick:()=>void l.onReauth(e.name,t.id),children:f(`pws.reauthenticate`)}),u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{C.copy(Wa,t.id)},children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Mi(f,C.outcomeFor(t.id))})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`oauth`,t.id,t.alias),children:f(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${f(`common.remove`)} — ${n}`,title:`${f(`common.remove`)} — ${n}`,disabled:!!o,onClick:()=>void l.onRemoveAccount(e.name,t),children:(0,J.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||b&&t.quota==null)&&(0,J.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,J.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:f(`pws.accountQuotaUnavailable`)}):(0,J.jsx)($r,{quota:t.quota??null,plan:null,threshold:80,t:f,layout:`stacked`,pending:t.quota==null})})]},t.id)})}),a===`ready`&&j&&r.length===0&&(0,J.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:f(`pws.noAccounts`)}),j&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>void l.onLogin(e.name,!0),disabled:s||!!o,children:f(`pws.addAccount`)})]}),E&&(0,J.jsxs)(J.Fragment,{children:[i.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,J.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,J.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,f(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`api-key`,t.id,t.label),children:f(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${f(`common.remove`)} — ${t.label??t.masked}`,title:`${f(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void l.onRemoveApiKey(e.name,t),children:(0,J.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),p?(0,J.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,J.jsx)(`input`,{className:`input`,type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:v}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void P(),disabled:v||!h.trim(),children:f(v?`pws.saving`:`pws.addKey`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m(!1),g(``)},children:f(`common.cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>m(!0),children:f(`pws.addKey`)})]})]})]})}function Ya(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 Xa(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 Za(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Qa=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],$a=[];function $({item:e,availableModels:t=$a,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Z(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),[c,l]=(0,_.useState)(e.adapter),[u,d]=(0,_.useState)(e.baseUrl),[f,p]=(0,_.useState)(e.defaultModel??``),[m,h]=(0,_.useState)(s),[g,v]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[y,b]=(0,_.useState)(e.note??``),[x,S]=(0,_.useState)(e.allowPrivateNetwork??!1),[C,w]=(0,_.useState)(e.liveModels!==!1),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(),[j,M]=(0,_.useState)(n?`loading`:`idle`),[N,P]=(0,_.useState)(()=>`custom`);(0,_.useEffect)(()=>{l(e.adapter),d(e.baseUrl),p(e.defaultModel??``),h(String(e.authMode??(e.keyOptional?`local`:`key`))),v(e.apiKeyTransport??`x-api-key`),b(e.note??``),S(e.allowPrivateNetwork??!1),w(e.liveModels!==!1),O(null),queueMicrotask(()=>P(Xa(k,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,e.liveModels,k]),(0,_.useEffect)(()=>{if(!n)return;let t=!1,r=e.name,i=e.baseUrl;return fetch(`${n}/api/provider-presets`).then(e=>_t(e)).then(e=>{if(t)return;if(!e){A(void 0),M(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;A(n),M(`ready`),P(Xa(n,i))}).catch(()=>{t||(A(void 0),M(`error`))}),()=>{t=!0}},[n,e.name]);let F=c.trim()!==e.adapter||u.trim()!==e.baseUrl||f.trim()!==(e.defaultModel??``)||m!==String(e.authMode??(e.keyOptional?`local`:`key`))||c.trim()===`anthropic`&&m===`key`&&g!==(e.apiKeyTransport??`x-api-key`)||y.trim()!==(e.note??``)||x!==(e.allowPrivateNetwork??!1)||C!==(e.liveModels!==!1);(0,_.useEffect)(()=>(i?.(F),()=>i?.(!1)),[F,i]);let I=(0,_.useMemo)(()=>{let n=new Set(t);return f.trim()&&n.add(f.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,f,e.defaultModel]),L=(0,_.useMemo)(()=>{let e=[...Qa];return c&&!e.includes(c)&&e.unshift(c),e},[c]),R=jr(e.name),z=j===`ready`&&!!(k&&k.length>0),B=c.trim()===`anthropic`&&m===`key`,V=R&&j!==`error`,H=async()=>{if(!r)return O({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;let t=z?Za(k,N,u):u.trim();if(!c.trim()||!t)return O({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;E(!0),O(null);try{let n={adapter:c.trim(),baseUrl:t,defaultModel:f.trim(),authMode:m,note:y.trim(),allowPrivateNetwork:x};C!==(e.liveModels!==!1)&&(n.liveModels=C),B?n.apiKeyTransport=g:e.apiKeyTransport!==void 0&&(n.apiKeyTransport=``);let i=await r(e.name,n);return O(i.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:i.error||o(`prov.saveFailed`)}),i.ok}finally{E(!1)}},U=(0,_.useRef)(H);(0,_.useEffect)(()=>{U.current=H}),(0,_.useEffect)(()=>{if(a)return a(()=>U.current()),()=>a(null)},[a]);let W=()=>{l(e.adapter),d(e.baseUrl),p(e.defaultModel??``),h(s),v(e.apiKeyTransport??`x-api-key`),b(e.note??``),S(e.allowPrivateNetwork??!1),w(e.liveModels!==!1),O(null),P(Xa(k,e.baseUrl))},G=(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,J.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,J.jsx)(ke,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,J.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),R?(0,J.jsx)(`input`,{className:`input`,value:c,readOnly:!0,disabled:!0}):(0,J.jsx)(`select`,{className:`input`,value:c,onChange:e=>l(e.target.value),children:L.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})]}),z?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,J.jsx)(`select`,{className:`input`,value:N,onChange:e=>{let t=e.target.value;P(t),d(Ya(k,t,u))},children:k.map(e=>(0,J.jsx)(`option`,{value:e.id,children:G(e.id,e.label)},e.id))})]}),N===`custom`&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),readOnly:V,disabled:V})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),I.length>0?(0,J.jsxs)(`select`,{className:`input`,value:f,onChange:e=>p(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),I.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}):(0,J.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),R?(0,J.jsx)(`input`,{className:`input`,value:Nr(e,o),readOnly:!0,disabled:!0}):(0,J.jsxs)(`select`,{className:`input`,value:m,onChange:e=>h(e.target.value),children:[(0,J.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,J.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,J.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,J.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),B&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,J.jsxs)(`select`,{className:`input`,value:g,onChange:e=>v(e.target.value),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,J.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:y,onChange:e=>b(e.target.value),rows:2})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,J.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),F&&(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,J.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:W,disabled:T,children:o(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void H(),disabled:T,children:o(T?`pws.saving`:`pws.saveSettings`)})]})]}),D&&(0,J.jsx)(`div`,{className:D.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:D.text})]})}function eo({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Z();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,J.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function to({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Z();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,J.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function no({item:e,usageTotals:t,modelUsage:n,quotaReport:r,availableModels:i,hasLiveModels:a,selectedModels:o,modelsLoading:s,modelsLoadFailed:c,onRetryModels:l,oauthEmail:u,onDeselect:d,apiBase:f,oauth:p,accounts:m,accountLoadState:h,switchingAccountId:g,keys:v,busyProvider:y,loginHint:b,authHandlers:x,onCodexActiveNeedsReauthChange:S,codexController:C,onUpdateProvider:w,isDefault:T,onRemoveProvider:E,onSetDisabled:D,onSetDefault:O}){let k=Z(),[A,j]=(0,_.useState)(`overview`),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)(!1),R=(0,_.useRef)(null),z=(0,_.useCallback)(e=>{R.current=e},[]),B=e.disabled===!0,V=(0,_.useMemo)(()=>tr(e),[e]),H=(0,_.useMemo)(()=>cr(e),[e]),U=(0,_.useMemo)(()=>pi(e),[e]),W=JSON.stringify([C?.activeId??``,m?.find(e=>e.active)?.id??``,v?.find(e=>e.active)?.id??``,p?.loggedIn===void 0?``:String(p.loggedIn),p?.needsReauth===void 0?``:String(p.needsReauth),u??``]),G=(0,_.useMemo)(()=>[{id:`overview`,label:k(`pws.tab.overview`)},{id:`models`,label:k(`pws.tab.models`)},{id:`usage`,label:k(`pws.tab.usage`)},...U?[{id:`accounts`,label:k(U===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:k(`pws.tab.settings`)}],[U,k]),ee=(0,_.useCallback)(e=>{if(M&&A===`settings`&&e!==`settings`){F(e);return}j(e)},[A,M]),K=(0,_.useCallback)(()=>{if(M&&A===`settings`){F(`deselect`);return}d()},[M,A,d]),q=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%G.length;else if(e.key===`ArrowLeft`)n=(t-1+G.length)%G.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=G.length-1;else return;e.preventDefault(),ee(G[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ee,G]),te=`pws-tab-${A}`,Y=`pws-panel-${A}`;return(0,J.jsxs)(`div`,{className:`pws-detail`,children:[(0,J.jsx)(`div`,{className:`pws-detail-head`,children:(0,J.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:K,children:[(0,J.jsx)(we,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),k(`pws.allProviders`)]})}),(0,J.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,J.jsx)(Fr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,J.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,J.jsxs)(`h2`,{className:`pws-detail-title`,children:[Ar(e.name,k),H&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:k(`modal.badge.local`)}),!H&&V&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:k(`modal.badge.free`)})]})}),(0,J.jsxs)(`div`,{className:`pws-detail-actions`,children:[!T&&!B&&O&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>O(e.name),children:k(`prov.setDefault`)}),E&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>E(e.name),"aria-label":k(`pws.removeConfirmTitle`),title:k(`pws.removeConfirmTitle`),children:(0,J.jsx)(_e,{style:{width:15,height:15},"aria-hidden":`true`})}),D&&(0,J.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,J.jsx)(`span`,{className:`pws-detail-toggle-label`,children:k(`pws.enabledLabel`)}),(0,J.jsx)(ut,{on:!B,onClick:()=>D(e.name,!B),disabled:T,label:k(`pws.enabledLabel`)})]})]})]}),(0,J.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:G.map((e,t)=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":A===e.id,tabIndex:A===e.id?0:-1,className:`pws-detail-tab${A===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ee(e.id),onKeyDown:e=>q(e,t),children:e.label},e.id))}),(0,J.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:Y,"aria-labelledby":te,tabIndex:0,children:[A===`overview`&&(0,J.jsx)(hi,{accountPanel:U?(0,J.jsx)(Ja,{item:e,apiBase:f,oauth:p,accounts:m,keys:v,accountLoadState:h,switchingAccountId:g,busy:y===e.name,loginHint:b,authHandlers:x,onCodexActiveNeedsReauthChange:S,codexController:C}):void 0,item:e,apiBase:f,connectionIdentity:W,usageTotals:t,quotaReport:r,oauthEmail:u,onEditSettings:()=>ee(`settings`),onViewUsage:()=>ee(`usage`),onUpdateProvider:w,reauthBusy:y===e.name,onCancelLogin:x?.onCancelLogin?()=>void x.onCancelLogin?.(e.name):void 0,onReauthenticate:e.activeNeedsReauth?()=>{if(e.authMode===`oauth`){let t=m??[],n=t.find(e=>e.active&&e.needsReauth)??t.find(e=>e.needsReauth);x?.onReauth(e.name,n?.id);return}ee(`accounts`)}:void 0}),A===`models`&&(0,J.jsx)(_i,{item:e,apiBase:f,availableModels:i,hasLiveModels:a,selectedModels:o,modelsLoading:s,modelsLoadFailed:c,needsReauth:(m??[]).some(e=>e.active&&e.needsReauth)||p?.needsReauth===!0,onRetryModels:l,onOpenAccounts:U?()=>ee(`accounts`):void 0},e.name),A===`usage`&&(0,J.jsx)(vi,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),A===`accounts`&&(0,J.jsx)(Ja,{item:e,apiBase:f,oauth:p,accounts:m,keys:v,accountLoadState:h,switchingAccountId:g,busy:y===e.name,loginHint:b,authHandlers:x,onCodexActiveNeedsReauthChange:S,codexController:C}),A===`settings`&&(0,J.jsx)($,{item:e,apiBase:f,availableModels:i,onUpdateProvider:w,onDirtyChange:N,onRegisterSave:z},e.name)]}),P&&(0,J.jsx)(to,{saving:I,onCancel:()=>{I||F(null)},onDiscard:()=>{if(I)return;let e=P;F(null),N(!1),e===`deselect`?d():j(e)},onSave:()=>{(async()=>{if(!I){L(!0);try{if(!(await R.current?.()??!1))return;let e=P;F(null),N(!1),e===`deselect`?d():e&&j(e)}finally{L(!1)}}})()}})]})}var ro=`https://chatgpt.com/backend-api/codex`;function io(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 ao(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 oo(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||io(e.baseUrl)!==ro?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function so(e){return e.id===`openai`}function co(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function lo(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),t}function uo(e,t){return so(e)?fo(e):{name:t.name.trim(),provider:lo(t)}}function fo(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var po=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function mo(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 po(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new po(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new po(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(fo(i))})).ok)throw new po(`codexAuth.enableOpenaiFailed`)}var ho=new Set([`anthropic`,`google-antigravity`]),go=new Set([`github-copilot`,`cursor`]);function _o(e){let t=e.trim().toLowerCase();return ho.has(t)?`high`:go.has(t)?`elevated`:null}function vo(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function yo(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function bo(e,t=!1){let n={};for(let[t,r]of Object.entries(e))wi(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function xo(e){let{apiBase:t,t:n,config:r,aliveRef:i,notify:a,fetchConfig:o,fetchOauth:s,fetchProviderQuotas:c,codexActiveNeedsReauth:l}=e,[u,d]=(0,_.useState)({}),[f,p]=(0,_.useState)({}),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)({}),[y,b]=(0,_.useState)({}),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(``),T=(0,_.useRef)({}),E=(0,_.useRef)(null),D=(0,_.useRef)(null),O=(0,_.useRef)(null),k=(0,_.useCallback)(async e=>{let n=[...new Set(e)];return p(e=>{let t={...e};for(let e of n)t[e]=`loading`;return t}),(await Promise.all(n.map(async e=>{let n=(T.current[e]??0)+1;T.current[e]=n;try{let r=await fetch(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`);if(!r.ok)throw Error(String(r.status));let a=await r.json();return!i.current||T.current[e]!==n?!0:(d(t=>({...t,[e]:{activeAccountId:a.activeAccountId??null,accounts:a.accounts??[]}})),p(t=>({...t,[e]:`ready`})),(async()=>{try{let r=await fetch(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}&quota=1`);if(!r.ok)return;let o=await r.json();if(!i.current||T.current[e]!==n)return;d(t=>({...t,[e]:{activeAccountId:o.activeAccountId??a.activeAccountId??null,accounts:o.accounts??a.accounts??[]}}))}catch{}})(),!0)}catch{return!i.current||T.current[e]!==n?!0:(p(t=>({...t,[e]:`error`})),!1)}}))).every(Boolean)},[i,t]),A=(0,_.useCallback)(async e=>{let n=await Promise.all(e.map(async e=>[e,(await fetch(`${t}/api/providers/keys?name=${encodeURIComponent(e)}`).then(async e=>{if(!e.ok)throw Error(String(e.status));return e.json()}).catch(()=>null))?.keys??[]]));b(Object.fromEntries(n))},[t]),j=async(e,r)=>{if(r.active||r.needsReauth||O.current)return;let o={provider:e,accountId:r.id};O.current=o,h(o);let l=mi(u[e]?.accounts??[r],r,n);try{if(!(await fetch(`${t}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:r.id})})).ok){a(n(`prov.accountSwitchFail`),!1);return}let i=await k([e]);if(await Promise.all([s(),c(!0)]),!i){a(n(`pws.accountsLoadFailed`),!1);return}a(n(`prov.accountSwitched`,{email:l}),!0)}catch{a(n(`prov.accountSwitchFail`),!1)}finally{O.current?.provider===o.provider&&O.current.accountId===o.accountId&&(O.current=null,i.current&&h(null))}},M=async(e,r)=>{if(r.active)return;let i=await fetch(`${t}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:r.id})});i.ok?(a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),A(Object.keys(y)),c(!0)):a((await i.json().catch(()=>({}))).error||n(`prov.keySwitchFail`),!1)},N=async(e,r)=>{window.confirm(n(`prov.keyRemoveConfirm`,{key:r.label??r.masked}))&&(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),A(Object.keys(y)),o(),c(!0))},P=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})});return r.ok?(a(n(`prov.keyAdded`,{name:e}),!0),S(null),await Promise.all([A(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),o(),c(!0)]),!0):(a((await r.json().catch(()=>({}))).error||n(`prov.keyAddFail`),!1),!1)}catch{return a(n(`prov.keyAddFail`),!1),!1}},F=async e=>{await P(e,C)&&w(``)},I=async(e,r,i,o)=>{let s=window.prompt(n(`prov.aliasPrompt`),o??``);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){a((await l.json().catch(()=>({}))).error||n(`prov.aliasSaveFailed`),!1);return}r===`oauth`?await k([e]):await A(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),a(n(`prov.aliasSaved`),!0)},L=async(e,r)=>{let i=mi(u[e]?.accounts??[r],r,n);if(window.confirm(n(`prov.accountRemoveConfirm`,{email:i})))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 k([e]),await Promise.all([s(),c(!0)])}catch{a(n(`prov.accountRemoveFail`,{email:i}),!1)}},R=(0,_.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[r]);(0,_.useEffect)(()=>{if(R.length===0)return;let e=R.join(`,`);E.current!==e&&(E.current=e,Promise.resolve().then(()=>{k(R)}))},[k,R]);let z=(0,_.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[r]);return(0,_.useEffect)(()=>{if(z.length===0)return;let e=z.join(`,`);D.current!==e&&(D.current=e,Promise.resolve().then(()=>{A(z)}))},[A,z]),{accountSets:u,accountLoadStates:f,switchingAccount:m,openAccounts:g,keyPools:y,addingKeyFor:x,newKeyValue:C,setAccountSets:d,setAccountLoadStates:p,setSwitchingAccount:h,setOpenAccounts:v,setKeyPools:b,setAddingKeyFor:S,setNewKeyValue:w,fetchAccountSets:k,fetchKeyPools:A,switchAccount:j,switchApiKey:M,removeApiKey:N,addApiKeyValue:P,addApiKey:F,editCredentialAlias:I,removeAccount:L,oauthCardProviders:R,keyCardProviders:z,activeAccountNeedsReauth:(0,_.useMemo)(()=>bo(u,l),[u,l])}}function So(e){let{apiBase:t,config:n,notify:r,fetchConfig:i,fetchProviderQuotas:a,onSaved:o,t:s}=e,[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),x=(0,_.useRef)(!1);(0,_.useEffect)(()=>{n&&!x.current&&d(JSON.stringify(n,null,2))},[n]);let S=(0,_.useCallback)(async()=>{v(!0);try{let e=JSON.parse(u),n=await fetch(`${t}/api/config`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});return n.ok?(r(s(`prov.saved`),!0),l(!1),p(!1),x.current=!1,b(!1),h(JSON.stringify(e,null,2)),i(),a(!0),o(),!0):(r((await n.json().catch(()=>({}))).error||s(`prov.saveFailed`),!1),!1)}catch{return r(s(`prov.invalidJson`),!1),!1}finally{v(!1)}},[t,u,i,a,r,o,s]),C=(0,_.useCallback)(()=>{let e=n?JSON.stringify(n,null,2):u;h(e),d(e),b(!1),p(!0),x.current=!0},[n,u]),w=(0,_.useCallback)(()=>{b(!1),p(!1),x.current=!1;let e=n?JSON.stringify(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:y,jsonEditorOpenRef:x,saveConfig:S,openJsonEditor:C,discardJsonEditor:w,requestCloseJsonEditor:(0,_.useCallback)(()=>{if(f&&u!==m){b(!0);return}w()},[w,u,m,f]),restoreJsonEditor:(0,_.useCallback)(()=>{d(m)},[m]),jsonIsDirty:f&&u!==m,setJsonLeaveOpen:b}}var Co={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},wo=e=>Co[e]??e;function To({apiBase:e,t,aliveRef:n,oauthLoginGenerationRef:r,accountSets:i,setBusy:a,setStatus:o,setLoginInfo:s,setOauthStatus:c,notify:l,fetchConfig:u,fetchOauth:d,fetchAccountSets:f,fetchProviderQuotas:p,bumpModelsRefresh:m}){return{cancelLoginOAuth:(0,_.useCallback)(async i=>{let o=(r.current.get(i)??0)+1;r.current.set(i,o);try{await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:i})})}catch{}n.current&&(r.current.get(i)===o&&(a(e=>e===i?null:e),s(e=>e?.provider===i?null:e)),l(t(`prov.loginCancelled`,{provider:wo(i)}),!1))},[n,e,l,r,a,s,t]),loginOAuth:async(d,h=!1,g)=>{let _=(r.current.get(d)??0)+1;r.current.set(d,_);let v=_,y=g?.trim()||void 0;a(d),o(``),s(null);try{let a=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:d,...h||y?{addAccount:!0}:{},...y?{accountId:y,reauth:!0}:{}})});if(r.current.get(d)!==v||!n.current)return;if(!a.ok){l((await a.json().catch(()=>({}))).error||t(`prov.loginFailStart`,{provider:wo(d)}),!1);return}let o=await a.json();(o.url||o.instructions||o.deviceCode)&&s({provider:d,url:o.url,instructions:o.instructions,deviceCode:o.deviceCode});let g=i[d]?.accounts.length??0,_=!1;for(let a=0;a<150&&n.current&&r.current.get(d)===v;a++){if(await new Promise(e=>setTimeout(e,2e3)),r.current.get(d)!==v||!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${d}`).catch(()=>null),o=a?await _t(a)??null:null;if(o){if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:wo(d)}):t(`prov.loginError`,{provider:wo(d),error:o.error}),!1),s(null),_=!0;break}if(h||y?(o.accounts?.length??0)>g||o.done===!0:o.loggedIn||o.done===!0){c(e=>({...e,[d]:o}));let e=y?o.accounts?.find(e=>e.id===y):o.accounts?.find(e=>e.active)??o.accounts?.find(e=>e.id===o.activeAccountId);if(y&&!e){l(t(`prov.loginError`,{provider:wo(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),_=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:wo(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),_=!0;break}l(t(`prov.loginOk`,{provider:wo(d),cmd:`ocx sync`}),!0),s(null),u();let n=Object.keys(i);f(new Set(n).has(d)?n:[...n,d]),p(!0),m(),_=!0;break}}}!_&&r.current.get(d)===v&&n.current&&(await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:d})}).catch(()=>{}),l(t(`prov.loginTimeout`,{provider:wo(d)}),!1),s(null))}catch{r.current.get(d)===v&&l(t(`prov.loginRequestFail`,{provider:wo(d)}),!1)}finally{n.current&&r.current.get(d)===v&&a(null)}},logoutOAuth:async n=>{try{if(!(await fetch(`${e}/api/oauth/logout?provider=${encodeURIComponent(n)}`,{method:`POST`})).ok){l(t(`prov.logoutFail`,{provider:wo(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:wo(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:wo(n)}),!1)}}}}async function Eo(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function Do(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 Oo({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l}){let u=(0,_.useCallback)(async e=>{a(e)},[a]),d=(0,_.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;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(Do(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]),f=(0,_.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 Eo(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),p=(0,_.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)});return i.ok?(await s(),{ok:!0}):{ok:!1,error:await Eo(i,t(`prov.updateFail`))}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,t]);return{removeProvider:u,confirmRemoveProvider:d,setProviderDisabled:f,setDefaultProvider:(0,_.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(Do(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:p}}function ko({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await Q(await fetch(`${e}/api/config`));n(t??null),s&&t&&yn(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await Q(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 _t(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function Ao({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Z(),a=(0,_.useId)(),o=(0,_.useId)(),s=(0,_.useRef)(null),c=(0,_.useRef)(!1),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(!1),p=_o(e);(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]);let m=(0,_.useCallback)(e=>{e.preventDefault(),n()},[n]);if(!p)return null;let h=e.trim().toLowerCase(),g=h===`anthropic`?`oauthTos.anthropicBody`:yo(p),v=h===`anthropic`||h===`google-antigravity`;return(0,J.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,J.jsx)(`h3`,{id:a,children:i(vo(p),{provider:t})}),(0,J.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,J.jsx)(ve,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,J.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,J.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,J.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function jo(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function Mo(e){return nr(e.id,jo(e))}function No(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[Mo(n)].push(n);return t}function Po(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}var Fo={},Io=[],Lo={};function Ro({presets:e,usageRank:t=Fo,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=Io,accountStatus:s=Lo,busyProvider:c=null,onLogin:l,onCancelLogin:u,onLogout:d}){let f=Z(),[p,m]=(0,_.useState)(r),[h,g]=(0,_.useState)(``),v=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),y=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return v.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)})},[v,t]),b=(0,_.useMemo)(()=>No(y),[y])[p],x=(0,_.useMemo)(()=>Po(b,h),[b,h]),S=e=>{let t=e.codexAccountMode===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.pool`)}):e.auth===`oauth`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.oauth`)}):e.auth===`forward`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.codexLogin`)}):e.auth===`local`?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:f(`modal.badge.local`)}):e.keyOptional?null:(0,J.jsx)(`span`,{className:`badge badge-muted`,children:f(`modal.badge.apiKey`)});return(0,J.jsxs)(J.Fragment,{children:[(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.free`)}):null,t]})};return(0,J.jsxs)(`div`,{className:`provider-catalog`,children:[(0,J.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":p===e,className:`provider-catalog-tab${p===e?` active`:``}`,onClick:()=>{m(e),g(``)},children:f(e===`accounts`?`modal.tab.accounts`:e===`free`?`modal.tab.free`:`modal.tab.paid`)},e))}),p===`accounts`&&(0,J.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:f(`modal.accountsHint`)}),(0,J.jsx)(`input`,{className:`input provider-catalog-search`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.search`)}),(0,J.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&x.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.catalogLoading`)}),p!==`accounts`&&x.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsxs)(`div`,{className:`sub`,children:[(0,J.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:S(e)})]},e.id)),p!==`accounts`&&!n&&x.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.noMatch`)}),p===`accounts`&&o.map(e=>{let t=s[e.id],n=c===e.id,r=!!t?.loggedIn,i=r?t?.email??e.statusLabel??f(`modal.accountLoggedIn`):t?.error??e.statusLabel??f(`modal.accountLoggedOut`);return(0,J.jsxs)(`div`,{className:`list-row provider-catalog-account-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsx)(`div`,{className:`sub`,children:i})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,J.jsxs)(J.Fragment,{children:[r&&(0,J.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-auth`,children:f(`modal.accountManage`)}),l&&(0,J.jsx)(`button`,{type:`button`,className:r?`btn btn-ghost`:`btn btn-primary`,disabled:n,onClick:()=>{n||l(e.id)},children:f(n?`codexAuth.enablingOpenai`:r?`modal.accountAdd`:`modal.accountLogin`)})]}):r?d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(e.id),children:f(`modal.accountLogout`)}):n?u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:f(`common.cancel`)}):l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>l(e.id),children:f(`modal.accountLogin`)})})]},e.id)}),p===`accounts`&&o.length===0&&!n&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.noMatch`)})]}),(0,J.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,J.jsx)(`div`,{style:{flex:1}}),p!==`accounts`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:f(`modal.notListed`)})]})]})}function zo({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,manualCode:o,manualCodeBusy:s,manualCodeMsg:c,manualCodeOk:l,onRequestLogin:u,onUseApiKeyInstead:d,onManualCodeChange:f,onSubmitManualCode:p,onBack:m}){let h=Z();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,J.jsx)(`div`,{className:`muted text-control`,children:e.note??h(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>u(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,J.jsx)(ke,{}),n?h(`modal.waitingBrowser`):h(`modal.logInWith`,{label:e.label})]}):(0,J.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:h(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,J.jsx)(Ri,{url:a}),n&&(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:h(`prov.pasteRedirectHint`)}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,J.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:o,onChange:e=>f(e.target.value),onKeyDown:t=>{t.key===`Enter`&&e.oauthProvider&&(t.preventDefault(),p(e.oauthProvider))},placeholder:h(`prov.pasteRedirect`),"aria-label":h(`prov.pasteRedirect`),disabled:s,className:`input text-label`,style:{flex:1}}),(0,J.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,disabled:s||!o.trim()||!e.oauthProvider,onClick:()=>e.oauthProvider&&p(e.oauthProvider),children:h(s?`prov.pasteSubmitting`:`prov.pasteSubmit`)})]}),c&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:l?`var(--accent-hover)`:`var(--amber)`},children:c})]}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:d,children:h(`modal.useApiKeyInstead`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}function Bo({label:e,children:t}){return(0,J.jsxs)(`label`,{style:{display:`block`},children:[(0,J.jsx)(`span`,{className:`field-label`,children:e}),t]})}function Vo({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=Z();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,J.jsxs)(`details`,{className:`setup-guide`,children:[(0,J.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,J.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,J.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,J.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,J.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,J.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,J.jsx)(Bo,{label:h(`modal.providerName`),children:(0,J.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Bo,{label:h(`modal.adapter`),children:(0,J.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>u({...t,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Bo,{label:h(`modal.endpoint`),children:(0,J.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:Ya(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,J.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,J.jsx)(Bo,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,J.jsx)(Bo,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,J.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,J.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,J.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,J.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,J.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`)}):e.keyOptional?(0,J.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,J.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,J.jsxs)(J.Fragment,{children:[e.dashboardUrl&&(0,J.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,J.jsx)(Oe,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,J.jsx)(De,{style:{width:13,height:13}})]}),(0,J.jsx)(Bo,{label:h(`modal.apiKey`),children:(0,J.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,J.jsx)(Bo,{label:h(`modal.apiKeyTransport`),children:(0,J.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,J.jsx)(Bo,{label:h(`modal.defaultModel`),children:(0,J.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,J.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Ho=2e3;function Uo({apiBase:e,t,aliveRef:n,onAdded:r}){return{loginOAuth:(0,_.useCallback)(async(i,a)=>{let{setOauthBusy:o,setOauthMsg:s,setOauthMsgTone:c,setOauthUrl:l,setManualCode:u,setManualCodeMsg:d,setManualCodeOk:f}=a;o(!0),s(``),c(`ok`),l(``,i),u(``),d(``),f(!0);try{let a=await fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:i})});if(!n.current)return;if(!a.ok){let e=await a.json().catch(()=>({}));c(`warn`),s(e.error===`unknown oauth provider`?t(`modal.oauthComingSoonShort`):e.error||t(`modal.loginFailStart`));return}let o=await a.json();o.url?(l(o.url,i),s(t(`modal.waitingLogin`))):s(o.instructions||t(`modal.loggingIn`));for(let a=0;a<100;a++){if(await new Promise(e=>setTimeout(e,Ho)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await _t(a):null;if(!n.current)return;if(o?.error){c(`warn`),s(t(`modal.loginError`,{error:o.error}));return}if(o?.loggedIn){r(i);return}}c(`warn`),s(t(`modal.loginTimeout`))}catch{n.current&&(c(`warn`),s(t(`modal.networkError`)))}finally{n.current&&o(!1)}},[n,e,r,t]),submitManualCode:(0,_.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 Wo(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:``,oauthUrlProvider:null,manualCode:``,manualCodeBusy:!1,manualCodeMsg:``,manualCodeOk:!0,endpointChoice:`custom`,oauthTosPending:null}}function Go(e,t){switch(t.type){case`choose-preset`:return{...e,preset:t.preset,form:t.form,endpointChoice:t.endpointChoice,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`back`:return{...e,preset:null,form:null,endpointChoice:`custom`,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,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,oauthUrlProvider:t.providerId}: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:``,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function Ko({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:c,onAccountLogin:l,onAccountCancelLogin:u,onAccountLogout:d,onOpen:f}){let p=Z(),m=(0,_.useMemo)(()=>[{id:`custom`,label:p(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[p]),[h,g]=(0,_.useReducer)(Go,a,e=>Wo(e,p(`modal.customProvider`))),v=(0,_.useRef)(!0),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=K(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),S=K(`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}),C=K(`add-provider-usage:${e}`,[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)return{};let r=await n.json(),i={};for(let e of r.providers??[])i[e.provider]=e.requests;return i},{deadlineMs:6e4}),w=x.data??[],T=S.data??m,E=S.loading,D=C.data??{},{preset:O,form:k,saving:A,error:j,oauthBusy:M,oauthMsg:N,oauthMsgTone:P,oauthUrl:F,oauthUrlProvider:I,manualCode:L,manualCodeBusy:R,manualCodeMsg:z,manualCodeOk:B,endpointChoice:V,oauthTosPending:H}=h;(0,_.useEffect)(()=>{v.current=!0,y.current=document.activeElement,f?.();let e=b.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()=>{v.current=!1,y.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!H&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,H]);let U=e=>{let t=co(e);return t?p(t):e.note},W=e=>{let t=Xa(e.baseUrlChoices,e.baseUrl);g({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?Ya(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},G=async()=>{if(!k)return;let t=O?so(O):!1,n=O?.baseUrlChoices?.length?Za(O.baseUrlChoices,V,k.baseUrl):k.baseUrl.trim();if(!t&&!k.name.trim()){g({type:`set-error`,error:p(`modal.nameRequired`)});return}if(!t&&!n){g({type:`set-error`,error:p(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){g({type:`set-error`,error:p(`modal.baseUrlPlaceholderError`)});return}let i={...k,baseUrl:n},a;try{a=uo(O??{id:`custom`},i)}catch{g({type:`set-error`,error:p(`modal.invalidPreset`)});return}g({type:`set-saving`,saving:!0}),g({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){g({type:`set-error`,error:(await t.json().catch(()=>({}))).error||p(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{g({type:`set-error`,error:p(`modal.networkError`)})}finally{g({type:`set-saving`,saving:!1})}},{loginOAuth:ee,submitManualCode:q}=Uo({apiBase:e,t:p,aliveRef:v,onAdded:r}),te={setOauthBusy:e=>g({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>g({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>g({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t)=>g({type:`set-oauth-url`,url:e,providerId:t}),setManualCode:e=>g({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>g({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>g({type:`set-manual-code-msg`,msg:z,ok:e})},Y=k?t.includes(k.name.trim())&&k.name.trim()!==``:!1,ne=e=>{if(!M){if(_o(e)){g({type:`set-oauth-tos-pending`,providerId:e});return}ee(e,te)}},re=e=>{q(e,L,R,{setManualCodeBusy:e=>g({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>g({type:`set-manual-code`,code:e}),setManualCodeOk:e=>g({type:`set-manual-code-msg`,msg:z,ok:e}),setManualCodeMsg:e=>g({type:`set-manual-code-msg`,msg:e})})},ie=O?.id===`custom`,ae=k?.authMode===`local`,oe=O?so(O):!1;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":p(`modal.add`),className:`modal-overlay`,onClick:n,children:(0,J.jsxs)(`div`,{ref:b,className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:O?p(`modal.addNamed`,{label:O.label}):p(`modal.add`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":p(`common.close`),onClick:n,children:(0,J.jsx)(fe,{})})]}),O?k&&(O.auth===`oauth`&&k.authMode===`oauth`?(0,J.jsx)(zo,{preset:O,oauthSupported:w,oauthBusy:M,oauthMsg:N,oauthMsgTone:P,oauthUrl:I===O.oauthProvider?F:``,manualCode:L,manualCodeBusy:R,manualCodeMsg:z,manualCodeOk:B,onRequestLogin:ne,onUseApiKeyInstead:()=>{g({type:`use-api-key-instead`,form:{...k,authMode:`key`}})},onManualCodeChange:e=>g({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{re(e)},onBack:()=>g({type:`back`})}):(0,J.jsx)(Vo,{preset:O,form:k,endpointChoice:V,error:j,saving:A,dup:Y,isCustom:ie,isLocal:ae,isReservedForward:oe,presetDescription:U,onFormChange:e=>g({type:`set-form`,form:e}),onEndpointChoiceChange:e=>g({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{G()},onUseOauthLogin:()=>g({type:`use-oauth-login`,form:{...k,authMode:`oauth`}}),onBack:()=>g({type:`back`})})):(0,J.jsx)(Ro,{presets:T,usageRank:D,presetsLoading:E,initialTier:i,onSelectPreset:e=>W(e),onSelectCustom:()=>W(m[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:l,onCancelLogin:u,onLogout:d})]})}),H&&(0,J.jsx)(Ao,{providerId:H,providerLabel:O?.label??H,onCancel:()=>g({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=H;e&&(g({type:`set-oauth-tos-pending`,providerId:null}),ee(e,te))}},H)]})}function qo({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,removeConfirmName:s,removeDefaultProvider:c,codexLoginOpen:l,jsonLeaveOpen:u,jsonSaving:d,oauthTosPending:f,onCloseAdd:p,onAdded:m,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onOpenAdd:v,onCloseCodexLogin:y,onCodexAdded:b,onCancelRemove:x,onConfirmRemove:S,onCancelJsonLeave:C,onDiscardJson:w,onSaveJson:T,onCancelOauthTos:E,onContinueOauthTos:D}){return(0,J.jsxs)(J.Fragment,{children:[n&&(0,J.jsx)(Ko,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:p,onAdded:m,accountRows:a,accountStatus:o,accountBusy:i,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onOpen:v}),l&&(0,J.jsx)(Vi,{apiBase:e,onClose:y,onAdded:b}),s&&(0,J.jsx)(eo,{providerName:s,defaultProviderName:c,onCancel:x,onConfirm:S}),u&&C&&w&&T&&(0,J.jsx)(to,{saving:d??!1,onCancel:C,onDiscard:w,onSave:T}),f&&(0,J.jsx)(Ao,{providerId:f.provider,providerLabel:wo(f.provider),onCancel:E,onContinue:D},`${f.provider}:${f.addAccount?`add`:`login`}`)]})}function Jo(e,t,n){return[...ao(e.providers).map(e=>({id:e,label:Ar(e,n),kind:`codex`,href:`#codex-auth`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:wo(e),kind:`oauth`}))]}function Yo(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 Xo({apiBase:e}){let t=Z(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>vn(n)),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)({}),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(null),M=(0,_.useRef)(!0),N=(0,_.useRef)(null),P=(0,_.useRef)(!1),F=(0,_.useRef)(new Map),I=(0,_.useCallback)((e,t=!0)=>{c(e),u(t)},[]);(0,_.useEffect)(()=>(M.current=!0,()=>{M.current=!1}),[]),K(`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(`add-provider-usage:${e}`,[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)return{};let r=await n.json(),i={};for(let e of r.providers??[])i[e.provider]=e.requests;return i},{deadlineMs:6e4});let[L,R]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:z,fetchOauth:B,fetchProviderQuotas:V}=ko({apiBase:e,t,setConfig:i,setOauthProviders:f,setOauthStatus:m,notify:I,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{R(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),H=Qi(e),U=H.activeNeedsReauth,W=(0,_.useMemo)(()=>{let e=H.accounts;if(e.length===0&&H.loadState===`loading`)return p;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{...p,openai:{loggedIn:i,...a?{email:a}:{},...U?{needsReauth:!0}:{}}}},[p,H.accounts,H.loadState,U]),{accountSets:G,accountLoadStates:ee,switchingAccount:q,keyPools:te,fetchAccountSets:Y,switchAccount:ne,switchApiKey:re,removeApiKey:ie,addApiKeyValue:ae,editCredentialAlias:oe,removeAccount:se,activeAccountNeedsReauth:ce}=xo({apiBase:e,t,config:r,oauthStatus:W,aliveRef:M,notify:I,fetchConfig:z,fetchOauth:B,fetchProviderQuotas:V,codexActiveNeedsReauth:U}),{draft:le,setDraft:ue,jsonEditorOpen:de,jsonSaving:fe,jsonLeaveOpen:me,saveConfig:he,openJsonEditor:ge,discardJsonEditor:_e,requestCloseJsonEditor:ve,restoreJsonEditor:ye,jsonIsDirty:be,setJsonLeaveOpen:xe}=So({apiBase:e,config:r,notify:I,fetchConfig:z,fetchProviderQuotas:V,onSaved:()=>k(e=>e+1),t});(0,_.useEffect)(()=>{N.current!==e&&(N.current=e,Promise.resolve().then(()=>{z(),B()}))},[e,z,B]);let Se=()=>k(e=>e+1),{cancelLoginOAuth:Ce,loginOAuth:we,logoutOAuth:Te}=To({apiBase:e,t,aliveRef:M,oauthLoginGenerationRef:F,accountSets:G,setBusy:g,setStatus:c,setLoginInfo:y,setOauthStatus:m,notify:I,fetchConfig:z,fetchOauth:B,fetchAccountSets:Y,fetchProviderQuotas:V,bumpModelsRefresh:Se}),{removeProvider:Ee,confirmRemoveProvider:De,setProviderDisabled:Oe,setDefaultProvider:ke,updateProvider:Ae}=Oo({apiBase:e,t,removeBusyRef:P,workspaceSelected:b,setWorkspaceSelected:x,setRemoveConfirmName:T,notify:I,fetchConfig:z,fetchOauth:B,fetchProviderQuotas:V}),je=(e,t=!1)=>{if(h!==e){if(_o(e)){j({provider:e,addAccount:t});return}we(e,t)}};if(!r)return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,J.jsx)(dt,{tone:`err`,children:s}):(0,J.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,J.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`providers-workspace-main`,children:(0,J.jsxs)(`p`,{className:`muted`,children:[(0,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let Me=Jo(r,d,t),Ne=Yo(r,W),Pe=e=>r.providers[e]?.authMode===`forward`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.providers`)}),(0,J.jsx)(`div`,{className:`row`,children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,J.jsx)(pe,{}),t(`prov.add`)]})})]}),s&&(0,J.jsx)(dt,{tone:l?`ok`:`err`,children:s}),(0,J.jsx)(di,{onRemoveProvider:Ee,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:b,onSelect:x,onAddProvider:e=>{C(e??null),o(!0)},onEditConfig:ge,jsonEditor:{open:de,draft:le,isDirty:be,onDraftChange:ue,onSave:()=>he(),onClose:ve,onRestore:ye},jsonSaving:fe,modelsRefreshToken:O,activeAccountNeedsReauth:ce,quotaRefreshEpoch:L.epoch,quotaForceRefresh:L.force,detail:(t,n)=>{let i=Ne[t.name]??p[t.name];return(0,J.jsx)(no,{item:t,usageTotals:n.usageTotals,modelUsage:n.modelUsage,quotaReport:n.quotaReport,availableModels:n.availableModels,hasLiveModels:n.hasLiveModels,selectedModels:n.selectedModels,modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:i?.email,onDeselect:()=>x(null),apiBase:e,oauth:i,accounts:G[t.name]?.accounts??[],keys:te[t.name]??[],accountLoadState:ee[t.name]??(t.authMode===`oauth`?`idle`:`ready`),switchingAccountId:q?.provider===t.name?q.accountId:null,busyProvider:h,loginHint:v,authHandlers:{onLogin:je,onCancelLogin:Ce,onLogout:Te,onReauth:(e,t)=>we(e,!0,t),onSwitchAccount:ne,onRemoveAccount:se,onRetryAccounts:async e=>{await Y([e])},onAddApiKey:ae,onSwitchApiKey:re,onRemoveApiKey:ie,onEditAlias:oe},isDefault:t.name===r.defaultProvider,onRemoveProvider:Ee,onSetDisabled:Oe,onSetDefault:e=>{ke(e)},onUpdateProvider:Ae,codexController:H},t.name)}}),(0,J.jsx)(qo,{apiBase:e,config:r,adding:a,addIntent:S,busy:h,addModalAccountRows:Me,accountLoginStatus:Ne,removeConfirmName:w,removeDefaultProvider:w===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==w&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:E,jsonLeaveOpen:me,jsonSaving:fe,oauthTosPending:A,onCloseAdd:()=>{h&&Ce(h),o(!1),C(null)},onAdded:e=>{o(!1),C(null),I(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),z(),B(),V(!0),Se()},onAccountLogin:async n=>{if(n===`openai`){if(h===`openai`)return;let n=r.providers.openai,i=oo(n);if(i===`invalid`){I(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){g(`openai`);try{await mo(e,i),await z()}catch(e){e instanceof po?I(t(e.i18nKey),!1):I(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{M.current&&g(e=>e===`openai`?null:e)}}D(!0);return}if(Pe(n)){D(!0);return}(r.providers[n]?.authMode===`oauth`||d.includes(n))&&je(n)},onAccountCancelLogin:e=>{Ce(e)},onAccountLogout:e=>{Te(e)},onOpenAdd:B,onCloseCodexLogin:()=>D(!1),onCodexAdded:()=>{D(!1),I(t(`prov.loginOk`,{provider:Ar(`openai`,t),cmd:`ocx sync`}),!0),z(),B(),V(!0),Se()},onCancelRemove:()=>T(null),onConfirmRemove:()=>{De(w)},onCancelJsonLeave:()=>{fe||xe(!1)},onDiscardJson:_e,onSaveJson:()=>{he()},onCancelOauthTos:()=>j(null),onContinueOauthTos:()=>{let e=A;e&&(j(null),we(e.provider,e.addAccount))}})]})}var Zo={"gpt-5.6-sol":Me,"gpt-5.6-terra":Fe,"gpt-5.6-luna":Ne},Qo={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function $o(e){return e.slice(e.lastIndexOf(`/`)+1)}function es(e){return Zo[e]??Zo[$o(e)]??null}function ts(e){let t=es(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:Qo,"aria-hidden":!0}),e):e}var ns=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function rs(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...ns];let r=new Set(ns),i=null;for(let e of n){let n=`${e.provider.trim()}/${e.model.trim()}`,a=t.get(n),o=a===void 0?[]:a.filter(e=>r.has(e));if(i===null)i=o;else{let e=new Set(o);i=i.filter(t=>e.has(t))}}let a=new Set(i??[]);return ns.filter(e=>a.has(e))}var is=0;function as(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++is}`}}var os=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,ss=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,cs=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function ls(e){return os.test(e.trim())}function us(e){return`combo/${e.trim()}`}function ds(e,t){return(typeof t==`string`?t.trim():``)||us(e)}function fs(e){return typeof e==`string`&&e.trim()?e.trim():null}function ps(e){return e===`round-robin`?`round-robin`:`failover`}function ms(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function hs(e){return typeof e==`string`&&ns.includes(e)?e:null}function gs(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function _s(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=gs(t.weight);a.push(as(i===void 0?{provider:n,model:r}:{provider:n,model:r,weight:i}))}n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():ds(r,fs(t.alias)),alias:fs(t.alias),strategy:ps(t.strategy),stickyLimit:ms(t.stickyLimit),defaultEffort:hs(t.defaultEffort),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function vs(e){let t=[],n=[];for(let r of e)r.strategy===`round-robin`?n.push(r):t.push(r);return{failover:t,roundRobin:n}}function ys(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 bs(e,t={}){let n=[],r=t.cataloguedComboIds;for(let t of e)t.targets.length===0?n.push({id:t.id,model:t.model,reason:`empty-targets`}):t.targets.length<2&&n.push({id:t.id,model:t.model,reason:`few-targets`}),r&&t.targets.length>0&&!r.has(t.id)&&n.push({id:t.id,model:t.model,reason:`catalog-omitted`});return n}function xs(e,t){return e.id!==t.id||e.alias!==t.alias||e.strategy!==t.strategy||e.stickyLimit!==t.stickyLimit||e.defaultEffort!==t.defaultEffort||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)})}function Ss(e,t={}){return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},combo:{targets:e.targets.map(t=>e.strategy===`round-robin`?{provider:t.provider.trim(),model:t.model.trim(),weight:t.weight??1}:{provider:t.provider.trim(),model:t.model.trim()}),strategy:e.strategy,defaultEffort:e.defaultEffort,...e.strategy===`round-robin`?{stickyLimit:e.stickyLimit}:{},...e.alias&&e.alias.trim()?{alias:e.alias.trim()}:{}}}}function Cs(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!ls(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()??``;if(r){if(!ss.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&cs.test(r))return`aliasNativeFamily`;if((t.existingAliases??[]).includes(r))return`duplicateAlias`}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`}let i=new Set;for(let t of e.targets){let e=`${t.provider.trim()}/${t.model.trim()}`;if(i.has(e))return`duplicateTarget`;i.add(e)}if(e.strategy===`round-robin`){if(!Number.isInteger(e.stickyLimit)||e.stickyLimit<1||e.stickyLimit>100)return`invalidStickyLimit`;for(let t of e.targets){let e=t.weight??1;if(!Number.isInteger(e)||e<1||e>1e4)return`invalidWeight`}}return e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function ws(e=``){return{id:e,model:e?us(e):`combo/`,alias:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,targets:[as()]}}function Ts(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 Es(e,t,n,r){let{isEmpty:i,...a}=r,o=K(e,t,n,a);return{...o,state:Ts(o,i,r.enabled!==!1)}}function Ds({className:e,style:t}){return(0,J.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function Os({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,J.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,J.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,J.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,J.jsx)(Ds,{})},t))]})}function ks({children:e,busy:t=!0,live:n=!0,className:r}){return(0,J.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,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:e})]})}function As(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),liveModels:n?.liveModels!==!1,configuredModels:n?.models??[],discovery:n?.discovery}}).sort((e,t)=>e.native===t.native?e.provider.localeCompare(t.provider):e.native?-1:1)}function js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ms(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Ns(e){if(!js(e))throw Error(`invalid selected models response`);let t=e.selected;if(!js(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ms(t)]))}async function Ps(e,t=fetch){let n=await t(`${e}/api/selected-models`);if(!n.ok)throw Error(`selected models HTTP ${n.status}`);return Ns(await n.json())}function Fs(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Is(e,t,n,r,i){return Fs(e,t,n,r)&&!i}async function Ls(e,t,n,r,i,a=fetch){return a(`${e}/api/model-visibility`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope:t,provider:n,targets:r,enabled:i})})}function Rs(e,t){return e===t}function zs(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`)}}var Bs=Array.from({length:18},(e,t)=>1e5+t*5e4),Vs=new Set(Bs),Hs=`custom`,Us=[4,8,16,32,64,128,256,500,1e3],Ws=new Set(Us),Gs=`ocx-models-collapsed:v2`,Ks=`ocx-models-combos-open:v1`;function qs(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function Js(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ys(e,t,n){let r=[];for(let i of e){let e=t.has(i.id)||t.has(i.namespaced);Is(n,i.provider,i.id,i.native===!0,e)&&r.push({value:i.namespaced,label:i.namespaced})}return r}function Xs(e=localStorage){try{let t=e.getItem(Gs);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 Zs(e,t=localStorage){try{t.setItem(Gs,JSON.stringify([...e]))}catch{}}function Qs(e=localStorage){try{return(e.getItem(`ocx-models-combos-open:v1`)??e.getItem(`ocx-models-combos-open`))===`1`}catch{return!1}}function $s(e,t=localStorage){try{t.setItem(Ks,e?`1`:`0`)}catch{}}function ec({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Z(),i=e&&t?.status===`failed`?t:void 0;return(0,J.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,J.jsx)(ye,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,J.jsxs)(`span`,{children:[i&&n&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${zs(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,J.jsx)(`a`,{href:`#providers`,children:r(`models.openProviderSettings`)})]})]})}function tc(e){return Array.isArray(e)?_s({combos:e}):null}function nc({apiBase:e}){let t=Z(),n=`ocx.models.catalog.v1:${e}`,r=(0,_.useMemo)(()=>vn(n),[n]),[i,a]=(0,_.useState)(()=>r?.models??[]),[o,s]=(0,_.useState)(()=>r?.providers??[]),[c,l]=(0,_.useState)(()=>new Set(r?.disabled??[])),[u,d]=(0,_.useState)(()=>r?.selectedModels??null),[f,p]=(0,_.useState)({}),[m,h]=(0,_.useState)({}),[g,v]=(0,_.useState)(()=>r?.contextCaps??{}),[b,x]=(0,_.useState)(()=>r?.contextCapValue??35e4),[S,C]=(0,_.useState)(``),[w,T]=(0,_.useState)(!1),E=Xs(),[D,O]=(0,_.useState)(()=>E??new Set),k=(0,_.useRef)(E===null),[A,j]=(0,_.useState)(``),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(!1),I=(0,_.useRef)(!1),L=(0,_.useRef)(0),R=(0,_.useRef)(!1),[z,B]=(0,_.useState)(null),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(``),G=(0,_.useRef)(!1),[ee,K]=(0,_.useState)(``),[te,Y]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(!1),[ae,oe]=(0,_.useState)(!1),[se,ce]=(0,_.useState)(`add`),[le,ue]=(0,_.useState)(``),[de,fe]=(0,_.useState)(``),[pe,me]=(0,_.useState)(``),[he,ge]=(0,_.useState)(``),[_e,ve]=(0,_.useState)(``),[be,xe]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)([`text`]),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)(``),[ke,Ae]=(0,_.useState)(null),je=(0,_.useRef)(null),[Me,Ne]=(0,_.useState)(null),[Pe,Fe]=(0,_.useState)(!1),Ie=`ocx.models.combos.v1:${e}`,Re=(0,_.useMemo)(()=>{let t=tc(vn(Ie));return t===null?tc(vn(`ocx.combos.workspace.v1:${e}`)?.combos):t},[e,Ie]),ze=Es(`models-combos:${e}`,[e],async t=>{let n=_s(await Q(await fetch(`${e}/api/combos`,{signal:t})));return yn(Ie,n),n},{isEmpty:()=>!1,initialData:Re??void 0}),Be=ze.state,Ve=Be.data??Re,He=Be.showError,[Ue,We]=(0,_.useState)(Qs),[Ge,Ke]=(0,_.useState)(null),qe=()=>{let e=!Ue;$s(e),We(e)};(0,_.useEffect)(()=>()=>{je.current&&clearTimeout(je.current)},[]);let X=(0,_.useMemo)(()=>Ys(i,c,u??{}),[i,c,u]),Je=(0,_.useCallback)(async()=>{let t=y(15e3);try{let n=await _t(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&Ne(n)}catch{}finally{t.clear()}},[e]),Ye=(0,_.useCallback)(async()=>{if(G.current)return;let t=y(15e3);try{let n=await fetch(`${e}/api/v2`,{signal:t.signal});if(!(n.headers.get(`content-type`)??``).includes(`application/json`)){B(null);return}let r=await _t(n);if(!r||typeof r.enabled!=`boolean`){B(null);return}B({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`})}catch{B(null)}finally{t.clear()}},[e]),Xe=(0,_.useCallback)(async t=>{let[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}),Ps(e,(e,n)=>fetch(e,{...n,signal:t}))]),[s,c,l]=await Promise.all([Q(r),Q(i),Q(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=Js(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??{},contextCapValue:f};return yn(n,p),p},[e,n]),Ze=(0,_.useCallback)(e=>{let t=As(e.models,e.providers);Ke(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),a(e.models),s(e.providers),l(new Set(e.disabled)),d(e.selectedModels),x(e.contextCapValue),v(e.contextCaps)},[]),Qe=Es(n,[e],async e=>{let t=await Xe(e);if(e.aborted)throw Error(`models request aborted`);return Ze(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:r??void 0,deadlineMs:6e4}),$e=Qe.state,et=(0,_.useCallback)(async(e=!1)=>{if(R.current&&!e)return!1;R.current=!0;let t=++L.current;try{let e=await Xe(new AbortController().signal);return Rs(t,L.current)?(Ze(e),q(n,e),!0):!1}catch{return!1}finally{Rs(t,L.current)&&(R.current=!1)}},[Ze,n,Xe]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{Je(),Ye()},0),t=Jt(()=>{G.current||Ye()},1e4);return()=>{window.clearTimeout(e),t()}},[Je,Ye]);let tt=(0,_.useMemo)(()=>As(i,o),[i,o]);(0,_.useEffect)(()=>{if(!k.current||tt.length===0)return;k.current=!1;let e=new Set(tt.map(e=>e.provider));O(e),Zs(e)},[tt]);let nt=(0,_.useMemo)(()=>u?i.filter(e=>Is(u,e.provider,e.id,e.native===!0,c.has(e.namespaced))).length:0,[c,i,u]),rt=async(n,r,i,a)=>{++L.current,F(!0),I.current=!0,j(``);let o=null;try{(await Ls(e,n,r,i,a)).ok||(o=`models.saveFailed`)}catch{o=`models.networkError`}finally{let e=await et(!0);o?(N(!1),j(t(o))):e&&(N(!0),j(t(`models.applied`))),F(!1),I.current=!1}},it=async n=>{F(!0),I.current=!0,j(``);let r=g[n]!==b;try{let i=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,enabled:r})});try{v((await Q(i,t(`models.capSaveFailed`)))?.caps??{}),N(!0),j(t(`models.capApplied`)),await et(!0)}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{F(!1),I.current=!1}},at=e=>{O(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Zs(n),n})},ot=e=>{O(()=>{let t=e?new Set(tt.map(e=>e.provider)):new Set;return Zs(t),t})},st=async n=>{F(!0),I.current=!0,j(``);try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{let e=await Q(r,t(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&x(e.value),v(e?.caps??{}),N(!0),j(t(`models.capApplied`)),await et(!0)}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{F(!1),I.current=!1}},ct=e=>{!Number.isFinite(e)||e<=0||st({value:Math.floor(e)})},lt=e=>{if(e===`custom`){T(!0),C(String(b));return}T(!1);let t=Number(e);Number.isFinite(t)&&t>0&&t!==b&&ct(t)},ht=()=>{let e=Number(S.replace(/[_,\s]/g,``));if(!Number.isFinite(e)||e<=0){N(!1),j(t(`models.capSaveFailed`));return}T(!1),ct(e)},gt=(0,_.useMemo)(()=>{let e=tt.filter(e=>!e.native&&e.rows.length>0);return e.length>0&&e.every(e=>g[e.provider]===b)},[tt,g,b]),vt=()=>{st({setAll:!gt})},yt=async t=>{if(!(!Me||Pe)){Fe(!0),Ne({...Me,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Fe(!1)}}},bt=async n=>{if(!(!z||G.current)&&z.multiAgentMode!==n){H(!0),G.current=!0,W(``),j(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:n})});try{let e=await Q(r,t(`models.saveFailed`));Ye(),N(!0),j(t(`models.v2Applied`)),W((e?.warnings??[]).join(` `))}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{H(!1),G.current=!1}}},xt=async n=>{if(!(!z||G.current)){if(!Number.isInteger(n)||n<1){N(!1),j(t(`models.v2ThreadsInvalid`));return}if(z.maxConcurrentThreadsPerSession!==n){H(!0),G.current=!0,W(``),j(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await Q(r,t(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){N(!1),j(t(`models.saveFailed`));return}B({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`}),N(!0),j(t(`models.v2ThreadsApplied`)),Y(!1)}catch(e){N(!1),j(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{N(!1),j(t(`models.networkError`))}finally{H(!1),G.current=!1}}}},St=e=>{if(e===`custom`){Y(!0),K(String(z?.maxConcurrentThreadsPerSession??``));return}Y(!1),xt(Number(e))},Ct=(e,t)=>{je.current&&clearTimeout(je.current),je.current=setTimeout(()=>{Ae({namespaced:e,rect:t.getBoundingClientRect()})},300)},wt=(e,t)=>{je.current&&clearTimeout(je.current),Ae({namespaced:e,rect:t.getBoundingClientRect()})},Tt=()=>{je.current&&clearTimeout(je.current),je.current=setTimeout(()=>Ae(null),120)},Et=()=>{je.current&&clearTimeout(je.current)},Dt=async(n,r,i,a,o)=>{Ee(!0),Oe(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:n,modelId:r,displayName:i,contextWindow:a,inputModalities:o})});try{await Q(s,t(`models.customSaveFailed`)),oe(!1),N(!0),j(t(`models.customAdded`)),await et(!0)}catch(e){Oe(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Oe(t(`models.networkError`))}finally{Ee(!1)}},Ot=async(n,r)=>{Ee(!0),Oe(``);try{let i=await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});try{await Q(i,t(`models.customSaveFailed`)),oe(!1),N(!0),j(t(`models.customUpdated`)),await et(!0)}catch(e){Oe(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Oe(t(`models.networkError`))}finally{Ee(!1)}},kt=async n=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`DELETE`})).ok?(N(!0),j(t(`models.customDeleted`)),await et(!0)):(N(!1),j(t(`models.customSaveFailed`)))}catch{N(!1),j(t(`models.networkError`))}},At=$e.data??r;if($e.showSkeleton&&!At)return(0,J.jsx)(Os,{label:t(`models.loading`),rows:5});if($e.kind===`failed-cold`)return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:$e.error instanceof Error?$e.error.message:t(`models.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Qe.refresh(),children:t(`common.retry`)})]});let jt=u??{},Mt=e=>{let{provider:n,rows:r,native:i,liveModels:a,discovery:o}=e,s=D.has(n),l=e=>Is(jt,n,e.id,e.native===!0,c.has(e.namespaced)),u=r.filter(l).length,d=g[n]===b,_=i,v=a&&o?.status===`failed`?o:void 0,y=(f[n]??``).trim().toLowerCase(),x=y?r.filter(e=>e.id.toLowerCase().includes(y)):r,S=x.toSorted((e,t)=>Number(!l(e))-Number(!l(t))),C=m[n]??60,w=S.slice(0,C),T=x.length-w.length,E=r.length>0,O=!E||r.every(l),k=!E||r.every(e=>!l(e)),A=e=>{E&&rt(`provider`,n,r.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,J.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,J.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>at(n),"aria-expanded":!s,style:{flex:1,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,J.jsx)(we,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,J.jsx)(`span`,{className:`text-body font-semibold`,children:n}),_&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.nativeGroupLabel`)}),v&&(0,J.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:zs(t,v),children:t(`models.discoveryFailedBadge`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:u,total:r.length})})]}),(0,J.jsxs)(`div`,{className:`row models-provider-actions`,children:[!_&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),ce(`add`),ue(n),fe(``),me(``),ge(``),ve(``),xe(!1),Ce([`text`]),Oe(``),oe(!0)},"aria-label":t(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:P||O,onClick:()=>A(!0),children:t(`models.allOn`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:P||k,onClick:()=>A(!1),children:t(`models.allOff`)}),!_&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ut,{on:d,onClick:()=>it(n),disabled:P,label:t(`models.capValue`,{value:qs(b)})}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.capValue`,{value:qs(b)})})]})]})]}),!s&&(0,J.jsxs)(`div`,{className:`models-provider-body`,children:[_&&(0,J.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:t(`models.nativeHint`)}),r.length===0&&(0,J.jsx)(ec,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>60/2&&(0,J.jsx)(`input`,{className:`input`,placeholder:t(`models.search`),value:f[n]??``,onChange:e=>p(t=>({...t,[n]:e.target.value})),"aria-label":t(`models.search`)}),w.map(e=>{let r=!l(e);return(0,J.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Ct(e.namespaced,t.currentTarget),onMouseLeave:Tt,onFocus:t=>wt(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||Ae(null)},children:[(0,J.jsxs)(`div`,{className:`row models-model-row`,children:[(0,J.jsx)(ut,{on:!r,onClick:()=>void rt(`models`,n,[{id:e.id,native:e.native===!0}],r),disabled:P,label:e.native?e.id:e.namespaced}),(0,J.jsx)(`code`,{className:`mono text-control`,style:{color:r?`var(--faint)`:`var(--text)`,textDecoration:r?`line-through`:`none`},children:e.native?ts(e.id):e.namespaced}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.customBadge`)}),e.contextCapped&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.contextCappedValue`,{value:qs(e.contextCap??b)})})]}),ke?.namespaced===e.namespaced&&(()=>{let n=ke.rect,i=n.bottom+4,a=i+360>window.innerHeight;return(0,J.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${a?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:n.left+24,...a?{bottom:window.innerHeight-n.top+4}:{top:i}},onMouseEnter:Et,onMouseLeave:Tt,children:[(0,J.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,J.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:t(`models.customBadge`)}),(0,J.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipProvider`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:e.provider}),(e.contextWindow||e.contextCap)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipContext`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:qs(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipModalities`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,J.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipStatus`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:t(r?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,J.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{ce(`edit`),ue(e.provider),fe(e.customId),me(e.id),ge(e.displayName??``),ve(e.contextWindow?String(e.contextWindow):``),xe(!1),Ce(e.inputModalities??[`text`]),Oe(``),oe(!0),Ae(null)},children:t(`models.customEdit`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{window.confirm(t(`models.customDeleteConfirm`,{name:e.displayName??e.id}))&&kt(e.customId),Ae(null)},children:t(`models.customDelete`)})]})]})})()]},e.namespaced)}),T>0&&(0,J.jsx)(`button`,{type:`button`,onClick:()=>h(e=>({...e,[n]:C+60})),className:`btn btn-ghost btn-sm models-show-more`,children:t(`models.showMore`,{n:T})})]})]},n)},Nt=Ge?tt.filter(e=>e.provider===Ge):tt,Pt=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`models-control-top-row`,children:[(0,J.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!Me||void 0,children:[(0,J.jsxs)(`span`,{className:`models-shadow-label`,children:[t(`models.shadowCallIntercept`),` `,(0,J.jsx)(mt,{content:t(`models.shadowCallInterceptHint`,{models:Ft(Me?.sourceModels)}),side:`top`,maxWidth:320,children:(0,J.jsx)(`span`,{style:{cursor:`help`},"aria-label":t(`models.shadowCallInterceptHint`,{models:Ft(Me?.sourceModels)}),children:`ⓘ`})})]}),(0,J.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:t(`models.shadowCallOriginal`,{models:It(Me?.sourceModels)})}),(0,J.jsx)(ut,{on:Me?.enabled??!1,onClick:()=>void yt({enabled:!Me?.enabled}),disabled:!Me||Pe,label:t(`models.shadowCallIntercept`)}),(0,J.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,J.jsx)(ft,{value:Me?.model??``,options:[{value:``,label:`—`},...X],onChange:e=>{Ne(t=>t&&{...t,model:e}),yt({model:e})},disabled:!Me||Pe||!Me.enabled,label:t(`models.shadowCallIntercept`)})})]}),z&&(0,J.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2Label`)}),(0,J.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":t(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(z.multiAgentMode??`default`)===e,className:`btn btn-sm${(z.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(z.multiAgentMode??`default`)===e?void 0:`transparent`,color:(z.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:V,onClick:()=>void bt(e),children:t(`models.v2Mode_${e}`)},e))}),(0,J.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)`},onClick:()=>re(!0),"aria-label":t(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,J.jsx)(ye,{width:14,height:14,"aria-hidden":`true`})})]})]}),z&&(z.enabled||z.agentsMaxThreadsConflict||U)&&(0,J.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[z.enabled&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2ThreadsLabel`)}),(0,J.jsx)(ft,{value:te?`custom`:z.maxConcurrentThreadsPerSession!==null&&z.maxConcurrentThreadsPerSession!==void 0?Ws.has(z.maxConcurrentThreadsPerSession)?String(z.maxConcurrentThreadsPerSession):`custom`:``,options:[...z.maxConcurrentThreadsPerSession===null||z.maxConcurrentThreadsPerSession===void 0?[{value:``,label:t(`models.v2ThreadsDefault`)}]:[],...z.maxConcurrentThreadsPerSession!==null&&z.maxConcurrentThreadsPerSession!==void 0&&!Ws.has(z.maxConcurrentThreadsPerSession)&&!te?[{value:`custom`,label:String(z.maxConcurrentThreadsPerSession)}]:[],...Us.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:t(`models.custom`)}],onChange:e=>St(e),disabled:V,label:t(`models.v2ThreadsLabel`)}),te&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:ee,onChange:e=>K(e.target.value),onKeyDown:e=>{e.key===`Enter`&&xt(Number(ee.replace(/[_,\s]/g,``)))},disabled:V,"aria-label":t(`models.v2ThreadsLabel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:V,onClick:()=>{xt(Number(ee.replace(/[_,\s]/g,``)))},children:t(`models.v2ThreadsApply`)})]})]}),z.enabled&&z.agentsMaxThreadsConflict&&(0,J.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:t(`models.v2Conflict`)}),U&&(0,J.jsx)(`span`,{className:`muted text-label`,children:U})]}),(0,J.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`models.contextCapLabel`)}),(0,J.jsx)(ft,{value:w?Hs:Vs.has(b)?String(b):Hs,options:[...!Vs.has(b)&&!w?[{value:String(b),label:qs(b)}]:[],...Bs.map(e=>({value:String(e),label:qs(e)})),{value:Hs,label:t(`models.custom`)}],onChange:e=>lt(e),disabled:P,label:t(`models.contextCapLabel`)}),w&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:t(`models.customPlaceholder`),value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ht()},disabled:P,"aria-label":t(`models.customPlaceholder`)}),(0,J.jsx)(`button`,{type:`button`,onClick:ht,disabled:P,className:`btn btn-ghost btn-sm`,children:t(`models.customApply`)})]}),(0,J.jsx)(ut,{on:gt,onClick:vt,disabled:P,label:t(`models.setAll`)}),(0,J.jsx)(`span`,{className:`muted text-label leading-body`,children:t(`models.setAllHint`,{value:qs(b)})})]}),(()=>{let e=i.filter(e=>e.custom).length;return e===0?null:(0,J.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:t(`models.customSummary`,{count:e})})})})(),(0,J.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,J.jsx)(ye,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:t(`models.orderHint`)})]})]}),Lt=(0,J.jsxs)(J.Fragment,{children:[Ve===null&&!He&&(0,J.jsx)(`div`,{className:`card models-combos-card`,"aria-busy":`true`,children:(0,J.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,J.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),(0,J.jsx)(`span`,{className:`muted text-label`,children:t(`common.loading`)})]}),(0,J.jsx)(`a`,{className:`btn btn-sm`,href:`#combos`,style:{flexShrink:0,visibility:`hidden`},tabIndex:-1,"aria-hidden":`true`,children:t(`models.combosSetup`)})]})}),Ve===null&&He&&(0,J.jsx)(`div`,{className:`card models-combos-card`,children:(0,J.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,J.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),(0,J.jsx)(`span`,{className:`muted text-label`,role:`alert`,children:t(`models.loadFail`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{flexShrink:0},onClick:()=>ze.refresh(),children:t(`common.retry`)})]})}),Ve!==null&&Ve.length===0&&(0,J.jsx)(`div`,{className:`card models-combos-card`,children:(0,J.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,J.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),He?(0,J.jsx)(`span`,{className:`muted text-label`,role:`alert`,children:t(`models.loadFail`)}):(0,J.jsx)(`span`,{className:`muted text-label`,children:t(`models.combosEmpty`)})]}),He?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{flexShrink:0},onClick:()=>ze.refresh(),children:t(`common.retry`)}):(0,J.jsx)(`a`,{className:`btn btn-sm`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]})}),Ve!==null&&Ve.length>0&&(0,J.jsxs)(`div`,{className:`card models-combos-card`,children:[(0,J.jsxs)(`div`,{className:`row group-head models-field-row${Ue?` open`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`row models-field-row`,"aria-expanded":Ue,onClick:qe,style:{flex:1,background:`none`,border:`none`,padding:0,cursor:`pointer`,font:`inherit`,color:`inherit`,textAlign:`left`,minWidth:0},children:[(0,J.jsx)(we,{style:{width:14,height:14,color:`var(--muted)`,flexShrink:0,transform:Ue?`rotate(90deg)`:`none`,transition:`transform .12s`}}),(0,J.jsx)(Le,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,J.jsx)(`strong`,{children:t(`nav.combos`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.combosActive`,{count:Ve.length})}),He&&(0,J.jsx)(`span`,{className:`muted text-label`,role:`alert`,children:t(`models.loadFail`)})]}),He?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{flexShrink:0},onClick:()=>ze.refresh(),children:t(`common.retry`)}):(0,J.jsx)(`a`,{className:`btn btn-sm btn-ghost`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]}),Ue&&(0,J.jsxs)(`div`,{children:[Ve.map(e=>(0,J.jsxs)(`div`,{className:`row models-combo-row`,children:[(0,J.jsx)(`span`,{className:`mono leading-ui`,children:e.model}),(0,J.jsxs)(`span`,{className:`muted text-label`,children:[e.strategy,` · `,e.targets.length]})]},e.id)),(0,J.jsxs)(`a`,{className:`row muted models-combos-add`,href:`#combos`,children:[`+ `,t(`models.combosAdd`)]})]})]})]}),Rt=(0,J.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ot(!0),disabled:P,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ot(!1),disabled:P,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),zt=(0,J.jsx)(J.Fragment,{children:tt.length===0&&(0,J.jsx)(pt,{icon:(0,J.jsx)(ie,{}),title:t(`models.noRouted`),children:t(`models.noRoutedHint`)})}),Bt=(0,J.jsxs)(J.Fragment,{children:[ne&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.v2Label`),onClick:()=>re(!1),onKeyDown:e=>{e.key===`Escape`&&re(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:t(`models.v2Label`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>re(!1),"aria-label":t(`common.close`),children:`×`})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,J.jsx)(`div`,{className:`models-help-link`,children:(0,J.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,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>re(!1),children:t(`common.ok`)})})]})}),ae&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.customAdd`),onClick:()=>{Te||oe(!1)},onKeyDown:e=>{e.key===`Escape`&&!Te&&oe(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:t(se===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:le})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>oe(!1),disabled:Te,"aria-label":t(`common.close`),children:`×`})]}),De&&(0,J.jsx)(dt,{tone:`err`,children:De}),(0,J.jsxs)(`div`,{className:`models-field-stack`,children:[(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldModelId`),(0,J.jsx)(`input`,{className:`input`,value:pe,onChange:e=>me(e.target.value),disabled:Te,placeholder:t(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldDisplayName`),(0,J.jsx)(`input`,{className:`input`,value:he,onChange:e=>ge(e.target.value),disabled:Te,placeholder:t(`models.customFieldDisplayNamePlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldContext`),(0,J.jsxs)(`div`,{className:`row models-field-row`,children:[(0,J.jsx)(ft,{value:be?`custom`:_e,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:t(`models.custom`)}],onChange:e=>{if(e===`custom`){xe(!0);return}xe(!1),ve(e)},disabled:Te,label:t(`models.customFieldContext`)}),be&&(0,J.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:_e,onChange:e=>ve(e.target.value),disabled:Te,placeholder:t(`models.customPlaceholder`),"aria-label":t(`models.customFieldContext`)})]})]}),(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[t(`models.customFieldModalities`),(0,J.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:Se.includes(e),onChange:t=>{Ce(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Te}),(0,J.jsx)(`span`,{className:`text-control`,children:e})]},e))})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>oe(!1),disabled:Te,children:t(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Te||!pe.trim(),onClick:()=>{let e=pe.trim(),t=he.trim(),n=_e?Number(_e.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;se===`add`?Dt(le,e,t||void 0,r,Se.length>0?Se:void 0):Ot(de,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:Se})},children:t(Te?`models.customSaving`:se===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]});return(0,J.jsxs)(`div`,{className:`models-workspace-shell`,children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.models`)}),(0,J.jsx)(`div`,{className:`row`,children:(0,J.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:nt,total:i.length})})})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`models.subtitle`)}),A&&(0,J.jsx)(dt,{tone:M?`ok`:`err`,children:A}),$e.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`models.loadFail`)}),(0,J.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":$e.refreshing||void 0,children:[(0,J.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":t(`nav.models`),children:[(0,J.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-title`,children:t(`models.workspace.providers`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-count`,children:tt.length})]}),(0,J.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ge===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ke(null),"aria-current":Ge===null?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:t(`models.workspace.allProviders`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:nt,total:i.length})})]}),tt.map(e=>{let{provider:n,rows:r}=e,i=r.filter(e=>Is(jt,n,e.id,e.native===!0,c.has(e.namespaced))).length;return(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ge===n?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ke(n),"aria-current":Ge===n?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:n}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:i,total:r.length})})]},n)})]})]}),(0,J.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":t(`models.workspace.mainAria`),children:[Pt,Lt,Rt,(0,J.jsx)(`div`,{className:`models-provider-list`,children:Nt.map(e=>Mt(e))}),tt.length===0&&zt]})]}),Bt]})}function rc(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function ic(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function ac(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 oc(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||ac(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 sc({value:e,onChange:t,disabled:n}){let r=Z();return(0,J.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:[[`failover`,`cws.strategy.failover`],[`round-robin`,`cws.strategy.roundRobin`]].map(([i,a])=>(0,J.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(a)},i))})}function cc({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Z(),o=i??ns,s=t!==null&&!o.includes(t);return(0,J.jsxs)(J.Fragment,{children:[(0,J.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,J.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,J.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),s?(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function lc({targets:e,strategy:t,providers:n,models:r,onChange:i}){let a=Z(),o=rc(n),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(null),d=(t,n)=>{i(e.map((e,r)=>r===t?{...e,...n}:e))},f=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[a]=r.splice(t,1);r.splice(n,0,a),i(r)};return(0,J.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((p,m)=>{let h=n.find(e=>e.name===p.provider),g=h&&!o.some(e=>e.name===p.provider)?[...o,h]:o,_=oc(r,p.provider,n),v=p.model&&!_.includes(p.model)?[p.model,..._]:_,y=!p.provider;return(0,J.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`?`cwi-target-row--failover`:``,s===m?`cwi-target-row--dragging`:``,l===m&&s!==null&&s!==m?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{s!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,l!==m&&u(m))},onDrop:e=>{e.preventDefault(),s!==null&&f(s,m),c(null),u(null)},onDragEnd:()=>{c(null),u(null)},children:[(0,J.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":a(`cws.target.drag`),title:a(`cws.target.drag`),onDragStart:e=>{c(m),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(m))},children:(0,J.jsx)(Re,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:m===0,"aria-label":a(`cws.target.moveUp`),onClick:()=>f(m,m-1),children:(0,J.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:m===e.length-1,"aria-label":a(`cws.target.moveDown`),onClick:()=>f(m,m+1),children:(0,J.jsx)(Se,{width:14,height:14,"aria-hidden":`true`})})]}),(0,J.jsxs)(`select`,{className:`input`,value:p.provider,"aria-label":a(`cws.target.provider`),onChange:e=>{let t=e.target.value;d(m,{provider:t,model:oc(r,t,n)[0]??``})},children:[(0,J.jsx)(`option`,{value:``,children:a(`cws.target.pickProvider`)}),g.map(e=>(0,J.jsx)(`option`,{value:e.name,children:e.disabled?a(`cws.target.disabled`,{name:e.name}):e.name},e.name))]}),(0,J.jsxs)(`select`,{className:`input`,value:p.model,disabled:y,"aria-label":a(`cws.target.model`),onChange:e=>d(m,{model:e.target.value}),children:[(0,J.jsx)(`option`,{value:``,children:y?a(`cws.target.pickProviderFirst`):v.length===0?a(`cws.target.noModels`):a(`cws.target.pickModel`)}),v.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),t===`round-robin`&&(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:p.weight??1,"aria-label":a(`cws.target.weight`),onChange:e=>{let t=ic(e.target.value,1,1e4);t!==void 0&&d(m,{weight:t})}}),(0,J.jsx)(`div`,{className:`cwi-target-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>i(e.filter((e,t)=>t!==m)),"aria-label":a(`common.remove`),children:(0,J.jsx)(_e,{width:14,height:14})})})]},p.clientKey??`${p.provider}:${p.model}`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>i([...e,as()]),children:[(0,J.jsx)(pe,{width:14,height:14}),` `,a(`cws.target.add`)]})]})}function uc({existingIds:e,existingAliases:t,providerMap:n,providers:r,models:i,onClose:a,onSubmit:o}){let s=Z(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(()=>ws()),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(``),h=(0,_.useMemo)(()=>{let e=new Map;for(let t of i)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[i]),g=(0,_.useMemo)(()=>rs(l.targets,h),[l.targets,h]);(0,_.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let v=(0,_.useCallback)(()=>{d||a()},[d,a]),y=(0,_.useCallback)(e=>{e.preventDefault(),v()},[v]),b=async()=>{let r=Cs(l,{existingIds:e,existingAliases:t,isCreate:!0,providers:n});if(r){m(s(`cws.err.${r}`));return}f(!0),m(``);let i=l.id.trim(),a=l.alias?.trim()||null;try{let e=await o({...l,id:i,alias:a,model:ds(i,a)});if(!e.ok){m(e.error||s(`cws.saveFailed`));return}}finally{f(!1)}};return(0,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:y,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:v}),(0,J.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,J.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:s(`cws.addTitle`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:d,"aria-label":s(`common.close`),children:(0,J.jsx)(fe,{width:16,height:16})})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:s(`cws.addSubtitle`)}),p&&(0,J.jsx)(dt,{tone:`err`,children:p}),(0,J.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-id`,children:s(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:l.id,disabled:d,onChange:e=>u(t=>({...t,id:e.target.value,model:ds(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idInternalHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:s(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:l.alias??``,placeholder:s(`cws.field.aliasPlaceholder`),disabled:d,onChange:e=>u(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:ds(t.id,e.target.value)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.aliasHint`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idHint`,{model:l.id.trim()?ds(l.id,l.alias):`…`})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:s(`cws.strategy`)}),(0,J.jsx)(sc,{value:l.strategy,disabled:d,onChange:e=>u(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:l.strategy===`failover`?s(`cws.strategy.failoverHint`):s(`cws.strategy.roundRobinHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:s(`cws.field.defaultEffort`)}),(0,J.jsx)(cc,{id:`cwi-new-effort`,value:l.defaultEffort,disabled:d,allowedEfforts:g,onChange:e=>u(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.defaultEffortHint`)})]}),l.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:s(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:l.stickyLimit,disabled:d,onChange:e=>{let t=ic(e.target.value,1,100);t!==void 0&&u(e=>({...e,stickyLimit:t}))}}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.stickyLimitHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:s(`cws.targets`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:l.strategy===`failover`?s(`cws.targets.failoverHint`):s(`cws.targets.roundRobinHint`)}),(0,J.jsx)(lc,{targets:l.targets,strategy:l.strategy,providers:r,models:i,onChange:e=>u(t=>({...t,targets:e}))})]})]}),(0,J.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,disabled:d,children:s(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{b()},disabled:d,children:s(d?`common.saving`:`cws.create`)})]})]})]})}function dc({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providers:a,models:o,onBack:s,onSaved:c,onRequestRemove:l,onSave:u,onDirtyChange:d}){let f=Z(),[p,m]=(0,_.useState)(`config`),[h,g]=(0,_.useState)(e),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(!1),w=!xs(h,e),T=`${e.id}:${e.alias??``}:${e.strategy}:${e.stickyLimit}:${e.defaultEffort}:${e.targets.map(e=>`${e.provider}/${e.model}:${e.weight??1}`).join(`,`)}`,E=(0,_.useMemo)(()=>{let e=new Map;for(let t of o)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[o]),D=(0,_.useMemo)(()=>rs(h.targets,E),[h.targets,E]),O=(0,_.useCallback)(t=>{let n=t(h);g(n),d(!xs(n,e))},[h,e,d]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{g(e),x(null),m(`config`),d(!1)},0);return()=>window.clearTimeout(t)},[T]);let k=async()=>{try{await navigator.clipboard.writeText(e.model),C(!0),window.setTimeout(()=>C(!1),1200)}catch{}},A=async()=>{let a=Cs(h,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){x({ok:!1,text:f(`cws.err.${a}`)});return}y(!0);let o=h.id.trim(),s=h.alias?.trim()||null,l={...h,id:o,alias:s,model:ds(o,s)},d=!t&&o!==e.id?e.id:void 0;try{let e=await u(l,t,d);if(!e.ok){x({ok:!1,text:e.error||f(`cws.saveFailed`)});return}x({ok:!0,text:t?f(`cws.created`,{model:l.model}):f(`cws.saved`)}),c(l)}finally{y(!1)}},j=t?h.id.trim()?ds(h.id,h.alias):f(`cws.addTitle`):e.model;return(0,J.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[s&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:s,"aria-label":f(`cws.backToAll`),children:[(0,J.jsx)(we,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),f(`cws.allCombos`)]}),(0,J.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:j}),!t&&(0,J.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{k()},title:f(`cws.copyModel`),children:f(S?`cws.copied`:`cws.copyModel`)}),(0,J.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&l&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,J.jsx)(_e,{width:14,height:14}),` `,f(`common.remove`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!w||v,onClick:()=>{A()},children:f(v?`common.saving`:t?`cws.create`:`common.save`)})]})]}),b&&(0,J.jsx)(dt,{tone:b.ok?`ok`:`err`,children:b.text}),(0,J.jsxs)(`div`,{className:`combos-workspace-tabs`,role:`tablist`,children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":p===`config`,className:`combos-workspace-tab${p===`config`?` combos-workspace-tab--active`:``}`,onClick:()=>m(`config`),children:f(`cws.tab.config`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":p===`about`,className:`combos-workspace-tab${p===`about`?` combos-workspace-tab--active`:``}`,onClick:()=>m(`about`),children:f(`cws.tab.about`)})]}),(0,J.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,children:p===`config`?(0,J.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:f(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:h.id,disabled:v,onChange:e=>O(t=>({...t,id:e.target.value,model:ds(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:t?f(`cws.field.idInternalHint`):f(`cws.field.idHintEdit`,{model:ds(h.id,h.alias)})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:f(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:h.alias??``,placeholder:us(h.id.trim()||`…`),disabled:v,onChange:e=>O(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:ds(t.id,e.target.value)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.aliasHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,J.jsx)(sc,{value:h.strategy,disabled:v,onChange:e=>O(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:h.strategy===`failover`?f(`cws.strategy.failoverHint`):f(`cws.strategy.roundRobinHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-effort`,children:f(`cws.field.defaultEffort`)}),(0,J.jsx)(cc,{id:`cwi-effort`,value:h.defaultEffort,disabled:v,allowedEfforts:D,onChange:e=>O(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),h.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-sticky`,children:f(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:h.stickyLimit,disabled:v,onChange:e=>{let t=ic(e.target.value,1,100);t!==void 0&&O(e=>({...e,stickyLimit:t}))}})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:h.strategy===`failover`?f(`cws.targets.failoverHint`):f(`cws.targets.roundRobinHint`)}),(0,J.jsx)(lc,{targets:h.targets,strategy:h.strategy,providers:a,models:o,onChange:e=>O(t=>({...t,targets:e}))})]})]}):(0,J.jsxs)(`section`,{className:`pwi-section`,children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:f(`cws.aboutTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0},children:f(`cws.aboutBody`)})]})})]})}function fc({model:e,onCancel:t,onConfirm:n}){let r=Z(),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,J.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,J.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function pc({onKeep:e,onDiscard:t}){let n=Z(),r=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]),(0,J.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,J.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,J.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function mc(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:`cws.attention.few`)}function hc({combos:e,cataloguedComboIds:t,onSelect:n,onAdd:r}){let i=Z(),a=vs(e),o=bs(e,{cataloguedComboIds:t});return(0,J.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,J.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:i(`cws.overviewTitle`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,children:[(0,J.jsx)(pe,{width:14,height:14}),` `,i(`cws.add`)]})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:i(`cws.overviewBlurb`)}),(0,J.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:e.length}),(0,J.jsx)(`span`,{children:i(`cws.count.total`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:a.failover.length}),(0,J.jsx)(`span`,{children:i(`cws.count.failover`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:a.roundRobin.length}),(0,J.jsx)(`span`,{children:i(`cws.count.roundRobin`)})]})]}),(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.howTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.howTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0},children:i(`cws.howBody`)})]}),o.length>0&&(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.attentionTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.attentionTitle`)}),(0,J.jsx)(`div`,{className:`cwi-attention-list`,children:o.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>n(e.id),children:[(0,J.jsx)(ve,{width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`code`,{className:`chip`,children:e.model}),(0,J.jsx)(`span`,{className:`muted`,children:mc(e.reason,i)}),(0,J.jsx)(we,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function gc({combos:e,providers:t,models:n,cataloguedComboIds:r,loading:i,onRefresh:a,onSave:o,onRemove:s,onAdd:c,adding:l,onCloseAdd:u,onCreated:d}){let f=Z(),p=(0,_.useMemo)(()=>Object.fromEntries(t.map(e=>[e.name,{disabled:e.disabled}])),[t]),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(void 0),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),T=(0,_.useMemo)(()=>ws(),[]),E=(0,_.useMemo)(()=>ys(e,m),[e,m]),D=(0,_.useMemo)(()=>vs(E),[E]),O=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),k=g&&e.some(e=>e.id===g)?g:null,A=e.find(e=>e.id===k)??null,j=A&&C?.id===A.id?C:A,[M,N]=(0,_.useState)(!1),P=[],F=[];if(j)for(let t of e)t.id!==j.id&&(P.push(t.id),t.alias&&F.push(t.alias));let I=(0,_.useCallback)(e=>{if(e!==k){if(!M){v(e),w(null);return}b(e)}},[k,M]),L=()=>{y!==void 0&&(v(y),w(null),N(!1),b(void 0))},R=()=>b(void 0),z=y!==void 0&&M,B=!i&&e.length===0;return(0,J.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":f(`cws.railAria`),children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`combos-workspace-rail-title`,children:f(`nav.combos`)}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(B){document.getElementById(`cwi-edit-id`)?.focus();return}c()},"aria-label":f(`cws.add`),children:[(0,J.jsx)(pe,{width:14,height:14}),` `,f(`cws.add`)]})]}),(0,J.jsx)(`div`,{className:`cwi-search-row`,children:(0,J.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,J.jsx)(be,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,J.jsx)(`input`,{className:`input cwi-search-input`,value:m,onChange:e=>h(e.target.value),placeholder:f(`cws.searchPlaceholder`),"aria-label":f(`cws.searchPlaceholder`)})]})}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-list`,children:E.length===0&&e.length>0?(0,J.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:f(`cws.noSearchResults`)}):(0,J.jsx)(J.Fragment,{children:[[`failover`,D.failover,`cws.group.failover`],[`round-robin`,D.roundRobin,`cws.group.roundRobin`]].map(([e,t,n])=>t.length>0?(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,J.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),f(n),(0,J.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${k===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>I(e.id),"aria-current":k===e.id?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,J.jsx)(Le,{width:16,height:16})}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?f(`cws.targetCountOne`):f(`cws.targetCount`,{count:e.targets.length})}),(0,J.jsx)(we,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,J.jsx)(`div`,{className:`combos-workspace-main`,children:j?(0,J.jsx)(dc,{baseline:j,otherIds:P,otherAliases:F,providerMap:p,providers:t,models:n,onBack:()=>I(null),onSaved:e=>{N(!1),e.id===j.id?w(e):(v(e.id),w(null)),a()},onRequestRemove:()=>S(j.id),onSave:o,onDirtyChange:N},j.id):B?(0,J.jsx)(dc,{baseline:T,isCreate:!0,otherIds:[],otherAliases:[],providerMap:p,providers:t,models:n,onSaved:e=>{N(!1),v(e.id),w(e),d(e.id)},onSave:o,onDirtyChange:N},`first-combo`):(0,J.jsx)(hc,{combos:e,cataloguedComboIds:r,onSelect:e=>I(e),onAdd:c})}),l&&!B&&(0,J.jsx)(uc,{existingIds:e.map(e=>e.id),existingAliases:O,providerMap:p,providers:t,models:n,onClose:u,onSubmit:async e=>{let t=await o(e,!0);return t.ok&&(u(),d(e.id),v(e.id),w(null)),t}}),x&&(0,J.jsx)(fc,{model:e.find(e=>e.id===x)?.model??us(x),onCancel:()=>S(null),onConfirm:()=>{(async()=>{let e=await s(x);S(null),e.ok&&(k===x&&(v(null),w(null)),a())})()}}),z&&(0,J.jsx)(pc,{onKeep:R,onDiscard:L})]})}function _c(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function vc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function yc(e){return vn(e)}function bc({apiBase:e}){let t=Z(),n=`ocx.combos.workspace.v1:${e}`,r=yc(n),[i,a]=(0,_.useState)(``),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),u=(e,t)=>{a(e),s(t)};(0,_.useEffect)(()=>{if(!i||!o)return;let e=window.setTimeout(()=>{a(``),s(!1)},5e3);return()=>window.clearTimeout(e)},[i,o]);let d=(0,_.useCallback)(async()=>{let[t,r,i]=await Promise.all([fetch(`${e}/api/combos`),fetch(`${e}/api/config`),fetch(`${e}/api/models`)]);if(!t.ok||!r.ok||!i.ok)throw Error(`combo workspace load failed`);let a=await t.json(),o=await r.json(),s=await i.json(),c=Array.isArray(s)?s:Array.isArray(s?.models)?s.models:[],l=_s(a),u=o.providers??{},d=sr(u),f=Object.entries(u).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:!Object.hasOwn(d,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl})),p=[],m=new Set;for(let e of c){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`){m.add(r);continue}if(t.disabled===!0)continue;let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0;p.push({provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{}})}for(let[e,t]of Object.entries(u)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;!n||t.disabled||p.some(t=>t.provider===e&&t.id===n)||p.push({provider:e,id:n,namespaced:`${e}/${n}`})}let h={combos:l,providers:f,models:p,cataloguedComboIds:[...m]};return yn(n,h),h},[e,n]),f=Es(n,[e],d,{isEmpty:()=>!1}),{state:p}=f,m=p.data??r,h=m?.combos??[],g=m?.providers??[],v=m?.models??[],y=new Set(m?.cataloguedComboIds??[]);return p.showSkeleton&&!m?(0,J.jsx)(Os,{label:t(`cws.loading`),rows:5}):p.kind===`failed-cold`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:p.error instanceof Error?p.error.message:t(`cws.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,J.jsxs)(`div`,{className:`combos-workspace-shell`,children:[i&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)(dt,{tone:o?`ok`:`err`,children:i})}),p.showError&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)(dt,{tone:`err`,children:t(`cws.loadFailed`)})}),p.refreshing&&(0,J.jsx)(ks,{live:!p.showError,children:t(`cws.loading`)}),(0,J.jsx)(`div`,{className:`combos-workspace-shell-body`,children:(0,J.jsx)(gc,{combos:h,providers:g,models:v,cataloguedComboIds:y,loading:!1,onRefresh:()=>f.refresh(),onSave:async(n,r,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(Ss(n,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=_c(o);if(!a.ok||s||!vc(o)){let e=s||t(`cws.saveFailed`);return u(e,!1),{ok:!1,error:e}}return f.refresh(),u(i?t(`cws.renamed`,{from:us(i),to:n.model}):r?t(`cws.created`,{model:n.model}):t(`cws.saved`),!0),{ok:!0}}catch{let e=t(`cws.saveFailed`);return u(e,!1),{ok:!1,error:e}}},onRemove:async n=>{try{let r=await fetch(`${e}/api/combos?id=${encodeURIComponent(n)}`,{method:`DELETE`}),i=r.ok?await r.json():await r.json().catch(()=>null),a=_c(i);if(!r.ok||a||!vc(i)){let e=a||t(`cws.removeFailed`);return u(e,!1),{ok:!1,error:e}}return f.refresh(),u(t(`cws.removed`,{id:n}),!0),{ok:!0}}catch{let e=t(`cws.removeFailed`);return u(e,!1),{ok:!1,error:e}}},onAdd:()=>l(!0),adding:c,onCloseAdd:()=>l(!1),onCreated:()=>f.refresh()})})]})}var xc=`section`;function Sc(e,t){return[e,xc,t].join(`-`)}function Cc(e){return[e,xc,``].join(`-`)}var wc=1200;function Tc({scope:e,items:t,ariaLabel:n}){let[r,i]=(0,_.useState)(t[0]?.id??``),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useCallback)(()=>{a.current=null,o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),c=(0,_.useCallback)(()=>{s();let n=null,r=1/0;for(let i of t){let t=document.getElementById(Sc(e,i.id));if(!t)continue;let a=Math.abs(t.getBoundingClientRect().top-72);a<r&&(r=a,n=i.id)}n&&i(n)},[s,t,e]);(0,_.useEffect)(()=>()=>s(),[s]),(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(Sc(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=a.current;if(n){let r=document.getElementById(Sc(e,n));t.some(e=>e.isIntersecting&&e.target===r)&&(s(),i(n));return}let r=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!r)return;let o=r.target.id.slice(Cc(e).length);i(e=>e===o?e:o)},{rootMargin:`-72px 0px -60% 0px`,threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[s,t,e]);let l=t=>{let n=document.getElementById(Sc(e,t));n&&(a.current=t,o.current!==null&&clearTimeout(o.current),o.current=setTimeout(c,wc),i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,J.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,J.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":Sc(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>l(t.id),children:[t.label,t.meta?(0,J.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function Ec({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s}){let c=Z();return(0,J.jsxs)(`div`,{className:`swi-delegation`,children:[(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:c(`sub.delegation.model`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:c(`sub.delegation.modelHint`)})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,J.jsx)(ft,{value:e,options:[{value:``,label:c(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:`${e.provider} / ${e.model}`}))],onChange:e=>s({model:e||null,effort:t||null}),disabled:o,label:c(`dash.injectionLabel`)}),e&&n.length>0&&(0,J.jsx)(ft,{value:t,options:[{value:``,label:c(`dash.injectionEffortNone`)},...n.map(e=>({value:e,label:e}))],onChange:t=>s({model:e||null,effort:t||null}),disabled:o,label:c(`dash.injectionEffortLabel`)})]})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:c(`dash.syncCodexSubagentDefaults`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>s({syncCodexSubagentDefaults:!a}),disabled:o||!e,"aria-label":c(`dash.syncCodexSubagentDefaults`),"aria-pressed":a,children:(0,J.jsx)(`span`,{className:`knob`})})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:c(`dash.multiAgentGuidance`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.multiAgentGuidanceHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":c(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,J.jsx)(`span`,{className:`knob`})})]})]})}function Dc({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=Z(),[c,l]=(0,_.useState)(``),u=(0,_.useMemo)(()=>new Set(t),[t]),d=t.length>=5,f=(0,_.useMemo)(()=>{let t=c.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,c]);return(0,J.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,J.jsx)(Tc,{scope:`subagents`,items:(0,_.useMemo)(()=>[{id:`featured`,label:s(`sub.featured`),meta:`${t.length}/5`},{id:`models`,label:s(`sub.models`),meta:String(f.length)},{id:`settings`,label:s(`sub.settings`)}],[s,t.length,f.length]),ariaLabel:s(`sub.sections`)}),(0,J.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,J.jsxs)(`section`,{id:Sc(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,J.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,J.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,J.jsx)(ye,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:(0,J.jsx)(Ye,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,J.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,J.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,J.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,J.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,J.jsx)(`span`,{className:`swi-featured-name`,children:ts(e)}),(0,J.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,-1),disabled:n||a===0,"aria-label":s(`sub.moveUp`,{m:e}),children:(0,J.jsx)(xe,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,1),disabled:n||a===t.length-1,"aria-label":s(`sub.moveDown`,{m:e}),children:(0,J.jsx)(Se,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>r(e),disabled:n,"aria-label":s(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,J.jsx)(fe,{})})]})]},e))}),(0,J.jsx)(`div`,{className:`swi-save-row`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,J.jsxs)(`section`,{id:Sc(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,J.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,J.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,J.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,J.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,J.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,J.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:s(`sub.noModels`)}):f.map(e=>{let i=u.has(e),a=i?t.indexOf(e)+1:null,o=!i&&(d||n);return(0,J.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,J.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,J.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,J.jsx)(ae,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:ts(e)})]}),(0,J.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${i?` subagents-workspace-rail-toggle--on`:``}${o?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{o||r(e)},disabled:o,"aria-pressed":i,"aria-label":s(i?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:i?s(`sub.workspace.removeFromFeatured`,{m:e}):d?s(`sub.workspace.featuredFull`):s(`sub.workspace.addToFeatured`,{m:e}),children:i?(0,J.jsx)(de,{style:{width:14,height:14}}):(0,J.jsx)(pe,{style:{width:14,height:14}})})]},e)})})]})]}),(0,J.jsxs)(`section`,{id:Sc(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,J.jsx)(`div`,{className:`swi-featured-head`,children:(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,J.jsx)(Ec,{model:o.model,effort:o.effort,efforts:o.efforts,available:o.available,guidanceEnabled:o.guidanceEnabled,syncCodexDefaults:o.syncCodexDefaults,saving:o.saving,onSave:o.onSave})]})]})]})}function Oc(e){let[t,n]=(0,_.useState)(!1),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)([]),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useCallback)(e=>{let t=On(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,_.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await St(await fetch(`${e}/api/injection-model`));if(t)return;v(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,v]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,_.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`);v(await St(await fetch(`${e}/api/injection-model`)))}catch{}finally{i(!1)}}},[e,v,r])}}function kc(e){return vn(e)}function Ac({apiBase:e}){let t=Z(),n=`ocx.subagents.v1:${e}`,r=kc(n),[i,a]=(0,_.useState)(()=>r?.chosen??[]),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),f=(0,_.useRef)(!1),p=Oc(e),m=(0,_.useCallback)(async r=>{let i=await Q(await fetch(`${e}/api/subagent-models`,{signal:r}),t(`sub.loadFail`));if(!i)throw Error(t(`sub.loadFail`));let o=i.available??[],s=new Set(o),c={available:o,chosen:(i.chosen??[]).filter(e=>s.has(e))};return a(c.chosen),yn(n,c),c},[e,n,t]),h=Es(n,[e],m,{isEmpty:()=>!1,initialData:r??void 0}),{state:g}=h,v=h.refresh,y=g.data??r,b=y?.available??[],x=e=>{u||(s(``),a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e]))},S=(e,t)=>{u||a(n=>{let r=[...n],i=e+t;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)})},C=async()=>{if(!(u||f.current)){f.current=!0,d(!0),s(``);try{let r=await Q(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:i})}),t(`sub.saveFailed`)),o=r?.applied??i;r?.applied&&a(r.applied),yn(n,{available:b,chosen:o}),l(!0),s(t(`sub.saved`,{n:o.length,cmd:`ocx sync`}))}catch(e){l(!1),s(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{f.current=!1,d(!1)}}};return g.showSkeleton&&!y?(0,J.jsx)(Os,{label:t(`sub.loading`),rows:4}):g.kind===`failed-cold`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:g.error instanceof Error?g.error.message:t(`sub.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,J.jsx)(dt,{tone:c?`ok`:`err`,children:o}),g.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`sub.loadFail`)}),(0,J.jsx)(Dc,{available:b,chosen:i,busy:u,onToggle:x,onMove:S,onSave:()=>{C()},delegation:{model:p.model,effort:p.effort,efforts:p.efforts,available:p.available,guidanceEnabled:p.guidanceEnabled,syncCodexDefaults:p.syncCodexDefaults,saving:p.saving,onSave:e=>{p.save(e)}}})]})}function jc(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 Mc(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 Nc(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Pc=(e,t)=>Math.abs(e-t)<1.01,Fc=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Ic,Lc=()=>{if(Ic!==void 0)return Ic;if(typeof navigator>`u`)return Ic=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Ic=!0;let e=navigator.maxTouchPoints;return Ic=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Rc=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},zc=e=>e,Bc=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},Vc=(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(Rc(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(Rc(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Hc={passive:!0},Uc=typeof window>`u`?!0:`onscrollend`in window,Wc=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Uc,o=0,s=a?null:Fc(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,Hc),a&&r.addEventListener(`scrollend`,u,Hc),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Gc=(e,t)=>Wc(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Kc=(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`]},qc=(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})},Jc=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:zc,rangeExtractor:Bc,onChange:()=>{},measureElement:Kc,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=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=Mc(()=>(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.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.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=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,!(!Lc()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Hc),e.addEventListener(`touchend`,n,Hc),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&&(Lc()&&(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;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.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=Mc(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(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}),{key:!1}),this.getMeasurements=Mc(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=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 l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=jc(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Mc(()=>[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=Mc(()=>{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=t-(this.itemSizeCache.get(i)??n);if(o!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,s=a?this.getTotalSize():0,c=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(i)||this.scrollDirection!==`backward`):this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,a?this.applyScrollAdjustment(this.getTotalSize()-s):c&&this.applyScrollAdjustment(o),this.notify(!1)}},this.getVirtualItems=Mc(()=>[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 Nc(t[Yc(0,t.length-1,r?e=>n[e*2]:e=>Nc(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`}={})=>{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`}={})=>{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){e!==0&&(Lc()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=e:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=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&&Pc(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()}},Yc=(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 Xc(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=Xc(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=Yc(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 Qc=typeof document<`u`?_.useLayoutEffect:_.useEffect;function $c({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=_.useReducer(e=>e+1,0)[1],a=_.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`}let r=!!e.options.horizontal,i=t.mode===`transform`,o=r?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let n of c){let a=n.start-s,c=e.elementsCache.get(n.key);c&&t.lastPositions.get(c)!==a&&(t.lastPositions.set(c,a),i?c.style.transform=r?`translate3d(${a}px, 0, 0)`:`translate3d(0, ${a}px, 0)`:c.style[o]=`${a}px`)}},s={...r,onChange:(t,n)=>{var s;let c=a.current,l=!0;if(c.enabled){o(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,$e.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[c]=_.useState(()=>{let e=new Jc(s);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 c.setOptions(s),Qc(()=>c._didMount(),[]),Qc(()=>c._willUpdate()),Qc(()=>{o(c)}),c}function el(e){return $c({observeElementRect:Vc,observeElementOffset:Gc,scrollToFn:qc,...e})}var tl=32;function nl(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function rl(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}async function il(e){let t=e.trim();if(t&&!rl(t)&&!(t.length>4096))return nl(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,tl)}function al(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r?!0:n!==void 0&&e===n:!1}var ol={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{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 本文を確認してください。`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{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 が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`}},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.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{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:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`}},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.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다.`},zh:{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 キーが不正とは限りません。`}},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.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{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 プロバイダー設定を確認してください。`}},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.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{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:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`}},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.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{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:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`}},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.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{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:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`}},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.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{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:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`}},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.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{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 がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`}},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.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{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:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`}},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.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{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 がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{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 回再試行し、繰り返す場合はプロキシログを確認してください。`}},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.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{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:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{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:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`}},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.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{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:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{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:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`}}},sl={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{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:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`}},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.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{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 または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`}}};function cl(e){return e===`de`||e===`ko`||e===`zh`||e===`ru`||e===`ja`?e:`en`}function ll(e,t){if(e<400)return null;let n=cl(t);return(ol[Math.trunc(e)]??(e<500?sl.client:sl.server))[n]}var ul=[`provider`,`usage`,`injection`];function dl(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function fl(e){return new Date(e).toLocaleTimeString()}function pl(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function ml(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function hl({entries:e}){let{t}=X();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,J.jsx)(`div`,{style:{overflowX:`auto`},children:(0,J.jsxs)(`table`,{className:`table text-label`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,J.jsx)(`th`,{children:`thinking`}),(0,J.jsx)(`th`,{children:`effort`}),(0,J.jsx)(`th`,{children:`beta`}),(0,J.jsx)(`th`,{children:`metadata`}),(0,J.jsx)(`th`,{children:`system`})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted mono`,children:fl(e.at)}),(0,J.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,J.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,J.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,J.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,J.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,J.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,J.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function gl({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=X();return e?n?r.length===0?(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,J.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,J.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,J.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${dl(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function _l({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=X();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=ml(e,n);return(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,J.jsx)(ut,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,J.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:i,children:o(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,J.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function vl({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=X();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,J.jsx)(`h2`,{children:o(`debug.title`)}),(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,J.jsx)(me,{}),` `,o(`debug.refresh`)]}),(0,J.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function yl(e){return`debug-settings:${e}`}function bl({apiBase:e,embedded:t,active:n=!0}){let{t:r}=X(),i=`ocx.debug.settings.v1:${e}`,a=vn(i),o=yl(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(`provider`),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useRef)(0),b=(0,_.useRef)(0),x=(0,_.useRef)(0),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),T=Es(o,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return yn(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),E=T.state,D=T.data??a??null,O=K(`debug-claude-inbound:${e}`,[e,D?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:n&&!!D?.claude}).data??[],k=el({count:d.length,getScrollElement:()=>C.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),A=(0,_.useCallback)(e=>pl(D,e),[D]);(0,_.useEffect)(()=>{if(!D||A(l))return;let e=ul.find(A);if(!e)return;let t=window.setTimeout(()=>u(e),0);return()=>window.clearTimeout(t)},[D,l,A]);let j=A(l),M=l===`provider`?`${e}/api/debug/logs`:l===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,N=(0,_.useCallback)(async(e,t)=>{let n=++x.current;if(!j){n===x.current&&(f([]),v.current=0);return}g(!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!==x.current)return;let a=await i.json();if(t?.aborted||n!==x.current||a.length===0)return;f(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===x.current&&g(!1)}},[M,j]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${l}:${j}`,r=w.current!==t;if(w.current=t,!r&&d.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&f([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),x.current+=1,i.abort()}},[n,e,l,j]);let P=(0,_.useRef)(!1),F=(0,_.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let e=y(1e4);N(!1,e.signal).finally(()=>{e.clear(),P.current=!1})});(0,_.useEffect)(()=>{if(!(!n||!p||!j))return Jt(()=>F(),1e3)},[n,p,j]),(0,_.useEffect)(()=>{p&&d.length>0&&k.scrollToIndex(d.length-1,{align:`end`})},[d,p,k]);let I=async t=>{let n=++b.current;c(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let a=await r.json();if(n!==b.current)return;yn(i,a),q(o,a)}catch{}},a=(S.current??Promise.resolve()).then(r,r);S.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===b.current&&c(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(vl,{embedded:t,refreshing:h,streamEnabled:j,follow:p,onRefresh:()=>void N(!0),onFollowChange:m}),!D&&E.showError?(0,J.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,J.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>T.refresh(),children:r(`common.retry`)})]}):E.showSkeleton&&!D?(0,J.jsx)(Os,{label:r(`debug.loading`),rows:3}):D?(0,J.jsx)(_l,{debug:D,debugBusy:s,stream:l,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()},onStreamChange:u}):null,D&&E.showError&&(0,J.jsx)(dt,{tone:`err`,children:r(`debug.loadFailed`)}),D?.claude&&(0,J.jsx)(hl,{entries:O}),(0,J.jsx)(gl,{debug:!!D,stream:l,streamEnabled:j,entries:d,scrollContainerRef:C,lineVirtualizer:k})]})}function xl(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function Sl(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function Cl(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),Sl(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),Sl(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function wl(e){return e.requestedSpeedLabel||void 0}function Tl(e,t){return t===`all`?!0:t===`claude`?e.surface===`claude`||e.surface===`claude-desktop`:t===`grok`?e.surface===`grok`:e.surface===void 0}function El(e){return`ocx.logs.list.v1:${e}`}function Dl(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`)return null;return e}function Ol(e){return e===`cursor`||e.startsWith(`cursor-`)}function kl(e,t){if(!e.usage)return;let n=Ml(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(Ol(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function Al(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 jl(e){let t=Al(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function Ml(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 Nl(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 Pl(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function Fl(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}`}function Il(e,t){if(!e||e.kind===`unavailable`||!Number.isFinite(e.estimate.cost.total)||e.estimate.cost.total<0)return`—`;let n=e.estimate.cost.total;return`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(n)}`}function Ll(e,t){return!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var Rl=3,zl={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`},Bl={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`};function Vl(e){return zl[e]}function Hl(e){return Bl[e]}function Ul(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function Wl(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Gl(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 Kl(e,t,n){let{date:r,time:i}=Gl(e,t,n);return`${r} ${i}`}function ql(e){return[`model=${e.model}`,e.resolvedModel?`resolved=${e.resolvedModel}`:void 0,e.requestedServiceTier?`requestedTier=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`configuredTier=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`responseTier=${e.responseServiceTier}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`supportsTier=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function Jl(e){let t=0,n=0,r=0,i=0;for(let a of e){let e=Al(a);if(e!==void 0&&(t+=e),a.usageStatus===`unsupported`){i+=1;continue}let o=a.displayMetrics?.cost,s=o?.kind===`value`?o.estimate.cost.total:void 0;if(s!==void 0&&Number.isFinite(s)&&s>=0){n+=s;continue}r+=1}return{requests:e.length,totalTokens:t,estimatedCostUsd:n,unpricedRequests:r,unmeteredRequests:i}}function Yl({apiBase:e}){let{t,locale:n}=X(),r=El(e),i=Dl(vn(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(`all`),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(),v=(0,_.useRef)(null),y=Ue.find(e=>e.code===n)?.htmlLang,[b,x]=(0,_.useState)();(0,_.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()&&x(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[S,C]=(0,_.useState)(xl),[w,T]=(0,_.useState)(()=>xl()===`debug`);(0,_.useEffect)(()=>{let e=()=>C(xl());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{S===`debug`&&T(!0)},[S]);let E=Sl,D=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/logs?limit=2000`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let i=await n.json(),a=Array.isArray(i)?i:i.logs??[];return yn(r,a),a},[e,r]),O=Es(r,[e],D,{isEmpty:e=>e.length===0,enabled:S===`logs`,pollMs:a?2e3:void 0,initialData:i??void 0}),k=O.state,A=k.data??i??[],j=O.refresh,M=!O.refreshing&&k.showError,N=!O.refreshing&&!k.showError&&k.data!==void 0,[P,F]=(0,_.useState)({error:null,count:0});N&&P.count!==0?F({error:null,count:0}):M&&P.error!==k.error&&F(e=>({error:k.error,count:e.count+1}));let I=P.count>=Rl||!a&&M,L=s?ll(s.status,n):null,R=p.trim();(0,_.useEffect)(()=>{let e=!1;if(!R){g(void 0);return}return il(R).then(t=>{e||g(t)}),()=>{e=!0}},[R]);let z=A.filter(e=>Tl(e,l)&&(!d||!!e.shadowCallRewrittenFrom)&&(!R||al(e.conversationId,R,h))),B=R?Jl(z):null,V=el({count:z.length,getScrollElement:()=>v.current,estimateSize:()=>44,overscan:15}),H=V.getVirtualItems(),U=H.length>0?H[0].start:0,W=H.length>0?V.getTotalSize()-H[H.length-1].end:0;return(0,J.jsxs)(`div`,{className:`logs-page`,children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.logs`)}),S===`logs`&&(0,J.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,J.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":S===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:S===`logs`?0:-1,className:`page-tab${S===`logs`?` page-tab--active`:``}`,onClick:()=>E(`logs`),onKeyDown:Cl,children:t(`logs.tabLogs`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":S===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:S===`debug`?0:-1,className:`page-tab${S===`debug`?` page-tab--active`:``}`,onClick:()=>E(`debug`),onKeyDown:Cl,children:t(`logs.tabDebug`)})]}),w&&(0,J.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:S!==`debug`,children:(0,J.jsx)(bl,{apiBase:e,embedded:!0,active:S===`debug`})}),(0,J.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:S!==`logs`,children:[(0,J.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,J.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,J.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm${l===e?` btn-primary`:` btn-ghost`}`,style:{background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},onClick:()=>u(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),t(`logs.filter.interceptedHelpersOnly`)]}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,J.jsx)(`input`,{type:`search`,className:`input mono`,value:p,onChange:e=>m(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),R&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>m(``),children:t(`logs.filter.conversation.clear`)})]}),B&&(0,J.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,J.jsxs)(dt,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:B.requests,tokens:Vt(B.totalTokens,y??n),cost:Ll(B.estimatedCostUsd,y)}),` `,(0,J.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),B.unpricedRequests+B.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:B.unpricedRequests,unmetered:B.unmeteredRequests})}`:``]})]})}),k.kind===`failed-cold`&&(0,J.jsxs)(dt,{tone:`err`,children:[k.error instanceof Error?`${t(`logs.loadError`)} ${k.error.message}`:t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j({forceLoading:!0}),disabled:k.refreshing,children:t(`common.retry`)})]}),I&&A.length>0&&(0,J.jsxs)(dt,{tone:`err`,children:[t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j({forceLoading:!0}),disabled:O.refreshing,children:t(`common.retry`)})]}),k.kind===`failed-cold`?null:k.showSkeleton&&A.length===0?(0,J.jsx)(Os,{label:t(`common.loading`),rows:6}):z.length===0?(0,J.jsx)(pt,{title:t(`logs.noRequests`)}):(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{ref:v,className:`tbl-wrap logs-table-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`logs.col.time`)}),(0,J.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,J.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,J.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,J.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,J.jsx)(`th`,{children:t(`logs.col.status`)}),(0,J.jsx)(`th`,{children:t(`logs.col.request`)}),(0,J.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)})]})}),(0,J.jsxs)(`tbody`,{children:[U>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:9,className:`logs-virtual-spacer`,style:{height:U}})}),H.map(e=>{let r=z[z.length-1-e.index],i=Pl(r),a=Gl(r.timestamp,y,b);return(0,J.jsxs)(`tr`,{"data-index":e.index,ref:V.measureElement,children:[(0,J.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:a.date}),(0,J.jsx)(`span`,{children:a.time})]})}),(0,J.jsx)(`td`,{className:`num mono log-col-tokens`,title:kl(r,t),children:(()=>{let e=jl(r),{read:i,write:a}=Ml(r);return e===void 0?(0,J.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,J.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,J.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Vt(e,n)]}),i!==void 0&&i>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Vt(i,n)]}),a!==void 0&&a>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Vt(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(Ol(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,J.jsx)(`td`,{className:`num mono log-col-cost`,children:Il(r.displayMetrics?.cost,y)}),(0,J.jsx)(`td`,{className:`mono log-col-model`,title:ql(r),children:(0,J.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,J.jsx)(`span`,{children:ts(r.resolvedModel??r.model)}),r.shadowCallRewrittenFrom&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:t(`logs.badge.interceptedHelperTitle`),children:t(`logs.badge.interceptedHelper`,{model:r.shadowCallRewrittenFrom})}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),wl(r)&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:wl(r)})]})}),(0,J.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:Nl(r)}),i&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,J.jsx)(`td`,{className:`muted`,children:r.provider}),(0,J.jsx)(`td`,{children:(0,J.jsxs)(`span`,{className:`log-status-cell`,children:[(0,J.jsx)(`span`,{className:`mono font-semibold`,style:{color:Wl(r.status)},children:r.status}),(0,J.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>c(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,J.jsx)(`td`,{className:`muted mono`,children:(0,J.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,J.jsx)(`td`,{className:`num mono log-col-rate`,children:Fl(r.displayMetrics?.tokPerSecond,y)})]},r.requestId??`${r.timestamp}-${e.index}`)}),W>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:9,className:`logs-virtual-spacer`,style:{height:W}})})]})]})})}),s&&(0,J.jsx)(Zl,{detail:s,detailInfo:L,localeCode:n,localeTag:y,serverTimeZone:b,t,onClose:()=>c(null),onFilterConversation:e=>{m(e),c(null)}})]})]})}function Xl(e){let t=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function Zl({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Xl(!0),[l,u]=(0,_.useState)(!1),d=Ml(e),f=e.displayMetrics?.cost,p=Pl(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,J.jsx)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:(0,J.jsxs)(`div`,{className:`modal-card log-detail-card`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,J.jsx)(`span`,{className:`mono`,style:{color:Wl(e.status)},children:e.status}),t&&(0,J.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,J.jsx)(fe,{})})]}),t&&(0,J.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,J.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,J.jsx)(`span`,{className:`mono`,children:Kl(e.timestamp,r,i)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,J.jsx)(`span`,{className:`mono`,children:ts(e.resolvedModel??e.model)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,J.jsx)(`span`,{children:e.provider}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[Nl(e),p?` (${p})`:``]})]}),e.errorCode&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,J.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`span`,{className:`mono`,children:Fl(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Vl(e.displayMetrics.tokPerSecond.reason))})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,J.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.total,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.input,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.cacheRead,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.cacheWrite,r)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:Ll(f.estimate.cost.output,r)}),f.estimate.price&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,J.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,J.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Ul(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,J.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,J.jsx)(`li`,{children:a(Hl(e))},e))})]}):(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,J.jsx)(`span`,{children:f?.kind===`unavailable`?a(Vl(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,J.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,J.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{className:`num`,children:`#`}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,J.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=Pl(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.join(`, `):void 0)??(t?.kind===`unavailable`?a(Vl(t.reason)):a(`logs.detail.attempt.completed`));return(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,J.jsxs)(`td`,{children:[(0,J.jsx)(`span`,{children:e.provider}),(0,J.jsx)(`br`,{}),(0,J.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[Nl(e),n?` (${n})`:``]})]}),i&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Ul(i.status))]})]})]}),(0,J.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`td`,{className:`num mono`,children:Fl(e.displayMetrics?.tokPerSecond,r)}),(0,J.jsx)(`td`,{className:`num mono`,children:Il(t,r)}),(0,J.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,J.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Vt(e.usage.inputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Vt(e.usage.outputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Vt(d.read,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Vt(d.write,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Vt(e.usage.reasoningOutputTokens,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,J.jsx)(`span`,{className:`mono`,children:jl(e)===void 0?`—`:Vt(jl(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:Vt(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,J.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,J.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,J.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})})}function Ql(e){return`${Math.round(e*100)}%`}function $l(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 eu(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 tu(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 nu(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function ru(e){let t=tu(e.map(e=>e.totalTokens)),n=new Map(e.map(e=>[e.date,e])),r=new Date;r.setHours(0,0,0,0);let i=new Date(r);i.setDate(i.getDate()-364),i.setDate(i.getDate()-i.getDay());let a=[],o=[],s=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],c=-4,l=-1,u=[],d=new Date(i);for(;d<=r;){let e=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,`0`)}-${String(d.getDate()).padStart(2,`0`)}`,r=d.getMonth();d.getDay()===0&&r!==l&&a.length-c>=4&&(o.push({label:s[r],col:a.length}),c=a.length,l=r);let i=n.get(e);u.push({date:e,requests:i?.requests??0,totalTokens:i?.totalTokens??0,level:i?nu(i.totalTokens,t):0,dayOfWeek:d.getDay()}),d.getDay()===6&&(a.push(u),u=[]),d.setDate(d.getDate()+1)}if(u.length>0){for(;u.length<7;)u.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:u.length});a.push(u)}return{weeks:a,months:o,buckets:t}}function iu({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,J.jsxs)(`div`,{className:`usage-filters`,children:[(0,J.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,J.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,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,J.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,J.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 au({summary:e,activeDays:t,locale:n,t:r}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Vt(e.totalTokens,n)})]}),(0,J.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Vt(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,J.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Vt(e.cacheCreationInputTokens??0,n)]})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Ql(e.coverageRatio)})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,J.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,J.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,J.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:Ta(e.estimatedCostUsd,n)}),(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function ou({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,J.jsx)(`div`,{className:`daybars`,role:`img`,"aria-label":n(`usage.section.heatmap`),children:e.map(e=>{let n=Math.round(e.totalTokens/a*100),o=e.date.slice(5);return(0,J.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,J.jsx)(`div`,{className:`daybar-track`,children:(0,J.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:$l(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,J.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,J.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,J.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,J.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:$l(e.model,e.provider)}}),(0,J.jsx)(`span`,{className:`daybar-tip-name`,children:ts(e.model)}),(0,J.jsx)(`span`,{className:`daybar-tip-val`,children:Vt(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,J.jsx)(`span`,{className:`daybar-count`,children:Vt(e.totalTokens,t)}),(0,J.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function su({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,_.useRef)(null),[o,s]=(0,_.useState)(null);return(0,_.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,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,J.jsx)(ou,{weekBars:n,locale:r,t:i}):(0,J.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,J.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,J.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,J.jsxs)(`div`,{className:`heatmap-body`,children:[(0,J.jsxs)(`div`,{className:`heatmap-days`,children:[(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,J.jsx)(`span`,{})]}),(0,J.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,J.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,J.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.currentTarget.getBoundingClientRect();s({weekIndex:t,dayIndex:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>s(e=>e?.weekIndex===t&&e.dayIndex===n?null:e)},e.date||`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),o&&(()=>{let e=t.weeks[o.weekIndex]?.[o.dayIndex];return e?.date?(0,J.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,J.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,J.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Vt(e.totalTokens,r)})}),(0,J.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,J.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,J.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,J.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,J.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function cu({title:e,titleId:t,children:n}){return(0,J.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,J.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function lu({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=(0,J.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`logs.col.model`)}),(0,J.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:ts(e.model)}),(0,J.jsx)(`td`,{className:`muted`,children:e.provider}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Vt(e.totalTokens,r)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,J.jsxs)(cu,{title:s,titleId:c,children:[(0,J.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function uu({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:e.provider}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Vt(e.totalTokens,t)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,J.jsx)(cu,{title:i,titleId:a,children:o}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,J.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function du({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,J.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,J.jsx)(cu,{title:r,titleId:i,children:a}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,J.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function fu({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,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(au,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,J.jsx)(su,{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,J.jsx)(lu,{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,J.jsx)(uu,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Ql(e.summary.coverageRatio):`—`,body:e?(0,J.jsx)(du,{summary:e.summary,t:u,workspace:!0}):null}];return(0,J.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,J.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,J.jsx)(Tc,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,J.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,J.jsx)(pt,{title:u(`usage.empty`)}):f.map(e=>(0,J.jsx)(`div`,{id:Sc(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var pu=new Map;function mu(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function hu(e,t,n){let r=mu(e,t,n);return pu.get(r)??vn(r)}function gu(e,t,n,r){let i=mu(e,t,n);pu.set(i,r),yn(i,r)}function _u({apiBase:e}){let{t,locale:n}=X(),[r,i]=(0,_.useState)(`30d`),[a,o]=(0,_.useState)(`all`),[s,c]=(0,_.useState)(``),l=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/usage?range=${r}&surface=${a}`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let i=await n.json();return gu(e,r,a,i),i},[e,r,a]),u=mu(e,r,a),d=hu(e,r,a),f=Es(u,[e,r,a],l,{isEmpty:()=>!1,initialData:d??void 0}),{state:p}=f,m=p.data??d??null,h=(0,_.useMemo)(()=>ru(m?.days??[]),[m?.days]),g=(0,_.useMemo)(()=>eu(m?.days??[]),[m?.days]),v=(0,_.useMemo)(()=>(m?.days??[]).filter(e=>e.requests>0).length,[m?.days]),y=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(m?.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)},[m?.models,s]),b=(0,_.useMemo)(()=>(m?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[m?.providers]);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,J.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,J.jsx)(iu,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),p.showSkeleton&&!m?(0,J.jsx)(Os,{label:t(`usage.loading`),rows:5}):p.kind===`failed-cold`?(0,J.jsxs)(dt,{tone:`err`,children:[p.error instanceof Error?`${t(`usage.loadError`)} ${p.error.message}`:t(`usage.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,J.jsxs)(J.Fragment,{children:[p.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`usage.loadError`)}),m?.historyTruncated&&(0,J.jsx)(dt,{tone:`ok`,children:t(`usage.historyTruncated`)}),(0,J.jsx)(fu,{data:m,heatmap:h,weekBars:g,activeDays:v,filteredModels:y,modelQuery:s,onModelQuery:c,sortedProviders:b,range:r,locale:n,t})]})]})}function vu(e,t){if(e<1024)return`${e} B`;let n=[`KB`,`MB`,`GB`,`TB`],r=e,i=-1;do r/=1024,i++;while(r>=1024&&i<n.length-1);return`${r.toLocaleString(t,{maximumFractionDigits:1})} ${n[i]}`}var yu={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 bu(e,t){let n=yu[e.key];return n?t(n):e.label}function xu(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function Su(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function Cu({report:e,locale:t}){let n=Z(),[r,i]=(0,_.useState)(null),a=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),o=a.find(e=>e.key===r)??null,s=(0,_.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,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,J.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":n(`storage.section.buckets`),children:[(0,J.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-title`,children:n(`storage.section.buckets`)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-count`,children:a.length})]}),(0,J.jsx)(`div`,{className:`storage-workspace-rail-list`,children:a.length===0?(0,J.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:n(`storage.empty`)}):a.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${r===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>i(t=>t===e.key?null:e.key),"aria-current":r===e.key?`true`:void 0,children:[(0,J.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-name`,children:bu(e,n)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-size`,children:vu(e.bytes,t)})]}),(0,J.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,n(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,J.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":o?bu(o,n):n(`storage.section.largest`),children:o?(0,J.jsxs)(`div`,{className:`stw-detail`,children:[(0,J.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>i(null),children:[(0,J.jsx)(we,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),n(`modal.back`)]})}),(0,J.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,J.jsx)(`h2`,{className:`stw-detail-title`,children:bu(o,n)}),(0,J.jsxs)(`dl`,{className:`stw-kv`,children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.size`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:vu(o.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.files`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:o.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.oldest`)}),(0,J.jsx)(`dd`,{children:xu(o.oldest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.newest`)}),(0,J.jsx)(`dd`,{children:xu(o.newest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:Su(o,t,n)})]})]}),(o.largest?.length??0)>0&&(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),o.largest.map(e=>(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:vu(e.bytes,t)})]},e.path))]})]})]}):(0,J.jsxs)(`div`,{className:`stw-overview`,children:[(0,J.jsxs)(`div`,{className:`stw-summary`,children:[(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.total`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:vu(e.total.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.files`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.home`)}),(0,J.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),s.length>0?(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),s.map(e=>{let r=c.get(e.bucketKey);return(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),r&&(0,J.jsx)(`span`,{className:`stw-file-bucket`,children:bu(r,n)}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:vu(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,J.jsxs)(`p`,{className:`stw-hint`,children:[(0,J.jsx)(ue,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),n(`storage.workspace.selectBucket`)]})]})})]})}var wu=1024**3,Tu=[10,25,50],Eu=(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 Du({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,_.useState)(25),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(null),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=(0,_.useRef)(!1),S=(0,_.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,_.useEffect)(()=>{x.current=f},[f]),(0,_.useEffect)(()=>{if(!c)return;b.current=document.activeElement,y.current?.focus();let e=e=>{e.key===`Escape`&&!x.current&&S()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),b.current?.focus()}},[c,S]);let C=(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`)}},w=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),T=async()=>{p(!0),v(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(C(e.error,n(`storage.cleanup.previewFailed`)))}s(await t.json()),l(!0)}catch(e){v(Eu(e,n(`storage.cleanup.previewFailed`)))}finally{p(!1)}},E=async()=>{if(o){p(!0),v(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`&&S(!0),Error(C(e.error,e.message,e.trashDir))}let a=await i.json();if(!a.ok)throw a.error===`stale_preview`&&S(!0),Error(C(a.error,a.message,a.trashDir));S(!0),h(n(u?`storage.cleanup.donePermanent`:`storage.cleanup.doneQuarantine`,{count:String(a.count),size:vu(a.bytes,t)})),r()}catch(e){v(Eu(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,J.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,J.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,J.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,J.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,J.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Tu.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:vu(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,J.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,J.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,J.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,J.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,J.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void E(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function Ou({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(null),g=(0,_.useRef)(!1);(0,_.useEffect)(()=>{g.current=o},[o]);let v=(0,_.useCallback)(()=>l(null),[]);(0,_.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&v()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,v]);let y=(0,_.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]),b=Es(`storage-trash:${e}`,[e,i],y,{isEmpty:e=>e.length===0}).state,x=b.data??[],S=(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`)}},C=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(S(e.error,e.message))}let a=await i.json();if(!a.ok)throw Error(S(a.error,a.message));v(),d(n(`storage.trash.done`,{count:String(a.count),size:vu(a.bytes,t)})),r()}catch(e){p(Eu(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},w=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},T=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:b.error instanceof Error?b.error.message:n(`storage.trash.listFailed`)}),b.refreshing&&!b.showSkeleton&&(0,J.jsx)(ks,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,J.jsx)(Os,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,J.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,J.jsx)(`th`,{})]})}),(0,J.jsx)(`tbody`,{children:x.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted`,children:w(e)}),(0,J.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,J.jsx)(`td`,{className:`num mono`,children:vu(e.bytes,t)}),(0,J.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,J.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:vu(c.bytes,t),id:c.id})}),f&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function ku(e){let{job:t,...n}=e;return n}function Au(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/wu*100)/100));return e.target.reduceToBytes===void 0?{policy:ku(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:ku(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/wu*100)/100))}}async function ju(e){await new Promise(t=>window.setTimeout(t,e))}function Mu({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=vn(i),o=(0,_.useRef)(!!a),[s,c]=(0,_.useState)(()=>a?.policy??null),[l,u]=(0,_.useState)(()=>!a),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>a?.targetMode??`percent`),[S,C]=(0,_.useState)(()=>a?.percent??`25`),[w,T]=(0,_.useState)(()=>a?.reduceGb??`4`),[E,D]=(0,_.useState)(()=>a?.thresholdGb??`5`),O=(0,_.useRef)(null),k=(0,_.useRef)(!1),A=(0,_.useRef)(!1),j=(0,_.useRef)(0),M=(0,_.useCallback)(e=>{let t=Au(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,yn(i,t),k.current=!1},[i]),N=(0,_.useCallback)(()=>{k.current=!0},[]),P=(0,_.useCallback)(e=>{A.current=e},[]),F=(0,_.useCallback)(async t=>{let r=++j.current;o.current||u(!0),y(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!==j.current||k.current||A.current)return;M(i)}catch{if(t?.aborted||r!==j.current)return;o.current||(c(null),y(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===j.current&&u(!1)}},[e,M,n]);(0,_.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{F(e.signal)},0);return()=>{window.clearTimeout(t),j.current+=1,e.abort()}},[F]),(0,_.useEffect)(()=>()=>{O.current?.abort(),O.current=null},[]);let I=()=>{if(!s)return null;let e=E.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(b===`reduce`){let e=w.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*wu)}}else{let e=Number(S);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*wu)},target:n,schedule:s.schedule,mode:s.mode}},L=async t=>{let r=I();if(!r){y(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),y(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){y(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){y(n(`storage.policy.saveFailed`));return}M(r.policy),g(n(`storage.policy.saved`))}catch{y(n(`storage.policy.saveFailed`))}finally{f(!1)}},R=async()=>{O.current?.abort();let i=new AbortController;O.current=i;let{signal:a}=i;m(!0),y(null),g(null);try{let i=I();if(!i){y(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){y(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){y(n(`storage.policy.saveFailed`));return}M(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&&M(e.policy),y(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&M(e.policy),e.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}y(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&M(l.policy),l.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){y(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await ju(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=ku(n),M(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&&M(p),!f){y(n(`storage.policy.runFailed`));return}f.skipped===`disabled`?g(n(`storage.policy.skippedDisabled`)):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`?y(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:vu(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:vu(f.freedBytes??0,t)})),r()):y(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;y(n(`storage.policy.runFailed`))}finally{O.current===i&&(O.current=null),a.aborted||m(!1)}},z=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,J.jsx)(`div`,{className:`storage-policy-enable`,children:(0,J.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,J.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 L({enabled:!s.enabled}),children:(0,J.jsx)(`span`,{className:`toggle-knob`})}),(0,J.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,J.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,J.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,J.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,J.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:E,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>P(!0),onChange:e=>{N(),D(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(ea,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D($i(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D($i(E,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,J.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:S,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>P(!0),onChange:e=>{N(),C(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(ea,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C($i(S,1,1,100))},onDecrement:()=>{N(),C($i(S,-1,1,100))}})]})]}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:w,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>P(!0),onChange:e=>{N(),T(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(ea,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T($i(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T($i(w,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,J.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;L({schedule:t})},children:[(0,J.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,J.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,J.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,J.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,J.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;L({mode:t})},children:[(0,J.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,J.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,J.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,J.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[z(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:vu(s.lastRun.freedBytes,t)})}`:``]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,J.jsx)(`span`,{className:`storage-policy-meta-value`,children:z(s.nextRun)})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,J.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,J.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function Nu({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,_.useState)(`policy`),u=(0,_.useRef)(null),d=(0,_.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,J.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,J.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,J.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,J.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,J.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,J.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,J.jsx)(Mu,{apiBase:e,locale:t,t:n,onDone:o}),(0,J.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,J.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,J.jsx)(Du,{apiBase:e,locale:t,t:n,onDone:o}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,J.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,J.jsx)(Ou,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function Pu({apiBase:e}){let{t,locale:n}=X(),r=`ocx.storage.report.v1:${e}`,i=vn(r),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(0),l=(0,_.useRef)(!1),[u,d]=(0,_.useState)({apiBase:e,settled:!1,hasEntries:!1}),f=(0,_.useCallback)(async n=>{try{let i=await fetch(`${e}/api/storage`,{signal:n});if(!i.ok)throw Error(t(`storage.error`));let a=await i.json();return yn(r,a),l.current&&(l.current=!1,o(t(`storage.rescanned`))),a}catch(e){throw l.current&&(l.current=!1,o(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,r,t]),p=Es(`storage-report:${e}`,[e],f,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),m=p.state,h=m.data??i,g=m.refreshing||m.showSkeleton&&!h,v=p.refresh,y=(0,_.useCallback)(()=>{o(null),l.current=!0,v(),c(e=>e+1)},[v]),b=(0,_.useCallback)(t=>{d({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=u.apiBase===e&&u.settled,S=u.apiBase===e&&u.hasEntries,C=h?.error!==void 0,w=!g&&!m.showError&&!C&&h.total.fileCount===0&&x&&!S,T=h?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!h&&!C,D=E&&(h.total.fileCount>0||!x||S);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,J.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,J.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,J.jsx)(me,{}),` `,t(`storage.refresh`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,J.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,J.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,J.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,J.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,J.jsx)(Os,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,J.jsxs)(J.Fragment,{children:[m.showError&&(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,J.jsx)(pt,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,J.jsx)(Cu,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,J.jsx)(ks,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,J.jsx)(Nu,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}function Fu(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 Iu({state:e,busy:t,onEnable:n}){let r=Z();return(0,J.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,J.jsxs)(`div`,{className:`row`,children:[(0,J.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===null?(0,J.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot openai-account-mode-banner__badge-slot--pending`,"aria-hidden":`true`,children:r(`codexAuth.accountModePool`)}):e===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===null&&(0,J.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc openai-account-mode-banner__desc--pending`,"aria-hidden":`true`,children:`\xA0`}),e===`pool`&&(0,J.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,J.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,J.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,J.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,J.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,J.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,J.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]})]})}function Lu(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 Ru({apiBase:e}){let t=Z(),n=`ocx.codex-auth.config.v1:${e}`,r=vn(n),[i,a]=(0,_.useState)(()=>r?.bannerState??null),[o,s]=(0,_.useState)(()=>r?.accountModeState??null),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(``),p=(0,_.useCallback)(async()=>{let t=y(15e3);try{let r=await fetch(`${e}/api/config`,{signal:t.signal});if(!r.ok)throw Error(String(r.status));let i=await r.json(),o=oo(Lu(i));if(o===`absent`||o===`disabled`||o===`invalid`){a(o);let e=o===`disabled`?`disabled`:`absent`;s(e),yn(n,{bannerState:o,accountModeState:e});return}let c=Fu(i);a(c),s(c),yn(n,{bannerState:c,accountModeState:c})}catch{}finally{t.clear()}},[e,n]);(0,_.useEffect)(()=>{c.current!==e&&(c.current=e,Promise.resolve().then(()=>{p()}));let t=Jt(()=>{p()},3e4);return()=>{t()}},[e,p]);let m=async()=>{u(!0),f(``);try{if(i!==`absent`&&i!==`disabled`)return;await mo(e,i),await p()}catch(e){e instanceof po?f(t(e.i18nKey)):f(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{u(!1)}};return(0,J.jsx)(Ha,{apiBase:e,accountModeState:o,banner:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Iu,{state:i,busy:l,onEnable:()=>{m()}}),d&&(0,J.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:d})]})})}function zu(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function Bu(e){let t=e.id.indexOf(`/`),n=typeof e.owned_by==`string`&&e.owned_by.trim()?e.owned_by.trim():void 0,r=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 Vu(e){return e.id}function Hu(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.ambiguous===!0?!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 Uu=new Set([`required`,`accepted`,`rejected`]);function Wu(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`&&Uu.has(t.bearer)&&Uu.has(t.dedicated)&&Uu.has(t.xApiKey)})}var Gu={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 Ku(e){let t=e||Gu.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 qu(e,t){let n=new Date(e);return!e||Number.isNaN(n.getTime())?`—`:n.toLocaleDateString(t)}function Ju({url:e}){return(0,J.jsx)(Yu,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,J.jsx)(`code`,{className:`api-code api-code-inline api-endpoint-url`,children:e})})}function Yu({text:e,hintKey:t,copiedKey:n,className:r,children:i}){let{t:a}=X(),o=(0,_.useId)(),s=(0,_.useRef)(null),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(null),h=c||u;(0,_.useEffect)(()=>()=>{m.current!==null&&window.clearTimeout(m.current)},[]),(0,_.useLayoutEffect)(()=>{if(!h)return;let e=()=>{let e=s.current;if(!e)return;let t=e.getBoundingClientRect();p({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)}},[h]);let g=()=>l(!0),v=()=>l(!1),y=async()=>{try{await navigator.clipboard.writeText(e),d(!0),m.current!==null&&window.clearTimeout(m.current),m.current=window.setTimeout(()=>d(!1),1500)}catch{d(!1)}},b=h&&f?(0,$e.createPortal)((0,J.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble api-copy-tip-fixed`,role:`tooltip`,style:{top:f.top,left:f.left},children:a(u?n:t)}),document.body):null;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,ref:s,className:`ocx-tooltip ${r}`,onMouseEnter:g,onMouseLeave:v,onFocus:g,onBlur:v,onClick:e=>{if(typeof window<`u`&&window.getSelection()?.toString())return;let t=e.target;if(t instanceof HTMLElement&&t!==e.currentTarget){let n=t.getBoundingClientRect();if(t.scrollHeight>t.clientHeight+1&&e.clientX>=n.right-16||t.scrollWidth>t.clientWidth+1&&e.clientY>=n.bottom-16)return}y()},onKeyDown:e=>{e.key===`Escape`&&v()},"aria-label":a(t),"aria-describedby":h?o:void 0,children:i}),b]})}function Xu({text:e}){return(0,J.jsx)(Yu,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,J.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}function Zu(e,t){return t(e===`required`?`api.auth.required`:e===`accepted`?`api.auth.accepted`:`api.auth.rejected`)}function Qu({endpoints:e,claudeCodeEnabled:t,authMatrix:n}){let{t:r}=X();return(0,J.jsxs)(`div`,{className:`panel api-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`api.endpointsTitle`)}),(0,J.jsxs)(`div`,{className:`api-endpoints`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.baseUrl`)}),(0,J.jsx)(Ju,{url:e.baseUrl})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.responsesEndpoint`)}),(0,J.jsx)(Ju,{url:e.responses})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.chatCompletionsEndpoint`)}),(0,J.jsx)(Ju,{url:e.chatCompletions})]}),t&&(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.messagesEndpoint`)}),(0,J.jsx)(Ju,{url:e.messages})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted small`,children:r(`api.modelsEndpoint`)}),(0,J.jsx)(Ju,{url:e.models})]})]}),(0,J.jsx)(`p`,{className:`muted small`,children:r(`api.endpointNote`)}),(0,J.jsxs)(`div`,{className:`api-auth-matrix-block`,children:[(0,J.jsx)(`h4`,{className:`api-auth-matrix-title`,children:r(`api.authTitle`)}),(0,J.jsx)(`div`,{className:`api-auth-matrix-scroll`,children:(0,J.jsxs)(`table`,{className:`api-auth-matrix`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:r(`api.auth.endpoint`)}),(0,J.jsx)(`th`,{children:(0,J.jsx)(`code`,{children:`Authorization: Bearer`})}),(0,J.jsx)(`th`,{children:(0,J.jsx)(`code`,{children:`x-opencodex-api-key`})}),(0,J.jsx)(`th`,{children:(0,J.jsx)(`code`,{children:`x-api-key`})})]})}),(0,J.jsx)(`tbody`,{children:n.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:(0,J.jsx)(`code`,{children:e.endpoint})}),(0,J.jsx)(`td`,{children:Zu(e.bearer,r)}),(0,J.jsx)(`td`,{children:Zu(e.dedicated,r)}),(0,J.jsx)(`td`,{children:Zu(e.xApiKey,r)})]},e.endpoint))})]})}),(0,J.jsx)(`p`,{className:`muted small`,children:r(`api.authLoopback`)}),(0,J.jsx)(`p`,{className:`muted small`,children:r(`api.authBaseUrlNote`)})]})]})}function $u({keys:e,keysLoading:t=!1,keysLoadFailed:n,newName:r,creating:i,newKey:a,copied:o,confirmDelete:s,localeTag:c,showKeyList:l=!0,onNewNameChange:u,onCreate:d,onDismissNewKey:f,onCopyKey:p,onConfirmDelete:m,onCancelDelete:h,onDelete:g}){let{t:_}=X();return(0,J.jsxs)(J.Fragment,{children:[a&&(0,J.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:_(`api.newKeyTitle`)}),(0,J.jsx)(`p`,{className:`muted small`,children:_(`api.newKeyNote`)}),(0,J.jsxs)(`div`,{className:`api-form-row`,children:[(0,J.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:a}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:p,children:o?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(de,{}),` `,_(`api.copied`)]}):_(`api.copy`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:f,children:_(`api.dismiss`)})]}),(0,J.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:_(`api.generateTitle`)}),(0,J.jsxs)(`div`,{className:`api-form-row`,children:[(0,J.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:_(`api.keyNamePlaceholder`),"aria-label":_(`api.keyNamePlaceholder`),value:r,maxLength:64,onChange:e=>u(e.target.value),className:`input`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:d,disabled:i,children:[(0,J.jsx)(pe,{}),` `,_(i?`api.generating`:`api.generate`)]})]})]}),l&&(0,J.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:t?_(`api.activeKeysLoading`):_(`api.activeKeys`,{count:e.length})}),t?(0,J.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":_(`common.loading`)}):e.length>0?(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:_(`api.colName`)}),(0,J.jsx)(`th`,{children:_(`api.colKey`)}),(0,J.jsx)(`th`,{children:_(`api.colCreated`)}),(0,J.jsx)(`th`,{})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:e.name}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`code`,{children:e.prefix})}),(0,J.jsx)(`td`,{children:qu(e.createdAt,c)}),(0,J.jsx)(`td`,{children:s===e.id?(0,J.jsxs)(`span`,{className:`api-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>g(e.id),children:_(`api.confirm`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:h,children:_(`common.cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":_(`api.deleteAria`),onClick:()=>m(e.id),children:(0,J.jsx)(fe,{})})})]},e.id))})]})}):n?(0,J.jsx)(`p`,{className:`muted`,children:_(`api.keysLoadFailed`)}):(0,J.jsx)(`p`,{className:`muted`,children:_(`api.noKeys`)})]})]})}function ed({filteredModels:e,modelsLoading:t,modelsRefreshing:n=!1,modelsLoadFailed:r,modelCount:i,hasModelData:a,modelQuery:o,copiedModelId:s,modelTests:c,claudeCodeEnabled:l,onModelQueryChange:u,onCopyModelId:d,onTestModel:f,onRetryModels:p,canTestModels:m,sourceLabel:h,protocolLabel:g}){let{t:_}=X();return(0,J.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,J.jsxs)(`div`,{className:`api-panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:_(`api.modelsTitle`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:_(`api.modelsCount`,{count:e.length})})]}),(0,J.jsx)(`p`,{className:`muted small`,children:_(`api.modelsSubtitle`)}),(0,J.jsx)(`input`,{type:`search`,className:`input`,value:o,onChange:e=>u(e.target.value),placeholder:_(`api.modelsSearch`),"aria-label":_(`api.modelsSearch`)}),r&&(0,J.jsxs)(`div`,{className:`api-models-error`,children:[(0,J.jsx)(`p`,{className:`muted small`,role:`alert`,children:_(`api.modelsLoadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:_(`common.retry`)})]}),n&&!t&&(0,J.jsx)(`p`,{className:`muted small`,"aria-live":`polite`,children:_(`api.modelsLoading`)}),t?(0,J.jsx)(Os,{label:_(`api.modelsLoading`),rows:3}):a?e.length===0?(0,J.jsx)(`p`,{className:`muted small api-models-empty`,children:i===0?_(`api.modelsEmpty`):_(`api.modelsNoMatch`,{query:o.trim()})}):(0,J.jsx)(`div`,{className:`api-models-scroll`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:_(`api.colModel`)}),(0,J.jsx)(`th`,{children:_(`api.colSource`)}),(0,J.jsx)(`th`,{children:_(`api.colProtocols`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>{let t=Vu(e),n=zu(l);return(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:(0,J.jsxs)(`div`,{className:`api-model-cell`,children:[(0,J.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,J.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,J.jsx)(`td`,{children:h(e)}),(0,J.jsx)(`td`,{children:(0,J.jsxs)(`div`,{className:`api-model-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{d(t)},children:_(s===t?`api.modelCopied`:`api.copyModelId`)}),n.map(n=>{let r=c[t]?.[n],i=r?.state??`idle`;return(0,J.jsxs)(`span`,{className:`api-model-test-chip`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:i===`testing`||!m,title:m?void 0:_(`api.auth.testNeedsFreshKey`),onClick:()=>{f(e,n)},children:_(`api.auth.testProtocol`,{protocol:g(n)})}),i!==`idle`&&(0,J.jsx)(`span`,{className:`api-test-note api-test-note--${i}`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:i===`testing`?_(`api.testingModel`):i===`ok`?_(`api.testSucceeded`):r?.detail??_(`api.testFailed`)})]},n)})]})})]},t)})})]})}):null]})}function td({endpoints:e,claudeCodeEnabled:t}){let{t:n}=X(),r=JSON.stringify(n(`api.usageSampleInput`)),i=`curl ${e.chatCompletions} \\
48
48
  -H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
49
49
  -H "Content-Type: application/json" \\
50
50
  -d '{
@@ -64,4 +64,4 @@ v2: spawn_agent を備えたマルチスレッドエージェント。すべて
64
64
  "max_tokens": 64,
65
65
  "messages": [{"role": "user", "content": ${r}}]
66
66
  }'`;return(0,J.jsxs)(`section`,{className:`panel api-panel awi-usage-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:n(`api.workspace.usageExamples`)}),(0,J.jsxs)(`div`,{className:`awi-usage-panel-body`,children:[(0,J.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,J.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageChatTitle`)}),(0,J.jsx)(Xu,{text:i})]}),(0,J.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,J.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageResponsesTitle`)}),(0,J.jsx)(Xu,{text:a})]}),t&&(0,J.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,J.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageMessagesTitle`)}),(0,J.jsx)(Xu,{text:o})]})]})]})}var nd=[`opencode`,`pi`],rd={opencode:`api.clientConfig.clientOpencode`,pi:`api.clientConfig.clientPi`},id={opencode:`/provider-icons/opencode.svg`,pi:`/provider-icons/pi.svg`};function ad({client:e,apiBase:t,onOpenDetails:n,onCopy:r,onDownload:i}){let a=Z(),[o,s]=(0,_.useState)(0),c=[t,e,String(o)].join(`|`),[l,u]=(0,_.useState)(null);(0,_.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(rd[e]),g=id[e],v=f?`${JSON.stringify(f.config,null,2)}\n`:``,y=(0,_.useCallback)(t=>{f&&n(e,f,v,t.currentTarget)},[e,f,v,n]);return(0,J.jsxs)(`li`,{className:`awi-clientconfig-row`,children:[(0,J.jsx)(`span`,{className:`awi-clientconfig-mark`,"aria-hidden":`true`,children:g?(0,J.jsx)(`img`,{src:g,alt:``,width:20,height:20}):(0,J.jsx)(`span`,{className:`awi-clientconfig-monogram`,children:h.slice(0,1)})}),(0,J.jsxs)(`span`,{className:`awi-clientconfig-identity`,children:[(0,J.jsx)(`span`,{className:`awi-clientconfig-name`,children:h}),(0,J.jsx)(`span`,{className:`muted text-label awi-clientconfig-meta`,children:m?a(`api.clientConfig.loading`):p||!f?(0,J.jsx)(`span`,{role:`alert`,children:a(`api.clientConfig.rowError`,{client:h})}):a(`api.clientConfig.rowMeta`,{destination:f.destination,count:f.modelCount})})]}),(0,J.jsx)(`span`,{className:`awi-clientconfig-row-actions`,children:p&&!m?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e=>e+1),children:a(`common.retry`)}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":a(`api.clientConfig.copyAria`,{client:h}),disabled:!f,onClick:()=>{f&&r(e,v)},children:a(`api.clientConfig.copy`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"aria-label":a(`api.clientConfig.downloadAria`,{client:h}),disabled:!f,onClick:()=>{f&&i(e,f,v)},children:a(`api.clientConfig.download`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":a(`api.clientConfig.detailsAria`,{client:h}),disabled:!f,onClick:y,children:a(`api.clientConfig.details`)})]})})]})}function od({client:e,envelope:t,json:n,hasKeys:r,onClose:i,onCopy:a,onDownload:o}){let s=Z(),c=(0,_.useRef)(null),l=`awi-clientconfig-dialog-${e}`;return(0,_.useEffect)(()=>{let e=c.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]),(0,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":l,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]),children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,J.jsxs)(`div`,{className:`modal-card awi-clientconfig-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:l,children:s(rd[e])}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:s(`common.close`)})]}),(0,J.jsx)(`pre`,{className:`api-code api-example-pre awi-clientconfig-json`,tabIndex:0,role:`group`,"aria-label":s(`api.clientConfig.jsonLabel`,{client:s(rd[e])}),children:n}),(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-count`,children:s(`api.clientConfig.modelCount`,{count:t.modelCount})}),t.modelsWithoutLimits>0&&(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-degraded`,children:s(`api.clientConfig.missingLimits`,{count:t.modelsWithoutLimits,total:t.modelCount})}),!r&&(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-nokey`,children:s(`api.clientConfig.noKeyYet`,{env:t.apiKeyEnv})}),(0,J.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.destination`)}),(0,J.jsx)(Xu,{text:t.destination})]}),(0,J.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.envHint`)}),(0,J.jsx)(Xu,{text:t.exportHint})]}),(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-merge`,children:s(`api.clientConfig.mergeWarning`)}),(0,J.jsx)(`p`,{className:`muted text-label awi-clientconfig-where-title`,children:s(`api.clientConfig.whereDisclosure`)}),(0,J.jsx)(`p`,{className:`muted small`,children:s(`api.clientConfig.whereBody`)}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:s(`api.clientConfig.copy`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:o,children:s(`api.clientConfig.download`)})]})]})]})}function sd({apiBase:e,baseUrl:t,hasKeys:n}){let r=Z(),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(``),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(i!==null)return;let e=c.current;e&&(c.current=null,e.isConnected&&e.focus())},[i]);let l=(0,_.useCallback)(async(e,t,n)=>{try{await navigator.clipboard.writeText(t),s(n?r(`api.clientConfig.copiedAnnounceClient`,{client:r(rd[e])}):r(`api.clientConfig.copiedAnnounce`))}catch{s(r(`api.clientConfig.copyFailed`))}},[r]),u=(0,_.useCallback)((e,t,n)=>{let i=URL.createObjectURL(new Blob([n],{type:`application/json`})),a=document.createElement(`a`);a.href=i,a.download=t.filename,a.click(),URL.revokeObjectURL(i),s(r(`api.clientConfig.downloadedAnnounce`,{filename:t.filename,destination:t.destination}))},[r]),d=(0,_.useCallback)(()=>a(null),[]),f=(0,_.useCallback)((e,t,n,r)=>{c.current=r,a({client:e,envelope:t,json:n})},[]);return(0,J.jsxs)(`section`,{className:`panel api-panel awi-clientconfig-panel`,children:[(0,J.jsx)(`div`,{className:`api-panel-head awi-clientconfig-head`,children:(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`api.clientConfig.title`)})}),(0,J.jsx)(`ul`,{className:`awi-clientconfig-rows`,"aria-label":r(`api.clientConfig.rowsLabel`),children:nd.map(t=>(0,J.jsx)(ad,{client:t,apiBase:e,onOpenDetails:f,onCopy:(e,t)=>{l(e,t,!0)},onDownload:u},t))}),(0,J.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:r(`api.baseUrl`)}),(0,J.jsx)(Xu,{text:t})]}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:o}),i&&(0,J.jsx)(od,{client:i.client,envelope:i.envelope,json:i.json,hasKeys:n,onClose:d,onCopy:()=>{l(i.client,i.json,!1)},onDownload:()=>u(i.client,i.envelope,i.json)})]})}function cd({keys:e,keysLoading:t,keysLoadFailed:n,attributionSince:r,localeTag:i,busy:a,onSelect:o}){let s=Z();return(0,J.jsxs)(`div`,{className:`panel api-panel awi-keylist-panel`,"aria-busy":t,children:[(0,J.jsx)(`div`,{className:`api-panel-head`,children:(0,J.jsx)(`h3`,{className:`panel-title`,children:t?s(`api.activeKeysLoading`):s(`api.activeKeys`,{count:e.length})})}),t?(0,J.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":s(`common.loading`)}):e.length===0?(0,J.jsx)(`p`,{className:`muted small`,children:s(n?`api.keysLoadFailed`:`api.noKeys`)}):(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl awi-keylist-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:s(`api.colName`)}),(0,J.jsx)(`th`,{children:s(`api.colKey`)}),(0,J.jsx)(`th`,{children:s(`api.attribution.requests7d`)}),(0,J.jsx)(`th`,{children:s(`api.attribution.lastUsed`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:(0,J.jsx)(`button`,{type:`button`,className:`awi-keylist-name`,disabled:a,onClick:()=>o(e.id),children:e.name})}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`code`,{children:e.prefix})}),(0,J.jsx)(`td`,{children:r?e.usage.ambiguous?s(`api.attribution.railAmbiguous`):e.usage.requests7d.toLocaleString(i):s(`api.attribution.unavailable`)}),(0,J.jsx)(`td`,{children:!r||e.usage.ambiguous?`—`:e.usage.lastUsedAt?qu(e.usage.lastUsedAt,i):s(`api.attribution.neverUsed`)})]},e.id))})]})})]})}function ld({keys:e,apiBase:t,attributionSince:n,historyTruncated:r,authMatrix:i,keysLoading:a,keysLoadFailed:o,endpoints:s,claudeCodeEnabled:c,localeTag:l,newName:u,creating:d,newKey:f,copied:p,filteredModels:m,modelsLoading:h,modelsRefreshing:g=!1,modelsLoadFailed:v,modelCount:y,hasModelData:b,modelQuery:x,copiedModelId:S,modelTests:C,canTestModels:w,onNewNameChange:T,onCreate:E,onDismissNewKey:D,onCopyKey:O,onDelete:k,onRename:A,onModelQueryChange:j,onCopyModelId:M,onTestModel:N,onRetryModels:P,sourceLabel:F,protocolLabel:I}){let L=Z(),[R,z]=(0,_.useState)(null),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(!1),[W,G]=(0,_.useState)(!1),[ee,K]=(0,_.useState)(!1),[q,te]=(0,_.useState)(``),[Y,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(!1),[ae,oe]=(0,_.useState)(!1),se=R?e.find(e=>e.id===R)??null:null,ce=W||Y,le=(0,_.useMemo)(()=>[{id:`keys`,label:L(`api.section.keys`),meta:a?void 0:String(e.length)},{id:`connect`,label:L(`api.section.connect`)},{id:`endpoints`,label:L(`api.section.endpoints`)},{id:`models`,label:L(`api.section.models`),meta:String(y)},{id:`examples`,label:L(`api.section.examples`)}],[L,e.length,a,y]),ue=()=>{V(!1),U(!1)},de=()=>{z(null),ue(),K(!1),ie(!1),oe(!1)};(0,_.useEffect)(()=>{if(!B)return;let e=window.setTimeout(()=>U(!0),300);return()=>window.clearTimeout(e)},[B]);let fe=()=>{se&&V(!0)},pe=async()=>{if(!(!se||!H||W)){G(!0),oe(!1);try{await k(se.id)?(ue(),z(null)):oe(!0)}finally{G(!1)}}},me=()=>{se&&(te(se.name),ie(!1),K(!0))},he=async()=>{if(!se||Y)return;let e=q.trim();if(!e||e===se.name){K(!1);return}ne(!0),ie(!1);try{await A(se.id,e)?K(!1):ie(!0)}finally{ne(!1)}};return(0,J.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!se&&(0,J.jsx)(Tc,{scope:`api`,items:le,ariaLabel:L(`api.workspace.sections`)}),(0,J.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,J.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":L(`api.workspace.details`),children:se?(0,J.jsxs)(`div`,{className:`awi-detail`,children:[(0,J.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:de,disabled:ce,children:[(0,J.jsx)(we,{className:`awi-back-chevron`,"aria-hidden":`true`}),L(`modal.back`)]})}),(0,J.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,J.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,J.jsx)(`h2`,{className:`awi-detail-title`,children:se.name}),(0,J.jsx)(`span`,{className:`awi-detail-actions`,children:B?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{pe()},disabled:!H||W,children:[(0,J.jsx)(_e,{}),` `,L(W?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ue,disabled:W,children:L(`common.cancel`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:me,disabled:ee,children:L(`api.key.rename`)},`rename`),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:fe,"aria-label":L(`api.deleteAria`),children:[(0,J.jsx)(_e,{}),` `,L(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),B&&(0,J.jsx)(`p`,{className:`muted awi-delete-hint`,children:L(`api.workspace.deleteConfirm`)}),ae&&(0,J.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:L(`api.deleteFailed`)}),ee&&(0,J.jsxs)(`div`,{className:`awi-rename`,children:[(0,J.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:L(`api.key.name`)}),(0,J.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:q,maxLength:64,disabled:Y,onChange:e=>te(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),he())}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{he()},disabled:Y,children:L(Y?`api.key.renaming`:`api.key.saveName`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>K(!1),disabled:Y,children:L(`common.cancel`)}),re&&(0,J.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:L(`api.key.renameFailed`)})]}),(0,J.jsxs)(`div`,{className:`awi-section`,children:[(0,J.jsx)(`h3`,{className:`awi-section-title`,children:L(`api.workspace.keyDetails`)}),(0,J.jsxs)(`dl`,{className:`awi-kv`,children:[(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.workspace.keyPrefix`)}),(0,J.jsx)(`dd`,{children:(0,J.jsx)(`code`,{children:se.prefix})})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.colCreated`)}),(0,J.jsx)(`dd`,{children:qu(se.createdAt,l)})]})]})]}),(0,J.jsxs)(`div`,{className:`awi-section`,children:[(0,J.jsx)(`h3`,{className:`awi-section-title`,children:L(`api.attribution.title`)}),n?se.usage.ambiguous?(0,J.jsx)(`p`,{className:`muted`,children:L(`api.attribution.ambiguous`)}):(0,J.jsxs)(`dl`,{className:`awi-kv`,children:[(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.attribution.requests7d`)}),(0,J.jsx)(`dd`,{children:se.usage.requests7d.toLocaleString(l)})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(r?`api.attribution.totalRequestsAvailable`:`api.attribution.totalRequests`)}),(0,J.jsx)(`dd`,{children:se.usage.totalRequests.toLocaleString(l)})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.attribution.lastUsed`)}),(0,J.jsx)(`dd`,{children:se.usage.lastUsedAt?qu(se.usage.lastUsedAt,l):L(`api.attribution.neverUsed`)})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(r?`api.attribution.sinceAvailable`:`api.attribution.since`)}),(0,J.jsx)(`dd`,{children:qu(n,l)})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:L(`api.attribution.unavailableDetail`)})]})]})]}):(0,J.jsx)(`div`,{className:`awi-overview`,children:(0,J.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,J.jsxs)(`div`,{id:Sc(`api`,`keys`),className:`awi-section-anchor`,children:[(0,J.jsx)($u,{keys:e,keysLoading:a,keysLoadFailed:o,newName:u,creating:d,newKey:f,copied:p,confirmDelete:null,localeTag:l,showKeyList:!1,onNewNameChange:T,onCreate:E,onDismissNewKey:D,onCopyKey:O,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,J.jsx)(cd,{keys:e,keysLoading:a,keysLoadFailed:o,attributionSince:n,localeTag:l,busy:ce,onSelect:e=>{z(e),ue(),K(!1),ie(!1),oe(!1)}})]}),(0,J.jsx)(`div`,{id:Sc(`api`,`connect`),className:`awi-section-anchor`,children:(0,J.jsx)(sd,{apiBase:t,baseUrl:s.baseUrl,hasKeys:e.length>0})}),(0,J.jsx)(`div`,{id:Sc(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,J.jsx)(Qu,{endpoints:s,claudeCodeEnabled:c,authMatrix:i})}),(0,J.jsx)(`div`,{id:Sc(`api`,`models`),className:`awi-section-anchor`,children:(0,J.jsx)(ed,{filteredModels:m,modelsLoading:h,modelsRefreshing:g,modelsLoadFailed:v,modelCount:y,hasModelData:b,modelQuery:x,copiedModelId:S,modelTests:C,claudeCodeEnabled:c,onModelQueryChange:j,onCopyModelId:M,onTestModel:N,onRetryModels:P,canTestModels:w,sourceLabel:F,protocolLabel:I})}),(0,J.jsx)(`div`,{id:Sc(`api`,`examples`),className:`awi-section-anchor`,children:(0,J.jsx)(td,{endpoints:s,claudeCodeEnabled:c})})]})})})})]})}var ud=[],dd=15e3;function fd(e){let t=e.replace(/\/$/,``);if(!t)return Gu;try{return new URL(t).host?Ku(`${t}/v1/responses`):Gu}catch{return Gu}}function pd(e){return!e||!Wu(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!Hu(e.usage))?null:e}function md({apiBase:e}){let{t,locale:n}=X(),r=Ue.find(e=>e.code===n)?.htmlLang,i=`ocx.apikeys.list.v2:${e}`,a=`ocx.apikeys.models.v1:${e}`,o=`api-keys:${e}`,s=`api-models:${e}`,c=pd(vn(i)),l=vn(a),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)({}),[b,x]=(0,_.useState)(``),[S,C]=(0,_.useState)(!1),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),O=(0,_.useRef)(!1),k=(0,_.useCallback)(async n=>{let r=await _t(await fetch(`${e}/api/keys`,{signal:n}));if(!r||!Wu(r.authMatrix))throw Error(t(`api.keysLoadFailed`));let a=r.keys??[];if(a.some(e=>!Hu(e.usage)))throw Error(t(`api.keysLoadFailed`));let o=a,s=Ku(r.endpoint??``),c={keys:o,endpoints:{baseUrl:r.baseUrl??s.baseUrl,responses:r.responsesEndpoint??r.endpoint??Gu.responses,chatCompletions:r.chatCompletionsEndpoint??s.chatCompletions,messages:r.messagesEndpoint??s.messages,models:r.modelsEndpoint??s.models},claudeCodeEnabled:r.claudeCodeEnabled!==!1,...r.attributionSince?{attributionSince:r.attributionSince}:{},...r.historyTruncated===!0?{historyTruncated:!0}:{},authMatrix:r.authMatrix};return yn(i,c),c},[e,i,t]),A=(0,_.useCallback)(async n=>{let r=await fetch(`${e}/v1/models`,{signal:n});if(!r.ok)throw Error(t(`api.modelsLoadFailed`));let i=await r.json(),o=Array.isArray(i)?i:typeof i==`object`&&i&&Array.isArray(i.data)?i.data:null;if(!o)throw Error(t(`api.modelsLoadFailed`));let s=o.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`).map(e=>Bu(e)).sort((e,t)=>Vu(e).localeCompare(Vu(t)));return yn(a,s),s},[e,a,t]),j=Es(o,[e],k,{isEmpty:e=>e.keys.length===0,initialData:c??void 0}),M=Es(s,[e],A,{isEmpty:e=>e.length===0,initialData:l??void 0}),N=j.state,P=M.state,F=N.data??c,I=P.data??l??ud,L=F?.keys??[],R=F?.endpoints??fd(e),z=F?.claudeCodeEnabled??!0,B=F?.attributionSince,V=F?.historyTruncated===!0,H=F?.authMatrix??[],U=j.refresh,W=M.refresh,G=(0,_.useMemo)(()=>{let e=f.trim().toLowerCase();return e?I.filter(t=>Vu(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):I},[f,I]),ee=async n=>{if(O.current)return!1;O.current=!0,C(!0),d(null);try{let r=n??b,i=await Q(await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:r||`default`})}),t(`api.createFailed`));return typeof i?.key!=`string`||i.key.length===0?(d(t(`api.createFailed`)),!1):(T(i.key),x(``),U(),!0)}catch{return d(t(`api.createFailed`)),!1}finally{O.current=!1,C(!1)}},K=async t=>{d(null);let n=y(dd);try{return(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal})).ok?(U(),!0):!1}catch{return!1}finally{n.clear()}},q=async(t,n)=>{d(null);let r=y(dd);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?(U(),!0):!1}catch{return!1}finally{r.clear()}},te=async()=>{if(w){d(null);try{await navigator.clipboard.writeText(w),D(!0),window.setTimeout(()=>D(!1),2e3)}catch{D(!1),d(t(`api.key.copyFailed`))}}},Y=async e=>{try{await navigator.clipboard.writeText(e),h(e),window.setTimeout(()=>h(t=>t===e?null:t),2e3)}catch{}},ne=e=>e.native?t(`api.sourceNative`):e.provider===`combo`?t(`api.sourceCombo`):e.custom?t(`api.sourceCustom`):e.provider,re=e=>t(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),ie=(e,t)=>e===`responses`?{url:R.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:R.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:R.chatCompletions,body:{model:t,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1}},ae=(e,t,n)=>v(r=>({...r,[e]:{...r[e],[t]:n}})),oe=async(e,n)=>{if(!w)return;let r=Vu(e),i=ie(n,r);ae(r,n,{state:`testing`});try{let e=await fetch(i.url,{method:`POST`,headers:{"Content-Type":`application/json`,"x-opencodex-api-key":w},body:JSON.stringify(i.body)});if(!e.ok){ae(r,n,{state:`error`,detail:(await e.text()).slice(0,160)||String(e.status)});return}ae(r,n,{state:`ok`})}catch(e){ae(r,n,{state:`error`,detail:e instanceof Error?e.message:t(`api.testFailed`)})}},se=t(`api.subtitle`).split(`{authHeader}`);return(0,J.jsxs)(`section`,{className:`api-page`,"aria-busy":N.refreshing||P.refreshing||void 0,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`api.title`)})}),(0,J.jsxs)(`p`,{className:`page-sub`,children:[se[0],(0,J.jsx)(`code`,{children:`x-opencodex-api-key`}),se[1]]}),u&&(0,J.jsx)(dt,{tone:`err`,children:u}),N.showError&&F&&(0,J.jsx)(dt,{tone:`err`,children:t(`api.keysLoadFailed`)}),N.showSkeleton&&!F?(0,J.jsx)(Os,{label:t(`api.activeKeysLoading`),rows:4}):N.kind===`failed-cold`&&!F?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(dt,{tone:`err`,children:N.error instanceof Error?N.error.message:t(`api.keysLoadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>U(),children:t(`common.retry`)})]}):(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(ld,{keys:L,apiBase:e,attributionSince:B,historyTruncated:V,authMatrix:H,keysLoading:!1,keysLoadFailed:N.showError,endpoints:R,claudeCodeEnabled:z,localeTag:r,newName:b,creating:S,newKey:w,copied:E,filteredModels:G,modelsLoading:P.showSkeleton&&!P.data&&!l,modelsRefreshing:P.refreshing&&P.showError&&(P.data!==void 0||l!==null),modelsLoadFailed:P.showError,modelCount:I.length,hasModelData:P.data!==void 0||l!==null,modelQuery:f,copiedModelId:m,modelTests:g,onNewNameChange:x,onCreate:()=>{ee()},onDismissNewKey:()=>T(null),onCopyKey:()=>{te()},onDelete:K,onRename:q,onModelQueryChange:p,onCopyModelId:e=>{Y(e)},onTestModel:(e,t)=>{oe(e,t)},onRetryModels:()=>{W({forceLoading:!0})},canTestModels:w!==null,sourceLabel:ne,protocolLabel:re})})]})}function hd(e,t){let n=(e??[]).map(e=>({value:e,label:ts(e)}));return[{value:``,label:t},...n]}function gd(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}var _d=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`];function vd(e){let t=`http://127.0.0.1:${e.port}`,n=e.authMode===`auto`?e.markerMode??`subscription`:e.authMode,r=e.autoContext&&e.maxContextTokens===null,i=_d.filter(t=>e.effectiveModelEnv[t]).map(t=>`export ${t}=${e.effectiveModelEnv[t]}`);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']:[],...r?[`export CLAUDE_CODE_AUTO_COMPACT_WINDOW=${e.autoCompactWindow??35e4}`]:[],...i,`claude`].join(`
67
- `)}function yd(e){return e?e.backend??`auto`:`inherit`}function bd(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function xd(e,t){return{...e,model:t}}function Sd(e){if(!e)return null;let t=(e.model??``).trim();return e.backend?{backend:e.backend,model:t}:t?{backend:null,model:t}:null}function Cd({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,J.jsxs)(`label`,{className:`toggle`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,J.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function wd({supported:e,checked:t,onChange:n}){let r=Z(),i=e?void 0:`claude-system-env-unsupported`;return(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,J.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,J.jsx)(`span`,{className:`desc`,id:i,children:(0,J.jsx)(Ye,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,J.jsx)(Cd,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function Td({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=Z(),a=t??e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,J.jsx)(ft,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,J.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function Ed(){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)}`}function Dd(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 Od(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 kd({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=Z();return(0,J.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.enabledLabel`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.enabledHint`)})]}),(0,J.jsx)(Cd,{label:i(`claude.enabledLabel`),checked:e.enabled,onChange:t=>r({...e,enabled:t})})]}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{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,J.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,J.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,J.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:Od(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,J.jsx)(wd,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{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,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,J.jsx)(Cd,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{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,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,J.jsx)(Cd,{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}`;return(0,J.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,J.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,J.jsx)(`span`,{className:`title`,children:i(o)}),(0,J.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,J.jsx)(ft,{value:yd(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]:bd(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,J.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:xd(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),style:{minWidth:210},autoComplete:`off`}),a&&(0,J.jsx)(`datalist`,{id:c,children:n.map(e=>(0,J.jsx)(`option`,{value:e},e))})]})]},t)})]})}function Ad({manualEnv:e}){let t=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,J.jsx)(Ye,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,J.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,J.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,J.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function jd({rows:e,onRowsChange:t}){let n=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,J.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,J.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,J.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,J.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,J.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,J.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,J.jsx)(fe,{})})]},r.id))}),(0,J.jsx)(`div`,{style:{marginTop:8},children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:Ed(),from:``,to:``}]),children:[(0,J.jsx)(pe,{}),` `,n(`claude.addMapping`)]})})]})}var Md=`etc`;function Nd(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:Md,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function Pd({aliases:e}){let t=Z();return(0,J.jsxs)(`div`,{className:`claude-aliases`,children:[(0,J.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,J.jsx)(`div`,{className:`claude-aliases-scroll`,children:Nd(e).map(([e,n])=>(0,J.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,J.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===Md?t(`claude.aliasProviderOther`):e,(0,J.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,J.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,J.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,J.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,J.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function Fd({apiBase:e,active:t=!0}){let n=Z(),{locale:r}=X(),i=Ue.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=`claude-code:${e}`,s=(0,_.useMemo)(()=>vn(a),[a]),[c,l]=(0,_.useState)(()=>s?.state??null),[u,d]=(0,_.useState)(()=>s?.rows??[]),[f,p]=(0,_.useState)(!!s),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(`settings`),x=(0,_.useCallback)(async t=>{let r=await Q(await fetch(`${e}/api/claude-code`,{signal:t}),n(`claude.loadFail`));if(!r)throw Error(n(`claude.loadFail`));let i={...r,authMode:r.authMode===`proxy`||r.authMode===`subscription`?r.authMode:`auto`,...gd(r),fastMode:r.fastMode??null,maxContextTokens:r.maxContextTokens??null,autoContext:r.autoContext!==!1,autoCompactWindow:r.autoCompactWindow??null,injectAgents:r.injectAgents!==!1,effectiveModelEnv:r.effectiveModelEnv??{}},o=Object.entries(r.modelMap??{}).map(([e,t])=>({id:Ed(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return l(i),d(o),p(!0),yn(a,s),s},[e,a,n]),S=Es(o,[e],x,{isEmpty:()=>!1,enabled:t,initialData:s??void 0}),C=S.state,w=C.data??s,T=c??w?.state??null,E=f?u:w?.rows??u,D=(0,_.useMemo)(()=>hd(T?.available,n(`claude.smallFastModelUnsetOption`)),[T?.available,n]),O=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,9e5,1e6],t=T?.autoCompactWindow??null,r=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:n(`claude.autoCompactDefault`)},...r.map(e=>({value:String(e),label:Dd(e,i)}))]},[T?.autoCompactWindow,n,i]),k=async()=>{if(!T)return;h(``);let t={};for(let e of E)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await Q(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:T.enabled,authMode:T.authMode,systemEnv:T.systemEnv,fastMode:T.fastMode,autoContext:T.autoContext,autoCompactWindow:T.autoCompactWindow,injectAgents:T.injectAgents,smallFastModel:T.smallFastModel,modelMap:t,webSearchSidecar:Sd(T.webSearchSidecar),visionSidecar:Sd(T.visionSidecar)})}),n(`claude.saveFailed`)),v(!0),h(n(`claude.saved`)),S.refresh()}catch(e){v(!1),h(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(C.kind===`disabled`&&!w)return null;if(C.showSkeleton&&!w)return(0,J.jsx)(Os,{label:n(`claude.loading`),rows:3});if(C.kind===`failed-cold`)return(0,J.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,J.jsx)(dt,{tone:`err`,children:C.error instanceof Error?C.error.message:n(`claude.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>S.refresh(),children:n(`common.retry`)})]});if(!T)return null;let A=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,J.jsx)(kd,{state:T,autoCompactOptions:O,availableModels:T.available??[],onStateChange:l})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,J.jsx)(Ad,{manualEnv:vd(T)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,J.jsx)(Td,{value:T.smallFastModel,tierHaikuModel:T.tierModels?.haiku,options:D,onChange:e=>l({...T,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),meta:String(E.length),body:(0,J.jsx)(jd,{rows:E,onRowsChange:e=>{p(!0),d(e)}})},{id:`aliases`,label:n(`claude.aliases`),meta:String(T.aliases.length),body:(0,J.jsx)(Pd,{aliases:T.aliases})}],j=A.find(e=>e.id===y)??A[0],M=y===`settings`||y===`smallFast`||y===`modelMap`;return(0,J.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[m&&(0,J.jsx)(dt,{tone:g?`ok`:`err`,children:m}),C.showError&&(0,J.jsx)(dt,{tone:`err`,children:n(`claude.loadFail`)}),(0,J.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,J.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,J.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:A.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${y===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>b(e.id),"aria-current":y===e.id?`true`:void 0,children:(0,J.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,J.jsxs)(`section`,{className:`claudecode-workspace-main`,"aria-label":j.label,children:[(0,J.jsxs)(`div`,{className:`ccw-main-head`,children:[(0,J.jsxs)(`h3`,{className:`ccw-main-title`,children:[j.label,j.meta==null?null:(0,J.jsx)(`span`,{className:`count`,children:j.meta})]}),(0,J.jsx)(`div`,{className:`claudecode-workspace-save`,"data-visible":M?`true`:`false`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!M,tabIndex:M?0:-1,"aria-hidden":!M,onClick:()=>{k()},children:n(`common.save`)})})]}),(0,J.jsx)(`div`,{className:`ccw-body`,children:j.body})]})]})]})}function Id(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 Ld(e){return new Set(Object.keys(e))}function Rd(e,t){return t!==null&&e===t}function zd(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function Bd(e){return{read(t){let n=zd(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=zd(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function Vd(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var Hd=[`opus`,`fable`,`sonnet`,`haiku`],Ud=Bd(`ocx.claudeDesktop.collapsedFamilies.v2`),Wd={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function Gd(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 Kd(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:Hd.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 qd(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function Jd(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 Yd(e){return vn(e)}function Xd(e){let t=Yd(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?Gd(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function Zd({apiBase:e,active:t=!0,onPortChange:n}){let{t:r,locale:i}=X(),a=Ue.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,_.useMemo)(()=>Xd(o),[o]),[l,u]=(0,_.useState)(()=>c.profile),[d,f]=(0,_.useState)(()=>c.savedProfile),[p,m]=(0,_.useState)(()=>c.destinations),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)({}),[w,T]=(0,_.useState)({}),[E,D]=(0,_.useState)(()=>Ud.read()??new Set(Hd)),[O,k]=(0,_.useState)({}),A=(0,_.useRef)(null),j=(0,_.useCallback)(async t=>{let n=await Q(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(qd(n,r(`claudeDesktop.loadFail`)));let i=Kd(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f(Gd(i)),m(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),Ud.read()===null){let e=Object.fromEntries(Hd.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;D(Ld(e))}return yn(o,a),a},[e,o,r,m,u,f]),M=Es(s,[e],j,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0}),N=M.state,P=N.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),F=P?.data??null,I=l??P?.profile??null,L=d??P?.profile??null,R=P?Object.fromEntries(P.data.models.map(e=>[e.route,P.profile.assignments[e.route]?.family??`opus`])):{},z=Object.keys(p).length>0?p:R;(0,_.useEffect)(()=>{if(n){if(typeof F?.port==`number`){n(F.port);return}N.kind===`failed-cold`&&n(null)}},[F?.port,N.kind,n]);let B=(0,_.useMemo)(()=>I!==null&&L!==null&&JSON.stringify(I)!==JSON.stringify(L),[I,L]),V=(0,_.useMemo)(()=>{let e=Object.fromEntries(Hd.map(e=>[e,[]]));if(!F||!I)return e;for(let t of F.models)e[I.assignments[t.route]?.family??`opus`].push(t);return e},[F,I]),H=(0,_.useMemo)(()=>{let e={};for(let t of Hd){let n=V[t].filter(e=>e.available).map(e=>e.route).sort(),r=I?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[V,I]),U=`ocx.claude-desktop.status.v1:${e}`,W=`claude-desktop-status:${e}`,G=vn(U),ee=Es(W,[e],async t=>{let n=await _t(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return yn(U,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:G??void 0}),K=ee.state,q=K.data??G??null,te=K.showError,Y=(e,t)=>{!I||I.assignments[e]?.family===t||(u(n=>{if(!n)return n;let r=n.assignments[e];if(!r||r.family===t)return n;let i={...n.assignments,[e]:{...r,family:t}},a={...n.defaults};return a[r.family]===e&&(a[r.family]=Object.keys(i).filter(t=>t!==e&&i[t].family===r.family).sort()[0]??null),a[t]===null&&(a[t]=e),{...n,assignments:i,defaults:a}}),m(n=>({...n,[e]:t})),y(r(`claudeDesktop.moved`,{route:e,family:r(Wd[t])})))},ne=e=>{let t=Vd(E,e);Ud.write(t),D(t)},re=async t=>{if(!(!I||b)){x(`save`),g(null);try{await Q(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:I})}),r(`claudeDesktop.saveFailed`)),f(Gd(I)),t?(x(`apply`),await Q(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`}),r(`claudeDesktop.applyFailed`)),g({tone:`ok`,text:r(`claudeDesktop.savedApplied`)}),y(r(`claudeDesktop.savedAppliedAnnounce`))):(g({tone:`ok`,text:r(`claudeDesktop.saved`)}),y(r(`claudeDesktop.savedAnnounce`))),ee.refresh()}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.updateFailed`);g({tone:`err`,text:t}),y(t)}finally{x(null)}}},ie=()=>{if(!I)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(I,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),y(r(`claudeDesktop.exported`))},ae=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(r(`claudeDesktop.importExpected`));u(Kd({...F,profile:e})),g({tone:`ok`,text:r(`claudeDesktop.importReady`)}),y(r(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.importInvalid`);g({tone:`err`,text:t}),y(r(`claudeDesktop.importFailed`,{error:t}))}},oe=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&Y(n,t)};return N.kind===`disabled`&&!P?null:N.showSkeleton&&!P?(0,J.jsx)(Os,{label:r(`claudeDesktop.loading`),rows:4}):N.kind===`failed-cold`?(0,J.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,J.jsx)(dt,{tone:`err`,children:N.error instanceof Error?N.error.message:r(`claudeDesktop.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>M.refresh(),children:r(`claudeDesktop.retry`)})]}):!F||!I?null:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,J.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,J.jsx)(`input`,{ref:A,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ae(e)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ie,children:r(`claudeDesktop.exportJson`)})]})}),(0,J.jsxs)(`div`,{className:`claude-status-bar ${te&&!q?`not-applied`:q?q.activeProfile===!1?`not-applied`:q.stale?`stale`:q.applied?`applied`:`not-applied`:`pending`}`,"aria-busy":!q&&!te||void 0,children:[(0,J.jsx)(`span`,{className:`claude-status-dot`}),(0,J.jsx)(`span`,{children:te&&!q?r(`claudeDesktop.loadFail`):q?q.activeProfile===!1?r(`claudeDesktop.status.notActiveProfile`):q.stale?r(`claudeDesktop.status.stale`):q.applied?r(`claudeDesktop.status.applied`):r(`claudeDesktop.status.notApplied`):r(`claudeDesktop.loading`)}),q?.health.lastRequestAt&&(0,J.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(q.health.lastRequestAt).toLocaleTimeString(a)]}),q&&q.health.requestCount>0&&(0,J.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:q.health.requestCount,errors:q.health.errorCount})})]}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:v}),h&&(0,J.jsx)(dt,{tone:h.tone,children:h.text}),N.showError&&(0,J.jsx)(dt,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),te&&q&&(0,J.jsx)(dt,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),(0,J.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,J.jsx)(`span`,{className:`claude-dirty${B?` active`:``}`,children:r(B?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,J.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!B||b!==null,onClick:()=>void re(!1),children:r(b===`save`?`claudeDesktop.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:b!==null,onClick:()=>void re(!0),children:r(b===`apply`?`claudeDesktop.applying`:b===`save`?`claudeDesktop.saving`:`claudeDesktop.saveApply`)})]})]}),F.models.length===0&&(0,J.jsx)(pt,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),(0,J.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:Hd.map(e=>{let t=V[e],n=Id(t,S[e]??``,w[e]??6),i=E.has(e),a=H[e];return(0,J.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>oe(t,e),children:[(0,J.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,J.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,J.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>ne(e),children:[(0,J.jsx)(we,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,J.jsx)(`span`,{className:`ocx-group-name`,children:r(Wd[e])}),(0,J.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,J.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&I.defaults[e]===null&&(0,J.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==I.defaults[e]&&(0,J.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,J.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,J.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:S[e]??``,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),T(t=>({...t,[e]:6}))}}),(0,J.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,J.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,J.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=I.assignments[t.route],i=Jd(t.contextWindow,r),a=z[t.route]??`opus`,o=O[t.route]??Rd(t.route,H[e]);return(0,J.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,J.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>k(e=>({...e,[t.route]:!o})),children:[(0,J.jsx)(we,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,J.jsxs)(`span`,{className:`claude-model-names`,children:[(0,J.jsx)(`strong`,{title:t.label,children:t.label}),(0,J.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,J.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,J.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,J.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,J.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,J.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),I.defaults[e]===t.route&&(0,J.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,J.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,J.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[H[e]===t.route&&I.defaults[e]!==t.route&&(0,J.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,J.jsxs)(`div`,{className:`claude-field`,children:[(0,J.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,J.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,J.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:I.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(Wd[e])})]}),(0,J.jsxs)(`div`,{className:`claude-move-row`,children:[(0,J.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,J.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:Hd.map(e=>(0,J.jsx)(`option`,{value:e,children:r(Wd[e])},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>Y(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>T(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})}function Qd(e){let t=vn(`ocx.claude-desktop.v1:${e}`);return typeof t?.data?.port==`number`?t.data.port:null}function $d({apiBase:e}){let[t,n]=(0,_.useState)(`code`),r=Z(),i=(0,_.useRef)(null),a=(0,_.useRef)(null),o=Qd(e),[s,c]=(0,_.useState)(null),l=s?.base===e?s.port:o,u=s?.base===e,d=(0,_.useCallback)(t=>{c(n=>n?.base===e&&n.port===t?n:{base:e,port:t})},[e]),f=e=>{n(e),window.requestAnimationFrame(()=>{(e===`code`?i:a).current?.focus({preventScroll:!0})})},p=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),f(t===`code`?`desktop`:`code`)):e.key===`Home`?(e.preventDefault(),f(`code`)):e.key===`End`&&(e.preventDefault(),f(`desktop`))};return(0,J.jsxs)(`section`,{className:`claude-page`,children:[(0,J.jsxs)(`div`,{className:`claude-page-intro`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:r(t===`code`?`claude.pageTitle`:`claudeDesktop.title`)})}),t===`code`?(0,J.jsx)(`p`,{className:`page-sub`,children:r(`claude.subtitle`)}):(0,J.jsx)(`p`,{className:`page-sub`,children:l==null?r(u?`claudeDesktop.loadFail`:`claudeDesktop.loading`):r(`claudeDesktop.subtitle`,{port:l})})]}),(0,J.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":r(`claude.tabsLabel`),children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,ref:i,"aria-selected":t===`code`,"aria-controls":`claude-code-panel`,id:`claude-code-tab`,className:t===`code`?`active`:``,tabIndex:t===`code`?0:-1,onKeyDown:p,onClick:()=>f(`code`),children:r(`claude.tabCode`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,ref:a,"aria-selected":t===`desktop`,"aria-controls":`claude-desktop-panel`,id:`claude-desktop-tab`,className:t===`desktop`?`active`:``,tabIndex:t===`desktop`?0:-1,onKeyDown:p,onClick:()=>f(`desktop`),children:r(`claude.tabDesktop`)})]}),(0,J.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:t!==`code`,children:(0,J.jsx)(Fd,{apiBase:e,active:t===`code`},e)}),(0,J.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:t!==`desktop`,children:(0,J.jsx)(Zd,{apiBase:e,active:t===`desktop`,onPortChange:d},e)})]})}function ef(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 tf=Bd(`ocx.grok.collapsedGroups.v2`),nf=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],rf=new Set(nf.map(e=>e.id));function af(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 of({apiBase:e}){let t=Z(),n=`ocx.grok.status.v1:${e}`,r=vn(n),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(()=>tf.read()??new Set(rf)),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(``),m=(0,_.useCallback)(async()=>{let r=await Q(await fetch(`${e}/api/grok`),t(`grok.loadFail`));if(!r)throw Error(t(`grok.loadFail`));let i={...r,candidates:r.candidates??[],excluded:r.excluded??[]};return yn(n,i),i},[e,n,t]),h=`grok-status:${e}`,g=Es(h,[e],m,{isEmpty:()=>!1,initialData:r??void 0}),{state:v}=g,y=g.refresh,b=v.data??r,x=(0,_.useMemo)(()=>new Set(b?.excluded??[]),[b]),S=i??x,C=(0,_.useMemo)(()=>i!==null&&(i.size!==x.size||[...i].some(e=>!x.has(e))),[i,x]),w=(0,_.useMemo)(()=>new Map((b?.models??[]).map(e=>[e.id,e.alias])),[b]),T=e=>{let t=Vd(o,e);tf.write(t),s(t)},E=e=>{let t=e?new Set(nf.map(e=>e.id)):new Set;tf.write(t),s(t)},D=(e,t)=>{a(n=>{let r=new Set(n??x);return t?r.delete(e):r.add(e),r})},O=async r=>{if(!c){l(`save`),d(null);try{await Q(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...S]})}),t(`grok.saveFailed`));let i=[...S];if(b&&q(h,{...b,excluded:i}),a(null),r){l(`apply`);let n=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.message??e.error??t(`grok.applyFailed`))}let r=await n.json().catch(()=>({}));r.skippedReason?(d({tone:`err`,text:r.message??t(`grok.applySkipped`)}),p(r.message??t(`grok.applySkipped`))):(d({tone:`ok`,text:t(`grok.savedApplied`)}),p(t(`grok.savedApplied`))),await y()}else d({tone:`ok`,text:t(`grok.saved`)}),p(t(`grok.saved`)),b&&yn(n,{...b,excluded:i})}catch(e){let n=e instanceof Error?e.message:t(`grok.saveFailed`);d({tone:`err`,text:n}),p(n)}finally{l(null)}}};return v.showSkeleton&&!b?(0,J.jsx)(`section`,{className:`grok-page`,children:(0,J.jsx)(Os,{label:t(`grok.loading`),rows:4})}):v.kind===`failed-cold`?(0,J.jsxs)(`section`,{className:`grok-page`,children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:v.error instanceof Error?v.error.message:t(`grok.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>y(),children:t(`common.retry`)})]}):(0,J.jsxs)(`section`,{className:`grok-page`,"aria-busy":v.refreshing||void 0,children:[(0,J.jsx)(`h2`,{className:`page-title`,children:t(`grok.title`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`grok.subtitle`)}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:f}),u&&(0,J.jsx)(dt,{tone:u.tone,children:u.text}),v.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`grok.loadFail`)}),b&&b.candidates.length>0&&(0,J.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,J.jsx)(`span`,{className:`claude-dirty${C?` active`:``}`,children:t(C?`grok.unsaved`:`grok.upToDate`)}),(0,J.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!C||c!==null,onClick:()=>void O(!1),children:t(c===`save`?`grok.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!C||c!==null,onClick:()=>void O(!0),children:t(c===`apply`?`grok.applying`:c===`save`?`grok.saving`:`grok.saveApply`)})]})]}),b?.present?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,J.jsx)(`span`,{children:t(`grok.endpoint`)}),(0,J.jsx)(`code`,{children:b.baseUrl??`—`})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:(0,J.jsx)(`code`,{children:b.configPath})})]}):(0,J.jsxs)(pt,{title:t(`grok.notConfiguredTitle`),children:[t(`grok.notConfiguredHint`),(0,J.jsx)(`br`,{}),(0,J.jsx)(`code`,{children:b?.configPath})]}),b&&b.candidates.length>0&&(0,J.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,J.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!0),disabled:c!==null,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!1),disabled:c!==null,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),nf.map(e=>{let n=ef(b.candidates,w,S,e.id);if(n.total===0)return null;let r=o.has(e.id);return(0,J.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,J.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,J.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,J.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>T(e.id),children:[(0,J.jsx)(we,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,J.jsx)(`span`,{className:`ocx-group-name`,children:t(e.tkey)}),(0,J.jsx)(`span`,{className:`ocx-group-count`,children:t(`grok.enabledCount`,{on:n.enabled,total:n.total})})]})})}),!r&&(0,J.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:n.rows.map(e=>(0,J.jsxs)(`div`,{className:`grok-model-row`,children:[(0,J.jsx)(ut,{on:e.enabled,onClick:()=>D(e.id,!e.enabled),disabled:c!==null,label:t(`grok.toggleModel`,{id:e.id})}),(0,J.jsxs)(`span`,{className:`grok-model-names`,children:[(0,J.jsx)(`strong`,{title:e.id,children:e.id}),(0,J.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,J.jsx)(`span`,{className:`claude-model-context`,children:af(e.contextWindow,t)})]},e.id))})]},e.id)})]})]})}function sf(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 cf={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},lf={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},uf={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function df({ok:e,yes:t,no:n}){return(0,J.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function ff({failed:e,data:t}){let{t:n}=X(),r=e?`startup-hero--risk`:t.status===`protected`?`startup-hero--safe`:t.status===`at-risk`?`startup-hero--risk`:`startup-hero--native`,i=e||t.status===`at-risk`?ve:de,a=t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,J.jsx)(`div`,{className:`startup-hero-icon`,children:(0,J.jsx)(i,{})}),(0,J.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,J.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:cf[t.status])}),(0,J.jsx)(`h3`,{children:n(e?`startup.error`:lf[t.status])}),(0,J.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(bn(t)):n(`startup.safeDetail`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,J.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,J.jsx)(`div`,{className:`value`,children:n(uf[t.protection])})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,J.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function pf({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=X(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,J.jsxs)(`section`,{className:`panel startup-details`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,J.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.service`)}),(0,J.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(df,{ok:e.serviceViable,yes:o(`startup.viable`),no:o(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-service`),children:o(r===`install-service`?`startup.installing`:`startup.install`)}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-service`,{repair:!0}),children:o(r===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.shim`)}),(0,J.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(df,{ok:e.shimHealthy&&e.autostartEnabled,yes:o(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:o(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-shim`),children:o(r===`install-shim`?`startup.installing`:`startup.install`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-shim`,{repair:!0}),children:o(r===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),i&&(0,J.jsx)(`div`,{className:`notice ${i.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:i.kind===`success`?i.action===`install-service`?o(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):o(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${o(`startup.installFailed`)} ${i.detail??``}`})]})}function mf({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=X();return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,J.jsx)(Ee,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,J.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,J.jsx)(df,{ok:e.running&&!e.stale,yes:a(`startup.tray.running`),no:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,J.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:r,onClick:()=>{window.confirm(a(`startup.tray.uninstall`))&&i(`uninstall`)},children:a(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function hf({data:e,copied:t,onCopy:n}){let{t:r}=X();return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,J.jsx)(ce,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,J.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,J.jsx)(`code`,{children:e.commands.installService})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installService),children:t===e.commands.installService?r(`startup.copied`):r(`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,J.jsx)(`code`,{children:e.commands.installShim})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?r(`startup.copied`):r(`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,J.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?r(`startup.copied`):r(`startup.copy`)})]})]}),e.status===`at-risk`&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,J.jsx)(Ee,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var gf=`ocx.startup.page.v1:`;function _f(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function vf(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=_f([`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 yf({apiBase:e}){let{t}=X(),n=`${gf}${e}`,r=(0,_.useMemo)(()=>vn(n),[n]),i=`startup-page:${e}`,[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(()=>r?.tray??null),[l,u]=(0,_.useState)(()=>!r?.data),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>r?.warning??null),[S,C]=(0,_.useState)(()=>r?.fix??null),[w,T]=(0,_.useState)(()=>!r?.data),E=(0,_.useRef)(!!r?.data),D=(0,_.useCallback)(async r=>{let i=E.current;i||(u(!0),T(!0));try{let i=fetch(`${e}/api/settings`,{signal:r}).then(async e=>e.ok?await e.json():null).catch(()=>null),a=await fetch(`${e}/api/startup-health`,{signal:r});if(!a.ok)throw Error(`fetch failed`);let o=await a.json();E.current=!0;let s=vn(n);yn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:s?.tray??null});let l=o.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:r}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!sf(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([i,l]).then(([e,i])=>{if(r.aborted)return;let a=o.platform===`win32`?i.tray:null;if(o.platform===`win32`?(c(a),m(i.error)):(c(null),m(!1)),u(!1),T(!1),e){let r=vf(e.codexRuntime,t,o.platform);x(r.warning),C(r.fix),yn(n,{data:o,warning:r.warning,fix:r.fix,tray:a});return}let s=vn(n);yn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:a})}),o}catch(e){throw r.aborted?e:(i||(c(null),m(!0),x(null),C(null)),T(!1),u(!1),e)}},[e,n,t]),O=Es(i,[e],D,{isEmpty:()=>!1,initialData:r?.data??void 0}),k=O.state,A=O.refresh,j=k.data??r?.data??null,M=k.refreshing,N=!!j?.diagnosticStale||k.showError;(0,_.useEffect)(()=>{if(!j?.diagnosticStale)return;let e=window.setTimeout(A,2e3);return()=>window.clearTimeout(e)},[j,A]);let P=async e=>{try{await navigator.clipboard.writeText(e),o(e),window.setTimeout(()=>o(t=>t===e?null:t),1600)}catch{o(null)}},F=async t=>{f(!0),m(!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(!sf(r.status))throw Error(`invalid tray action status`);c(r.status),m(!1)}catch{c(null),m(!0)}finally{f(!1)}},I=async(t,n)=>{g(t),y(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`)}y({kind:`success`,action:t,repair:n?.repair===!0}),A()}catch(e){y({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e)})}finally{g(null)}};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:t(`startup.title`)}),(0,J.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,J.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,J.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`#dashboard`,children:t(`startup.backToDashboard`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),disabled:M,children:[(0,J.jsx)(me,{}),` `,t(`startup.refresh`)]})]})]}),k.showSkeleton&&!j?(0,J.jsx)(Os,{label:t(`startup.loading`),rows:5}):k.kind===`failed-cold`?(0,J.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,J.jsx)(dt,{tone:`err`,children:k.error instanceof Error?k.error.message:t(`startup.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),children:t(`common.retry`)})]}):j?(0,J.jsxs)(J.Fragment,{children:[k.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`startup.error`)}),N&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(w||b)&&(0,J.jsx)(`div`,{className:`startup-runtime-notice-slot${w&&!b?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":w&&!b?!0:void 0,children:b&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,J.jsx)(`p`,{className:`startup-runtime-notice__text`,children:b}),S&&(0,J.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,J.jsx)(`code`,{children:S}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void P(S),children:t(a===S?`startup.copied`:`startup.copy`)})]})]})}),(0,J.jsx)(ff,{failed:N,data:j}),(0,J.jsx)(pf,{data:j,failed:N,loading:M,installBusy:h,installResult:v,onInstall:(e,t)=>{I(e,t)}}),j.platform===`win32`&&(0,J.jsx)(mf,{tray:s,trayLoading:l,trayError:p,trayBusy:d,onTrayAction:e=>{F(e)}}),(0,J.jsx)(hf,{data:j,copied:a,onCopy:e=>{P(e)}})]}):null]})}var bf=class extends _.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,J.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,J.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,J.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,J.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},xf=5*6e4,Sf=10*6e4,Cf=`https://github.com/lidge-jun/opencodex`;async function wf(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Tf({apiBase:e,onOpenUpdate:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=K(`sidebar-star:${e}`,[e],t=>wf(`${e}/api/github/star`,t),{pollMs:xf}),c=K(`sidebar-update-badge:${e}`,[e],t=>wf(`${e}/api/update/badge`,t),{pollMs:Sf}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??Cf,f=u===`starred`,p=c.data,m=p?.updateAvailable===!0,h=p?.latestVersion??null,g=()=>window.open(d,`_blank`,`noopener,noreferrer`),v=async()=>{if(!(f||r)){if(u===`unauthenticated`){g();return}i(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){o({state:`starred`,basedOn:l});return}n?.state&&o({state:n.state,basedOn:l}),g()}catch{g()}finally{i(!1),s.refresh()}}},y=n(f?`sidebar.starred`:u===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),b=m&&h?n(`sidebar.updateAvailable`,{version:h}):n(`sidebar.checkUpdate`);return(0,J.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,J.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,J.jsx)(Te,{}),` `,n(`common.github`)]}),(0,J.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`sidebar-orb${f?` sidebar-orb--starred`:``}`,onClick:()=>{v()},disabled:r||f,"aria-label":y,"aria-pressed":f,title:y,children:(0,J.jsx)(ze,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,J.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,J.jsx)(Ce,{"aria-hidden":`true`}),m&&(0,J.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Ef=!1,Df=null,Of=null,kf=!1,Af=`/`;function jf(e){try{let t=e instanceof Request?e.url:String(e),n=new URL(t,window.location.href);return n.origin===window.location.origin?n.pathname.startsWith(`/api/`):!1}catch{return!1}}var Mf=`opencodex-api-token`,Nf=null,Pf=null,Ff=null;function If(){return Nf}function Lf(e){Nf=e}function Rf(){Nf=null,Pf=null,Ff=null}function zf(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function Bf(){Hf(zf(`opencodex-session-token`),zf(`opencodex-session-csrf`),zf(`opencodex-session-origin`))}function Vf(e){e!=null&&If()===e&&Rf()}function Hf(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(Nf=e,Pf=t,Ff=n,!0)}function Uf(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname="([^"]+)"/i)?.[1]===t)return n.match(/\bcontent="([^"]*)"/i)?.[1]?.trim()||null;return null}async function Wf(){if(!Of)return null;try{let e=await Of(Af,{cache:`no-store`});if(!e.ok)return null;let t=await e.text();return Hf(Uf(t,`opencodex-session-token`),Uf(t,`opencodex-session-csrf`),Uf(t,`opencodex-session-origin`))?If():null}catch{return null}}function Gf(){try{sessionStorage.removeItem(Mf)}catch{}}function Kf(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),Ff&&Pf&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,Ff);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,Pf)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function qf(e){return kf?null:Df||(Df=(async()=>{if(kf)return null;let t=If();if(t&&t!==e)return t;let n=await Wf();if(n)return n;let r=window.prompt(`OpenCodex admin token (OPENCODEX_ADMIN_AUTH_TOKEN)`)?.trim()||null;return r?(Lf(r),r):(kf=!0,null)})().finally(()=>{Df=null}),Df)}function Jf(){if(Ef)return;Ef=!0,Gf(),Bf();let e=window.fetch.bind(window);Of=e,window.fetch=async(t,n)=>{if(!jf(t))return e(t,n);let r=If(),[i,a]=r?Kf(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;let s=If();if(s&&s!==r){let[r,i]=Kf(t,n,s),a=await e(r,i);if(a.status!==401)return a;Vf(s)}else Vf(r);let c=await qf(r);if(!c)return o;let[l,u]=Kf(t,n,c),d=await e(l,u);return d.status===401&&Vf(c),d}}var Yf=new Set([`dashboard`,`startup`,`providers`,`models`,`combos`,`subagents`,`logs`,`usage`,`storage`,`codex-auth`,`api`,`claude`,`grok`]);function Xf(e){let t=Xe(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:Yf.has(t)?t:`dashboard`}var Zf=[`dashboard/providers`,`dashboard/models`];function Qf(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`dashboard`&&(e===`dashboard/update`||Zf.includes(e))}function $f(e){let t=Xf(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:Qf(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var ep=[`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 tp(){try{for(let e of ep)localStorage.removeItem(e)}catch{}}function np(){let[e,t]=(0,_.useState)(Xf);(0,_.useEffect)(()=>{tp()},[]);let n=(0,_.useCallback)(e=>{let n=$f(e);n.replaceTo&&Ze(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(Xe(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,_.useEffect)(()=>{let t=Xe(window.location.hash);if(t===`debug`||t.startsWith(`debug/`)){Ze(`logs/debug`);return}if(t===`providers/workspace`){Ze(`providers`);return}Qf(t,e)||Ze(e)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{Qe(n?`${e}/${n}`:e),t(e)}}}var rp=15e3;function ip(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}function ap(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function op(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=rp,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`}=t,a;try{a=await n(`${e}/api/stop`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return ap(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:ip(o,a.status,i)}:{accepted:!0}}Jf();var sp={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,combos:`nav.combos`,subagents:`nav.subagents`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,"codex-auth":`nav.codexAuth`,api:`nav.api`,claude:`nav.claude`,grok:`nav.grok`},cp=``,lp=`ocx-theme`,up=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:ne},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:Oe},{id:`providers`,tkey:`nav.providers`,Icon:re},{id:`models`,tkey:`nav.models`,Icon:ie},{id:`subagents`,tkey:`nav.subagents`,Icon:ae},{id:`logs`,tkey:`nav.logs`,Icon:oe},{id:`usage`,tkey:`nav.usage`,Icon:le},{id:`storage`,tkey:`nav.storage`,Icon:ue},{id:`api`,tkey:`nav.api`,Icon:Fe},{id:`claude`,tkey:`nav.claude`,Icon:Ie},{id:`grok`,tkey:`nav.grok`,Icon:ie}],dp={light:Me,dark:Ne,system:Pe},fp={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function pp(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 mp(){let e=localStorage.getItem(lp);return e===`light`||e===`dark`?e:`system`}function hp(){let{page:e,navigateToPage:t}=np(),[n,r]=(0,_.useState)(mp),{locale:i,setLocale:a}=X(),o=Z(),[s,c]=(0,_.useState)(!1),l=(0,_.useRef)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>c(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,_.useEffect)(()=>{let e=document.documentElement;n===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(lp)):(e.setAttribute(`data-theme`,n),localStorage.setItem(lp,n))},[n]);let f=K(`app-healthz:${cp}`,[],async e=>{let t=await fetch(`${cp}/healthz`,{signal:e});return t.ok?pp(await t.json()):null},{pollMs:3e4}),p=()=>r(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),m=dp[n],h=f.data??`2.8.0-cs.15`,[g,v]=(0,_.useState)(!1),y=(0,_.useCallback)(async e=>{let t=await _t(await fetch(`${cp}/api/claude-code`,{signal:e}));return t&&typeof t.enabled==`boolean`?t.enabled:null},[]),b=K(`app-claude-code:${cp}`,[],y).data??null,x=(0,_.useRef)(!1),[S,C]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&c(!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}},[s]),(0,_.useEffect)(()=>{if(s){d.current=!0;let e=setTimeout(()=>u.current?.focus(),200);return()=>clearTimeout(e)}d.current&&(d.current=!1,l.current?.focus())},[s]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&c(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let w=async()=>{if(b===null||x.current)return;x.current=!0,C(!0);let e=!b;q(`app-claude-code:${cp}`,e);try{(await fetch(`${cp}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:e})})).ok||q(`app-claude-code:${cp}`,!e)}catch{q(`app-claude-code:${cp}`,!e)}finally{x.current=!1,C(!1)}},T=async()=>{if(!confirm(o(`dash.stopConfirm`)))return;v(!0);let e=await op(cp,{formatFailure:e=>o(`dash.stopFailed`,{status:String(e)})});e.accepted||(v(!1),alert(e.message))},E=(0,J.jsxs)(`div`,{className:`brand`,children:[(0,J.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":o(`app.logoAria`)}),(0,J.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,J.jsxs)(`span`,{className:`ver`,children:[`v`,h]})]});return(0,J.jsxs)(`div`,{className:`app`,children:[(0,J.jsxs)(`header`,{className:`mobile-topbar`,inert:s,children:[(0,J.jsx)(`button`,{ref:l,type:`button`,className:`menu-toggle`,onClick:()=>c(e=>!e),"aria-expanded":s,"aria-controls":`app-sidebar`,"aria-label":o(s?`nav.closeMenu`:`nav.openMenu`),title:o(s?`nav.closeMenu`:`nav.openMenu`),children:(0,J.jsx)(se,{})}),E,(0,J.jsx)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:(0,J.jsx)(Ee,{})})]}),s&&(0,J.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>c(!1),"aria-hidden":`true`}),(0,J.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${s?` open`:``}`,ref:u,tabIndex:-1,children:[(0,J.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,J.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>c(!1),"aria-label":o(`nav.closeMenu`),title:o(`nav.closeMenu`),children:(0,J.jsx)(fe,{})})]}),(0,J.jsx)(`nav`,{children:up.map(({id:n,tkey:r,Icon:i})=>(0,J.jsxs)(`div`,{className:`nav-entry${n===`claude`?` nav-entry-claude${e===n?` active`:``}`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`nav-item${e===n?` active`:``}`,"data-page":n,onClick:()=>{t(n),c(!1)},"aria-current":e===n?`page`:void 0,children:[(0,J.jsx)(i,{}),` `,o(r)]}),n===`claude`&&b!==null&&(0,J.jsx)(ut,{on:b,onClick:()=>void w(),disabled:S,label:o(`claude.toggleAria`)})]},n))}),(0,J.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,J.jsxs)(`div`,{className:`lang-toggle`,children:[(0,J.jsx)(Fe,{"aria-hidden":!0}),(0,J.jsx)(ft,{value:i,options:Ue.map(e=>({value:e.code,label:e.name})),onChange:e=>a(e),label:o(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,J.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:p,"aria-label":`${o(`theme.label`)}: ${o(fp[n])}`,title:`${o(`theme.label`)}: ${o(fp[n])}`,children:[(0,J.jsx)(m,{}),` `,(0,J.jsx)(`span`,{className:`mode`,children:o(fp[n])})]}),(0,J.jsxs)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:[(0,J.jsx)(Ee,{}),` `,(0,J.jsx)(`span`,{className:`mode`,children:o(g?`dash.stopping`:`dash.stop`)})]}),(0,J.jsx)(Tf,{apiBase:cp,onOpenUpdate:()=>{c(!1),t(`dashboard`,`update`)}})]})]}),(0,J.jsx)(`main`,{className:`main`,inert:s,children:(0,J.jsx)(`div`,{className:`main-inner${e===`combos`?` main-inner--combos`:``}`,children:(0,J.jsxs)(bf,{pageName:o(sp[e]),title:o(`errorBoundary.title`),message:o(`errorBoundary.message`),detailsLabel:o(`errorBoundary.details`),reloadLabel:o(`errorBoundary.reload`),children:[e===`dashboard`&&(0,J.jsx)(qn,{apiBase:cp}),e===`startup`&&(0,J.jsx)(yf,{apiBase:cp}),e===`providers`&&(0,J.jsx)(Xo,{apiBase:cp}),e===`models`&&(0,J.jsx)(nc,{apiBase:cp}),e===`combos`&&(0,J.jsx)(bc,{apiBase:cp},cp),e===`subagents`&&(0,J.jsx)(Ac,{apiBase:cp},cp),e===`logs`&&(0,J.jsx)(Yl,{apiBase:cp}),e===`usage`&&(0,J.jsx)(_u,{apiBase:cp}),e===`storage`&&(0,J.jsx)(Pu,{apiBase:cp}),e===`codex-auth`&&(0,J.jsx)(Ru,{apiBase:cp}),e===`api`&&(0,J.jsx)(md,{apiBase:cp}),e===`claude`&&(0,J.jsx)($d,{apiBase:cp}),e===`grok`&&(0,J.jsx)(of,{apiBase:cp})]},e)})})]})}v.createRoot(document.getElementById(`root`)).render((0,J.jsx)(_.StrictMode,{children:(0,J.jsx)(Je,{children:(0,J.jsx)(hp,{})})}));
67
+ `)}function yd(e){return e?e.backend??`auto`:`inherit`}function bd(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function xd(e,t){return{...e,model:t}}function Sd(e){if(!e)return null;let t=(e.model??``).trim();return e.backend?{backend:e.backend,model:t}:t?{backend:null,model:t}:null}function Cd({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,J.jsxs)(`label`,{className:`toggle`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,J.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function wd({supported:e,checked:t,onChange:n}){let r=Z(),i=e?void 0:`claude-system-env-unsupported`;return(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,J.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,J.jsx)(`span`,{className:`desc`,id:i,children:(0,J.jsx)(Ye,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,J.jsx)(Cd,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function Td({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=Z(),a=t??e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,J.jsx)(ft,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,J.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function Ed(){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)}`}function Dd(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 Od(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 kd({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=Z();return(0,J.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.enabledLabel`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.enabledHint`)})]}),(0,J.jsx)(Cd,{label:i(`claude.enabledLabel`),checked:e.enabled,onChange:t=>r({...e,enabled:t})})]}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{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,J.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,J.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,J.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:Od(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,J.jsx)(wd,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{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,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,J.jsx)(Cd,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(ft,{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,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,J.jsx)(Cd,{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}`;return(0,J.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,J.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,J.jsx)(`span`,{className:`title`,children:i(o)}),(0,J.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,J.jsx)(ft,{value:yd(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]:bd(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,J.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:xd(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),style:{minWidth:210},autoComplete:`off`}),a&&(0,J.jsx)(`datalist`,{id:c,children:n.map(e=>(0,J.jsx)(`option`,{value:e},e))})]})]},t)})]})}function Ad({manualEnv:e}){let t=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,J.jsx)(Ye,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,J.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,J.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,J.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function jd({rows:e,onRowsChange:t}){let n=Z();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,J.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,J.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,J.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,J.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,J.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,J.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,J.jsx)(fe,{})})]},r.id))}),(0,J.jsx)(`div`,{style:{marginTop:8},children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:Ed(),from:``,to:``}]),children:[(0,J.jsx)(pe,{}),` `,n(`claude.addMapping`)]})})]})}var Md=`etc`;function Nd(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:Md,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function Pd({aliases:e}){let t=Z();return(0,J.jsxs)(`div`,{className:`claude-aliases`,children:[(0,J.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,J.jsx)(`div`,{className:`claude-aliases-scroll`,children:Nd(e).map(([e,n])=>(0,J.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,J.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===Md?t(`claude.aliasProviderOther`):e,(0,J.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,J.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,J.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,J.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,J.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function Fd({apiBase:e,active:t=!0}){let n=Z(),{locale:r}=X(),i=Ue.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=`claude-code:${e}`,s=(0,_.useMemo)(()=>vn(a),[a]),[c,l]=(0,_.useState)(()=>s?.state??null),[u,d]=(0,_.useState)(()=>s?.rows??[]),[f,p]=(0,_.useState)(!!s),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(`settings`),x=(0,_.useCallback)(async t=>{let r=await Q(await fetch(`${e}/api/claude-code`,{signal:t}),n(`claude.loadFail`));if(!r)throw Error(n(`claude.loadFail`));let i={...r,authMode:r.authMode===`proxy`||r.authMode===`subscription`?r.authMode:`auto`,...gd(r),fastMode:r.fastMode??null,maxContextTokens:r.maxContextTokens??null,autoContext:r.autoContext!==!1,autoCompactWindow:r.autoCompactWindow??null,injectAgents:r.injectAgents!==!1,effectiveModelEnv:r.effectiveModelEnv??{}},o=Object.entries(r.modelMap??{}).map(([e,t])=>({id:Ed(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return l(i),d(o),p(!0),yn(a,s),s},[e,a,n]),S=Es(o,[e],x,{isEmpty:()=>!1,enabled:t,initialData:s??void 0}),C=S.state,w=C.data??s,T=c??w?.state??null,E=f?u:w?.rows??u,D=(0,_.useMemo)(()=>hd(T?.available,n(`claude.smallFastModelUnsetOption`)),[T?.available,n]),O=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,9e5,1e6],t=T?.autoCompactWindow??null,r=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:n(`claude.autoCompactDefault`)},...r.map(e=>({value:String(e),label:Dd(e,i)}))]},[T?.autoCompactWindow,n,i]),k=async()=>{if(!T)return;h(``);let t={};for(let e of E)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await Q(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:T.enabled,authMode:T.authMode,systemEnv:T.systemEnv,fastMode:T.fastMode,autoContext:T.autoContext,autoCompactWindow:T.autoCompactWindow,injectAgents:T.injectAgents,smallFastModel:T.smallFastModel,modelMap:t,webSearchSidecar:Sd(T.webSearchSidecar),visionSidecar:Sd(T.visionSidecar)})}),n(`claude.saveFailed`)),v(!0),h(n(`claude.saved`)),S.refresh()}catch(e){v(!1),h(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(C.kind===`disabled`&&!w)return null;if(C.showSkeleton&&!w)return(0,J.jsx)(Os,{label:n(`claude.loading`),rows:3});if(C.kind===`failed-cold`)return(0,J.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,J.jsx)(dt,{tone:`err`,children:C.error instanceof Error?C.error.message:n(`claude.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>S.refresh(),children:n(`common.retry`)})]});if(!T)return null;let A=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,J.jsx)(kd,{state:T,autoCompactOptions:O,availableModels:T.available??[],onStateChange:l})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,J.jsx)(Ad,{manualEnv:vd(T)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,J.jsx)(Td,{value:T.smallFastModel,tierHaikuModel:T.tierModels?.haiku,options:D,onChange:e=>l({...T,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),meta:String(E.length),body:(0,J.jsx)(jd,{rows:E,onRowsChange:e=>{p(!0),d(e)}})},{id:`aliases`,label:n(`claude.aliases`),meta:String(T.aliases.length),body:(0,J.jsx)(Pd,{aliases:T.aliases})}],j=A.find(e=>e.id===y)??A[0],M=y===`settings`||y===`smallFast`||y===`modelMap`;return(0,J.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[m&&(0,J.jsx)(dt,{tone:g?`ok`:`err`,children:m}),C.showError&&(0,J.jsx)(dt,{tone:`err`,children:n(`claude.loadFail`)}),(0,J.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,J.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,J.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:A.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${y===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>b(e.id),"aria-current":y===e.id?`true`:void 0,children:(0,J.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,J.jsxs)(`section`,{className:`claudecode-workspace-main`,"aria-label":j.label,children:[(0,J.jsxs)(`div`,{className:`ccw-main-head`,children:[(0,J.jsxs)(`h3`,{className:`ccw-main-title`,children:[j.label,j.meta==null?null:(0,J.jsx)(`span`,{className:`count`,children:j.meta})]}),(0,J.jsx)(`div`,{className:`claudecode-workspace-save`,"data-visible":M?`true`:`false`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!M,tabIndex:M?0:-1,"aria-hidden":!M,onClick:()=>{k()},children:n(`common.save`)})})]}),(0,J.jsx)(`div`,{className:`ccw-body`,children:j.body})]})]})]})}function Id(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 Ld(e){return new Set(Object.keys(e))}function Rd(e,t){return t!==null&&e===t}function zd(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function Bd(e){return{read(t){let n=zd(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=zd(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function Vd(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var Hd=[`opus`,`fable`,`sonnet`,`haiku`],Ud=Bd(`ocx.claudeDesktop.collapsedFamilies.v2`),Wd={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function Gd(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 Kd(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:Hd.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 qd(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function Jd(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 Yd(e){return vn(e)}function Xd(e){let t=Yd(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?Gd(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function Zd({apiBase:e,active:t=!0,onPortChange:n}){let{t:r,locale:i}=X(),a=Ue.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,_.useMemo)(()=>Xd(o),[o]),[l,u]=(0,_.useState)(()=>c.profile),[d,f]=(0,_.useState)(()=>c.savedProfile),[p,m]=(0,_.useState)(()=>c.destinations),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)({}),[w,T]=(0,_.useState)({}),[E,D]=(0,_.useState)(()=>Ud.read()??new Set(Hd)),[O,k]=(0,_.useState)({}),A=(0,_.useRef)(null),j=(0,_.useCallback)(async t=>{let n=await Q(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(qd(n,r(`claudeDesktop.loadFail`)));let i=Kd(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f(Gd(i)),m(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),Ud.read()===null){let e=Object.fromEntries(Hd.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;D(Ld(e))}return yn(o,a),a},[e,o,r,m,u,f]),M=Es(s,[e],j,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0}),N=M.state,P=N.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),F=P?.data??null,I=l??P?.profile??null,L=d??P?.profile??null,R=P?Object.fromEntries(P.data.models.map(e=>[e.route,P.profile.assignments[e.route]?.family??`opus`])):{},z=Object.keys(p).length>0?p:R;(0,_.useEffect)(()=>{if(n){if(typeof F?.port==`number`){n(F.port);return}N.kind===`failed-cold`&&n(null)}},[F?.port,N.kind,n]);let B=(0,_.useMemo)(()=>I!==null&&L!==null&&JSON.stringify(I)!==JSON.stringify(L),[I,L]),V=(0,_.useMemo)(()=>{let e=Object.fromEntries(Hd.map(e=>[e,[]]));if(!F||!I)return e;for(let t of F.models)e[I.assignments[t.route]?.family??`opus`].push(t);return e},[F,I]),H=(0,_.useMemo)(()=>{let e={};for(let t of Hd){let n=V[t].filter(e=>e.available).map(e=>e.route).sort(),r=I?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[V,I]),U=`ocx.claude-desktop.status.v1:${e}`,W=`claude-desktop-status:${e}`,G=vn(U),ee=Es(W,[e],async t=>{let n=await _t(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return yn(U,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:G??void 0}),K=ee.state,q=K.data??G??null,te=K.showError,Y=(e,t)=>{!I||I.assignments[e]?.family===t||(u(n=>{if(!n)return n;let r=n.assignments[e];if(!r||r.family===t)return n;let i={...n.assignments,[e]:{...r,family:t}},a={...n.defaults};return a[r.family]===e&&(a[r.family]=Object.keys(i).filter(t=>t!==e&&i[t].family===r.family).sort()[0]??null),a[t]===null&&(a[t]=e),{...n,assignments:i,defaults:a}}),m(n=>({...n,[e]:t})),y(r(`claudeDesktop.moved`,{route:e,family:r(Wd[t])})))},ne=e=>{let t=Vd(E,e);Ud.write(t),D(t)},re=async t=>{if(!(!I||b)){x(`save`),g(null);try{await Q(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:I})}),r(`claudeDesktop.saveFailed`)),f(Gd(I)),t?(x(`apply`),await Q(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`}),r(`claudeDesktop.applyFailed`)),g({tone:`ok`,text:r(`claudeDesktop.savedApplied`)}),y(r(`claudeDesktop.savedAppliedAnnounce`))):(g({tone:`ok`,text:r(`claudeDesktop.saved`)}),y(r(`claudeDesktop.savedAnnounce`))),ee.refresh()}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.updateFailed`);g({tone:`err`,text:t}),y(t)}finally{x(null)}}},ie=()=>{if(!I)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(I,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),y(r(`claudeDesktop.exported`))},ae=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(r(`claudeDesktop.importExpected`));u(Kd({...F,profile:e})),g({tone:`ok`,text:r(`claudeDesktop.importReady`)}),y(r(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.importInvalid`);g({tone:`err`,text:t}),y(r(`claudeDesktop.importFailed`,{error:t}))}},oe=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&Y(n,t)};return N.kind===`disabled`&&!P?null:N.showSkeleton&&!P?(0,J.jsx)(Os,{label:r(`claudeDesktop.loading`),rows:4}):N.kind===`failed-cold`?(0,J.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,J.jsx)(dt,{tone:`err`,children:N.error instanceof Error?N.error.message:r(`claudeDesktop.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>M.refresh(),children:r(`claudeDesktop.retry`)})]}):!F||!I?null:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,J.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,J.jsx)(`input`,{ref:A,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ae(e)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ie,children:r(`claudeDesktop.exportJson`)})]})}),(0,J.jsxs)(`div`,{className:`claude-status-bar ${te&&!q?`not-applied`:q?q.activeProfile===!1?`not-applied`:q.stale?`stale`:q.applied?`applied`:`not-applied`:`pending`}`,"aria-busy":!q&&!te||void 0,children:[(0,J.jsx)(`span`,{className:`claude-status-dot`}),(0,J.jsx)(`span`,{children:te&&!q?r(`claudeDesktop.loadFail`):q?q.activeProfile===!1?r(`claudeDesktop.status.notActiveProfile`):q.stale?r(`claudeDesktop.status.stale`):q.applied?r(`claudeDesktop.status.applied`):r(`claudeDesktop.status.notApplied`):r(`claudeDesktop.loading`)}),q?.health.lastRequestAt&&(0,J.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(q.health.lastRequestAt).toLocaleTimeString(a)]}),q&&q.health.requestCount>0&&(0,J.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:q.health.requestCount,errors:q.health.errorCount})})]}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:v}),h&&(0,J.jsx)(dt,{tone:h.tone,children:h.text}),N.showError&&(0,J.jsx)(dt,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),te&&q&&(0,J.jsx)(dt,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),(0,J.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,J.jsx)(`span`,{className:`claude-dirty${B?` active`:``}`,children:r(B?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,J.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!B||b!==null,onClick:()=>void re(!1),children:r(b===`save`?`claudeDesktop.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:b!==null,onClick:()=>void re(!0),children:r(b===`apply`?`claudeDesktop.applying`:b===`save`?`claudeDesktop.saving`:`claudeDesktop.saveApply`)})]})]}),F.models.length===0&&(0,J.jsx)(pt,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),(0,J.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:Hd.map(e=>{let t=V[e],n=Id(t,S[e]??``,w[e]??6),i=E.has(e),a=H[e];return(0,J.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>oe(t,e),children:[(0,J.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,J.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,J.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>ne(e),children:[(0,J.jsx)(we,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,J.jsx)(`span`,{className:`ocx-group-name`,children:r(Wd[e])}),(0,J.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,J.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&I.defaults[e]===null&&(0,J.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==I.defaults[e]&&(0,J.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,J.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,J.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:S[e]??``,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),T(t=>({...t,[e]:6}))}}),(0,J.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,J.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,J.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=I.assignments[t.route],i=Jd(t.contextWindow,r),a=z[t.route]??`opus`,o=O[t.route]??Rd(t.route,H[e]);return(0,J.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,J.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>k(e=>({...e,[t.route]:!o})),children:[(0,J.jsx)(we,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,J.jsxs)(`span`,{className:`claude-model-names`,children:[(0,J.jsx)(`strong`,{title:t.label,children:t.label}),(0,J.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,J.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,J.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,J.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,J.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,J.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),I.defaults[e]===t.route&&(0,J.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,J.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,J.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[H[e]===t.route&&I.defaults[e]!==t.route&&(0,J.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,J.jsxs)(`div`,{className:`claude-field`,children:[(0,J.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,J.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,J.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:I.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(Wd[e])})]}),(0,J.jsxs)(`div`,{className:`claude-move-row`,children:[(0,J.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,J.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:Hd.map(e=>(0,J.jsx)(`option`,{value:e,children:r(Wd[e])},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>Y(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>T(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})}function Qd(e){let t=vn(`ocx.claude-desktop.v1:${e}`);return typeof t?.data?.port==`number`?t.data.port:null}function $d({apiBase:e}){let[t,n]=(0,_.useState)(`code`),r=Z(),i=(0,_.useRef)(null),a=(0,_.useRef)(null),o=Qd(e),[s,c]=(0,_.useState)(null),l=s?.base===e?s.port:o,u=s?.base===e,d=(0,_.useCallback)(t=>{c(n=>n?.base===e&&n.port===t?n:{base:e,port:t})},[e]),f=e=>{n(e),window.requestAnimationFrame(()=>{(e===`code`?i:a).current?.focus({preventScroll:!0})})},p=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),f(t===`code`?`desktop`:`code`)):e.key===`Home`?(e.preventDefault(),f(`code`)):e.key===`End`&&(e.preventDefault(),f(`desktop`))};return(0,J.jsxs)(`section`,{className:`claude-page`,children:[(0,J.jsxs)(`div`,{className:`claude-page-intro`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:r(t===`code`?`claude.pageTitle`:`claudeDesktop.title`)})}),t===`code`?(0,J.jsx)(`p`,{className:`page-sub`,children:r(`claude.subtitle`)}):(0,J.jsx)(`p`,{className:`page-sub`,children:l==null?r(u?`claudeDesktop.loadFail`:`claudeDesktop.loading`):r(`claudeDesktop.subtitle`,{port:l})})]}),(0,J.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":r(`claude.tabsLabel`),children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,ref:i,"aria-selected":t===`code`,"aria-controls":`claude-code-panel`,id:`claude-code-tab`,className:t===`code`?`active`:``,tabIndex:t===`code`?0:-1,onKeyDown:p,onClick:()=>f(`code`),children:r(`claude.tabCode`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,ref:a,"aria-selected":t===`desktop`,"aria-controls":`claude-desktop-panel`,id:`claude-desktop-tab`,className:t===`desktop`?`active`:``,tabIndex:t===`desktop`?0:-1,onKeyDown:p,onClick:()=>f(`desktop`),children:r(`claude.tabDesktop`)})]}),(0,J.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:t!==`code`,children:(0,J.jsx)(Fd,{apiBase:e,active:t===`code`},e)}),(0,J.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:t!==`desktop`,children:(0,J.jsx)(Zd,{apiBase:e,active:t===`desktop`,onPortChange:d},e)})]})}function ef(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 tf=Bd(`ocx.grok.collapsedGroups.v2`),nf=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],rf=new Set(nf.map(e=>e.id));function af(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 of({apiBase:e}){let t=Z(),n=`ocx.grok.status.v1:${e}`,r=vn(n),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(()=>tf.read()??new Set(rf)),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(``),m=(0,_.useCallback)(async()=>{let r=await Q(await fetch(`${e}/api/grok`),t(`grok.loadFail`));if(!r)throw Error(t(`grok.loadFail`));let i={...r,candidates:r.candidates??[],excluded:r.excluded??[]};return yn(n,i),i},[e,n,t]),h=`grok-status:${e}`,g=Es(h,[e],m,{isEmpty:()=>!1,initialData:r??void 0}),{state:v}=g,y=g.refresh,b=v.data??r,x=(0,_.useMemo)(()=>new Set(b?.excluded??[]),[b]),S=i??x,C=(0,_.useMemo)(()=>i!==null&&(i.size!==x.size||[...i].some(e=>!x.has(e))),[i,x]),w=(0,_.useMemo)(()=>new Map((b?.models??[]).map(e=>[e.id,e.alias])),[b]),T=e=>{let t=Vd(o,e);tf.write(t),s(t)},E=e=>{let t=e?new Set(nf.map(e=>e.id)):new Set;tf.write(t),s(t)},D=(e,t)=>{a(n=>{let r=new Set(n??x);return t?r.delete(e):r.add(e),r})},O=async r=>{if(!c){l(`save`),d(null);try{await Q(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...S]})}),t(`grok.saveFailed`));let i=[...S];if(b&&q(h,{...b,excluded:i}),a(null),r){l(`apply`);let n=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.message??e.error??t(`grok.applyFailed`))}let r=await n.json().catch(()=>({}));r.skippedReason?(d({tone:`err`,text:r.message??t(`grok.applySkipped`)}),p(r.message??t(`grok.applySkipped`))):(d({tone:`ok`,text:t(`grok.savedApplied`)}),p(t(`grok.savedApplied`))),await y()}else d({tone:`ok`,text:t(`grok.saved`)}),p(t(`grok.saved`)),b&&yn(n,{...b,excluded:i})}catch(e){let n=e instanceof Error?e.message:t(`grok.saveFailed`);d({tone:`err`,text:n}),p(n)}finally{l(null)}}};return v.showSkeleton&&!b?(0,J.jsx)(`section`,{className:`grok-page`,children:(0,J.jsx)(Os,{label:t(`grok.loading`),rows:4})}):v.kind===`failed-cold`?(0,J.jsxs)(`section`,{className:`grok-page`,children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:v.error instanceof Error?v.error.message:t(`grok.loadFail`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>y(),children:t(`common.retry`)})]}):(0,J.jsxs)(`section`,{className:`grok-page`,"aria-busy":v.refreshing||void 0,children:[(0,J.jsx)(`h2`,{className:`page-title`,children:t(`grok.title`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`grok.subtitle`)}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:f}),u&&(0,J.jsx)(dt,{tone:u.tone,children:u.text}),v.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`grok.loadFail`)}),b&&b.candidates.length>0&&(0,J.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,J.jsx)(`span`,{className:`claude-dirty${C?` active`:``}`,children:t(C?`grok.unsaved`:`grok.upToDate`)}),(0,J.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!C||c!==null,onClick:()=>void O(!1),children:t(c===`save`?`grok.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!C||c!==null,onClick:()=>void O(!0),children:t(c===`apply`?`grok.applying`:c===`save`?`grok.saving`:`grok.saveApply`)})]})]}),b?.present?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,J.jsx)(`span`,{children:t(`grok.endpoint`)}),(0,J.jsx)(`code`,{children:b.baseUrl??`—`})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:(0,J.jsx)(`code`,{children:b.configPath})})]}):(0,J.jsxs)(pt,{title:t(`grok.notConfiguredTitle`),children:[t(`grok.notConfiguredHint`),(0,J.jsx)(`br`,{}),(0,J.jsx)(`code`,{children:b?.configPath})]}),b&&b.candidates.length>0&&(0,J.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,J.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!0),disabled:c!==null,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!1),disabled:c!==null,children:[(0,J.jsx)(we,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),nf.map(e=>{let n=ef(b.candidates,w,S,e.id);if(n.total===0)return null;let r=o.has(e.id);return(0,J.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,J.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,J.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,J.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>T(e.id),children:[(0,J.jsx)(we,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,J.jsx)(`span`,{className:`ocx-group-name`,children:t(e.tkey)}),(0,J.jsx)(`span`,{className:`ocx-group-count`,children:t(`grok.enabledCount`,{on:n.enabled,total:n.total})})]})})}),!r&&(0,J.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:n.rows.map(e=>(0,J.jsxs)(`div`,{className:`grok-model-row`,children:[(0,J.jsx)(ut,{on:e.enabled,onClick:()=>D(e.id,!e.enabled),disabled:c!==null,label:t(`grok.toggleModel`,{id:e.id})}),(0,J.jsxs)(`span`,{className:`grok-model-names`,children:[(0,J.jsx)(`strong`,{title:e.id,children:e.id}),(0,J.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,J.jsx)(`span`,{className:`claude-model-context`,children:af(e.contextWindow,t)})]},e.id))})]},e.id)})]})]})}function sf(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 cf={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},lf={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},uf={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function df({ok:e,yes:t,no:n}){return(0,J.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function ff({failed:e,data:t}){let{t:n}=X(),r=e?`startup-hero--risk`:t.status===`protected`?`startup-hero--safe`:t.status===`at-risk`?`startup-hero--risk`:`startup-hero--native`,i=e||t.status===`at-risk`?ve:de,a=t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,J.jsx)(`div`,{className:`startup-hero-icon`,children:(0,J.jsx)(i,{})}),(0,J.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,J.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:cf[t.status])}),(0,J.jsx)(`h3`,{children:n(e?`startup.error`:lf[t.status])}),(0,J.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(bn(t)):n(`startup.safeDetail`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,J.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,J.jsx)(`div`,{className:`value`,children:n(uf[t.protection])})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,J.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function pf({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=X(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,J.jsxs)(`section`,{className:`panel startup-details`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,J.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.service`)}),(0,J.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(df,{ok:e.serviceViable,yes:o(`startup.viable`),no:o(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-service`),children:o(r===`install-service`?`startup.installing`:`startup.install`)}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-service`,{repair:!0}),children:o(r===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.shim`)}),(0,J.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(df,{ok:e.shimHealthy&&e.autostartEnabled,yes:o(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:o(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-shim`),children:o(r===`install-shim`?`startup.installing`:`startup.install`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-shim`,{repair:!0}),children:o(r===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),i&&(0,J.jsx)(`div`,{className:`notice ${i.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:i.kind===`success`?i.action===`install-service`?o(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):o(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${o(`startup.installFailed`)} ${i.detail??``}`})]})}function mf({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=X();return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,J.jsx)(Ee,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,J.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,J.jsx)(df,{ok:e.running&&!e.stale,yes:a(`startup.tray.running`),no:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,J.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:r,onClick:()=>{window.confirm(a(`startup.tray.uninstall`))&&i(`uninstall`)},children:a(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function hf({data:e,copied:t,onCopy:n}){let{t:r}=X();return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,J.jsx)(ce,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,J.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,J.jsx)(`code`,{children:e.commands.installService})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installService),children:t===e.commands.installService?r(`startup.copied`):r(`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,J.jsx)(`code`,{children:e.commands.installShim})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?r(`startup.copied`):r(`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,J.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?r(`startup.copied`):r(`startup.copy`)})]})]}),e.status===`at-risk`&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,J.jsx)(Ee,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var gf=`ocx.startup.page.v1:`;function _f(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function vf(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=_f([`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 yf({apiBase:e}){let{t}=X(),n=`${gf}${e}`,r=(0,_.useMemo)(()=>vn(n),[n]),i=`startup-page:${e}`,[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(()=>r?.tray??null),[l,u]=(0,_.useState)(()=>!r?.data),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>r?.warning??null),[S,C]=(0,_.useState)(()=>r?.fix??null),[w,T]=(0,_.useState)(()=>!r?.data),E=(0,_.useRef)(!!r?.data),D=(0,_.useCallback)(async r=>{let i=E.current;i||(u(!0),T(!0));try{let i=fetch(`${e}/api/settings`,{signal:r}).then(async e=>e.ok?await e.json():null).catch(()=>null),a=await fetch(`${e}/api/startup-health`,{signal:r});if(!a.ok)throw Error(`fetch failed`);let o=await a.json();E.current=!0;let s=vn(n);yn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:s?.tray??null});let l=o.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:r}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!sf(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([i,l]).then(([e,i])=>{if(r.aborted)return;let a=o.platform===`win32`?i.tray:null;if(o.platform===`win32`?(c(a),m(i.error)):(c(null),m(!1)),u(!1),T(!1),e){let r=vf(e.codexRuntime,t,o.platform);x(r.warning),C(r.fix),yn(n,{data:o,warning:r.warning,fix:r.fix,tray:a});return}let s=vn(n);yn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:a})}),o}catch(e){throw r.aborted?e:(i||(c(null),m(!0),x(null),C(null)),T(!1),u(!1),e)}},[e,n,t]),O=Es(i,[e],D,{isEmpty:()=>!1,initialData:r?.data??void 0}),k=O.state,A=O.refresh,j=k.data??r?.data??null,M=k.refreshing,N=!!j?.diagnosticStale||k.showError;(0,_.useEffect)(()=>{if(!j?.diagnosticStale)return;let e=window.setTimeout(A,2e3);return()=>window.clearTimeout(e)},[j,A]);let P=async e=>{try{await navigator.clipboard.writeText(e),o(e),window.setTimeout(()=>o(t=>t===e?null:t),1600)}catch{o(null)}},F=async t=>{f(!0),m(!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(!sf(r.status))throw Error(`invalid tray action status`);c(r.status),m(!1)}catch{c(null),m(!0)}finally{f(!1)}},I=async(t,n)=>{g(t),y(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`)}y({kind:`success`,action:t,repair:n?.repair===!0}),A()}catch(e){y({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e)})}finally{g(null)}};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:t(`startup.title`)}),(0,J.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,J.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,J.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`#dashboard`,children:t(`startup.backToDashboard`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),disabled:M,children:[(0,J.jsx)(me,{}),` `,t(`startup.refresh`)]})]})]}),k.showSkeleton&&!j?(0,J.jsx)(Os,{label:t(`startup.loading`),rows:5}):k.kind===`failed-cold`?(0,J.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,J.jsx)(dt,{tone:`err`,children:k.error instanceof Error?k.error.message:t(`startup.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),children:t(`common.retry`)})]}):j?(0,J.jsxs)(J.Fragment,{children:[k.showError&&(0,J.jsx)(dt,{tone:`err`,children:t(`startup.error`)}),N&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(w||b)&&(0,J.jsx)(`div`,{className:`startup-runtime-notice-slot${w&&!b?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":w&&!b?!0:void 0,children:b&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,J.jsx)(`p`,{className:`startup-runtime-notice__text`,children:b}),S&&(0,J.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,J.jsx)(`code`,{children:S}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void P(S),children:t(a===S?`startup.copied`:`startup.copy`)})]})]})}),(0,J.jsx)(ff,{failed:N,data:j}),(0,J.jsx)(pf,{data:j,failed:N,loading:M,installBusy:h,installResult:v,onInstall:(e,t)=>{I(e,t)}}),j.platform===`win32`&&(0,J.jsx)(mf,{tray:s,trayLoading:l,trayError:p,trayBusy:d,onTrayAction:e=>{F(e)}}),(0,J.jsx)(hf,{data:j,copied:a,onCopy:e=>{P(e)}})]}):null]})}var bf=class extends _.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,J.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,J.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,J.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,J.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},xf=5*6e4,Sf=10*6e4,Cf=`https://github.com/lidge-jun/opencodex`;async function wf(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Tf({apiBase:e,onOpenUpdate:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=K(`sidebar-star:${e}`,[e],t=>wf(`${e}/api/github/star`,t),{pollMs:xf}),c=K(`sidebar-update-badge:${e}`,[e],t=>wf(`${e}/api/update/badge`,t),{pollMs:Sf}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??Cf,f=u===`starred`,p=c.data,m=p?.updateAvailable===!0,h=p?.latestVersion??null,g=()=>window.open(d,`_blank`,`noopener,noreferrer`),v=async()=>{if(!(f||r)){if(u===`unauthenticated`){g();return}i(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){o({state:`starred`,basedOn:l});return}n?.state&&o({state:n.state,basedOn:l}),g()}catch{g()}finally{i(!1),s.refresh()}}},y=n(f?`sidebar.starred`:u===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),b=m&&h?n(`sidebar.updateAvailable`,{version:h}):n(`sidebar.checkUpdate`);return(0,J.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,J.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,J.jsx)(Te,{}),` `,n(`common.github`)]}),(0,J.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`sidebar-orb${f?` sidebar-orb--starred`:``}`,onClick:()=>{v()},disabled:r||f,"aria-label":y,"aria-pressed":f,title:y,children:(0,J.jsx)(ze,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,J.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,J.jsx)(Ce,{"aria-hidden":`true`}),m&&(0,J.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Ef=!1,Df=null,Of=null,kf=!1,Af=`/`;function jf(e){try{let t=e instanceof Request?e.url:String(e),n=new URL(t,window.location.href);return n.origin===window.location.origin?n.pathname.startsWith(`/api/`):!1}catch{return!1}}var Mf=`opencodex-api-token`,Nf=null,Pf=null,Ff=null;function If(){return Nf}function Lf(e){Nf=e}function Rf(){Nf=null,Pf=null,Ff=null}function zf(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function Bf(){Hf(zf(`opencodex-session-token`),zf(`opencodex-session-csrf`),zf(`opencodex-session-origin`))}function Vf(e){e!=null&&If()===e&&Rf()}function Hf(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(Nf=e,Pf=t,Ff=n,!0)}function Uf(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname="([^"]+)"/i)?.[1]===t)return n.match(/\bcontent="([^"]*)"/i)?.[1]?.trim()||null;return null}async function Wf(){if(!Of)return null;try{let e=await Of(Af,{cache:`no-store`});if(!e.ok)return null;let t=await e.text();return Hf(Uf(t,`opencodex-session-token`),Uf(t,`opencodex-session-csrf`),Uf(t,`opencodex-session-origin`))?If():null}catch{return null}}function Gf(){try{sessionStorage.removeItem(Mf)}catch{}}function Kf(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),Ff&&Pf&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,Ff);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,Pf)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function qf(e){return kf?null:Df||(Df=(async()=>{if(kf)return null;let t=If();if(t&&t!==e)return t;let n=await Wf();if(n)return n;let r=window.prompt(`OpenCodex admin token (OPENCODEX_ADMIN_AUTH_TOKEN)`)?.trim()||null;return r?(Lf(r),r):(kf=!0,null)})().finally(()=>{Df=null}),Df)}function Jf(){if(Ef)return;Ef=!0,Gf(),Bf();let e=window.fetch.bind(window);Of=e,window.fetch=async(t,n)=>{if(!jf(t))return e(t,n);let r=If(),[i,a]=r?Kf(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;let s=If();if(s&&s!==r){let[r,i]=Kf(t,n,s),a=await e(r,i);if(a.status!==401)return a;Vf(s)}else Vf(r);let c=await qf(r);if(!c)return o;let[l,u]=Kf(t,n,c),d=await e(l,u);return d.status===401&&Vf(c),d}}var Yf=new Set([`dashboard`,`startup`,`providers`,`models`,`combos`,`subagents`,`logs`,`usage`,`storage`,`codex-auth`,`api`,`claude`,`grok`]);function Xf(e){let t=Xe(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:Yf.has(t)?t:`dashboard`}var Zf=[`dashboard/providers`,`dashboard/models`];function Qf(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`dashboard`&&(e===`dashboard/update`||Zf.includes(e))}function $f(e){let t=Xf(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:Qf(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var ep=[`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 tp(){try{for(let e of ep)localStorage.removeItem(e)}catch{}}function np(){let[e,t]=(0,_.useState)(Xf);(0,_.useEffect)(()=>{tp()},[]);let n=(0,_.useCallback)(e=>{let n=$f(e);n.replaceTo&&Ze(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(Xe(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,_.useEffect)(()=>{let t=Xe(window.location.hash);if(t===`debug`||t.startsWith(`debug/`)){Ze(`logs/debug`);return}if(t===`providers/workspace`){Ze(`providers`);return}Qf(t,e)||Ze(e)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{Qe(n?`${e}/${n}`:e),t(e)}}}var rp=15e3;function ip(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}function ap(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function op(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=rp,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`}=t,a;try{a=await n(`${e}/api/stop`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return ap(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:ip(o,a.status,i)}:{accepted:!0}}Jf();var sp={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,combos:`nav.combos`,subagents:`nav.subagents`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,"codex-auth":`nav.codexAuth`,api:`nav.api`,claude:`nav.claude`,grok:`nav.grok`},cp=``,lp=`ocx-theme`,up=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:ne},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:Oe},{id:`providers`,tkey:`nav.providers`,Icon:re},{id:`models`,tkey:`nav.models`,Icon:ie},{id:`subagents`,tkey:`nav.subagents`,Icon:ae},{id:`logs`,tkey:`nav.logs`,Icon:oe},{id:`usage`,tkey:`nav.usage`,Icon:le},{id:`storage`,tkey:`nav.storage`,Icon:ue},{id:`api`,tkey:`nav.api`,Icon:Fe},{id:`claude`,tkey:`nav.claude`,Icon:Ie},{id:`grok`,tkey:`nav.grok`,Icon:ie}],dp={light:Me,dark:Ne,system:Pe},fp={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function pp(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 mp(){let e=localStorage.getItem(lp);return e===`light`||e===`dark`?e:`system`}function hp(){let{page:e,navigateToPage:t}=np(),[n,r]=(0,_.useState)(mp),{locale:i,setLocale:a}=X(),o=Z(),[s,c]=(0,_.useState)(!1),l=(0,_.useRef)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>c(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,_.useEffect)(()=>{let e=document.documentElement;n===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(lp)):(e.setAttribute(`data-theme`,n),localStorage.setItem(lp,n))},[n]);let f=K(`app-healthz:${cp}`,[],async e=>{let t=await fetch(`${cp}/healthz`,{signal:e});return t.ok?pp(await t.json()):null},{pollMs:3e4}),p=()=>r(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),m=dp[n],h=f.data??`2.8.0-cs.17`,[g,v]=(0,_.useState)(!1),y=(0,_.useCallback)(async e=>{let t=await _t(await fetch(`${cp}/api/claude-code`,{signal:e}));return t&&typeof t.enabled==`boolean`?t.enabled:null},[]),b=K(`app-claude-code:${cp}`,[],y).data??null,x=(0,_.useRef)(!1),[S,C]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&c(!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}},[s]),(0,_.useEffect)(()=>{if(s){d.current=!0;let e=setTimeout(()=>u.current?.focus(),200);return()=>clearTimeout(e)}d.current&&(d.current=!1,l.current?.focus())},[s]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&c(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let w=async()=>{if(b===null||x.current)return;x.current=!0,C(!0);let e=!b;q(`app-claude-code:${cp}`,e);try{(await fetch(`${cp}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:e})})).ok||q(`app-claude-code:${cp}`,!e)}catch{q(`app-claude-code:${cp}`,!e)}finally{x.current=!1,C(!1)}},T=async()=>{if(!confirm(o(`dash.stopConfirm`)))return;v(!0);let e=await op(cp,{formatFailure:e=>o(`dash.stopFailed`,{status:String(e)})});e.accepted||(v(!1),alert(e.message))},E=(0,J.jsxs)(`div`,{className:`brand`,children:[(0,J.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":o(`app.logoAria`)}),(0,J.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,J.jsxs)(`span`,{className:`ver`,children:[`v`,h]})]});return(0,J.jsxs)(`div`,{className:`app`,children:[(0,J.jsxs)(`header`,{className:`mobile-topbar`,inert:s,children:[(0,J.jsx)(`button`,{ref:l,type:`button`,className:`menu-toggle`,onClick:()=>c(e=>!e),"aria-expanded":s,"aria-controls":`app-sidebar`,"aria-label":o(s?`nav.closeMenu`:`nav.openMenu`),title:o(s?`nav.closeMenu`:`nav.openMenu`),children:(0,J.jsx)(se,{})}),E,(0,J.jsx)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:(0,J.jsx)(Ee,{})})]}),s&&(0,J.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>c(!1),"aria-hidden":`true`}),(0,J.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${s?` open`:``}`,ref:u,tabIndex:-1,children:[(0,J.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,J.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>c(!1),"aria-label":o(`nav.closeMenu`),title:o(`nav.closeMenu`),children:(0,J.jsx)(fe,{})})]}),(0,J.jsx)(`nav`,{children:up.map(({id:n,tkey:r,Icon:i})=>(0,J.jsxs)(`div`,{className:`nav-entry${n===`claude`?` nav-entry-claude${e===n?` active`:``}`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`nav-item${e===n?` active`:``}`,"data-page":n,onClick:()=>{t(n),c(!1)},"aria-current":e===n?`page`:void 0,children:[(0,J.jsx)(i,{}),` `,o(r)]}),n===`claude`&&b!==null&&(0,J.jsx)(ut,{on:b,onClick:()=>void w(),disabled:S,label:o(`claude.toggleAria`)})]},n))}),(0,J.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,J.jsxs)(`div`,{className:`lang-toggle`,children:[(0,J.jsx)(Fe,{"aria-hidden":!0}),(0,J.jsx)(ft,{value:i,options:Ue.map(e=>({value:e.code,label:e.name})),onChange:e=>a(e),label:o(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,J.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:p,"aria-label":`${o(`theme.label`)}: ${o(fp[n])}`,title:`${o(`theme.label`)}: ${o(fp[n])}`,children:[(0,J.jsx)(m,{}),` `,(0,J.jsx)(`span`,{className:`mode`,children:o(fp[n])})]}),(0,J.jsxs)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:[(0,J.jsx)(Ee,{}),` `,(0,J.jsx)(`span`,{className:`mode`,children:o(g?`dash.stopping`:`dash.stop`)})]}),(0,J.jsx)(Tf,{apiBase:cp,onOpenUpdate:()=>{c(!1),t(`dashboard`,`update`)}})]})]}),(0,J.jsx)(`main`,{className:`main`,inert:s,children:(0,J.jsx)(`div`,{className:`main-inner${e===`combos`?` main-inner--combos`:``}`,children:(0,J.jsxs)(bf,{pageName:o(sp[e]),title:o(`errorBoundary.title`),message:o(`errorBoundary.message`),detailsLabel:o(`errorBoundary.details`),reloadLabel:o(`errorBoundary.reload`),children:[e===`dashboard`&&(0,J.jsx)(qn,{apiBase:cp}),e===`startup`&&(0,J.jsx)(yf,{apiBase:cp}),e===`providers`&&(0,J.jsx)(Xo,{apiBase:cp}),e===`models`&&(0,J.jsx)(nc,{apiBase:cp}),e===`combos`&&(0,J.jsx)(bc,{apiBase:cp},cp),e===`subagents`&&(0,J.jsx)(Ac,{apiBase:cp},cp),e===`logs`&&(0,J.jsx)(Yl,{apiBase:cp}),e===`usage`&&(0,J.jsx)(_u,{apiBase:cp}),e===`storage`&&(0,J.jsx)(Pu,{apiBase:cp}),e===`codex-auth`&&(0,J.jsx)(Ru,{apiBase:cp}),e===`api`&&(0,J.jsx)(md,{apiBase:cp}),e===`claude`&&(0,J.jsx)($d,{apiBase:cp}),e===`grok`&&(0,J.jsx)(of,{apiBase:cp})]},e)})})]})}v.createRoot(document.getElementById(`root`)).render((0,J.jsx)(_.StrictMode,{children:(0,J.jsx)(Je,{children:(0,J.jsx)(hp,{})})}));