@bitkyc08/opencodex 2.8.0 → 2.8.2-preview.20260731

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.
@@ -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.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.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.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.allProviders":`プロバイダー概要`,"pws.enabledLabel":`有効`,"pws.testConnection":`接続テスト`,"pws.testing":`テスト中…`,"pws.connectionOk":`接続 OK`,"pws.connectionFailed":`接続失敗`,"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":`アカウント切り替えでプロンプトキャッシュはリセットされます。新規セッションは空のキャッシュで開始します。`,"codexAuth.setAsNext":`アカウントを選択`,"codexAuth.cancel":`キャンセル`,"codexAuth.switchBack":`メインに戻しますか?`,"codexAuth.switchBackDesc":`既存および新規 Codex セッションの次のリクエストからアプリログインアカウントを使用します。`,"codexAuth.autoSwitch":`アカウントの自動切り替え`,"codexAuth.autoSwitchDesc":`使用率が {threshold}% 以上で、より使用率の低い利用可能なアカウントがある場合に切り替えます。Go/Free は 30 日枠のみを使用します`,"codexAuth.autoSwitchOffDesc":`アカウントの自動切り替えはオフです`,"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":`新規セッションがプールからアカウントを選ぶ方法です。`,"accountPool.strategyQuota":`クォータ`,"accountPool.strategyRoundRobin":`ラウンドロビン`,"accountPool.strategyFillFirst":`フィルファースト`,"accountPool.strategyHint":`新規セッションにのみ適用されます。既存スレッドはアカウント親和性を維持します。`,"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} または {altHeader} ヘッダーで認証します。`,"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.authResponses":`Responses リクエストは x-opencodex-api-key を使ってください。Authorization は Codex Direct 用に予約されている場合があります。`,"api.authChatCompletions":`Chat Completions と /v1/models は Authorization: Bearer ocx_... または x-opencodex-api-key を受け付けます。`,"api.authMessages":`Messages は Authorization: Bearer ocx_... または x-opencodex-api-key を受け付けます。`,"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.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.overview":`概要`,"api.workspace.details":`APIキーの詳細`,"api.workspace.keyDetails":`キーの詳細`,"api.workspace.keyPrefix":`キーのプレフィックス`,"api.workspace.deleteKey":`キーを削除`,"api.workspace.deleteConfirm":`このキーを削除しますか?この操作は元に戻せません。`,"api.workspace.noKeysHint":`API キーがまだありません。作成して始めましょう。`,"api.workspace.selectKeyHint":`一覧からキーを選択すると、詳細が表示されます。`,"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.keysLoadFailed":`APIキーを読み込めませんでした。`,"api.createFailed":`APIキーを作成できませんでした。`,"api.deleteFailed":`APIキーを削除できませんでした。`,"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":`今すぐ同期`}},Ie=[{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`}],Le=`ocx-lang`;function Re(){try{let e=localStorage.getItem(Le);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 ze=(0,_.createContext)(null);function Be(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 G(){let e=(0,_.useContext)(ze);if(!e)throw Error(`useI18n must be used within LanguageProvider`);return e}function K(){return G().t}function Ve({children:e}){let[t,n]=(0,_.useState)(Re);(0,_.useEffect)(()=>{let e=Ie.find(e=>e.code===t)??Ie[0];document.documentElement.lang=e.htmlLang;try{localStorage.setItem(`ocx-lang`,t)}catch{}},[t]);let r=(0,_.useCallback)((e,n)=>Be(Fe[t][e]??Pe[e]??e,n),[t]),i=(0,_.useMemo)(()=>({locale:t,setLocale:n,t:r}),[t,r]);return(0,R.jsx)(ze.Provider,{value:i,children:e})}function He({k:e,cmd:t,vars:n}){let{t:r}=G(),[i,a=``]=r(e,n).split(`{cmd}`);return(0,R.jsxs)(R.Fragment,{children:[i,(0,R.jsx)(`code`,{className:`chip`,children:t}),a]})}function Ue(e){return e.replace(/^#\/?/,``)}function We(e,t=window){let n=Ue(e);if(Ue(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function Ge(e,t=window){let n=Ue(e);Ue(t.location.hash)!==n&&(t.location.hash=n)}var Ke=m(),qe=4,Je=8,Ye=8,Xe=280,Ze=120,Qe=160;function $e(){return typeof window<`u`?window.innerHeight:800}function et(){return typeof window<`u`?window.innerWidth:1024}function tt(e,{align:t=`left`,placement:n=`below`,menuHeight:r=Xe}={}){let i=Math.min(Math.max(r,Ze),Xe),a=$e(),o=et();if(n===`right`){let t=a-e.top-Ye,n=e.top-Ye,r=i+Je>t&&n>t,s=Math.max(Ye,Math.min(e.right+6,o-Qe-Ye));return r?{position:`fixed`,left:s,bottom:a-e.top+Je,minWidth:Qe,maxHeight:Math.max(Ze,Math.min(Xe,e.top-Ye-qe))}:{position:`fixed`,top:e.top,left:s,minWidth:Qe,maxHeight:Math.max(Ze,Math.min(Xe,a-e.top-Ye))}}let s=Math.max(e.width,0),c=a-e.bottom-Ye,l=e.top-Ye;if(i+qe>c&&l>c){let n={position:`fixed`,bottom:a-e.top+Je,minWidth:s,maxHeight:Math.max(0,Math.min(Xe,l-qe))};return t===`right`?n.right=o-e.right:n.left=Math.max(Ye,Math.min(e.left,o-Ye-s)),n}let u={position:`fixed`,top:e.bottom+qe,minWidth:s,maxHeight:Math.max(0,Math.min(Xe,c-qe))};return t===`right`?u.right=o-e.right:u.left=Math.max(Ye,Math.min(e.left,o-Ye-s)),u}function nt({on:e,onClick:t,disabled:n,label:r}){return(0,R.jsx)(`button`,{type:`button`,className:`switch${e?` on`:``}`,onClick:t,disabled:n,"aria-pressed":e,"aria-label":r??(e?`enabled`:`disabled`),children:(0,R.jsx)(`span`,{className:`knob`})})}function q({tone:e,children:t}){return(0,R.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,R.jsx)(ie,{}):(0,R.jsx)(de,{}),(0,R.jsx)(`span`,{children:t})]})}function rt({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(tt(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=tt(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,R.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,R.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,R.jsxs)(`div`,{ref:y,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...o},children:[(0,R.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,R.jsx)(`span`,{children:C?.label??e}),(0,R.jsx)(_e,{style:{width:12,height:12,color:`var(--muted)`,transform:f?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),u?M&&(0,Ke.createPortal)(M,document.body):M]})}function it({icon:e,title:t,children:n,className:r,style:i}){return(0,R.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,R.jsx)(`div`,{className:`title`,children:t}),n&&(0,R.jsx)(`div`,{className:`text-control`,children:n})]})}function at({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,R.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,R.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}async function ot(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 st(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function ct(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=st(await e.json(),t)}catch{}throw Error(n)}return ot(e)}async function lt(e){if(!e.ok)return null;try{return await ot(e)}catch{return null}}var ut=`dashboard/update`;function dt(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function ft(){return window.location.hash.replace(/^#\/?/,``)===ut}function pt(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function mt(e,t){let n=await ct(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var ht=[`low`,`medium`,`high`,`xhigh`];function gt(e){return e?.includes(`-preview.`)?`preview`:`latest`}function _t(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 vt(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 yt(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 bt(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 xt(e,t){return e.find(e=>e.id===t)?.provider===`anthropic`?`anthropic`:`openai`}var St=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{St=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{St=!1},{capture:!0,passive:!0}));function Ct(e){if(e){if(St){e.focus({preventScroll:!0});return}try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function wt(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(),Ct(t.current)}},[e,t]),(0,_.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),Ct(t.current)},[t]),n}var Tt=[`gpt-5.4-mini`,`gpt-5.6-luna`];function Et(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length>0?t:Tt}function Dt(e){return Et(e).join(`, `)}function Ot(e){return Et(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function kt(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,R.jsxs)(R.Fragment,{children:[(0,R.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,R.jsxs)(`div`,{className:`modal-card`,children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,R.jsx)(ae,{})})]}),(0,R.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,R.jsxs)(`div`,{className:`update-row`,children:[(0,R.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,R.jsx)(rt,{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,R.jsx)(it,{className:`update-empty`,icon:(0,R.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,R.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,R.jsx)(de,{}),(0,R.jsx)(`span`,{children:c})]}),l&&!s&&(0,R.jsxs)(`div`,{className:`update-box`,children:[(0,R.jsxs)(`div`,{className:`spread`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,R.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,R.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,R.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),(0,R.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,R.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,R.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,R.jsx)(de,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,R.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,R.jsx)(de,{}),` `,t(`dash.updateUnavailable`),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,R.jsx)(se,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,R.jsxs)(`div`,{className:`update-recheck`,children:[(0,R.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:_t(l.reason,t)})}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,R.jsx)(se,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,R.jsxs)(`div`,{className:`spread update-restart`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,R.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,R.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,R.jsx)(`span`,{className:`knob`})})]})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,R.jsx)(ae,{})})]}),(0,R.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,R.jsx)(`div`,{style:{marginTop:12},children:(0,R.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,R.jsx)(`div`,{className:`modal-actions`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,R.jsx)(ae,{})})]}),(0,R.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,R.jsx)(`div`,{className:`modal-actions`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,R.jsx)(ae,{})})]}),(0,R.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:Dt(C?.sourceModels)})}),(0,R.jsx)(`div`,{className:`modal-actions`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]})]})}function At({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,R.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,R.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,R.jsx)(it,{title:e(`dash.noModels`)}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,R.jsx)(pe,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,R.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,R.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,R.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([e,t])=>{let n=r.trim().toLowerCase()!==``||o.has(e);return(0,R.jsxs)(`div`,{className:`dash-model-group`,children:[(0,R.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,R.jsx)(_e,{width:12,height:12,style:{transform:n?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,R.jsx)(`span`,{className:`font-semibold`,children:e}),(0,R.jsx)(`span`,{className:`count`,children:t.length})]}),n&&(0,R.jsx)(`div`,{className:`dash-model-chips`,children:t.map(e=>(0,R.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},e)})})]})]})}var jt={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 Mt(e){return e.replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Nt(e,t){let n=jt[t];if(n){for(let t of n)if(e>=t.v)return`${Mt((e/t.v).toFixed(1))}${t.s}`;return String(e)}return e<1e4?String(e):e<1e6?`${Mt((e/1e3).toFixed(1))}K`:e<1e9?`${Mt((e/1e6).toFixed(1))}M`:e<0xe8d4a51000?`${Mt((e/1e9).toFixed(1))}B`:`${Mt((e/0xe8d4a51000).toFixed(1))}T`}var Pt={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 Ft(e,t){let n=Math.max(0,Math.floor(e)),r=Pt[t]??Pt.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 It({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=K(),h=t?.status===`ok`;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,R.jsxs)(`div`,{className:`stat-row`,children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[m(`dash.multiAgent`),(0,R.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,R.jsx)(fe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,R.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,R.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,R.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,R.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,R.jsx)(`div`,{className:`label`,children:m(`dash.status`)}),(0,R.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:h?`var(--green)`:`var(--red)`},children:[(0,R.jsx)(`span`,{className:`dot ${h?`dot-green`:`dot-red`}`}),m(h?`dash.online`:`dash.offline`)]})]}),(0,R.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,R.jsx)(`div`,{className:`label`,children:m(`dash.version`)}),(0,R.jsx)(`div`,{className:`value mono`,children:t?.version??`—`})]}),(0,R.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,R.jsx)(`div`,{className:`label`,children:m(`dash.uptime`)}),(0,R.jsx)(`div`,{className:`value mono`,children:t?Ft(t.uptime,e):`—`})]}),(0,R.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,R.jsx)(`div`,{className:`label`,children:m(`dash.providers`)}),(0,R.jsx)(`div`,{className:`value`,children:n.length})]}),(0,R.jsxs)(`div`,{className:`stat`,"aria-busy":i||void 0,children:[(0,R.jsx)(`div`,{className:`label`,children:m(`dash.tokens30d`)}),(0,R.jsx)(`div`,{className:`value mono`,children:r&&r.summary.requests>0?Nt(r.summary.totalTokens,e):`—`}),(0,R.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,R.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,R.jsxs)(`a`,{className:`startup-health-bar`,href:`#startup`,children:[(0,R.jsx)(`span`,{className:`dot ${o===`error`?`dot-red`:o===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,R.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,R.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`dot dot-amber`}),(0,R.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),s.length>0&&(0,R.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,R.jsx)(de,{}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:m(`dash.projectConfigTitle`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:m(`dash.projectConfigHint`)}),(0,R.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,R.jsxs)(`li`,{style:{marginBottom:8},children:[(0,R.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,R.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}function Lt(e){let t=new AbortController;if(typeof AbortSignal<`u`&&typeof AbortSignal.any==`function`&&typeof AbortSignal.timeout==`function`)return{controller:t,signal:AbortSignal.any([t.signal,AbortSignal.timeout(e)]),clear:()=>void 0};let n=setTimeout(()=>t.abort(),e);return{controller:t,signal:t.signal,clear:()=>clearTimeout(n)}}var Rt=new Map;function zt(e,t){let n=`${e}:${t}`,r=Rt.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),Rt.set(n,r)),r}var Bt=new Map;function Vt(e){let t=Bt.get(e);return t||(t=new Intl.NumberFormat(e),Bt.set(e,t)),t}function Ht(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`${zt(t,r===0?0:1).format(i)} ${n[r]}`}function Ut(e,t){return!Number.isFinite(e)||e<0?`—`:Ft(e/1e3,t)}function Wt(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function Gt(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 Kt(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:(Wt(n)-Wt(t))/r*36e5}function qt({label:e,value:t,sub:n,tone:r}){return(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:e}),(0,R.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,R.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function Jt({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,R.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,R.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,R.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,R.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,R.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:Ht(e,r),t!==null&&(0,R.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,Ht(t,r)]})]})]}),(0,R.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,R.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,R.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var Yt=60,Xt=1500,Zt=12e4;function Qt({apiBase:e}){let{locale:t,t:n}=G(),[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=Lt(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=setInterval(()=>void a(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),clearInterval(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=Lt(5e3);i=o,fetch(`${e}/healthz`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=Zt&&(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>=Zt&&(c(`error`),u(n(`dash.mem.restartFailed`)))}}).catch(()=>{t||Date.now()-a>=Zt&&(c(`error`),u(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let l=setInterval(o,Xt);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:Yt})];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,R.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,R.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,R.jsx)(ne,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?Kt(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??Wt(r):null,x=r?Gt(r):null,S=(()=>{let e=r?.watchdog?.warnThresholdBytes;if(y===null||y<=0||b===null||!e)return;let t=e-b;if(t<=0)return`danger`;let n=t/y;if(n<=1)return`danger`;if(n<=8)return`warn`})(),C=r?.responseState,w=r?.activeTurnCount,T=s===`draining`||s===`reconnecting`;return(0,R.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,R.jsxs)(`div`,{className:`mem-head`,children:[(0,R.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,R.jsx)(ne,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,R.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,R.jsxs)(`span`,{className:`mem-inflight`,children:[(0,R.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,R.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?Vt(t).format(w):`—`})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,R.jsx)(Jt,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,R.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,R.jsx)(qt,{label:n(`dash.mem.rss`),value:r?Ht(r.rss,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.jsHeap`),value:r?Ht(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:Ht(r.heapTotal,t)}):void 0}),(0,R.jsx)(qt,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?Ht(r.jscHeap.heapSize,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${Ht(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,R.jsxs)(`details`,{style:{marginTop:10},children:[(0,R.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,R.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,R.jsxs)(`div`,{className:`stat-row`,children:[(0,R.jsx)(qt,{label:n(`dash.mem.observed`),value:b===null?`—`:`${Ht(b,t)} (${x})`}),(0,R.jsx)(qt,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:Ht(r.external,t)}),(0,R.jsx)(qt,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:Ht(r.arrayBuffers,t)})]}),(0,R.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,R.jsxs)(`div`,{className:`stat-row`,children:[(0,R.jsx)(qt,{label:n(`dash.mem.storeEntries`),value:C?Vt(t).format(C.count):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.storeTotal`),value:C?Ht(C.totalBytes,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.storeLargest`),value:C?Ht(C.largestBytes,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:Ut(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,R.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,R.jsx)(qt,{label:n(`dash.mem.threshold`),value:Ht(r.watchdog.warnThresholdBytes,t)}),(0,R.jsx)(qt,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,R.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,R.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,R.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,R.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,R.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function $t({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,R.jsx)(`div`,{className:`panel`,children:(0,R.jsxs)(`div`,{className:`injection-head`,children:[(0,R.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,R.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,R.jsx)(fe,{width:13,height:13,"aria-hidden":`true`})})]}),(0,R.jsx)(rt,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...ht.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await mt(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,R.jsx)(rt,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...ht.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await mt(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 en({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,R.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,R.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,R.jsx)(rt,{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,R.jsx)(rt,{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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ge(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function tn({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,R.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,R.jsxs)(`div`,{className:`spread maintenance-head`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginTop:3},children:t(`dash.syncModelsHint`)})]}),(0,R.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,disabled:r,children:[(0,R.jsx)(se,{}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,R.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,R.jsxs)(`div`,{className:`notice ${c.nativeSubagentDefaultsWarning?`notice-warn`:`notice-ok`} maintenance-notice`,role:`status`,children:[c.nativeSubagentDefaultsWarning?(0,R.jsx)(de,{}):(0,R.jsx)(se,{}),(0,R.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,R.jsxs)(R.Fragment,{children:[` `,(0,R.jsx)(He,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]})]}),l&&(0,R.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`status`,children:[(0,R.jsx)(de,{}),(0,R.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})})]}),u&&(0,R.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,R.jsx)(de,{}):(0,R.jsx)(se,{}),(0,R.jsxs)(`span`,{children:[vt(u.status,t),u.latestVersion?` ${u.currentVersion} -> ${u.latestVersion}.`:``,d?` ${t(`dash.updateReconnecting`)}`:``,u.error?` ${u.error}`:``]})]})]})}function nn({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,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`panel`,children:(0,R.jsxs)(`div`,{className:`spread`,children:[(0,R.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,R.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,R.jsx)(`span`,{className:`knob`})})]})}),(0,R.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,R.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,R.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,R.jsx)(rt,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({webSearch:{model:e,backend:xt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,R.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,R.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,R.jsx)(rt,{value:a?.vision.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({vision:{model:e,backend:xt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]})]}),(0,R.jsx)(`div`,{className:`panel`,"aria-busy":!u||void 0,children:(0,R.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,R.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,R.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,R.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,R.jsx)(fe,{width:13,height:13,"aria-hidden":`true`})}),(0,R.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${Ot(u?.sourceModels)}`})]}),(0,R.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,R.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,R.jsx)(`span`,{className:`knob`})}),(0,R.jsx)(rt,{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 rn(e){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)($t,{apiBase:e.apiBase,d:e}),(0,R.jsx)(en,{apiBase:e.apiBase,d:e}),(0,R.jsx)(tn,{d:e}),(0,R.jsx)(nn,{d:e}),(0,R.jsx)(Qt,{apiBase:e.apiBase})]})}function an(e){return(0,R.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,R.jsx)(It,{...e}),(0,R.jsx)(rn,{...e})]})}function on({t:e,providers:t}){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,R.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,R.jsx)(it,{title:(0,R.jsx)(He,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:e(`dash.col.name`)}),(0,R.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,R.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,R.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,R.jsx)(`tbody`,{children:t.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`font-semibold`,children:e.name}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`span`,{className:`chip`,children:e.adapter})}),(0,R.jsx)(`td`,{className:`muted mono text-label`,children:e.baseUrl}),(0,R.jsx)(`td`,{className:`muted`,children:e.defaultModel??`—`})]},e.name))})]})})]})}function sn(e){try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function J(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function cn(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function ln(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function un(e,t){return{request:++e.current,mutation:t.current}}var dn=2e3;function fn(e){let t=e.status;return t===`native`||t===`protected`||t===`at-risk`?t:null}function pn(e){return e?e.stale&&e.status!==`error`:!1}function mn(e,t){return!t||e!==null&&e!==`error`?e:t.status}var hn=3e4;function gn(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function _n(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function vn(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=fn(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(_n(e,t))throw e;return{status:`error`,stale:!1}}}async function yn(e,t){try{return(await lt(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function bn(e,t){return mt(await fetch(`${e}/api/models`,{signal:t}))}async function xn(e,t){return mt(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Sn(e,t,n){let{request:r,mutation:i}=un(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 mt(a),c;try{if(o.ok){let e=await o.json();ln({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else ln({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{ln({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 Cn(e,t,n){let{request:r,mutation:i}=un(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await mt(await fetch(`${e}/api/settings`,{signal:t})),o,s;return ln({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 wn(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(_n(e,t))throw e;return{maMode:`default`}}}async function Tn(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await mt(n),providers:await mt(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function En(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={...gn(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 Dn=`ocx.dash.controls.v1:`,On=`ocx.dash.overview.v1:`,kn=`ocx.dash.usage30d.v1:`,An=`ocx.dash.startup.v1:`,jn=`ocx.dash.maMode.v1:`;function Mn(e){return`${Dn}${e}`}function Nn(e){let{locale:t,t:n}=G(),[r,i]=(0,_.useState)(dt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>sn(Mn(e)),[e]),u=(0,_.useMemo)(()=>sn(`${On}${e}`),[e]),d=(0,_.useMemo)(()=>sn(`${kn}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=sn(`${An}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>sn(`${jn}${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),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(()=>p??`default`),[W,ee]=(0,_.useState)(!1),[te,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(!1),[ae,oe]=(0,_.useState)(!1),[se,ce]=(0,_.useState)(``),[le,ue]=(0,_.useState)(``),[de,fe]=(0,_.useState)([]),[pe,me]=(0,_.useState)([]),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(!0),[ye,be]=(0,_.useState)(!1),[xe,Se]=(0,_.useState)(``),[Ce,we]=(0,_.useState)(``),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)(null),[ke,Ae]=(0,_.useState)(null),[je,Me]=(0,_.useState)([]),[Ne,Pe]=(0,_.useState)(!1),[Fe,Ie]=(0,_.useState)(`latest`),[Le,Re]=(0,_.useState)(!0),[ze,Be]=(0,_.useState)(!1),K=(0,_.useRef)(0),Ve=(0,_.useRef)(null),He=(0,_.useRef)(0),Ue=(0,_.useRef)(0),Ge=(0,_.useRef)(0),Ke=(0,_.useRef)(!1),qe=(0,_.useRef)(0),Je=(0,_.useRef)(0),Ye=(0,_.useRef)(!1),[Xe,Ze]=(0,_.useState)(null),[Qe,$e]=(0,_.useState)(null),[et,tt]=(0,_.useState)(null),[nt,q]=(0,_.useState)(!1),[rt,it]=(0,_.useState)(!1),at=(0,_.useRef)(null),ot=(0,_.useRef)(null),st=(0,_.useRef)(null),ct=(0,_.useRef)(null),lt=wt(re,at),ut=wt(Ne,ot),pt=wt(te,st),ht=wt(ae,ct);(0,_.useEffect)(()=>{let e=()=>i(dt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{He.current+=1,Ve.current!==null&&(window.clearTimeout(Ve.current),Ve.current=null)},[]);let _t=(0,_.useRef)(f),vt=(0,_.useRef)(0),xt=(0,_.useRef)({settingsRequestEpochRef:Ue,settingsMutationEpochRef:Ge,settingsMutationInFlightRef:Ke,shadowCallRequestEpochRef:qe,shadowCallMutationEpochRef:Je,shadowCallMutationInFlightRef:Ye}).current,St=F(`dashboard-startup-health:${e}`,[e],t=>vn(e,t),{pollMs:3e4}),Ct=pn(St.data),Tt=St.refresh;(0,_.useEffect)(()=>{if(!Ct)return;let e=window.setTimeout(()=>{Tt()},dn);return()=>window.clearTimeout(e)},[Ct,Tt]);let Et=F(`dashboard-overview:${e}`,[e],t=>Tn(e,t),{pollMs:5e3}),Dt=m!==null||Et.data!==void 0,Ot=F(`dashboard-ma-mode:${e}`,[e],t=>wn(e,t),{pollMs:5e3}),kt=F(`dashboard-sidecars:${e}`,[e],async t=>{let n=vt.current;return{...await Sn(e,t,xt),startupHealthGeneration:n}},{pollMs:5e3}),At=F(`dashboard-settings:${e}`,[e],async t=>{let n=vt.current;return{...await Cn(e,t,xt),startupHealthGeneration:n}},{pollMs:5e3}),jt=F(`dashboard-multi-agent:${e}`,[e],t=>En(e,t),{pollMs:5e3,enabled:Dt}),Mt=F(`dashboard-usage:${e}`,[e],t=>xn(e,t),{pollMs:6e4,enabled:Dt}),Nt=F(`dashboard-diagnostics:${e}`,[e],t=>yn(e,t),{pollMs:hn,enabled:Dt}),Pt=F(`dashboard-models:${e}`,[e,rt],t=>bn(e,t),{enabled:Dt&&!rt});(0,_.useEffect)(()=>{if(St.data!==void 0){let t=St.data;vt.current+=1,v(t.status),_t.current=t.status,t.status!==`error`&&!t.stale&&J(`${An}${e}`,t.status)}},[St.data,e]),(0,_.useEffect)(()=>{let t=Et.data;t&&(t.health&&(h(t.health),b(t.providers),J(`${On}${e}`,{health:t.health,providers:t.providers})),it(t.error))},[Et.data,e]),(0,_.useEffect)(()=>{Ot.data!==void 0&&(U(Ot.data.maMode),J(`${jn}${e}`,Ot.data.maMode))},[Ot.data,e]);let Ft=Ot.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=jt.data;e&&(e.injection&&(ve(e.injection.multiAgentGuidanceEnabled),be(e.injection.syncCodexSubagentDefaults),ce(e.injection.injectionModel),ue(e.injection.injectionEffort),fe(e.injection.injectionEfforts),me(e.injection.injectionAvailable)),e.effortCaps&&(Se(e.effortCaps.effortCap),we(e.effortCaps.subagentEffortCap)))},[jt.data]),(0,_.useEffect)(()=>{let t=kt.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=sn(Mn(e))??{};J(Mn(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[kt.data,e]),(0,_.useEffect)(()=>{let t=At.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===vt.current){let n=mn(_t.current,t.startupHealthSeed);v(n),_t.current=n,n&&J(`${An}${e}`,n)}if(t.settings!==void 0){let n=sn(Mn(e))??{};J(Mn(e),{...n,settings:t.settings})}}},[At.data,e]),(0,_.useEffect)(()=>{Mt.data!==void 0&&(A(Mt.data),J(`${kn}${e}`,Mt.data))},[Mt.data,e]),(0,_.useEffect)(()=>{Nt.data&&Me(Nt.data)},[Nt.data]),(0,_.useEffect)(()=>{Pt.data&&S(Pt.data),L(Pt.loading)},[Pt.data,Pt.loading]),(0,_.useEffect)(()=>()=>{Ue.current+=1,qe.current+=1},[]);let It=F(et?.id&&et.restart?`update-job:${e}:${et.id}`:`update-job:idle:${e}`,[e,et?.id,et?.restart,et?.latestVersion],async t=>{if(!et?.id||!et.restart)return{reconnecting:!1};let n=et.latestVersion;try{let r=await mt(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(et.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await mt(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:!!(et?.id&&et.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=It.data;e&&(`job`in e&&e.job&&tt(e.job),q(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[It.data]);let Lt=(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]),Rt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return Lt;let t=[];for(let[n,r]of Lt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Lt,a]),zt=(0,_.useMemo)(()=>{let e=bt(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]),Bt=async t=>{if(!T||j)return;let n=T,r={webSearch:yt(T.webSearch,t.webSearch),vision:yt(T.vision,t.vision)};M(!0),E(r);try{let n=await mt(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=sn(Mn(e))??{};J(Mn(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision}})}catch{E(n)}finally{M(!1)}};async function Vt(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),Ye.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`);Je.current+=1}catch{O(n)}finally{Ye.current=!1,P(!1)}}let Ht=async t=>{if(!(W||H===t)){ee(!0);try{(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})})).ok&&(U(t),J(`${jn}${e}`,t))}catch{}finally{ee(!1)}}},Ut=async t=>{if(!he){ge(!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 mt(await fetch(`${e}/api/injection-model`)),r=gn(n);ve(r.multiAgentGuidanceEnabled),be(r.syncCodexSubagentDefaults),ce(r.injectionModel),ue(r.injectionEffort),Array.isArray(n.efforts)&&fe(n.efforts),Array.isArray(n.available)&&me(n.available)}catch{}finally{ge(!1)}}},Wt=async()=>{if(!C||R)return;let t=!C.codexAutoStart;z(!0),Ke.current=!0,w({...C,codexAutoStart:t});try{let n=await mt(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Ge.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),it(!0)}finally{Ke.current=!1,z(!1)}},Gt=async()=>{if(!B){V(!0),Oe(null),Ae(null);try{let t=await mt(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Oe(t),t.projectConfigGrouped&&Me(t.projectConfigGrouped)}catch(e){Ae(e instanceof Error?e.message:String(e))}finally{V(!1)}}},Kt=async(t,n=!1)=>{n&&(K.current=0),Ve.current!==null&&(window.clearTimeout(Ve.current),Ve.current=null);let r=++He.current;Be(!0),$e(null),Ze(null);try{let n=await mt(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==He.current)return;if(Ze(n),n.reason===`latest_unavailable`&&K.current<2){let e=++K.current;Ve.current=window.setTimeout(()=>{r===He.current&&(Ve.current=null,Kt(t))},800*e);return}n.reason!==`latest_unavailable`&&(K.current=0),Be(!1)}catch(e){if(r!==He.current)return;$e(e instanceof Error?e.message:String(e)),Be(!1)}},qt=()=>{He.current+=1,Ve.current!==null&&(window.clearTimeout(Ve.current),Ve.current=null),Be(!1),Pe(!1)},Jt=()=>{let e=gt(m?.version);Ie(e),Re(!0),Pe(!0),Kt(e,!0)},Yt=e=>{Ie(e),Kt(e,!0)},Xt=(0,_.useRef)(Jt);return(0,_.useEffect)(()=>{Xt.current=Jt}),(0,_.useEffect)(()=>{let e=()=>{ft()&&(We(`dashboard`),Xt.current())},t=ft()?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:Mt.loading&&!k,healthLoading:Et.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:I,settingsSaving:R,syncing:B,maMode:H,maModeResolved:Ft,maBusy:W,setMaHelpOpen:ne,maHelpOpen:te,effortCapHelpOpen:re,setEffortCapHelpOpen:ie,shadowCallHelpOpen:ae,setShadowCallHelpOpen:oe,injectionModel:se,injectionEffort:le,injectionEfforts:de,injectionAvailable:pe,injectionSaving:he,multiAgentGuidanceEnabled:_e,syncCodexSubagentDefaults:ye,saveInjection:Ut,effortCap:xe,subagentEffortCap:Ce,effortCapSaving:Te,setEffortCap:Se,setSubagentEffortCap:we,setEffortCapSaving:Ee,syncResult:De,syncError:ke,projectConfigWarnings:je,updateOpen:Ne,updateChannel:Fe,setUpdateRestart:Re,updateRestart:Le,updateLoading:ze,updateCheck:Xe,updateError:Qe,updateJob:et,reconnecting:nt,error:rt,effortCapHelpTriggerRef:at,updateTriggerRef:ot,maHelpTriggerRef:st,shadowCallHelpTriggerRef:ct,effortCapHelpDialogRef:lt,updateDialogRef:ut,maHelpDialogRef:pt,shadowCallHelpDialogRef:ht,filteredGroups:Rt,sidecarModels:zt,saveSidecar:Bt,saveShadowCall:Vt,switchMaMode:Ht,toggleCodexAutoStart:Wt,runSync:Gt,fetchUpdateCheck:Kt,closeUpdateDialog:qt,openUpdateDialog:Jt,changeUpdateChannel:Yt,runUpdate:async()=>{if(Xe?.canUpdate){$e(null);try{let t=await mt(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Fe,restart:Le})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);tt(t.job),q(!1),qt()}catch(e){$e(e instanceof Error?e.message:String(e))}}}}}function Pn(e){Ge(pt(e))}function Fn({apiBase:e}){let t=Nn(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,R.jsx)(it,{style:{marginTop:40},icon:(0,R.jsx)(de,{}),title:(0,R.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,R.jsx)(He,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,R.jsx)(an,{...t}),m=(0,R.jsx)(on,{t:n,providers:a}),h=(0,R.jsx)(At,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,R.jsx)(kt,{...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=Pn,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,R.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,R.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,R.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,R.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,R.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 In=`https://chatgpt.com/backend-api/codex`,Ln=`openai`;function Rn(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 Bn(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||zn(e.baseUrl)||e.hasApiKey===!0}function Vn(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Rn(e.baseUrl)===In}function Hn(e,t){return e===Ln&&Vn(t)}function Un(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||zn(e.baseUrl)}function Wn(e,t){return Hn(e,t)?`accounts`:Un(t)?`free`:`paid`}function Gn(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??Wn(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 Kn(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}Bn(a)?t.push({name:i,...a,tier:Wn(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function qn(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 Jn(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:Bn(e)?`ready`:`needs-setup`}function Yn(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!Hn(`openai`,t)||!Vn(n))return e;let r={...e};return delete r.chatgpt,r}function Xn(e){return e.authMode===`local`||zn(e.baseUrl)}var Zn=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function Qn(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(Xn(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return Zn.some(e=>n.includes(e))?`selfHosted`:`cloud`}function $n(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 er(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 tr(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 nr(e){let t={};for(let[n,r]of Object.entries($n(e)))t[n]=r.length;return t}function rr(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 ir={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function ar(e,t,n){let r=typeof t==`object`&&t?t:ir,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 or(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 sr(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 cr(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function lr(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 ur(e,t=`en`){return lr(e,t)}function dr(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var fr={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`},pr={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`};function mr(e){return fr[e.toLowerCase()]}function hr(e,t){let n=mr(e);return n?`/provider-icons/${n}`:void 0}function gr(e){let t=e.toLowerCase();return pr[t]?pr[t]:e===t&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)?e.split(`-`).map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(` `):e}function _r(e){return Object.prototype.hasOwnProperty.call(pr,e.toLowerCase())}function vr(e,t){let n=Jn(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 yr(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 br(e){let t=Jn(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 xr({name:e,adapter:t,baseUrl:n,cls:r}){let i=hr(e,{adapter:t,baseUrl:n});return(0,R.jsx)(`span`,{className:r,children:i?(0,R.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`}):(0,R.jsx)(V,{"aria-hidden":`true`})})}function Sr({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=K(),l=Un(e),u=Xn(e),d=vr(e,c),f=gr(e.name),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,R.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,R.jsx)(xr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,R.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,R.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,R.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,R.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,R.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,R.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,R.jsx)(Me,{width:17,height:17,"aria-hidden":`true`})}),(0,R.jsx)(`span`,{className:br(e),title:d,"aria-hidden":`true`})]})]})}function Cr(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}}]}):[],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 wr(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Tr(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 Er(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function Dr(e,t){return!e||!Er(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 Or(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function kr(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 Ar(e,t,n){let r=Dr(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=kr(e.label,n);i.push({rank:Or(e.label),row:{label:t,limitLabel:t,percent:e.percent,resetAt:e.resetAt}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function jr(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 Mr(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 Nr(e){return e>=99.5}function Pr(e,t){return t>0&&e>=t}function Fr(e,t){return Pr(e,t)||Nr(e)?`bar-warn`:`bar-green`}function Ir(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Lr(e){return{"--bar-scale":String(Ir(e)/100)}}function Rr({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1}){let{locale:s}=G(),c=Ar(e,t,r);return c.length===0?o?a===`stacked`?(0,R.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,R.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,R.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,R.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,R.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,R.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,R.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,R.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,R.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--val`})]},t)),(0,R.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,R.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:c.map(e=>(0,R.jsx)(Br,{row:e,threshold:n,t:r,locale:s},e.limitLabel))}):(0,R.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:c.map(e=>(0,R.jsx)(zr,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:s},e.label))})}function zr({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Nr(t),s=Pr(t,r),c=Fr(t,r),l=Vr(n,i,a);return(0,R.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,R.jsx)(`span`,{className:`quota-label`,children:e}),(0,R.jsx)(`span`,{className:`quota-reset-label`,children:i(`codexAuth.resets`)}),(0,R.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,R.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,R.jsx)(`div`,{className:`bar`,children:(0,R.jsx)(`div`,{className:`bar-fill ${c}`,style:Lr(t)})}),(0,R.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):void 0,children:[s&&(0,R.jsx)(de,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function Br({row:e,threshold:t,t:n,locale:r}){let i=Nr(e.percent),a=Pr(e.percent,t),o=Fr(e.percent,t),s=Hr(e.resetAt,n,r);return(0,R.jsxs)(`div`,{className:`quota-stacked-row${a?` quota-stacked-row--warn`:``}${i?` quota-stacked-row--exhausted`:``}`,children:[(0,R.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,R.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),(0,R.jsx)(`span`,{className:`quota-stacked-reset muted`,children:s})]}),(0,R.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,R.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,R.jsx)(`div`,{className:`bar-fill ${o}`,style:Lr(e.percent)})}),(0,R.jsx)(`span`,{className:`quota-stacked-used${a?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),i&&(0,R.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,R.jsx)(de,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function Vr(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=Mr(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 Hr(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=Mr(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 Ur({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=K(),{locale:c}=G(),l=or(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)(()=>sr(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?Cr(r):null;r&&i&&e.push({item:n,report:r,urgency:jr(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 rr(e).slice(0,4)},[n,d]),b=e=>{let t=cr(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,R.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,R.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,R.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,R.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,R.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,R.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,R.jsx)(Wr,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,R.jsx)(Wr,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,R.jsx)(Wr,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,R.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,R.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,R.jsx)(de,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,R.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,R.jsx)(xr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,R.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-name`,children:gr(e.name)}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,R.jsx)(_e,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,R.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,R.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,R.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,R.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,R.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,R.jsx)(xr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,R.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-name`,children:gr(e.name)}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:s(`pws.dashboard.checkedAgo`,{time:ar(t.updatedAt,l)})})]}),(0,R.jsx)(_e,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,R.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,R.jsx)(Rr,{quota:Cr(t),threshold:80,t:s,layout:`stacked`,pending:i&&!t.quota})})]},e.name))}):i?(0,R.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,R.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,R.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,R.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,R.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,R.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,R.jsx)(Rr,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,R.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,R.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,R.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,R.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,R.jsx)(xr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-name`,children:gr(e.name)}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:lr(e.requests,c)})}),(0,R.jsx)(_e,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,R.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,R.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,R.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,R.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,R.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function Wr({count:e,label:t,tone:n}){return(0,R.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,R.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function Gr({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=K(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,R.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,R.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,R.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,R.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,R.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,R.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,R.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var Kr=[{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 qr({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=K(),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[x,S]=(0,_.useState)({free:!0,paid:!0}),[C,w]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[T,E]=(0,_.useState)(`az`),[D,O]=(0,_.useState)(!1),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)({}),[N,P]=(0,_.useState)({}),[F,I]=(0,_.useState)({}),[L,z]=(0,_.useState)({}),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(!1),W=`ocx.providers.quotas.v1:${t}`,ee=`ocx.providers.usage.v1:${t}`,[te,ne]=(0,_.useState)(()=>sn(ee)?.totals??{}),[re,ie]=(0,_.useState)(()=>sn(ee)?.models??{}),[ae,oe]=(0,_.useState)(()=>sn(W)??{}),[se,ce]=(0,_.useState)(()=>!sn(ee)),[le,de]=(0,_.useState)(()=>!sn(W)),[fe,me]=(0,_.useState)(0),he=(0,_.useRef)(null),ge=(0,_.useMemo)(()=>qn(Kn(Yn(e)),d??{}),[e,d]),_e=(0,_.useCallback)(()=>{me(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{V(!0),(async()=>{try{let n=await ct(await fetch(`${t}/api/selected-models`));if(e)return;M(nr(n)),P($n(n)),I(er(n)),z(tr(n)),U(!1)}catch{if(e)return;U(!0)}finally{e||V(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,fe]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{sn(ee)||ce(!0),fetch(`${t}/api/usage?range=30d`).then(e=>lt(e)).then(t=>{if(e||!t)return;let n={};for(let e of t.providers??[])n[e.provider]={requests:e.requests,totalTokens:e.totalTokens};ne(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}})}ie(r),J(ee,{totals:n,models:r})}).catch(()=>{}).finally(()=>{e||ce(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,ee]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{sn(W)||de(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>lt(e)).then(t=>{e||!t||oe(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 J(W,n),n})}).catch(()=>{}).finally(()=>{e||de(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,W]),(0,_.useEffect)(()=>{if(!D)return;let e=e=>{he.current&&!he.current.contains(e.target)&&O(!1)},t=e=>{e.key===`Escape`&&O(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[D]);let ve=(0,_.useMemo)(()=>[...ge.ready,...ge.needsSetup,...ge.disabled],[ge]),ye=(0,_.useMemo)(()=>ve.filter(Un).length,[ve]),be=ve.length-ye,xe=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of ve)e[Qn(t)]+=1;return e},[ve]),Se=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>Gn(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=Un(t);return!(n&&!x.free||!n&&!x.paid||!C[Qn(t)])}),T);return{ready:y.ready?t(ge.ready):[],needsSetup:y.needsSetup?t(ge.needsSetup):[],disabled:y.disabled?t(ge.disabled):[]}},[ge,g,y,x,C,T]),Ce=!y.ready||!y.needsSetup||!y.disabled||!x.free||!x.paid||!C.cloud||!C.local||!C.selfHosted||!C.login||T!==`az`,we=()=>{b({ready:!0,needsSetup:!0,disabled:!0}),S({free:!0,paid:!0}),w({cloud:!0,local:!0,selfHosted:!0,login:!0}),E(`az`)},Te=(0,_.useMemo)(()=>r?ve.find(e=>e.name===r)??null:null,[r,ve]),Ee=(0,_.useMemo)(()=>{let e=new Map;for(let t of ve){let n=gr(t.name);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},[ve]);if(ve.length===0)return(0,R.jsx)(Jr,{onAddProvider:o});let De=[{key:`ready`,label:h(`pws.status.ready`),count:ge.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:ge.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:ge.disabled.length}],Oe=[{id:`ready`,label:h(`pws.status.ready`),count:Se.ready.length,ariaLabel:h(`pws.groupReady`,{count:Se.ready.length}),items:Se.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:Se.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:Se.needsSetup.length}),items:Se.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:Se.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:Se.disabled.length}),items:Se.disabled}],ke=Oe.flatMap(e=>e.items.map(e=>e.name)),Ae=k&&ke.includes(k)?k:r&&ke.includes(r)?r:ke[0]??null;return(0,R.jsx)(`div`,{className:`pws-shell-container`,children:(0,R.jsxs)(`div`,{className:`pws-root`,children:[(0,R.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,R.jsxs)(`div`,{className:`pws-search-row`,children:[(0,R.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,R.jsx)(pe,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,R.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,R.jsxs)(`div`,{className:`pws-filter-wrap`,ref:he,children:[(0,R.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${Ce||D?` pws-filter-btn--active`:``}`,onClick:()=>O(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":D,"aria-controls":`pws-provider-filters`,children:[(0,R.jsx)(Ne,{width:18,height:18,"aria-hidden":`true`}),Ce&&(0,R.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),D&&(0,R.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,R.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),De.map(({key:e,label:t,count:n})=>(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:y[e],onChange:()=>b(t=>({...t,[e]:!t[e]}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:x.free,onChange:()=>S(e=>({...e,free:!e.free}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:ye})]}),(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:x.paid,onChange:()=>S(e=>({...e,paid:!e.paid}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:be})]}),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:xe.cloud},{key:`local`,label:h(`pws.type.local`),count:xe.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:xe.selfHosted},{key:`login`,label:h(`pws.type.login`),count:xe.login}].map(({key:e,label:t,count:n})=>(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:C[e],onChange:()=>w(t=>({...t,[e]:!t[e]}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,R.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:Kr.map(e=>(0,R.jsx)(`button`,{type:`button`,className:`pws-sort-btn${T===e.id?` pws-sort-btn--active`:``}`,onClick:()=>E(e.id),"aria-pressed":T===e.id,children:h(e.labelKey)},e.id))}),(0,R.jsx)(`div`,{className:`pws-filter-footer`,children:(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:we,disabled:!Ce,children:h(`pws.resetAll`)})})]})]})]}),(0,R.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(Se).every(e=>e.length===0)&&(0,R.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:Ce?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Oe.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,R.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,R.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,R.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,R.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,R.jsx)(Sr,{item:e,selected:r===e.name,tabbable:Ae===e.name,modelCount:j[e.name],isDefault:n===e.name,showConfigId:Ee.has(gr(e.name)),onClick:()=>i(e.name),onFocus:()=>A(e.name)}),a&&(0,R.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,R.jsx)(ue,{width:14,height:14})})]},e.name))]},e))]})]}),(0,R.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,R.jsx)(Gr,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):Te?m?.(Te,{usageTotals:te[Te.name],modelUsage:re[Te.name],quotaReport:ae[Te.name],availableModels:N[Te.name]??[],hasLiveModels:(F[Te.name]??0)>0,selectedModels:L[Te.name]??[],modelsLoading:B,modelsLoadFailed:H,onRetryModels:_e})??(0,R.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,R.jsx)(`h3`,{children:gr(Te.name)}),(0,R.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,R.jsx)(Ur,{sections:ge,quotaReports:ae,usageTotals:te,usageLoading:se,quotasLoading:le,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function Jr({onAddProvider:e}){let t=K();return(0,R.jsx)(`div`,{className:`pws-empty-root`,children:(0,R.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,R.jsx)(`div`,{"aria-hidden":`true`,children:(0,R.jsx)(H,{style:{width:64,height:64}})}),(0,R.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,R.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,R.jsx)(`span`,{"aria-hidden":`true`,children:(0,R.jsx)(Oe,{width:18,height:18})}),(0,R.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,R.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,R.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,R.jsx)(`span`,{"aria-hidden":`true`,children:(0,R.jsx)(Se,{width:18,height:18})}),(0,R.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,R.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,R.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,R.jsx)(`span`,{"aria-hidden":`true`,children:(0,R.jsx)(xe,{width:18,height:18})}),(0,R.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,R.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function Yr(e){if(Hn(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||Xn(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 Xr(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 Zr({item:e,usageTotals:t,quotaReport:n,oauthEmail:r,onEditSettings:i,onViewUsage:a,onUpdateProvider:o,onReauthenticate:s,onCancelLogin:c,reauthBusy:l=!1,accountPanel:u}){let d=K(),{locale:f}=G(),p=or(d),m=Jn(e),h=!!e.activeNeedsReauth,g=d(m===`ready`?`pws.status.connected`:m===`needs-setup`?h?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),_=t?.requests,v=t?.totalTokens,y=Cr(n);return(0,R.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,R.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,R.jsxs)(`section`,{className:`pws-section`,"aria-label":d(`pws.connection`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:d(`pws.connection`)}),(0,R.jsxs)(`dl`,{className:`pws-kv`,children:[(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`dash.status`)}),(0,R.jsxs)(`dd`,{className:m===`ready`?`pws-status-ok`:`pws-status-warn`,children:[m===`ready`?(0,R.jsx)(ie,{style:{width:13,height:13},"aria-hidden":`true`}):(0,R.jsx)(de,{style:{width:13,height:13},"aria-hidden":`true`}),g]})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`modal.baseUrl`)}),(0,R.jsx)(`dd`,{children:(0,R.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.cell.auth`)}),(0,R.jsx)(`dd`,{children:r?`${yr(e,d)} · ${r}`:yr(e,d)})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`modal.defaultModel`)}),(0,R.jsx)(`dd`,{children:e.defaultModel??(0,R.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.cell.note`)}),(0,R.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),i&&(0,R.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:i,children:d(`pws.editSettings`)})]}),u?(0,R.jsx)(`section`,{className:`pws-section`,"aria-label":d(`pws.availableAccounts`),children:u}):(0,R.jsxs)(`section`,{className:`pws-section`,"aria-label":d(`pws.authSummary`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:d(`pws.authSummary`)}),h?(0,R.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,R.jsx)(de,{style:{width:14,height:14},"aria-hidden":`true`}),(0,R.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,R.jsxs)(`span`,{children:[(0,R.jsx)(`strong`,{children:d(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?d(`pws.attention.reauthForward`):d(`pws.attention.reauth`)]}),s&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:l,onClick:()=>s(),children:d(l?`prov.waitingBrowser`:`pws.reauthenticate`)}),l&&c&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>c(),children:d(`common.cancel`)})]})]}):(0,R.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,R.jsx)(`span`,{className:`pws-auth-dot`}),(0,R.jsx)(`span`,{children:e.authMode===`forward`?d(`pws.passthrough`):e.authMode===`oauth`?r?d(`pws.loggedInAs`,{email:r}):d(`pws.notLoggedIn`):e.hasApiKey?d(`pws.apiKeyConfigured`):yr(e,d)})]})]})]}),(0,R.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,R.jsxs)(`section`,{className:`pws-section`,"aria-label":d(`pws.statsAria`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:d(`pws.statsTitle`)}),(0,R.jsxs)(`dl`,{className:`pws-kv`,children:[typeof _==`number`&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.stats.totalRequests`)}),(0,R.jsx)(`dd`,{className:`pws-kv-mono`,children:lr(_,f)})]}),typeof v==`number`&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.stats.totalTokens`)}),(0,R.jsx)(`dd`,{className:`pws-kv-mono`,children:ur(v,f)})]}),n&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.stats.quotaUpdated`)}),(0,R.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?wr(n.source):void 0,children:ar(n.updatedAt,p)})]}),typeof _!=`number`&&typeof v!=`number`&&!n&&(0,R.jsx)(`div`,{className:`muted`,children:d(`pws.usageUnavailable`)})]}),a&&(0,R.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:a,children:[d(`pws.viewUsage`),` →`]}),y&&(0,R.jsx)(`div`,{className:`muted pws-stats-note`,children:d(`pws.stats.quotaTracked`)})]}),(0,R.jsx)(Qr,{item:e,onUpdateProvider:o})]})]})}function Qr({item:e,onUpdateProvider:t}){let n=K(),[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,R.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,R.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,R.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,R.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,R.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,R.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function $r({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=K(),[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)(()=>Tr(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 z=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let B=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{}},V=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)}}},H=n.length===0&&P.length===0&&S.length===0&&!e.defaultModel,U=n.length===0&&P.length>0,W=L.length>300,ee=W?L.slice(0,300):L;return(0,R.jsxs)(`div`,{className:`pws-section`,children:[(0,R.jsxs)(`div`,{className:`pws-section-head`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),L.length>0&&(0,R.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:L.length})})]}),s&&(0,R.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,R.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),U&&!s&&(0,R.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,R.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,R.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,R.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&V()},placeholder:u(`models.customFieldModelIdPlaceholder`),"aria-label":u(`models.customAdd`),disabled:h}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{V()},disabled:h||I,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,R.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,R.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:z,style:{marginLeft:8},children:u(`common.retry`)})]}),!H&&(0,R.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&&H?(0,R.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&H?(0,R.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,R.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):H?(0,R.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):L.length===0?(0,R.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,R.jsx)(`ul`,{className:`pws-model-list`,children:ee.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,R.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,R.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:()=>{B(t)},title:t,"aria-label":u(A===t?`pws.modelCopied`:`pws.copyModelId`),children:(0,R.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,R.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,R.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),W&&(0,R.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(L.length)})})]})}function ei({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=K(),{locale:a}=G(),o=or(i),s=t?.requests!==void 0,c=Cr(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,R.jsxs)(`div`,{className:`pws-section`,children:[(0,R.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,R.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,R.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:dr(f,a)}),(0,R.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,R.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,R.jsx)(`span`,{className:`pws-usage-metric-value`,children:lr(t?.requests,a)}),(0,R.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,R.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,R.jsx)(`span`,{className:`pws-usage-metric-value`,children:ur(t?.totalTokens,a)}),(0,R.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,R.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,R.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,R.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`pws-model-table`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:i(`pws.col.model`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,R.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,R.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,R.jsxs)(_.Fragment,{children:[(0,R.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,R.jsx)(`td`,{className:`mono`,children:(0,R.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,R.jsx)(`td`,{className:`num mono`,children:dr(e.estimatedCostUsd,a)}),(0,R.jsx)(`td`,{className:`num mono`,children:ur(e.totalTokens,a)}),(0,R.jsx)(`td`,{className:`num`,children:e.requests}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`div`,{className:`pws-share-bar`,children:(0,R.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,R.jsx)(`tr`,{className:`pws-model-detail`,children:(0,R.jsx)(`td`,{colSpan:5,children:(0,R.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[` `,ur(e.inputTokens,a)]})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[` `,ur(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,R.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Rr,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,R.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,R.jsx)(`dd`,{children:wr(n.source)})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,R.jsx)(`dd`,{children:ar(n?.updatedAt,o)})]})]})]}):(0,R.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function ti(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function ni(e){return ti(e)??`account-…`}function ri(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function ii(e){let t=ri(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function ai(e){return e===`reauth_required`}function oi(e){return!!e?.needsReauth||ai(e?.health?.status)}function si(e){return e===`cooldown`}function ci(e){return e===`warning`||e===`reauth_required`}function li(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 ui(e,t){let n=li(t);return n?e(n):null}function di(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):ni(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 fi(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return pi(e)}function pi(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 hi=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function gi(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 _i({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,R.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,R.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,R.jsx)(Oe,{width:20}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,R.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,R.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var vi=2500;function yi(){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;fi(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)},vi))})},[i])}}function bi({url:e}){let t=K(),{outcomeFor:n,copy:r}=yi();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,R.jsxs)(`div`,{className:`login-url-block`,children:[(0,R.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,R.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,R.jsx)(we,{style:{width:13,height:13},"aria-hidden":`true`}),(0,R.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,R.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,R.jsx)(be,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function xi({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=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,R.jsx)(bi,{url:t}),(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,marginTop:12},children:[(0,R.jsx)(`div`,{className:`muted text-label`,children:f(`prov.pasteRedirectHint`)}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,R.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,R.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,R.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,R.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,R.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,R.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}function Si({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`,y=n.manualCodeState===`waiting`;(0,_.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,_.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let b=(0,_.useCallback)(()=>{c.current&&=(clearInterval(c.current),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),x=(0,_.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),S=(0,_.useCallback)(async()=>{x();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-auth-url`,authUrl:``}),b(),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,x,r,b]);(0,_.useEffect)(()=>(a.current=!0,()=>{x(),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}),b(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,x,r,b]);let C=(0,_.useCallback)((e,t)=>{h.current=e,g.current=t},[]),w=(0,_.useCallback)(()=>{n.step===`oauth-waiting`&&S(),g.current()},[n.step,S]),T=(0,_.useCallback)(async n=>{x(),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 y=await ct(v,i(`modal.networkError`));if(!a.current||!y)return;if(y.url){d.current=y.flowId??null,r({type:`set-flow-id`,flowId:y.flowId??null}),r({type:`set-auth-url`,authUrl:y.url}),r({type:`set-step`,step:`oauth-waiting`}),b();let n=y.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=setInterval(async()=>{if(s.current||v.signal.aborted)return;s.current=!0;let e=AbortSignal.any([v.signal,AbortSignal.timeout(1e4)]);try{let n=await lt(await fetch(_,{signal:e}));if(!a.current||v.signal.aborted)return;if(!n){o.current+=1,o.current>=3&&r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthStatusRetrying`),statusTone:`warn`});return}if(o.current=0,f.current===`waiting`?r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}):r({type:`set-status-notice`,statusNotice:``,statusTone:`ok`}),n.status===`done`){if(b(),x(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(),g.current()}else(n.status===`error`||n.status===`expired`)&&(b(),x(),d.current=null,r({type:`set-flow-id`,flowId:null}),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:n.error??i(`codexAuth.loginFailed`)})))}catch(e){if(!a.current||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{s.current=!1}},2e3),l.current=setTimeout(()=>{c.current&&(x(),S(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},3e5)}y.error&&!y.url&&r({type:`set-error`,error:y.error})}catch(e){a.current&&!(e instanceof Error&&e.name===`AbortError`)&&r({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[e,S,x,r,t,b,i]);return(0,_.useEffect)(()=>{if(!t){m.current=null;return}m.current!==t&&(m.current=t,T())},[t,T]),{manualCodeBusy:v,manualCodeWaiting:y,bindCallbacks:C,closeModal:w,startOAuth:T,submitManualCode:(0,_.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(!(!t||!s||v||y)){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,y,i,n.manualCode])}}function Ci({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=K(),[a,o]=(0,_.useReducer)(gi,r,hi),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=Si({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,R.jsx)(`dialog`,{ref:c,"aria-label":i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`),className:`modal-overlay`,onCancel:h,children:(0,R.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,R.jsx)(_i,{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,R.jsx)(xi,{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 wi=1e4;function Y(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Ti(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Ei(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Di(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Oi(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function ki(e,t,n){if(e<=0){let t=Ei(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Ti(t)??Ei(0,n)}}async function Ai(e,t,n=(e,t)=>fetch(e,t),r=wi){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 ji=3e4,Mi=new Map;function Ni(e,t=!0){let n=Mi.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,y]=(0,_.useState)(()=>n!=null),[b,x]=(0,_.useState)(0),S=(0,_.useRef)(new Set),C=(0,_.useRef)(null),w=(0,_.useRef)(0),T=(0,_.useRef)(null),E=(0,_.useRef)(new Set),D=(0,_.useRef)(null),O=(0,_.useRef)(null),k=(0,_.useRef)(!!n?.accounts.length),A=(0,_.useRef)(n!=null),j=(0,_.useRef)(null),M=(0,_.useCallback)(e=>(E.current.add(e),()=>{E.current.delete(e)}),[]),N=(0,_.useCallback)(()=>Oi(D.current?.value),[]),P=(0,_.useCallback)(()=>D.current?.value,[]),F=(0,_.useCallback)(async(t=!1)=>{let n=++w.current;g(e=>e+1);try{let r=[...E.current],a=new Map;for(let e of r)a.set(e,e.beginActiveRead());!t&&!A.current&&c(`loading`);let s=null,l,u=(async()=>{try{let r=await fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`);if(!r.ok)throw Error(`account load failed`);let a=await r.json();return w.current===n&&(s=a.accounts??[],i(s),k.current=s.length>0,A.current=!0,c(`ready`)),!0}catch{return!1}})(),d=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(w.current===n){let e=i.activeCodexAccountId??null,t=T.current;t&&e!==t.id||(T.current=null,l=e,o(e)),D.current={value:i};for(let e of r)e.acceptActiveRead(i,a.get(e))}return!0}catch{if(w.current===n)for(let e of r)e.rejectActiveRead();return!1}})(),[f,p]=await Promise.all([u,d]);if(w.current!==n)return!1;if(f){c(`ready`),A.current=!0;let t=Mi.get(e);return Mi.set(e,{accounts:s??t?.accounts??[],activeId:l===void 0?t?.activeId??null:l}),p}return A.current||c(`error`),!1}finally{g(e=>Math.max(0,e-1)),y(!0)}},[e]);(0,_.useEffect)(()=>{t&&C.current!==e&&(C.current=e,Promise.resolve().then(()=>{F()}))},[e,t,F]);let I=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!I||b>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{F(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,I,b,F]),(0,_.useEffect)(()=>{if(!t||b>0)return;let e=window.setInterval(()=>{F()},ji);return()=>window.clearInterval(e)},[t,F,b]);let L=(0,_.useCallback)(()=>{let e={};return S.current.add(e),x(S.current.size),e},[]),R=(0,_.useCallback)(e=>{S.current.delete(e)&&x(S.current.size)},[]),z=(0,_.useCallback)(async t=>{if(O.current)return{ok:!1,reason:`busy`};O.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 T.current={id:r??null},o(r??null),F(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{O.current=null,u(null)}},[e,F]),B=(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 F(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,F]),V=(0,_.useCallback)(async(t,n)=>{if(j.current)return{ok:!1,reason:`busy`};j.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;T.current={id:e},o(e)}return F(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{j.current=null,f(null)}},[e,F]),H=(0,_.useCallback)(async()=>{if(j.current)return{ok:!1,reason:`busy`};j.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;T.current={id:e},o(e)}return F(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{j.current=null,m(!1)}},[e,F]),U=(0,_.useCallback)(async t=>{try{return(await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(await F(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,F]),W=(0,_.useCallback)(async()=>await F()?{ok:!0}:{ok:!1,reason:`reload`},[F]),ee=a&&a!==`__main__`?r.find(e=>e.id===a):null,te=r.find(e=>e.isMain),ne=ee??te,re=!ne?.paused&&oi(ne);return{accounts:r,activeId:a,loadState:s,refreshing:h>0,initialLoading:!v,switchingId:l,pauseUpdatingId:d,pausingExhausted:p,activeNeedsReauth:re,load:F,switchAccount:z,setAccountPaused:V,pauseExhaustedAccounts:H,saveAlias:B,removeAccount:U,syncAfterAccountAdded:W,pauseRefresh:L,resumeRefresh:R,subscribeLoadObserver:M,readLastThreshold:N,readLastActive:P}}function Pi(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 Fi({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,R.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,R.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,R.jsx)(me,{width:10,height:10,"aria-hidden":`true`})}),(0,R.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,R.jsx)(he,{width:10,height:10,"aria-hidden":`true`})})]})}function Ii({threshold:e,draft:t,hydrated:n=!0,saving:r,loadError:i,feedback:a,onDraftChange:o,onEditingChange:s,onCommit:c,onCancel:l,onToggle:u,onRetry:d}){let f=K(),p=(0,_.useRef)(!1),m=e>0,h=r||!n,g=r?f(`common.saving`):a?.message??``,v=r?`pending`:a?.tone,y=g?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,R.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":r||!n&&!i||void 0,children:[(0,R.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,R.jsx)(`strong`,{children:f(`codexAuth.autoSwitch`)}),(0,R.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:i?`alert`:void 0,children:i?f(`codexAuth.autoSwitchLoadFailed`):m?f(`codexAuth.autoSwitchDesc`,{threshold:e}):f(`codexAuth.autoSwitchOffDesc`)})]}),(0,R.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(s(!1),p.current){p.current=!1;return}m&&!h&&c()}},children:[i&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:d,children:f(`pws.retryAccounts`)}),m&&(0,R.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:f(`codexAuth.autoSwitchThreshold`)}),(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,R.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:h,"aria-disabled":h,"aria-label":f(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":y,onChange:e=>o(e.target.value),onFocus:()=>{h||s(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||h||(e.key===`Enter`?(e.preventDefault(),c()):e.key===`Escape`&&(e.preventDefault(),l()))}}),(0,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,R.jsx)(Fi,{disabled:h,incrementLabel:f(`codexAuth.autoSwitchThresholdInc`),decrementLabel:f(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{s(!0),o(Pi(t,1,1,100))},onDecrement:()=>{s(!0),o(Pi(t,-1,1,100))}})]})]}),(0,R.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,R.jsx)(`button`,{type:`button`,className:`toggle ${m?`on`:``}`,onPointerDownCapture:()=>{p.current=!0},onPointerUp:()=>{p.current=!1},onPointerCancel:()=>{p.current=!1},onClick:()=>{p.current=!1,u()},disabled:h,"aria-pressed":m,"aria-label":f(`codexAuth.autoSwitch`),"aria-describedby":y,title:f(`codexAuth.autoSwitch`),children:(0,R.jsx)(`span`,{className:`toggle-knob`})})})]}),g&&(0,R.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${v===`err`?` is-error`:``}`,role:v===`err`?`alert`:`status`,"aria-atomic":`true`,children:g})]})}var Li=[`quota`,`round-robin`,`fill-first`],Ri=`quota`,zi=new Set(Li);function Bi(e){return typeof e==`string`&&zi.has(e)?e:Ri}function Vi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Hi(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function Ui(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:Bi(i.accountPoolStrategy??t.strategy),stickyLimit:Vi(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var Wi={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`};function Gi({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=K(),l=Li.map(e=>({value:e,label:c(Wi[e])}));return(0,R.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,R.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,R.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyHint`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,R.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,R.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,R.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,R.jsx)(Fi,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=Pi(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=Pi(t,-1,1,100);o(e),s(e)}})]})})]})]})}function Ki(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:Bi(t.accountPoolStrategy),stickyLimit:Vi(t.accountPoolStickyLimit)}}function qi({apiBase:e,subscribeLoadObserver:t,readLastActive:n}){let r=K(),[i,a]=(0,_.useState)(Ri),[o,s]=(0,_.useState)(1),[c,l]=(0,_.useState)(`1`),[u,d]=(0,_.useState)(!1),f=(0,_.useRef)(!1),[p,m]=(0,_.useState)(!1),h=(0,_.useRef)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(0),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(null),C=(0,_.useCallback)(e=>{let t=Bi(e.accountPoolStrategy),n=Vi(e.accountPoolStickyLimit);a(t),s(n),l(String(n)),f.current=!0,d(!0),b(!1),S(null)},[]),w=(0,_.useCallback)(e=>{let t=Ki(e);t&&C({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[C]),T=(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(h.current){g.current=!0;return}C(n)}catch{h.current||b(!0)}},[e,C]),E=(0,_.useCallback)(()=>{g.current&&(g.current=!1,queueMicrotask(()=>{if(h.current){g.current=!0;return}T()}))},[T]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>v.current,acceptActiveRead:(e,t)=>{if(t===v.current){if(h.current){g.current=!0;return}w(e)}},rejectActiveRead:()=>{f.current||b(!0)}});return!h.current&&n&&w(n()),e},[t,w,n]),(0,_.useEffect)(()=>{!n||t||h.current||w(n())},[n,w,t]),(0,_.useEffect)(()=>{t||T()},[T,t]);let D=(0,_.useCallback)(async t=>{if(h.current)return;let n=i,c=o;t.strategy!==void 0&&a(t.strategy),t.stickyLimit!==void 0&&(s(t.stickyLimit),l(String(t.stickyLimit))),h.current=!0,m(!0),S(null),v.current+=1;let u=await Ui(e,t);v.current+=1,u.ok?(a(u.strategy),s(u.stickyLimit),l(String(u.stickyLimit)),f.current=!0,d(!0)):(S(r(`accountPool.strategyUpdateFailed`)),a(n),s(c),l(String(c))),h.current=!1,m(!1),E()},[e,E,o,i,r]),O=p||y||!u;return(0,R.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":p||!u&&!y,children:[y&&(0,R.jsx)(`div`,{className:`card-sub`,role:`alert`,children:r(`accountPool.strategyLoadFailed`)}),y&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{T()},children:r(`common.retry`)}),!y&&(0,R.jsx)(Gi,{strategy:i,stickyDraft:c,disabled:O,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{O||e===i||D({strategy:e})},onStickyDraftChange:l,onStickyCommit:e=>{if(O)return;let t=Hi(e??c);if(t===null){l(String(o)),S(r(`accountPool.stickyLimitInvalid`));return}if(t===o){l(String(t));return}D({stickyLimit:t})}}),x&&(0,R.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:x})]})}function Ji(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=Oi(e),r=Di(v.current,y.current,t,x.current);r===`defer`?S.current=Y(n):r===`apply`&&T(Y(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(Y(Oi(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 Ai(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=Ti(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=ki(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 Yi=new Map;function Xi(e,t){return`${e??``}\0${JSON.stringify(t)}`}function Zi(e,t){let n=Xi(e,t??{}),r=Yi.get(n);return r||(r=new Intl.NumberFormat(e,t),Yi.set(n,r)),r}var Qi={month:`short`,day:`numeric`,year:`numeric`},$i={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},ea=new Map;function ta(e,t){let n=Xi(e,t),r=ea.get(n);return r||(r=new Intl.DateTimeFormat(e,t),ea.set(n,r)),r}function na(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:ta(t,Qi).format(n)}function ra(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:ta(t,$i).format(n)}function ia(e,t){return!Number.isFinite(e)||e<0?`—`:`~${Zi(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function aa(e,t){return na(e,t)}function oa(e,t){return ra(e,t)}function sa(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function ca({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=sa(n),s=o<=7;return(0,R.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,R.jsxs)(`div`,{className:`credit-item-head`,children:[(0,R.jsx)(Ce,{width:13}),(0,R.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,R.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,R.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,R.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:aa(t,i)})}),(0,R.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:oa(n,i),days:String(o)})})]})]})}function la({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,R.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,R.jsx)(Ce,{width:12}),`0`]}):r===void 0?null:(0,R.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,R.jsx)(Ce,{width:12}),r]})}function ua({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,R.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${Math.max(r.length,i.length,a.length)}ch`},children:o})}function da({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=K(),g=e=>!e.paused&&t===e.id;return(0,R.jsx)(R.Fragment,{children:e.map(e=>{let t=e.health?.status,_=!!e.needsReauth||ai(t),v=si(t),y=ui(h,e.health),b=di(h,`codex`,e.id,e.health);return(0,R.jsxs)(`div`,{className:`card ${g(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,R.jsxs)(`div`,{className:`card-head`,children:[(0,R.jsx)(`span`,{className:`dot ${_?`dot-amber`:g(e)?`dot-blue`:`dot-muted`}`}),(0,R.jsx)(`strong`,{children:e.alias??e.email}),(0,R.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,R.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,R.jsx)(`span`,{className:`badge badge-muted`,title:h(`codexAuth.pausedHint`),children:h(`codexAuth.paused`)}),(0,R.jsx)(la,{t:h,account:e,onClick:()=>a(e)}),y&&(0,R.jsx)(`span`,{className:ii(t),children:y}),_&&!y&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:h(`codexAuth.needsReauth`)}),g(e)&&!_&&!v&&(0,R.jsx)(`span`,{className:`badge badge-primary`,children:h(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!g(e)&&!_&&!v&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),_&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>u(e.id),children:h(`codexAuth.reauthenticate`)}),p&&ci(t)&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>p(e.id),children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:mi(h,m?.(e.id))})}),(0,R.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,R.jsx)(le,{width:14}):(0,R.jsx)(ce,{width:14}),(0,R.jsx)(ua,{t:h,paused:e.paused,saving:c===e.id})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void d(e),children:h(`prov.editAlias`)}),(0,R.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,R.jsx)(ae,{width:14})})]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,h(`prov.accountId`),`: `,ni(e.id)]}),b&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:b}),v&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:h(`pws.healthCooldownHint`)}),_?(0,R.jsx)(`div`,{className:`card-sub faint`,children:h(`codexAuth.tokenExpired`)}):!v&&(0,R.jsx)(Rr,{quota:e.quota,plan:e.plan,threshold:i,t:h,pending:e.quota==null})]},e.id)})})}function fa({onReauth:e}){let t=K();return(0,R.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,R.jsxs)(`span`,{children:[(0,R.jsx)(de,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function pa({className:e,style:t}){return(0,R.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function ma({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,R.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,R.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,R.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,R.jsx)(pa,{})},t))]})}function ha({children:e,busy:t=!0,live:n=!0,className:r}){return(0,R.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,R.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,R.jsx)(`span`,{children:e})]})}function ga({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,onCancel:i,onConfirm:a}){let o=K(),s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,R.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?o(`codexAuth.preparePoolTitle`):e.id===`__main__`?o(`codexAuth.switchBack`):o(`codexAuth.switchTitle`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?o(`codexAuth.preparePoolDesc`):e.id===`__main__`?o(`codexAuth.switchBackDesc`):o(`codexAuth.switchDesc`)}),(0,R.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,R.jsx)(`strong`,{children:e.id===`__main__`?t||o(`codexAuth.codexApp`):e.email}),e.plan&&(0,R.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,R.jsxs)(`div`,{className:`notice-warn`,children:[(0,R.jsx)(de,{width:14}),` `,o(`codexAuth.cacheWarning`)]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`codexAuth.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r,onClick:a,children:o(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function _a({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=G(),d=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,R.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,R.jsx)(`div`,{className:`confirm-icon`,children:(0,R.jsx)(de,{width:22})}),(0,R.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,R.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:aa(n[0].granted_at,l)})}),(0,R.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,R.jsx)(Ce,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,R.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,R.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,R.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,R.jsx)(ca,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,R.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function va({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||ai(t?.health?.status),_=si(t?.health?.status),v=ui(e,t?.health),y=t?di(e,`codex`,m,t.health):null;return(0,R.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,R.jsxs)(`div`,{className:`card-head`,children:[(0,R.jsx)(`span`,{className:`dot ${g?`dot-amber`:`dot-green`}`}),(0,R.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,R.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,R.jsx)(la,{t:e,account:{...t,id:`__main__`},onClick:()=>u({...t,id:`__main__`})}),t?.paused&&(0,R.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),v&&(0,R.jsx)(`span`,{className:ii(t?.health?.status),children:v}),g&&!v&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(h),children:a}),d&&ci(t?.health?.status)&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>d(m),children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:mi(e,f?.(m))})}),t&&(0,R.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,R.jsx)(le,{width:14}):(0,R.jsx)(ce,{width:14}),(0,R.jsx)(ua,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,R.jsxs)(`span`,{className:`card-right`,children:[(0,R.jsx)(Se,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),y&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:y}),_&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),g?(0,R.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!_&&(0,R.jsx)(Rr,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function ya({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,R.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,R.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,R.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,R.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,R.jsx)(ce,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,R.jsx)(se,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function ba({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,R.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,R.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,R.jsxs)(`div`,{className:`card-head`,children:[(0,R.jsx)(`span`,{className:`dot dot-muted`}),(0,R.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,R.jsxs)(`span`,{className:`card-badges`,children:[(0,R.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,R.jsx)(Ce,{width:12}),`0`]}),(0,R.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,R.jsx)(ce,{width:14}),` `,e(`codexAuth.pause`)]}),(0,R.jsxs)(`span`,{className:`card-right`,children:[(0,R.jsx)(Se,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[(0,R.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,R.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,R.jsx)(Rr,{quota:null,threshold:0,t:e,pending:!0})]}),(0,R.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,R.jsx)(`div`,{className:`sep-line`}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,R.jsx)(oe,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,R.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,R.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,R.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,R.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,R.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function xa(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Sa(e,t,n,r){try{let i=await lt(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:xa(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 Ca=`ocx doctor`;function wa({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a}){let o=K(),s=Ji(e,{updated:o(`codexAuth.autoSwitchUpdated`),updateFailed:o(`codexAuth.autoSwitchUpdateFailed`),invalid:o(`codexAuth.autoSwitchThresholdInvalid`)}),{beginServerRead:c,acceptServerRead:l,rejectServerRead:u,hydrateServerValue:d}=s,f=Ni(e,!a),p=a??f,{accounts:m,activeId:h,loadState:g,switchingId:v,pauseUpdatingId:y,pausingExhausted:b,load:x}=p,{refreshing:S}=p,[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)(null),N=(0,_.useRef)(null),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(null),[ee,te]=(0,_.useState)(!1),ne=yi(),re=(0,_.useCallback)((e,t=!1)=>{N.current&&clearTimeout(N.current),A(e),M(t?`err`:`ok`),N.current=setTimeout(()=>{A(null),M(null),N.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let ie=(0,_.useCallback)(e=>{ne.copy(Ca,e)},[ne]),{subscribeLoadObserver:ae,readLastThreshold:se}=p;(0,_.useEffect)(()=>ae({beginActiveRead:c,acceptActiveRead:l,rejectActiveRead:u}),[ae,c,l,u]),(0,_.useEffect)(()=>{let e=se();e!==void 0&&d(e)},[se,d]),(0,_.useEffect)(()=>{if(!T)return;let e=p.pauseRefresh();return()=>p.resumeRefresh(e)},[p,T]);let ce=h&&h!==`__main__`?m.find(e=>e.id===h):null,le=!ce?.paused&&oi(ce);(0,_.useEffect)(()=>{i?.(le)},[le,i]);let ue=(0,_.useCallback)(e=>{O(e),E(!0)},[]),de=(0,_.useCallback)(()=>{E(!1),O(null)},[]),fe=(0,_.useCallback)(()=>{p.syncAfterAccountAdded(),re(o(`codexAuth.accountAdded`)),de()},[de,p,re,o]),pe=async e=>{let n=await p.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;re(o(`codexAuth.switchFailed`),!0);return}w(null);let r=n.activeId,i=r&&r!==`__main__`?m.find(e=>e.id===r)?.email??o(`pws.accountOrdinal`,{count:`1`}):o(`codexAuth.mainAccount`);re(o(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},me=async e=>{let t=window.prompt(o(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await p.saveAlias(e.id,t);re(o(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),!n.ok)},he=async e=>{let t=!e.paused,n=await p.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(w(t=>t?.id===e.id?null:t),re(o(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),!n.ok))},ge=async e=>{let t=m.find(t=>t.id===e)?.email??o(`pws.accountOrdinal`,{count:`1`});window.confirm(o(`codexAuth.removeConfirm`,{id:t}))&&((await p.removeAccount(e)).ok||re(o(`codexAuth.removeFailed`),!0))},_e=async()=>{F(!0);try{let e=await x(!0);re(o(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),!e)}finally{F(!1)}},ve=async()=>{let e=await p.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||re(e.ok?e.pausedCount>0?o(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):o(`codexAuth.pauseExhaustedNone`):o(`codexAuth.pauseExhaustedFailed`),!e.ok)},ye=async t=>{L(t),B(!1),W(null),te(!0);try{let n=await lt(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{te(!1)}},be=async t=>{H(!0);try{let n=await Sa(e,t,o,x);n.close&&(L(null),B(!1)),n.toast&&re(n.toast,!n.ok)}finally{H(!1)}},xe=m.find(e=>e.isMain),Se=m.filter(e=>!e.isMain),Ce=!xe?.paused&&(!h||h===`__main__`),we=o(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Te=y!==null||b,Ee=s.threshold??0;return(0,R.jsxs)(`div`,{children:[(0,R.jsx)(ya,{t:o,embedded:r,refreshingQuota:P,actionFeedback:k,actionFeedbackTone:j,pausingExhausted:b,pauseBusy:Te,onRefresh:()=>{_e()},onPauseExhausted:()=>{ve()}}),n,(0,R.jsx)(ba,{t:o,loadState:g,accountsCount:m.length,onRetry:()=>{x()}}),S&&m.length>0&&(0,R.jsx)(ha,{live:g!==`error`,children:o(`common.loading`)}),!(g===`loading`&&m.length===0)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(va,{t:o,main:xe,isMainActive:Ce,accountModeState:t,threshold:Ee,switchActionLabel:we,onSwitch:w,onTogglePause:he,pauseUpdatingId:y,pauseBusy:Te,onOpenReset:ye,onCopyDoctor:ie,doctorCopyOutcomeFor:ne.outcomeFor}),(0,R.jsxs)(`div`,{className:`section-sep`,children:[(0,R.jsx)(`span`,{className:`section-label`,children:o(`codexAuth.accountPool`)}),(0,R.jsx)(`div`,{className:`sep-line`}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>E(!0),children:[(0,R.jsx)(oe,{width:14}),` `,o(`codexAuth.add`)]})]}),le&&ce&&(0,R.jsx)(fa,{onReauth:()=>ue(ce.id)}),Se.length===0&&(0,R.jsx)(it,{title:o(`codexAuth.noPool`)}),(0,R.jsx)(da,{pool:Se,activeId:h,accountModeState:t,switchActionLabel:we,threshold:Ee,onOpenReset:ye,onSwitch:w,onTogglePause:he,pauseUpdatingId:y,pauseBusy:Te,onReauth:ue,onEditAlias:me,onRemove:ge,onCopyDoctor:ie,doctorCopyOutcomeFor:ne.outcomeFor})]}),(0,R.jsx)(Ii,{threshold:s.threshold,draft:s.draft,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(),x()}}),(0,R.jsx)(qi,{apiBase:e,subscribeLoadObserver:p.subscribeLoadObserver,readLastActive:p.readLastActive}),C&&(0,R.jsx)(ga,{confirm:C,mainEmail:xe?.email,accountModeState:t,switchingId:v,onCancel:()=>w(null),onConfirm:()=>{pe(C.id===`__main__`?`__main__`:C.id)}}),I&&(0,R.jsx)(_a,{resetPopup:I,resetConfirm:z,creditDetails:U,creditDetailsLoading:ee,redeeming:V,onClose:()=>{L(null),B(!1),W(null)},onShowConfirm:()=>B(!0),onCancelConfirm:()=>B(!1),onRedeem:()=>{be(I.id)}}),T&&(0,R.jsx)(Ci,{apiBase:e,reauthAccountId:D??void 0,onClose:de,onAdded:fe})]})}function Ta({apiBase:e,accountCount:t}){let n=K(),[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=Vi(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:Bi(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=Bi(r?.strategy??t.strategy),s=Vi(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,R.jsxs)(`div`,{className:`card`,style:{marginTop:12},"aria-busy":x||l,children:[(0,R.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,R.jsxs)(`div`,{style:{flex:1},children:[(0,R.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,R.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,R.jsxs)(`label`,{className:`toggle`,style:{display:`inline-flex`,alignItems:`center`,gap:8},children:[(0,R.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,R.jsx)(`span`,{children:n(g?`anthropicPool.on`:`anthropicPool.off`)})]})]}),(0,R.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,R.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`label`,{className:`field`,style:{display:`block`,marginTop:12},children:[(0,R.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,R.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,R.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,R.jsx)(Gi,{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=Hi(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,R.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}var Ea=`ocx doctor`,Da=4e3,Oa=[],ka=[];function Aa({item:e,apiBase:t,oauth:n,accounts:r=Oa,keys:i=ka,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d}){let f=K(),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(!1),S=yi(),C=yi();(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),Da);return()=>window.clearTimeout(e)},[r]);let w=Yr({...e,hasApiKey:e.hasApiKey||i.length>0}),T=w===`oauth-accounts`,E=w===`api-keys`;if(w===`codex-accounts`)return(0,R.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(`pws.availableAccounts`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:f(`pws.availableAccounts`)}),(0,R.jsx)(`div`,{className:`pwi-auth-body`,children:(0,R.jsx)(wa,{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,R.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(T?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:f(T?`pws.availableAccounts`:`pws.apiKeys`)}),(0,R.jsxs)(`div`,{className:`pwi-auth-body`,children:[T&&(0,R.jsxs)(R.Fragment,{children:[e.name===`anthropic`&&(0,R.jsx)(Ta,{apiBase:t,accountCount:r.length}),(0,R.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,R.jsx)(`span`,{className:`pwi-auth-dot ${N?`pwi-auth-dot--warn`:j?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,R.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,R.jsxs)(`span`,{className:`pwi-auth-actions`,children:[M&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:f(`prov.logout`)}):(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,R.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,R.jsx)(Se,{style:{width:13,height:13},"aria-hidden":`true`}),f(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),s&&D&&(0,R.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,R.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,R.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,R.jsx)(`div`,{className:`pwi-auth-wait-title`,children:f(`prov.waitingBrowser`)}),D.deviceCode&&(0,R.jsxs)(`div`,{className:`pwi-device-code-wrap`,children:[(0,R.jsx)(`span`,{children:f(`prov.deviceCode`)}),(0,R.jsx)(`code`,{className:`pwi-device-code`,children:D.deviceCode}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>S.copy(O,O),children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:A})})]}),(0,R.jsx)(bi,{url:D.url??``}),l.onCancelLogin&&(0,R.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,R.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,R.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),f(`pws.accountsLoading`)]}),a===`error`&&(0,R.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,R.jsx)(`span`,{children:f(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:f(`pws.retryAccounts`)})]}),r.length>0&&(0,R.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=Xr(r,t,f),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||ai(a),u=ci(a),d=si(a),p=ni(t.id),m=ui(f,t.health),h=di(f,e.name,t.id,t.health);return(0,R.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,R.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,R.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,R.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,R.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,R.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,R.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${f(`prov.accountId`)}: ${p}`].filter(Boolean).join(` · `)}),h&&(0,R.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:h}),d&&(0,R.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:f(`pws.healthCooldownHint`)})]}),m&&(0,R.jsx)(`span`,{className:ii(a),children:m}),c&&!m&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:f(`pws.reauth`)}),t.active&&(0,R.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)}),i&&(0,R.jsx)(`span`,{className:`badge badge-muted`,children:f(`pws.accountSwitching`)})]}),c&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{C.copy(Ea,t.id)},children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:mi(f,C.outcomeFor(t.id))})}),(0,R.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,R.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,R.jsx)(ue,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||b&&t.quota==null)&&(0,R.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,R.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:f(`pws.accountQuotaUnavailable`)}):(0,R.jsx)(Rr,{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,R.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:f(`pws.noAccounts`)}),j&&(0,R.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,R.jsxs)(R.Fragment,{children:[i.length>0&&(0,R.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,R.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,R.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,R.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,R.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,R.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,f(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,R.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)})]}),(0,R.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,R.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,R.jsx)(ue,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),p?(0,R.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,R.jsx)(`input`,{className:`input`,type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:v}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m(!1),g(``)},children:f(`common.cancel`)})]}):(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>m(!0),children:f(`pws.addKey`)})]})]})]})}function ja(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 Ma(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 Na(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Pa=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],Fa=[];function Ia({item:e,availableModels:t=Fa,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=K(),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(Ma(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=>lt(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(Ma(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=[...Pa];return c&&!e.includes(c)&&e.unshift(c),e},[c]),z=_r(e.name),B=j===`ready`&&!!(k&&k.length>0),V=c.trim()===`anthropic`&&m===`key`,H=z&&j!==`error`,U=async()=>{if(!r)return O({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;let t=B?Na(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,liveModels:C};V?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)}},W=(0,_.useRef)(U);(0,_.useEffect)(()=>{W.current=U}),(0,_.useEffect)(()=>{if(a)return a(()=>W.current()),()=>a(null)},[a]);let ee=()=>{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(Ma(k,e.baseUrl))},te=(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,R.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,R.jsx)(Se,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,R.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),z?(0,R.jsx)(`input`,{className:`input`,value:c,readOnly:!0,disabled:!0}):(0,R.jsx)(`select`,{className:`input`,value:c,onChange:e=>l(e.target.value),children:L.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))})]}),B?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,R.jsx)(`select`,{className:`input`,value:N,onChange:e=>{let t=e.target.value;P(t),d(ja(k,t,u))},children:k.map(e=>(0,R.jsx)(`option`,{value:e.id,children:te(e.id,e.label)},e.id))})]}),N===`custom`&&(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,R.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,R.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),readOnly:H,disabled:H})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),I.length>0?(0,R.jsxs)(`select`,{className:`input`,value:f,onChange:e=>p(e.target.value),children:[(0,R.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),I.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))]}):(0,R.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),z?(0,R.jsx)(`input`,{className:`input`,value:yr(e,o),readOnly:!0,disabled:!0}):(0,R.jsxs)(`select`,{className:`input`,value:m,onChange:e=>h(e.target.value),children:[(0,R.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,R.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,R.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,R.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),V&&(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,R.jsxs)(`select`,{className:`input`,value:g,onChange:e=>v(e.target.value),children:[(0,R.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,R.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,R.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:y,onChange:e=>b(e.target.value),rows:2})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,R.jsxs)(`span`,{children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,R.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),F&&(0,R.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,R.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,R.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ee,disabled:T,children:o(`pws.discardSettings`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void U(),disabled:T,children:o(T?`pws.saving`:`pws.saveSettings`)})]})]}),D&&(0,R.jsx)(`div`,{className:D.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:D.text})]})}function La({providerName:e,onConfirm:t,onCancel:n}){let r=K();return(0,R.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,R.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":r(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{children:r(`pws.removeConfirmTitle`)}),(0,R.jsx)(`p`,{children:r(`pws.removeConfirmBody`,{name:e})}),(0,R.jsxs)(`div`,{className:`dialog-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:r(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:t,children:r(`pws.removeConfirm`)})]})]})})}function Ra({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=K();return(0,R.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,R.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,R.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,R.jsxs)(`div`,{className:`dialog-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function za({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}){let O=K(),[k,A]=(0,_.useState)(`overview`),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(null),[F,I]=(0,_.useState)(!1),L=(0,_.useRef)(null),z=(0,_.useCallback)(e=>{L.current=e},[]),B=e.disabled===!0,V=(0,_.useMemo)(()=>Un(e),[e]),H=(0,_.useMemo)(()=>Xn(e),[e]),U=(0,_.useMemo)(()=>Yr(e),[e]),W=(0,_.useMemo)(()=>[{id:`overview`,label:O(`pws.tab.overview`)},{id:`models`,label:O(`pws.tab.models`)},{id:`usage`,label:O(`pws.tab.usage`)},...U?[{id:`accounts`,label:O(U===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:O(`pws.tab.settings`)}],[U,O]),ee=(0,_.useCallback)(e=>{if(j&&k===`settings`&&e!==`settings`){P(e);return}A(e)},[k,j]),te=(0,_.useCallback)(()=>{if(j&&k===`settings`){P(`deselect`);return}d()},[j,k,d]),ne=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%W.length;else if(e.key===`ArrowLeft`)n=(t-1+W.length)%W.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=W.length-1;else return;e.preventDefault(),ee(W[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ee,W]),re=`pws-tab-${k}`,ie=`pws-panel-${k}`;return(0,R.jsxs)(`div`,{className:`pws-detail`,children:[(0,R.jsx)(`div`,{className:`pws-detail-head`,children:(0,R.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:te,children:[(0,R.jsx)(_e,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),O(`pws.allProviders`)]})}),(0,R.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,R.jsx)(xr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,R.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,R.jsxs)(`h2`,{className:`pws-detail-title`,children:[gr(e.name),H&&(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:O(`modal.badge.local`)}),!H&&V&&(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:O(`modal.badge.free`)})]})}),(0,R.jsxs)(`div`,{className:`pws-detail-actions`,children:[E&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>E(e.name),"aria-label":O(`pws.removeConfirmTitle`),title:O(`pws.removeConfirmTitle`),children:(0,R.jsx)(ue,{style:{width:15,height:15},"aria-hidden":`true`})}),D&&(0,R.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,R.jsx)(`span`,{className:`pws-detail-toggle-label`,children:O(`pws.enabledLabel`)}),(0,R.jsx)(nt,{on:!B,onClick:()=>D(e.name,!B),disabled:T,label:O(`pws.enabledLabel`)})]})]})]}),(0,R.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:W.map((e,t)=>(0,R.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":k===e.id,tabIndex:k===e.id?0:-1,className:`pws-detail-tab${k===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ee(e.id),onKeyDown:e=>ne(e,t),children:e.label},e.id))}),(0,R.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:ie,"aria-labelledby":re,tabIndex:0,children:[k===`overview`&&(0,R.jsx)(Zr,{accountPanel:U?(0,R.jsx)(Aa,{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,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}),k===`models`&&(0,R.jsx)($r,{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),k===`usage`&&(0,R.jsx)(ei,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),k===`accounts`&&(0,R.jsx)(Aa,{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}),k===`settings`&&(0,R.jsx)(Ia,{item:e,apiBase:f,availableModels:i,onUpdateProvider:w,onDirtyChange:M,onRegisterSave:z},e.name)]}),N&&(0,R.jsx)(Ra,{saving:F,onCancel:()=>{F||P(null)},onDiscard:()=>{if(F)return;let e=N;P(null),M(!1),e===`deselect`?d():A(e)},onSave:()=>{(async()=>{if(!F){I(!0);try{if(!(await L.current?.()??!1))return;let e=N;P(null),M(!1),e===`deselect`?d():e&&A(e)}finally{I(!1)}}})()}})]})}var Ba=`https://chatgpt.com/backend-api/codex`;function Va(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 Ha(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 Ua(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Va(e.baseUrl)!==Ba?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function Wa(e){return e.id===`openai`}function Ga(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Ka(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return(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 qa(e,t){return Wa(e)?Ja(e):{name:t.name.trim(),provider:Ka(t)}}function Ja(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Ya=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function Xa(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 Ya(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Ya(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Ya(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ja(i))})).ok)throw new Ya(`codexAuth.enableOpenaiFailed`)}var Za=new Set([`anthropic`,`google-antigravity`]),Qa=new Set([`github-copilot`,`cursor`]);function $a(e){let t=e.trim().toLowerCase();return Za.has(t)?`high`:Qa.has(t)?`elevated`:null}function eo(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function to(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function no(e,t=!1){let n={};for(let[t,r]of Object.entries(e))oi(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function X(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=Xr(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=Xr(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)(()=>no(u,l),[u,l])}}function ro(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 io={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},ao=e=>io[e]??e;function oo({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:ao(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:ao(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 lt(a)??null:null;if(o){if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:ao(d)}):t(`prov.loginError`,{provider:ao(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:ao(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),_=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:ao(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),_=!0;break}l(t(`prov.loginOk`,{provider:ao(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:ao(d)}),!1),s(null))}catch{r.current.get(d)===v&&l(t(`prov.loginRequestFail`,{provider:ao(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:ao(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:ao(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:ao(n)}),!1)}}}}async function so(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function co({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l}){return{removeProvider:(0,_.useCallback)(async e=>{a(e)},[a]),confirmRemoveProvider:(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`});n.ok?(o(t(`prov.removed`,{name:d}),!0),r===d&&i(null),s(),c(),l(!0)):o(await so(n,f),!1)}catch{o(f,!1)}finally{n.current=!1}},[e,s,c,l,o,n,a,i,t,r]),setProviderDisabled:(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 i.json().catch(()=>({}))).error||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]),updateProvider:(0,_.useCallback)(async(t,n)=>{try{let r=await fetch(`${e}/api/providers?name=${encodeURIComponent(t)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});return r.ok?(await s(),{ok:!0}):{ok:!1,error:(await r.json().catch(()=>({}))).error||`Update failed`}}catch{return{ok:!1,error:`Network error`}}},[e,s])}}function lo({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await ct(await fetch(`${e}/api/config`));n(t??null),s&&t&&J(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await ct(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 lt(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function uo({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=K(),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=$a(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`:to(p),v=h===`anthropic`||h===`google-antigravity`;return(0,R.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,R.jsx)(`h3`,{id:a,children:i(eo(p),{provider:t})}),(0,R.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,R.jsx)(de,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,R.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,R.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,R.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,R.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,R.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 fo(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function po(e){return Wn(e.id,fo(e))}function mo(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[po(n)].push(n);return t}function ho(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}var go={},_o=[],vo={};function yo({presets:e,usageRank:t=go,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=_o,accountStatus:s=vo,busyProvider:c=null,onLogin:l,onCancelLogin:u,onLogout:d}){let f=K(),[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)(()=>mo(y),[y])[p],x=(0,_.useMemo)(()=>ho(b,h),[b,h]),S=e=>{let t=e.codexAccountMode===`direct`?(0,R.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,R.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.pool`)}):e.auth===`oauth`?(0,R.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.oauth`)}):e.auth===`forward`?(0,R.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.codexLogin`)}):e.auth===`local`?(0,R.jsx)(`span`,{className:`badge badge-amber`,children:f(`modal.badge.local`)}):e.keyOptional?null:(0,R.jsx)(`span`,{className:`badge badge-muted`,children:f(`modal.badge.apiKey`)});return(0,R.jsxs)(R.Fragment,{children:[(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,R.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.free`)}):null,t]})};return(0,R.jsxs)(`div`,{className:`provider-catalog`,children:[(0,R.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,R.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,R.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:f(`modal.accountsHint`)}),(0,R.jsx)(`input`,{className:`input provider-catalog-search`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.search`)}),(0,R.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&x.length===0&&(0,R.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.catalogLoading`)}),p!==`accounts`&&x.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`title`,children:e.label}),(0,R.jsxs)(`div`,{className:`sub`,children:[(0,R.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,R.jsx)(`div`,{className:`provider-catalog-badges`,children:S(e)})]},e.id)),p!==`accounts`&&!n&&x.length===0&&(0,R.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,R.jsxs)(`div`,{className:`list-row provider-catalog-account-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`title`,children:e.label}),(0,R.jsx)(`div`,{className:`sub`,children:i})]}),(0,R.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,R.jsxs)(R.Fragment,{children:[r&&(0,R.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-auth`,children:f(`modal.accountManage`)}),l&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(e.id),children:f(`modal.accountLogout`)}):n?u&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:f(`common.cancel`)}):l&&(0,R.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,R.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.noMatch`)})]}),(0,R.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,R.jsx)(`div`,{style:{flex:1}}),p!==`accounts`&&(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:f(`modal.notListed`)})]})]})}function bo({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=K();return(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,R.jsx)(`div`,{className:`muted text-control`,children:e.note??h(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>u(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,R.jsx)(Se,{}),n?h(`modal.waitingBrowser`):h(`modal.logInWith`,{label:e.label})]}):(0,R.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,R.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,R.jsx)(bi,{url:a}),n&&(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,R.jsx)(`div`,{className:`muted text-label`,children:h(`prov.pasteRedirectHint`)}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,R.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,R.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,R.jsx)(`div`,{className:`text-label`,style:{color:l?`var(--accent-hover)`:`var(--amber)`},children:c})]}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:d,children:h(`modal.useApiKeyInstead`)}),(0,R.jsx)(`div`,{style:{flex:1}}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}function xo({label:e,children:t}){return(0,R.jsxs)(`label`,{style:{display:`block`},children:[(0,R.jsx)(`span`,{className:`field-label`,children:e}),t]})}function So({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=K();return(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,R.jsxs)(`details`,{className:`setup-guide`,children:[(0,R.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,R.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,R.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,R.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,R.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,R.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,R.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,R.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,R.jsx)(xo,{label:h(`modal.providerName`),children:(0,R.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,R.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(xo,{label:h(`modal.adapter`),children:(0,R.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,R.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(xo,{label:h(`modal.endpoint`),children:(0,R.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:ja(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,R.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,R.jsx)(xo,{label:h(`modal.baseUrl`),children:(0,R.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,R.jsx)(xo,{label:h(`modal.baseUrl`),children:(0,R.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,R.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,R.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,R.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,R.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,R.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,R.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,R.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,R.jsxs)(R.Fragment,{children:[e.dashboardUrl&&(0,R.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,R.jsx)(xe,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,R.jsx)(be,{style:{width:13,height:13}})]}),(0,R.jsx)(xo,{label:h(`modal.apiKey`),children:(0,R.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,R.jsx)(xo,{label:h(`modal.apiKeyTransport`),children:(0,R.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,R.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,R.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,R.jsx)(xo,{label:h(`modal.defaultModel`),children:(0,R.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,R.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,R.jsx)(`div`,{style:{flex:1}}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Co=2e3;function wo({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,Co)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await lt(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 To(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 Eo(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 Do({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=K(),m=(0,_.useMemo)(()=>[{id:`custom`,label:p(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[p]),[h,g]=(0,_.useReducer)(Eo,a,e=>To(e,p(`modal.customProvider`))),v=(0,_.useRef)(!0),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=F(`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=F(`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=F(`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}),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:I,oauthUrlProvider:L,manualCode:z,manualCodeBusy:B,manualCodeMsg:V,manualCodeOk:H,endpointChoice:U,oauthTosPending:W}=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`&&!W&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,W]);let ee=e=>{let t=Ga(e);return t?p(t):e.note},te=e=>{let t=Ma(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?ja(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},ne=async()=>{if(!k)return;let t=O?Wa(O):!1,n=O?.baseUrlChoices?.length?Na(O.baseUrlChoices,U,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=qa(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:re,submitManualCode:ie}=wo({apiBase:e,t:p,aliveRef:v,onAdded:r}),oe={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:V,ok:e})},se=k?t.includes(k.name.trim())&&k.name.trim()!==``:!1,ce=e=>{if(!M){if($a(e)){g({type:`set-oauth-tos-pending`,providerId:e});return}re(e,oe)}},le=e=>{ie(e,z,B,{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:V,ok:e}),setManualCodeMsg:e=>g({type:`set-manual-code-msg`,msg:e})})},ue=O?.id===`custom`,de=k?.authMode===`local`,fe=O?Wa(O):!1;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":p(`modal.add`),className:`modal-overlay`,onClick:n,children:(0,R.jsxs)(`div`,{ref:b,className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{children:O?p(`modal.addNamed`,{label:O.label}):p(`modal.add`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":p(`common.close`),onClick:n,children:(0,R.jsx)(ae,{})})]}),O?k&&(O.auth===`oauth`&&k.authMode===`oauth`?(0,R.jsx)(bo,{preset:O,oauthSupported:w,oauthBusy:M,oauthMsg:N,oauthMsgTone:P,oauthUrl:L===O.oauthProvider?I:``,manualCode:z,manualCodeBusy:B,manualCodeMsg:V,manualCodeOk:H,onRequestLogin:ce,onUseApiKeyInstead:()=>{g({type:`use-api-key-instead`,form:{...k,authMode:`key`}})},onManualCodeChange:e=>g({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{le(e)},onBack:()=>g({type:`back`})}):(0,R.jsx)(So,{preset:O,form:k,endpointChoice:U,error:j,saving:A,dup:se,isCustom:ue,isLocal:de,isReservedForward:fe,presetDescription:ee,onFormChange:e=>g({type:`set-form`,form:e}),onEndpointChoiceChange:e=>g({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{ne()},onUseOauthLogin:()=>g({type:`use-oauth-login`,form:{...k,authMode:`oauth`}}),onBack:()=>g({type:`back`})})):(0,R.jsx)(yo,{presets:T,usageRank:D,presetsLoading:E,initialTier:i,onSelectPreset:e=>te(e),onSelectCustom:()=>te(m[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:l,onCancelLogin:u,onLogout:d})]})}),W&&(0,R.jsx)(uo,{providerId:W,providerLabel:O?.label??W,onCancel:()=>g({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=W;e&&(g({type:`set-oauth-tos-pending`,providerId:null}),re(e,oe))}},W)]})}function Oo({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,removeConfirmName:s,codexLoginOpen:c,jsonLeaveOpen:l,jsonSaving:u,oauthTosPending:d,onCloseAdd:f,onAdded:p,onAccountLogin:m,onAccountCancelLogin:h,onAccountLogout:g,onOpenAdd:_,onCloseCodexLogin:v,onCodexAdded:y,onCancelRemove:b,onConfirmRemove:x,onCancelJsonLeave:S,onDiscardJson:C,onSaveJson:w,onCancelOauthTos:T,onContinueOauthTos:E}){return(0,R.jsxs)(R.Fragment,{children:[n&&(0,R.jsx)(Do,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:f,onAdded:p,accountRows:a,accountStatus:o,accountBusy:i,onAccountLogin:m,onAccountCancelLogin:h,onAccountLogout:g,onOpen:_}),c&&(0,R.jsx)(Ci,{apiBase:e,onClose:v,onAdded:y}),s&&(0,R.jsx)(La,{providerName:s,onCancel:b,onConfirm:x}),l&&S&&C&&w&&(0,R.jsx)(Ra,{saving:u??!1,onCancel:S,onDiscard:C,onSave:w}),d&&(0,R.jsx)(uo,{providerId:d.provider,providerLabel:ao(d.provider),onCancel:T,onContinue:E},`${d.provider}:${d.addAccount?`add`:`login`}`)]})}function ko(e,t){return[...Ha(e.providers).map(e=>({id:e,label:gr(e),kind:`codex`,href:`#codex-auth`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:ao(e),kind:`oauth`}))]}function Ao(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 jo({apiBase:e}){let t=K(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>sn(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),I=(0,_.useRef)(new Map),L=(0,_.useCallback)((e,t=!0)=>{c(e),u(t)},[]);(0,_.useEffect)(()=>(M.current=!0,()=>{M.current=!1}),[]),F(`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}),F(`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});let[z,B]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:V,fetchOauth:H,fetchProviderQuotas:U}=lo({apiBase:e,t,setConfig:i,setOauthProviders:f,setOauthStatus:m,notify:L,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{B(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),W=Ni(e),ee=W.activeNeedsReauth,te=(0,_.useMemo)(()=>{let e=W.accounts;if(e.length===0&&W.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}:{},...ee?{needsReauth:!0}:{}}}},[p,W.accounts,W.loadState,ee]),{accountSets:ne,accountLoadStates:re,switchingAccount:ie,keyPools:ae,fetchAccountSets:se,switchAccount:ce,switchApiKey:le,removeApiKey:ue,addApiKeyValue:de,editCredentialAlias:fe,removeAccount:pe,activeAccountNeedsReauth:me}=X({apiBase:e,t,config:r,oauthStatus:te,aliveRef:M,notify:L,fetchConfig:V,fetchOauth:H,fetchProviderQuotas:U,codexActiveNeedsReauth:ee}),{draft:he,setDraft:ge,jsonEditorOpen:_e,jsonSaving:ve,jsonLeaveOpen:ye,saveConfig:be,openJsonEditor:xe,discardJsonEditor:Se,requestCloseJsonEditor:Ce,restoreJsonEditor:we,jsonIsDirty:Te,setJsonLeaveOpen:Ee}=ro({apiBase:e,config:r,notify:L,fetchConfig:V,fetchProviderQuotas:U,onSaved:()=>k(e=>e+1),t});(0,_.useEffect)(()=>{N.current!==e&&(N.current=e,Promise.resolve().then(()=>{V(),H()}))},[e,V,H]);let De=()=>k(e=>e+1),{cancelLoginOAuth:Oe,loginOAuth:ke,logoutOAuth:Ae}=oo({apiBase:e,t,aliveRef:M,oauthLoginGenerationRef:I,accountSets:ne,setBusy:g,setStatus:c,setLoginInfo:y,setOauthStatus:m,notify:L,fetchConfig:V,fetchOauth:H,fetchAccountSets:se,fetchProviderQuotas:U,bumpModelsRefresh:De}),{removeProvider:je,confirmRemoveProvider:Me,setProviderDisabled:Ne,updateProvider:Pe}=co({apiBase:e,t,removeBusyRef:P,workspaceSelected:b,setWorkspaceSelected:x,setRemoveConfirmName:T,notify:L,fetchConfig:V,fetchOauth:H,fetchProviderQuotas:U}),Fe=(e,t=!1)=>{if(h!==e){if($a(e)){j({provider:e,addAccount:t});return}ke(e,t)}};if(!r)return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,R.jsx)(q,{tone:`err`,children:s}):(0,R.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,R.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,R.jsx)(`div`,{className:`providers-workspace-main`,children:(0,R.jsxs)(`p`,{className:`muted`,children:[(0,R.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let Ie=ko(r,d),Le=Ao(r,te),Re=e=>r.providers[e]?.authMode===`forward`;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:t(`nav.providers`)}),(0,R.jsx)(`div`,{className:`row`,children:(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,R.jsx)(oe,{}),t(`prov.add`)]})})]}),s&&(0,R.jsx)(q,{tone:l?`ok`:`err`,children:s}),(0,R.jsx)(qr,{onRemoveProvider:je,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:b,onSelect:x,onAddProvider:e=>{C(e??null),o(!0)},onEditConfig:xe,jsonEditor:{open:_e,draft:he,isDirty:Te,onDraftChange:ge,onSave:()=>be(),onClose:Ce,onRestore:we},jsonSaving:ve,modelsRefreshToken:O,activeAccountNeedsReauth:me,quotaRefreshEpoch:z.epoch,quotaForceRefresh:z.force,detail:(t,n)=>{let i=Le[t.name]??p[t.name];return(0,R.jsx)(za,{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:ne[t.name]?.accounts??[],keys:ae[t.name]??[],accountLoadState:re[t.name]??(t.authMode===`oauth`?`idle`:`ready`),switchingAccountId:ie?.provider===t.name?ie.accountId:null,busyProvider:h,loginHint:v,authHandlers:{onLogin:Fe,onCancelLogin:Oe,onLogout:Ae,onReauth:(e,t)=>ke(e,!0,t),onSwitchAccount:ce,onRemoveAccount:pe,onRetryAccounts:async e=>{await se([e])},onAddApiKey:de,onSwitchApiKey:le,onRemoveApiKey:ue,onEditAlias:fe},isDefault:t.name===r.defaultProvider,onRemoveProvider:je,onSetDisabled:Ne,onUpdateProvider:Pe,codexController:W},t.name)}}),(0,R.jsx)(Oo,{apiBase:e,config:r,adding:a,addIntent:S,busy:h,addModalAccountRows:Ie,accountLoginStatus:Le,removeConfirmName:w,codexLoginOpen:E,jsonLeaveOpen:ye,jsonSaving:ve,oauthTosPending:A,onCloseAdd:()=>{h&&Oe(h),o(!1),C(null)},onAdded:e=>{o(!1),C(null),L(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),V(),H(),U(!0),De()},onAccountLogin:async n=>{if(n===`openai`){if(h===`openai`)return;let n=r.providers.openai,i=Ua(n);if(i===`invalid`){L(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){g(`openai`);try{await Xa(e,i),await V()}catch(e){e instanceof Ya?L(t(e.i18nKey),!1):L(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{M.current&&g(e=>e===`openai`?null:e)}}D(!0);return}if(Re(n)){D(!0);return}(r.providers[n]?.authMode===`oauth`||d.includes(n))&&Fe(n)},onAccountCancelLogin:e=>{Oe(e)},onAccountLogout:e=>{Ae(e)},onOpenAdd:H,onCloseCodexLogin:()=>D(!1),onCodexAdded:()=>{D(!1),L(t(`prov.loginOk`,{provider:gr(`openai`),cmd:`ocx sync`}),!0),V(),H(),U(!0),De()},onCancelRemove:()=>T(null),onConfirmRemove:()=>{Me(w)},onCancelJsonLeave:()=>{ve||Ee(!1)},onDiscardJson:Se,onSaveJson:()=>{be()},onCancelOauthTos:()=>j(null),onContinueOauthTos:()=>{let e=A;e&&(j(null),ke(e.provider,e.addAccount))}})]})}var Mo={"gpt-5.6-sol":Te,"gpt-5.6-terra":Oe,"gpt-5.6-luna":Ee},No={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function Po(e){return e.slice(e.lastIndexOf(`/`)+1)}function Fo(e){return Mo[e]??Mo[Po(e)]??null}function Io(e){let t=Fo(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:No,"aria-hidden":!0}),e):e}var Lo=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function Ro(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...Lo];let r=new Set(Lo),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 Lo.filter(e=>a.has(e))}var zo=0;function Bo(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++zo}`}}var Vo=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Ho=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,Uo=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Wo(e){return Vo.test(e.trim())}function Go(e){return`combo/${e.trim()}`}function Ko(e,t){return(typeof t==`string`?t.trim():``)||Go(e)}function qo(e){return typeof e==`string`&&e.trim()?e.trim():null}function Jo(e){return e===`round-robin`?`round-robin`:`failover`}function Yo(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Xo(e){return typeof e==`string`&&Lo.includes(e)?e:null}function Zo(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Qo(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=Zo(t.weight);a.push(Bo(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():Ko(r,qo(t.alias)),alias:qo(t.alias),strategy:Jo(t.strategy),stickyLimit:Yo(t.stickyLimit),defaultEffort:Xo(t.defaultEffort),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function $o(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 es(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 ts(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 ns(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 rs(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 is(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Wo(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(!Ho.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&Uo.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 as(e=``){return{id:e,model:e?Go(e):`combo/`,alias:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,targets:[Bo()]}}function os(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 ss(e,t,n,r){let{isEmpty:i,...a}=r,o=F(e,t,n,a);return{...o,state:os(o,i,r.enabled!==!1)}}function cs(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 ls(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function us(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function ds(e){if(!ls(e))throw Error(`invalid selected models response`);let t=e.selected;if(!ls(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,us(t)]))}async function fs(e,t=fetch){let n=await t(`${e}/api/selected-models`);if(!n.ok)throw Error(`selected models HTTP ${n.status}`);return ds(await n.json())}function ps(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function ms(e,t,n,r,i){return ps(e,t,n,r)&&!i}async function hs(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 gs(e,t){return e===t}function _s(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 vs=Array.from({length:18},(e,t)=>1e5+t*5e4),ys=new Set(vs),bs=`custom`,xs=[4,8,16,32,64,128,256,500,1e3],Ss=new Set(xs),Cs=`ocx-models-collapsed:v2`,ws=`ocx-models-combos-open:v1`;function Ts(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function Es(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ds(e,t,n){let r=[];for(let i of e){let e=t.has(i.id)||t.has(i.namespaced);ms(n,i.provider,i.id,i.native===!0,e)&&r.push({value:i.namespaced,label:i.namespaced})}return r}function Os(e=localStorage){try{let t=e.getItem(Cs);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 ks(e,t=localStorage){try{t.setItem(Cs,JSON.stringify([...e]))}catch{}}function As(e=localStorage){try{return(e.getItem(`ocx-models-combos-open:v1`)??e.getItem(`ocx-models-combos-open`))===`1`}catch{return!1}}function js(e,t=localStorage){try{t.setItem(ws,e?`1`:`0`)}catch{}}function Ms({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=K(),i=e&&t?.status===`failed`?t:void 0;return(0,R.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,R.jsx)(fe,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,R.jsxs)(`span`,{children:[i&&n&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${_s(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,R.jsx)(`a`,{href:`#providers`,children:r(`models.openProviderSettings`)})]})]})}function Ns({apiBase:e}){let t=K(),n=`ocx.models.catalog.v1:${e}`,r=(0,_.useMemo)(()=>sn(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??{}),[y,b]=(0,_.useState)(()=>r?.contextCapValue??35e4),[x,S]=(0,_.useState)(``),[C,w]=(0,_.useState)(!1),T=Os(),[E,D]=(0,_.useState)(()=>T??new Set),O=(0,_.useRef)(T===null),[k,A]=(0,_.useState)(``),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),F=(0,_.useRef)(!1),L=(0,_.useRef)(0),z=(0,_.useRef)(!1),[B,V]=(0,_.useState)(null),[U,W]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(``),ne=(0,_.useRef)(!1),[re,ie]=(0,_.useState)(``),[ae,oe]=(0,_.useState)(!1),[se,ce]=(0,_.useState)(!1),[le,ue]=(0,_.useState)(!1),[de,pe]=(0,_.useState)(`add`),[me,he]=(0,_.useState)(``),[ge,ve]=(0,_.useState)(``),[ye,be]=(0,_.useState)(``),[xe,Se]=(0,_.useState)(``),[Ce,we]=(0,_.useState)(``),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)([`text`]),[ke,je]=(0,_.useState)(!1),[Me,Ne]=(0,_.useState)(``),[Pe,Fe]=(0,_.useState)(null),Ie=(0,_.useRef)(null),[Le,Re]=(0,_.useState)(null),[ze,Be]=(0,_.useState)(!1),[G,Ve]=(0,_.useState)(null),[He,Ue]=(0,_.useState)(!1),[We,Ge]=(0,_.useState)(As),[Ke,qe]=(0,_.useState)(null),Je=()=>{let e=!We;js(e),Ge(e)};(0,_.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await ct(await fetch(`${e}/api/combos`));t||(Ve(Qo(n)),Ue(!1))}catch{t||(Ve(null),Ue(!0))}})(),()=>{t=!0}},[e]),(0,_.useEffect)(()=>()=>{Ie.current&&clearTimeout(Ie.current)},[]);let Ye=(0,_.useMemo)(()=>Ds(i,c,u??{}),[i,c,u]),Xe=(0,_.useCallback)(async()=>{try{let t=await lt(await fetch(`${e}/api/shadow-call-settings`));t&&Re(t)}catch{}},[e]),Ze=(0,_.useCallback)(async()=>{if(!ne.current)try{let t=await fetch(`${e}/api/v2`);if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){V(null);return}let n=await lt(t);if(!n||typeof n.enabled!=`boolean`){V(null);return}V({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`})}catch{V(null)}},[e]),Qe=(0,_.useCallback)(async t=>{let[r,i,a,o]=await Promise.all([fetch(`${e}/api/models`),fetch(`${e}/api/provider-context-caps`),fetch(`${e}/api/providers`),fs(e)]),[s,c,l]=await Promise.all([ct(r),ct(i),ct(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=Es(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 J(n,p),p},[e,n]),$e=(0,_.useCallback)(e=>{let t=cs(e.models,e.providers);qe(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),b(e.contextCapValue),v(e.contextCaps)},[]),et=ss(n,[e],async e=>{let t=await Qe(e);if(e.aborted)throw Error(`models request aborted`);return $e(t),t},{isEmpty:()=>!1,pollMs:1e4}),tt=et.state,ot=et.refresh;(0,_.useLayoutEffect)(()=>{r&&(I(n,r),ot())},[n,r,ot]);let st=(0,_.useCallback)(async(e=!1)=>{if(z.current&&!e)return!1;z.current=!0;let t=++L.current;try{let e=await Qe(new AbortController().signal);return gs(t,L.current)?($e(e),I(n,e),!0):!1}catch{return!1}finally{gs(t,L.current)&&(z.current=!1)}},[$e,n,Qe]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{Xe(),Ze()},0),t=window.setInterval(()=>{ne.current||Ze()},1e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[Xe,Ze]);let ut=(0,_.useMemo)(()=>cs(i,o),[i,o]);(0,_.useEffect)(()=>{if(!O.current||ut.length===0)return;O.current=!1;let e=new Set(ut.map(e=>e.provider));D(e),ks(e)},[ut]);let dt=(0,_.useMemo)(()=>u?i.filter(e=>ms(u,e.provider,e.id,e.native===!0,c.has(e.namespaced))).length:0,[c,i,u]),ft=async(n,r,i,a)=>{++L.current,P(!0),F.current=!0,A(``);let o=null;try{(await hs(e,n,r,i,a)).ok||(o=`models.saveFailed`)}catch{o=`models.networkError`}finally{let e=await st(!0);o?(M(!1),A(t(o))):e&&(M(!0),A(t(`models.applied`))),P(!1),F.current=!1}},pt=async n=>{P(!0),F.current=!0,A(``);let r=g[n]!==y;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 ct(i,t(`models.capSaveFailed`)))?.caps??{}),M(!0),A(t(`models.capApplied`)),await st(!0)}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{P(!1),F.current=!1}},mt=e=>{D(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),ks(n),n})},ht=e=>{D(()=>{let t=e?new Set(ut.map(e=>e.provider)):new Set;return ks(t),t})},gt=async n=>{P(!0),F.current=!0,A(``);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 ct(r,t(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&b(e.value),v(e?.caps??{}),M(!0),A(t(`models.capApplied`)),await st(!0)}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{P(!1),F.current=!1}},_t=e=>{!Number.isFinite(e)||e<=0||gt({value:Math.floor(e)})},vt=e=>{if(e===`custom`){w(!0),S(String(y));return}w(!1);let t=Number(e);Number.isFinite(t)&&t>0&&t!==y&&_t(t)},yt=()=>{let e=Number(x.replace(/[_,\s]/g,``));if(!Number.isFinite(e)||e<=0){M(!1),A(t(`models.capSaveFailed`));return}w(!1),_t(e)},bt=(0,_.useMemo)(()=>{let e=ut.filter(e=>!e.native&&e.rows.length>0);return e.length>0&&e.every(e=>g[e.provider]===y)},[ut,g,y]),xt=()=>{gt({setAll:!bt})},St=async t=>{if(!(!Le||ze)){Be(!0),Re({...Le,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Be(!1)}}},Ct=async n=>{if(!(!B||ne.current)&&B.multiAgentMode!==n){W(!0),ne.current=!0,te(``),A(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:n})});try{let e=await ct(r,t(`models.saveFailed`));Ze(),M(!0),A(t(`models.v2Applied`)),te((e?.warnings??[]).join(` `))}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{W(!1),ne.current=!1}}},wt=async n=>{if(!(!B||ne.current)){if(!Number.isInteger(n)||n<1){M(!1),A(t(`models.v2ThreadsInvalid`));return}if(B.maxConcurrentThreadsPerSession!==n){W(!0),ne.current=!0,te(``),A(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await ct(r,t(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){M(!1),A(t(`models.saveFailed`));return}V({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`}),M(!0),A(t(`models.v2ThreadsApplied`)),oe(!1)}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{W(!1),ne.current=!1}}}},Tt=e=>{if(e===`custom`){oe(!0),ie(String(B?.maxConcurrentThreadsPerSession??``));return}oe(!1),wt(Number(e))},Et=(e,t)=>{Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{Fe({namespaced:e,rect:t.getBoundingClientRect()})},300)},kt=(e,t)=>{Ie.current&&clearTimeout(Ie.current),Fe({namespaced:e,rect:t.getBoundingClientRect()})},At=()=>{Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>Fe(null),120)},jt=()=>{Ie.current&&clearTimeout(Ie.current)},Mt=async(n,r,i,a,o)=>{je(!0),Ne(``);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 ct(s,t(`models.customSaveFailed`)),ue(!1),M(!0),A(t(`models.customAdded`)),await st(!0)}catch(e){Ne(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Ne(t(`models.networkError`))}finally{je(!1)}},Nt=async(n,r)=>{je(!0),Ne(``);try{let i=await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});try{await ct(i,t(`models.customSaveFailed`)),ue(!1),M(!0),A(t(`models.customUpdated`)),await st(!0)}catch(e){Ne(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Ne(t(`models.networkError`))}finally{je(!1)}},Pt=async n=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`DELETE`})).ok?(M(!0),A(t(`models.customDeleted`)),await st(!0)):(M(!1),A(t(`models.customSaveFailed`)))}catch{M(!1),A(t(`models.networkError`))}},Ft=tt.data??r;if(tt.showSkeleton&&!Ft)return(0,R.jsx)(ma,{label:t(`models.loading`),rows:5});if(tt.kind===`failed-cold`)return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:tt.error instanceof Error?tt.error.message:t(`models.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>et.refresh(),children:t(`common.retry`)})]});let It=u??{},Lt=e=>{let{provider:n,rows:r,native:i,liveModels:a,discovery:o}=e,s=E.has(n),l=e=>ms(It,n,e.id,e.native===!0,c.has(e.namespaced)),u=r.filter(l).length,d=g[n]===y,_=i,v=a&&o?.status===`failed`?o:void 0,b=(f[n]??``).trim().toLowerCase(),x=b?r.filter(e=>e.id.toLowerCase().includes(b)):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,D=r.length>0,O=!D||r.every(l),k=!D||r.every(e=>!l(e)),A=e=>{D&&ft(`provider`,n,r.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,R.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,R.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>mt(n),"aria-expanded":!s,style:{flex:1,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,R.jsx)(_e,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,R.jsx)(`span`,{className:`text-body font-semibold`,children:n}),_&&(0,R.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.nativeGroupLabel`)}),v&&(0,R.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:_s(t,v),children:t(`models.discoveryFailedBadge`)}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:u,total:r.length})})]}),(0,R.jsxs)(`div`,{className:`row models-provider-actions`,children:[!_&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),pe(`add`),he(n),ve(``),be(``),Se(``),we(``),Ee(!1),Oe([`text`]),Ne(``),ue(!0)},"aria-label":t(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:N||O,onClick:()=>A(!0),children:t(`models.allOn`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:N||k,onClick:()=>A(!1),children:t(`models.allOff`)}),!_&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(nt,{on:d,onClick:()=>pt(n),disabled:N,label:t(`models.capValue`,{value:Ts(y)})}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.capValue`,{value:Ts(y)})})]})]})]}),!s&&(0,R.jsxs)(`div`,{className:`models-provider-body`,children:[_&&(0,R.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:t(`models.nativeHint`)}),r.length===0&&(0,R.jsx)(Ms,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>60/2&&(0,R.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,R.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Et(e.namespaced,t.currentTarget),onMouseLeave:At,onFocus:t=>kt(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||Fe(null)},children:[(0,R.jsxs)(`div`,{className:`row models-model-row`,children:[(0,R.jsx)(nt,{on:!r,onClick:()=>void ft(`models`,n,[{id:e.id,native:e.native===!0}],r),disabled:N,label:e.native?e.id:e.namespaced}),(0,R.jsx)(`code`,{className:`mono text-control`,style:{color:r?`var(--faint)`:`var(--text)`,textDecoration:r?`line-through`:`none`},children:e.native?Io(e.id):e.namespaced}),e.custom&&(0,R.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.customBadge`)}),e.contextCapped&&(0,R.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.contextCappedValue`,{value:Ts(e.contextCap??y)})})]}),Pe?.namespaced===e.namespaced&&(()=>{let n=Pe.rect,i=n.bottom+4,a=i+360>window.innerHeight;return(0,R.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:jt,onMouseLeave:At,children:[(0,R.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,R.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,R.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:t(`models.customBadge`)}),(0,R.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipProvider`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:e.provider}),(e.contextWindow||e.contextCap)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipContext`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:Ts(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipModalities`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipStatus`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:t(r?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,R.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{pe(`edit`),he(e.provider),ve(e.customId),be(e.id),Se(e.displayName??``),we(e.contextWindow?String(e.contextWindow):``),Ee(!1),Oe(e.inputModalities??[`text`]),Ne(``),ue(!0),Fe(null)},children:t(`models.customEdit`)}),(0,R.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}))&&Pt(e.customId),Fe(null)},children:t(`models.customDelete`)})]})]})})()]},e.namespaced)}),T>0&&(0,R.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)},Rt=Ke?ut.filter(e=>e.provider===Ke):ut,zt=(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`models-control-top-row`,children:[(0,R.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!Le||void 0,children:[(0,R.jsxs)(`span`,{className:`models-shadow-label`,children:[t(`models.shadowCallIntercept`),` `,(0,R.jsx)(at,{content:t(`models.shadowCallInterceptHint`,{models:Dt(Le?.sourceModels)}),side:`top`,maxWidth:320,children:(0,R.jsx)(`span`,{style:{cursor:`help`},"aria-label":t(`models.shadowCallInterceptHint`,{models:Dt(Le?.sourceModels)}),children:`ⓘ`})})]}),(0,R.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:t(`models.shadowCallOriginal`,{models:Ot(Le?.sourceModels)})}),(0,R.jsx)(nt,{on:Le?.enabled??!1,onClick:()=>void St({enabled:!Le?.enabled}),disabled:!Le||ze,label:t(`models.shadowCallIntercept`)}),(0,R.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,R.jsx)(rt,{value:Le?.model??``,options:[{value:``,label:`—`},...Ye],onChange:e=>{Re(t=>t&&{...t,model:e}),St({model:e})},disabled:!Le||ze||!Le.enabled,label:t(`models.shadowCallIntercept`)})})]}),B&&(0,R.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2Label`)}),(0,R.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":t(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,R.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(B.multiAgentMode??`default`)===e,className:`btn btn-sm${(B.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(B.multiAgentMode??`default`)===e?void 0:`transparent`,color:(B.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:U,onClick:()=>void Ct(e),children:t(`models.v2Mode_${e}`)},e))}),(0,R.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:()=>ce(!0),"aria-label":t(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,R.jsx)(fe,{width:14,height:14,"aria-hidden":`true`})})]})]}),B&&(B.enabled||B.agentsMaxThreadsConflict||ee)&&(0,R.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[B.enabled&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2ThreadsLabel`)}),(0,R.jsx)(rt,{value:ae?`custom`:B.maxConcurrentThreadsPerSession!==null&&B.maxConcurrentThreadsPerSession!==void 0?Ss.has(B.maxConcurrentThreadsPerSession)?String(B.maxConcurrentThreadsPerSession):`custom`:``,options:[...B.maxConcurrentThreadsPerSession===null||B.maxConcurrentThreadsPerSession===void 0?[{value:``,label:t(`models.v2ThreadsDefault`)}]:[],...B.maxConcurrentThreadsPerSession!==null&&B.maxConcurrentThreadsPerSession!==void 0&&!Ss.has(B.maxConcurrentThreadsPerSession)&&!ae?[{value:`custom`,label:String(B.maxConcurrentThreadsPerSession)}]:[],...xs.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:t(`models.custom`)}],onChange:e=>Tt(e),disabled:U,label:t(`models.v2ThreadsLabel`)}),ae&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:re,onChange:e=>ie(e.target.value),onKeyDown:e=>{e.key===`Enter`&&wt(Number(re.replace(/[_,\s]/g,``)))},disabled:U,"aria-label":t(`models.v2ThreadsLabel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:U,onClick:()=>{wt(Number(re.replace(/[_,\s]/g,``)))},children:t(`models.v2ThreadsApply`)})]})]}),B.enabled&&B.agentsMaxThreadsConflict&&(0,R.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:t(`models.v2Conflict`)}),ee&&(0,R.jsx)(`span`,{className:`muted text-label`,children:ee})]}),(0,R.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`models.contextCapLabel`)}),(0,R.jsx)(rt,{value:C?bs:ys.has(y)?String(y):bs,options:[...!ys.has(y)&&!C?[{value:String(y),label:Ts(y)}]:[],...vs.map(e=>({value:String(e),label:Ts(e)})),{value:bs,label:t(`models.custom`)}],onChange:e=>vt(e),disabled:N,label:t(`models.contextCapLabel`)}),C&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:t(`models.customPlaceholder`),value:x,onChange:e=>S(e.target.value),onKeyDown:e=>{e.key===`Enter`&&yt()},disabled:N,"aria-label":t(`models.customPlaceholder`)}),(0,R.jsx)(`button`,{type:`button`,onClick:yt,disabled:N,className:`btn btn-ghost btn-sm`,children:t(`models.customApply`)})]}),(0,R.jsx)(nt,{on:bt,onClick:xt,disabled:N,label:t(`models.setAll`)}),(0,R.jsx)(`span`,{className:`muted text-label leading-body`,children:t(`models.setAllHint`,{value:Ts(y)})})]}),(()=>{let e=i.filter(e=>e.custom).length;return e===0?null:(0,R.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,R.jsx)(`span`,{className:`models-chip mono text-caption`,children:t(`models.customSummary`,{count:e})})})})(),(0,R.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,R.jsx)(fe,{width:15,height:15,"aria-hidden":`true`}),(0,R.jsx)(`span`,{children:t(`models.orderHint`)})]})]}),Bt=(0,R.jsxs)(R.Fragment,{children:[G!==null&&!He&&G.length===0&&(0,R.jsx)(`div`,{className:`card models-combos-card`,children:(0,R.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,R.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,R.jsx)(Ae,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,R.jsx)(`strong`,{children:t(`nav.combos`)}),(0,R.jsx)(`span`,{className:`muted text-label`,children:t(`models.combosEmpty`)})]}),(0,R.jsx)(`a`,{className:`btn btn-sm`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]})}),G!==null&&!He&&G.length>0&&(0,R.jsxs)(`div`,{className:`card models-combos-card`,children:[(0,R.jsxs)(`div`,{className:`row group-head models-field-row${We?` open`:``}`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`row models-field-row`,"aria-expanded":We,onClick:Je,style:{flex:1,background:`none`,border:`none`,padding:0,cursor:`pointer`,font:`inherit`,color:`inherit`,textAlign:`left`,minWidth:0},children:[(0,R.jsx)(_e,{style:{width:14,height:14,color:`var(--muted)`,flexShrink:0,transform:We?`rotate(90deg)`:`none`,transition:`transform .12s`}}),(0,R.jsx)(Ae,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,R.jsx)(`strong`,{children:t(`nav.combos`)}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.combosActive`,{count:G.length})})]}),(0,R.jsx)(`a`,{className:`btn btn-sm btn-ghost`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]}),We&&(0,R.jsxs)(`div`,{children:[G.map(e=>(0,R.jsxs)(`div`,{className:`row models-combo-row`,children:[(0,R.jsx)(`span`,{className:`mono leading-ui`,children:e.model}),(0,R.jsxs)(`span`,{className:`muted text-label`,children:[e.strategy,` · `,e.targets.length]})]},e.id)),(0,R.jsxs)(`a`,{className:`row muted models-combos-add`,href:`#combos`,children:[`+ `,t(`models.combosAdd`)]})]})]})]}),Vt=(0,R.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ht(!0),disabled:N,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ht(!1),disabled:N,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),Ht=(0,R.jsx)(R.Fragment,{children:ut.length===0&&(0,R.jsx)(it,{icon:(0,R.jsx)(H,{}),title:t(`models.noRouted`),children:t(`models.noRoutedHint`)})}),Ut=(0,R.jsxs)(R.Fragment,{children:[se&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.v2Label`),onClick:()=>ce(!1),onKeyDown:e=>{e.key===`Escape`&&ce(!1)},children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{children:t(`models.v2Label`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ce(!1),"aria-label":t(`common.close`),children:`×`})]}),(0,R.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,R.jsx)(`div`,{className:`models-help-link`,children:(0,R.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,R.jsx)(`div`,{className:`modal-actions`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>ce(!1),children:t(`common.ok`)})})]})}),le&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.customAdd`),onClick:()=>{ke||ue(!1)},onKeyDown:e=>{e.key===`Escape`&&!ke&&ue(!1)},children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{children:t(de===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:me})}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ue(!1),disabled:ke,"aria-label":t(`common.close`),children:`×`})]}),Me&&(0,R.jsx)(q,{tone:`err`,children:Me}),(0,R.jsxs)(`div`,{className:`models-field-stack`,children:[(0,R.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldModelId`),(0,R.jsx)(`input`,{className:`input`,value:ye,onChange:e=>be(e.target.value),disabled:ke,placeholder:t(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,R.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldDisplayName`),(0,R.jsx)(`input`,{className:`input`,value:xe,onChange:e=>Se(e.target.value),disabled:ke,placeholder:t(`models.customFieldDisplayNamePlaceholder`)})]}),(0,R.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldContext`),(0,R.jsxs)(`div`,{className:`row models-field-row`,children:[(0,R.jsx)(rt,{value:Te?`custom`:Ce,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`){Ee(!0);return}Ee(!1),we(e)},disabled:ke,label:t(`models.customFieldContext`)}),Te&&(0,R.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:Ce,onChange:e=>we(e.target.value),disabled:ke,placeholder:t(`models.customPlaceholder`),"aria-label":t(`models.customFieldContext`)})]})]}),(0,R.jsxs)(`div`,{className:`text-label models-field`,children:[t(`models.customFieldModalities`),(0,R.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,R.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:De.includes(e),onChange:t=>{Oe(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:ke}),(0,R.jsx)(`span`,{className:`text-control`,children:e})]},e))})]})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ue(!1),disabled:ke,children:t(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:ke||!ye.trim(),onClick:()=>{let e=ye.trim(),t=xe.trim(),n=Ce?Number(Ce.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;de===`add`?Mt(me,e,t||void 0,r,De.length>0?De:void 0):Nt(ge,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:De})},children:t(ke?`models.customSaving`:de===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]});return(0,R.jsxs)(`div`,{className:`models-workspace-shell`,children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:t(`nav.models`)}),(0,R.jsx)(`div`,{className:`row`,children:(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:dt,total:i.length})})})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`models.subtitle`)}),k&&(0,R.jsx)(q,{tone:j?`ok`:`err`,children:k}),tt.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`models.loadFail`)}),tt.refreshing&&(0,R.jsx)(ha,{live:!tt.showError,children:t(`models.loading`)}),(0,R.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":tt.refreshing||void 0,children:[(0,R.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":t(`nav.models`),children:[(0,R.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,R.jsx)(`span`,{className:`models-workspace-rail-title`,children:t(`models.workspace.providers`)}),(0,R.jsx)(`span`,{className:`models-workspace-rail-count`,children:ut.length})]}),(0,R.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ke===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>qe(null),"aria-current":Ke===null?`true`:void 0,children:[(0,R.jsx)(`span`,{className:`models-workspace-rail-name`,children:t(`models.workspace.allProviders`)}),(0,R.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:dt,total:i.length})})]}),ut.map(e=>{let{provider:n,rows:r}=e,i=r.filter(e=>ms(It,n,e.id,e.native===!0,c.has(e.namespaced))).length;return(0,R.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ke===n?` models-workspace-rail-row--selected`:``}`,onClick:()=>qe(n),"aria-current":Ke===n?`true`:void 0,children:[(0,R.jsx)(`span`,{className:`models-workspace-rail-name`,children:n}),(0,R.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:i,total:r.length})})]},n)})]})]}),(0,R.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":t(`models.workspace.mainAria`),children:[zt,Bt,Vt,(0,R.jsx)(`div`,{className:`models-provider-list`,children:Rt.map(e=>Lt(e))}),ut.length===0&&Ht]})]}),Ut]})}function Ps(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function Fs(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function Is(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 Ls(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||Is(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 Rs({value:e,onChange:t,disabled:n}){let r=K();return(0,R.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,R.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 zs({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=K(),o=i??Lo,s=t!==null&&!o.includes(t);return(0,R.jsxs)(R.Fragment,{children:[(0,R.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,R.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,R.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))]}),s?(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function Bs({targets:e,strategy:t,providers:n,models:r,onChange:i}){let a=K(),o=Ps(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,R.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,_=Ls(r,p.provider,n),v=p.model&&!_.includes(p.model)?[p.model,..._]:_,y=!p.provider;return(0,R.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,R.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,R.jsx)(je,{width:14,height:14,"aria-hidden":`true`})}),(0,R.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,R.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,R.jsx)(me,{width:14,height:14,"aria-hidden":`true`})}),(0,R.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,R.jsx)(he,{width:14,height:14,"aria-hidden":`true`})})]}),(0,R.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:Ls(r,t,n)[0]??``})},children:[(0,R.jsx)(`option`,{value:``,children:a(`cws.target.pickProvider`)}),g.map(e=>(0,R.jsx)(`option`,{value:e.name,children:e.disabled?a(`cws.target.disabled`,{name:e.name}):e.name},e.name))]}),(0,R.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,R.jsx)(`option`,{value:``,children:y?a(`cws.target.pickProviderFirst`):v.length===0?a(`cws.target.noModels`):a(`cws.target.pickModel`)}),v.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))]}),t===`round-robin`&&(0,R.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=Fs(e.target.value,1,1e4);t!==void 0&&d(m,{weight:t})}}),(0,R.jsx)(`div`,{className:`cwi-target-actions`,children:(0,R.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,R.jsx)(ue,{width:14,height:14})})})]},p.clientKey??`${p.provider}:${p.model}`)}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>i([...e,Bo()]),children:[(0,R.jsx)(oe,{width:14,height:14}),` `,a(`cws.target.add`)]})]})}function Vs({existingIds:e,existingAliases:t,providerMap:n,providers:r,models:i,onClose:a,onSubmit:o}){let s=K(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(()=>as()),[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)(()=>Ro(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=is(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:Ko(i,a)});if(!e.ok){m(e.error||s(`cws.saveFailed`));return}}finally{f(!1)}};return(0,R.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:y,children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:v}),(0,R.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,R.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:s(`cws.addTitle`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:d,"aria-label":s(`common.close`),children:(0,R.jsx)(ae,{width:16,height:16})})]}),(0,R.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:s(`cws.addSubtitle`)}),p&&(0,R.jsx)(q,{tone:`err`,children:p}),(0,R.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-id`,children:s(`cws.field.id`)}),(0,R.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:l.id,disabled:d,onChange:e=>u(t=>({...t,id:e.target.value,model:Ko(e.target.value,t.alias)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idInternalHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:s(`cws.field.alias`)}),(0,R.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:Ko(t.id,e.target.value)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.aliasHint`)}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idHint`,{model:l.id.trim()?Ko(l.id,l.alias):`…`})})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:s(`cws.strategy`)}),(0,R.jsx)(Rs,{value:l.strategy,disabled:d,onChange:e=>u(t=>({...t,strategy:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:l.strategy===`failover`?s(`cws.strategy.failoverHint`):s(`cws.strategy.roundRobinHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:s(`cws.field.defaultEffort`)}),(0,R.jsx)(zs,{id:`cwi-new-effort`,value:l.defaultEffort,disabled:d,allowedEfforts:g,onChange:e=>u(t=>({...t,defaultEffort:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.defaultEffortHint`)})]}),l.strategy===`round-robin`&&(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:s(`cws.field.stickyLimit`)}),(0,R.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:l.stickyLimit,disabled:d,onChange:e=>{let t=Fs(e.target.value,1,100);t!==void 0&&u(e=>({...e,stickyLimit:t}))}}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.stickyLimitHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:s(`cws.targets`)}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:l.strategy===`failover`?s(`cws.targets.failoverHint`):s(`cws.targets.roundRobinHint`)}),(0,R.jsx)(Bs,{targets:l.targets,strategy:l.strategy,providers:r,models:i,onChange:e=>u(t=>({...t,targets:e}))})]})]}),(0,R.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,disabled:d,children:s(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{b()},disabled:d,children:s(d?`common.saving`:`cws.create`)})]})]})]})}function Hs({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=K(),[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=!ns(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)(()=>Ro(h.targets,E),[h.targets,E]),O=(0,_.useCallback)(t=>{let n=t(h);g(n),d(!ns(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=is(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:Ko(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()?Ko(h.id,h.alias):f(`cws.addTitle`):e.model;return(0,R.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,R.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[s&&(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:s,"aria-label":f(`cws.backToAll`),children:[(0,R.jsx)(_e,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),f(`cws.allCombos`)]}),(0,R.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:j}),!t&&(0,R.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{k()},title:f(`cws.copyModel`),children:f(S?`cws.copied`:`cws.copyModel`)}),(0,R.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&l&&(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,R.jsx)(ue,{width:14,height:14}),` `,f(`common.remove`)]}),(0,R.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,R.jsx)(q,{tone:b.ok?`ok`:`err`,children:b.text}),(0,R.jsxs)(`div`,{className:`combos-workspace-tabs`,role:`tablist`,children:[(0,R.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,R.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,R.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,children:p===`config`?(0,R.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:f(`cws.field.id`)}),(0,R.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:h.id,disabled:v,onChange:e=>O(t=>({...t,id:e.target.value,model:Ko(e.target.value,t.alias)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:t?f(`cws.field.idInternalHint`):f(`cws.field.idHintEdit`,{model:Ko(h.id,h.alias)})})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:f(`cws.field.alias`)}),(0,R.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:h.alias??``,placeholder:Go(h.id.trim()||`…`),disabled:v,onChange:e=>O(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:Ko(t.id,e.target.value)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.aliasHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,R.jsx)(Rs,{value:h.strategy,disabled:v,onChange:e=>O(t=>({...t,strategy:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:h.strategy===`failover`?f(`cws.strategy.failoverHint`):f(`cws.strategy.roundRobinHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-effort`,children:f(`cws.field.defaultEffort`)}),(0,R.jsx)(zs,{id:`cwi-effort`,value:h.defaultEffort,disabled:v,allowedEfforts:D,onChange:e=>O(t=>({...t,defaultEffort:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),h.strategy===`round-robin`&&(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-sticky`,children:f(`cws.field.stickyLimit`)}),(0,R.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:h.stickyLimit,disabled:v,onChange:e=>{let t=Fs(e.target.value,1,100);t!==void 0&&O(e=>({...e,stickyLimit:t}))}})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:h.strategy===`failover`?f(`cws.targets.failoverHint`):f(`cws.targets.roundRobinHint`)}),(0,R.jsx)(Bs,{targets:h.targets,strategy:h.strategy,providers:a,models:o,onChange:e=>O(t=>({...t,targets:e}))})]})]}):(0,R.jsxs)(`section`,{className:`pwi-section`,children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:f(`cws.aboutTitle`)}),(0,R.jsx)(`p`,{className:`muted`,style:{margin:0},children:f(`cws.aboutBody`)})]})})]})}function Us({model:e,onCancel:t,onConfirm:n}){let r=K(),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,R.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,R.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,R.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function Ws({onKeep:e,onDiscard:t}){let n=K(),r=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,R.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,R.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,R.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function Gs(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:`cws.attention.few`)}function Ks({combos:e,cataloguedComboIds:t,onSelect:n,onAdd:r}){let i=K(),a=$o(e),o=ts(e,{cataloguedComboIds:t});return(0,R.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,R.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,R.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:i(`cws.overviewTitle`)}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,children:[(0,R.jsx)(oe,{width:14,height:14}),` `,i(`cws.add`)]})]}),(0,R.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:i(`cws.overviewBlurb`)}),(0,R.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,R.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,R.jsx)(`strong`,{children:e.length}),(0,R.jsx)(`span`,{children:i(`cws.count.total`)})]}),(0,R.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,R.jsx)(`strong`,{children:a.failover.length}),(0,R.jsx)(`span`,{children:i(`cws.count.failover`)})]}),(0,R.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,R.jsx)(`strong`,{children:a.roundRobin.length}),(0,R.jsx)(`span`,{children:i(`cws.count.roundRobin`)})]})]}),(0,R.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.howTitle`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.howTitle`)}),(0,R.jsx)(`p`,{className:`muted`,style:{margin:0},children:i(`cws.howBody`)})]}),o.length>0&&(0,R.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.attentionTitle`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.attentionTitle`)}),(0,R.jsx)(`div`,{className:`cwi-attention-list`,children:o.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>n(e.id),children:[(0,R.jsx)(de,{width:14,height:14,"aria-hidden":`true`}),(0,R.jsx)(`code`,{className:`chip`,children:e.model}),(0,R.jsx)(`span`,{className:`muted`,children:Gs(e.reason,i)}),(0,R.jsx)(_e,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function qs({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=K(),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)(()=>as(),[]),E=(0,_.useMemo)(()=>es(e,m),[e,m]),D=(0,_.useMemo)(()=>$o(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))},z=()=>b(void 0),B=y!==void 0&&M,V=!i&&e.length===0;return(0,R.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,R.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":f(`cws.railAria`),children:[(0,R.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`combos-workspace-rail-title`,children:f(`nav.combos`)}),(0,R.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(V){document.getElementById(`cwi-edit-id`)?.focus();return}c()},"aria-label":f(`cws.add`),children:[(0,R.jsx)(oe,{width:14,height:14}),` `,f(`cws.add`)]})]}),(0,R.jsx)(`div`,{className:`cwi-search-row`,children:(0,R.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,R.jsx)(pe,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,R.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,R.jsx)(`div`,{className:`combos-workspace-rail-list`,children:E.length===0&&e.length>0?(0,R.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:f(`cws.noSearchResults`)}):(0,R.jsx)(R.Fragment,{children:[[`failover`,D.failover,`cws.group.failover`],[`round-robin`,D.roundRobin,`cws.group.roundRobin`]].map(([e,t,n])=>t.length>0?(0,R.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,R.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,R.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),f(n),(0,R.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,R.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,R.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,R.jsx)(Ae,{width:16,height:16})}),(0,R.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,R.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?f(`cws.targetCountOne`):f(`cws.targetCount`,{count:e.targets.length})}),(0,R.jsx)(_e,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,R.jsx)(`div`,{className:`combos-workspace-main`,children:j?(0,R.jsx)(Hs,{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):V?(0,R.jsx)(Hs,{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,R.jsx)(Ks,{combos:e,cataloguedComboIds:r,onSelect:e=>I(e),onAdd:c})}),l&&!V&&(0,R.jsx)(Vs,{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,R.jsx)(Us,{model:e.find(e=>e.id===x)?.model??Go(x),onCancel:()=>S(null),onConfirm:()=>{(async()=>{let e=await s(x);S(null),e.ok&&(k===x&&(v(null),w(null)),a())})()}}),B&&(0,R.jsx)(Ws,{onKeep:z,onDiscard:L})]})}function Js(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function Ys(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Xs(e){return sn(e)}function Zs({apiBase:e}){let t=K(),n=`ocx.combos.workspace.v1:${e}`,r=Xs(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=Qo(a),u=o.providers??{},d=Yn(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 J(n,h),h},[e,n]),f=ss(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,R.jsx)(ma,{label:t(`cws.loading`),rows:5}):p.kind===`failed-cold`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:p.error instanceof Error?p.error.message:t(`cws.loadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,R.jsxs)(`div`,{className:`combos-workspace-shell`,children:[i&&(0,R.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,R.jsx)(q,{tone:o?`ok`:`err`,children:i})}),p.showError&&(0,R.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,R.jsx)(q,{tone:`err`,children:t(`cws.loadFailed`)})}),p.refreshing&&(0,R.jsx)(ha,{live:!p.showError,children:t(`cws.loading`)}),(0,R.jsx)(`div`,{className:`combos-workspace-shell-body`,children:(0,R.jsx)(qs,{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(rs(n,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=Js(o);if(!a.ok||s||!Ys(o)){let e=s||t(`cws.saveFailed`);return u(e,!1),{ok:!1,error:e}}return f.refresh(),u(i?t(`cws.renamed`,{from:Go(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=Js(i);if(!r.ok||a||!Ys(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 Qs=`section`;function $s(e,t){return[e,Qs,t].join(`-`)}function ec(e){return[e,Qs,``].join(`-`)}function tc({scope:e,items:t,ariaLabel:n}){let[r,i]=(0,_.useState)(t[0]?.id??``),a=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById($s(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!n)return;let r=n.target.id.slice(ec(e).length);i(e=>e===r?e:r)},{rootMargin:`-72px 0px -60% 0px`,threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[t,e]);let o=t=>{let n=document.getElementById($s(e,t));n&&(i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,R.jsx)(`div`,{ref:a,className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,R.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":$s(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>o(t.id),children:[t.label,t.meta?(0,R.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function nc({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s}){let c=K();return(0,R.jsxs)(`div`,{className:`swi-delegation`,children:[(0,R.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,R.jsxs)(`div`,{className:`setting-copy`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:c(`sub.delegation.model`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:c(`sub.delegation.modelHint`)})]}),(0,R.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,R.jsx)(rt,{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,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,R.jsxs)(`div`,{className:`setting-copy`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:c(`dash.syncCodexSubagentDefaults`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,R.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,R.jsx)(`span`,{className:`knob`})})]}),(0,R.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,R.jsxs)(`div`,{className:`setting-copy`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:c(`dash.multiAgentGuidance`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.multiAgentGuidanceHint`)})]}),(0,R.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":c(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,R.jsx)(`span`,{className:`knob`})})]})]})}function rc({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=K(),[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,R.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,R.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,R.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,R.jsxs)(`section`,{id:$s(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,R.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,R.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,R.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,R.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,R.jsx)(fe,{width:15,height:15,"aria-hidden":`true`}),(0,R.jsx)(`span`,{children:(0,R.jsx)(He,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,R.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,R.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,R.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,R.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,R.jsx)(`span`,{className:`swi-featured-name`,children:Io(e)}),(0,R.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,R.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,R.jsx)(me,{})}),(0,R.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,R.jsx)(he,{})}),(0,R.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,R.jsx)(ae,{})})]})]},e))}),(0,R.jsx)(`div`,{className:`swi-save-row`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,R.jsxs)(`section`,{id:$s(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,R.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,R.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,R.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,R.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,R.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,R.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,R.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,R.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,R.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,R.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,R.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,R.jsx)(U,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,R.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:Io(e)})]}),(0,R.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,R.jsx)(ie,{style:{width:14,height:14}}):(0,R.jsx)(oe,{style:{width:14,height:14}})})]},e)})})]})]}),(0,R.jsxs)(`section`,{id:$s(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,R.jsx)(`div`,{className:`swi-featured-head`,children:(0,R.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,R.jsx)(nc,{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 ic(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=gn(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 mt(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 mt(await fetch(`${e}/api/injection-model`)))}catch{}finally{i(!1)}}},[e,v,r])}}function ac(e){return sn(e)}function oc({apiBase:e}){let t=K(),n=`ocx.subagents.v1:${e}`,r=ac(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=ic(e),m=(0,_.useCallback)(async()=>{let r=await ct(await fetch(`${e}/api/subagent-models`),t(`sub.loadFail`));if(!r)throw Error(t(`sub.loadFail`));let i=r.available??[],o=new Set(i),s={available:i,chosen:(r.chosen??[]).filter(e=>o.has(e))};return a(s.chosen),J(n,s),s},[e,n,t]),h=ss(n,[e],m,{isEmpty:()=>!1}),{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 ct(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),J(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,R.jsx)(ma,{label:t(`sub.loading`),rows:4}):g.kind===`failed-cold`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:g.error instanceof Error?g.error.message:t(`sub.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,R.jsx)(q,{tone:c?`ok`:`err`,children:o}),g.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`sub.loadFail`)}),g.refreshing&&(0,R.jsx)(ha,{live:!g.showError,children:t(`sub.loading`)}),(0,R.jsx)(rc,{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 sc(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 cc(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 lc(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var uc=(e,t)=>Math.abs(e-t)<1.01,dc=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},fc,pc=()=>{if(fc!==void 0)return fc;if(typeof navigator>`u`)return fc=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return fc=!0;let e=navigator.maxTouchPoints;return fc=navigator.platform===`MacIntel`&&e!==void 0&&e>0},mc=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},hc=e=>e,gc=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},_c=(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(mc(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(mc(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},vc={passive:!0},yc=typeof window>`u`?!0:`onscrollend`in window,bc=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&yc,o=0,s=a?null:dc(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,vc),a&&r.addEventListener(`scrollend`,u,vc),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},xc=(e,t)=>bc(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Sc=(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`]},Cc=(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})},wc=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:hc,rangeExtractor:gc,onChange:()=>{},measureElement:Sc,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=cc(()=>(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,!(!pc()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,vc),e.addEventListener(`touchend`,n,vc),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&&(pc()&&(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=cc(()=>[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=cc(()=>[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=sc(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=cc(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Dc(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=cc(()=>{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=cc(()=>[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 lc(t[Tc(0,t.length-1,r?e=>n[e*2]:e=>lc(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&&(pc()&&(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&&uc(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()}},Tc=(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 Ec(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 Dc(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=Ec(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=Tc(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 Oc=typeof document<`u`?_.useLayoutEffect:_.useEffect;function kc({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,Ke.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[c]=_.useState(()=>{let e=new wc(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),Oc(()=>c._didMount(),[]),Oc(()=>c._willUpdate()),Oc(()=>{o(c)}),c}function Ac(e){return kc({observeElementRect:_c,observeElementOffset:xc,scrollToFn:Cc,...e})}var jc=32;function Mc(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Nc(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 Pc(e){let t=e.trim();if(t&&!Nc(t)&&!(t.length>4096))return Mc(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,jc)}function Fc(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r?!0:n!==void 0&&e===n:!1}var Ic={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:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`}}},Lc={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 Rc(e){return e===`de`||e===`ko`||e===`zh`||e===`ru`||e===`ja`?e:`en`}function zc(e,t){if(e<400)return null;let n=Rc(t);return(Ic[Math.trunc(e)]??(e<500?Lc.client:Lc.server))[n]}var Bc=[`provider`,`usage`,`injection`];function Vc(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function Hc(e){return new Date(e).toLocaleTimeString()}function Uc(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function Wc(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function Gc({entries:e}){let{t}=G();return(0,R.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,R.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,R.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,R.jsx)(`div`,{style:{overflowX:`auto`},children:(0,R.jsxs)(`table`,{className:`table text-label`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,R.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,R.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,R.jsx)(`th`,{children:`thinking`}),(0,R.jsx)(`th`,{children:`effort`}),(0,R.jsx)(`th`,{children:`beta`}),(0,R.jsx)(`th`,{children:`metadata`}),(0,R.jsx)(`th`,{children:`system`})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`muted mono`,children:Hc(e.at)}),(0,R.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,R.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,R.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,R.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,R.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,R.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,R.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,R.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,R.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function Kc({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=G();return e?n?r.length===0?(0,R.jsxs)(`div`,{className:`empty`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,R.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,R.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,R.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Vc(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,R.jsxs)(`div`,{className:`empty`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function qc({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=G();return(0,R.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,R.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,R.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=Wc(e,n);return(0,R.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,R.jsx)(nt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,R.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,R.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,R.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function Jc({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=G();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,R.jsx)(`h2`,{children:o(`debug.title`)}),(0,R.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,R.jsx)(se,{}),` `,o(`debug.refresh`)]}),(0,R.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function Yc(e){return`debug-settings:${e}`}function Xc({apiBase:e,embedded:t,active:n=!0}){let{t:r}=G(),i=`ocx.debug.settings.v1:${e}`,a=sn(i),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(`provider`),[u,d]=(0,_.useState)([]),[f,p]=(0,_.useState)(!0),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(0),v=(0,_.useRef)(0),y=(0,_.useRef)(0),b=(0,_.useRef)(null),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=ss(Yc(e),[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 J(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1}),w=C.state,T=C.data??a??null,E=F(`debug-claude-inbound:${e}`,[e,T?.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&&!!T?.claude}).data??[],D=Ac({count:u.length,getScrollElement:()=>x.current,estimateSize:()=>20,overscan:30,getItemKey:e=>u[e].seq}),O=(0,_.useCallback)(e=>Uc(T,e),[T]);(0,_.useEffect)(()=>{if(!T||O(c))return;let e=Bc.find(O);if(!e)return;let t=window.setTimeout(()=>l(e),0);return()=>window.clearTimeout(t)},[T,c,O]);let k=O(c),A=c===`provider`?`${e}/api/debug/logs`:c===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,j=(0,_.useCallback)(async(e,t)=>{let n=++y.current;if(!k){n===y.current&&(d([]),g.current=0);return}h(!0);try{let r=new URLSearchParams({limit:`500`});!e&&g.current>0&&r.set(`after`,String(g.current));let i=await fetch(`${A}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==y.current)return;let a=await i.json();if(t?.aborted||n!==y.current||a.length===0)return;d(t=>(e?a:[...t,...a]).slice(-2e3)),g.current=a[a.length-1].seq}catch{}finally{n===y.current&&h(!1)}},[A,k]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${c}:${k}`,r=S.current!==t;if(S.current=t,!r&&u.length>0)return;g.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&d([]),j(!0,i.signal)},0);return()=>{window.clearTimeout(a),y.current+=1,i.abort()}},[n,e,c,k]);let M=(0,_.useEffectEvent)(e=>{j(e)});(0,_.useEffect)(()=>{if(!n||!f||!k)return;let e=setInterval(()=>M(!1),1e3);return()=>clearInterval(e)},[n,f,k]),(0,_.useEffect)(()=>{f&&u.length>0&&D.scrollToIndex(u.length-1,{align:`end`})},[u,f,D]);let N=async t=>{let n=++v.current;s(!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!==v.current)return;J(i,a),I(Yc(e),a)}catch{}},a=(b.current??Promise.resolve()).then(r,r);b.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===v.current&&s(!1)}},P=async(e,t)=>{await N({[e]:t})},L=async()=>{await N({reset:!0})};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Jc,{embedded:t,refreshing:m,streamEnabled:k,follow:f,onRefresh:()=>void j(!0),onFollowChange:p}),!T&&w.showError?(0,R.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,R.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>C.refresh(),children:r(`common.retry`)})]}):w.showSkeleton&&!T?(0,R.jsx)(ma,{label:r(`debug.loading`),rows:3}):T?(0,R.jsx)(qc,{debug:T,debugBusy:o,stream:c,onSetFlag:(e,t)=>{P(e,t)},onReset:()=>{L()},onStreamChange:l}):null,T&&w.refreshing&&(0,R.jsx)(ha,{live:!w.showError,children:r(`debug.loading`)}),T&&w.showError&&(0,R.jsx)(q,{tone:`err`,children:r(`debug.loadFailed`)}),T?.claude&&(0,R.jsx)(Gc,{entries:E}),(0,R.jsx)(Kc,{debug:!!T,stream:c,streamEnabled:k,entries:u,scrollContainerRef:x,lineVirtualizer:D})]})}function Zc(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function Qc(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function $c(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),Qc(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),Qc(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function el(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 nl(e){return`ocx.logs.list.v1:${e}`}function rl(e){return e===`cursor`||e.startsWith(`cursor-`)}function il(e,t){if(!e.usage)return;let n=sl(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(rl(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 ol(e){let t=al(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function sl(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 cl(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 ll(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function ul(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 dl(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 fl(e,t){return!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var pl=3,ml={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`},hl={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 gl(e){return ml[e]}function _l(e){return hl[e]}function vl(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function yl(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function bl(e,t){return new Date(e).toLocaleTimeString(t)}function xl(e,t){return new Date(e).toLocaleString(t)}function Sl(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 Cl(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 wl({apiBase:e}){let{t,locale:n}=G(),r=sn(nl(e)),[i,a]=(0,_.useState)(!0),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(`all`),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(),m=(0,_.useRef)(null),h=Ie.find(e=>e.code===n)?.htmlLang,[g,v]=(0,_.useState)(Zc),[y,b]=(0,_.useState)(()=>Zc()===`debug`);(0,_.useEffect)(()=>{let e=()=>v(Zc());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{g===`debug`&&b(!0)},[g]);let x=Qc,S=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/logs`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let r=await n.json();return J(nl(e),r),r},[e]),C=ss(nl(e),[e],S,{isEmpty:e=>e.length===0,enabled:g===`logs`,pollMs:i?2e3:void 0}),w=C.state,T=w.data??r??[],E=C.refresh,D=!C.refreshing&&w.showError,O=!C.refreshing&&!w.showError&&w.data!==void 0,[k,A]=(0,_.useState)({error:null,count:0});O&&k.count!==0?A({error:null,count:0}):D&&k.error!==w.error&&A(e=>({error:w.error,count:e.count+1}));let j=k.count>=pl,M=o?zc(o.status,n):null,N=u.trim();(0,_.useEffect)(()=>{let e=!1;if(!N){p(void 0);return}return Pc(N).then(t=>{e||p(t)}),()=>{e=!0}},[N]);let P=T.filter(e=>tl(e,c)&&(!N||Fc(e.conversationId,N,f))),F=N?Cl(P):null,I=Ac({count:P.length,getScrollElement:()=>m.current,estimateSize:()=>44,overscan:15}),L=I.getVirtualItems(),z=L.length>0?L[0].start:0,B=L.length>0?I.getTotalSize()-L[L.length-1].end:0;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:t(`nav.logs`)}),g===`logs`&&(0,R.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,R.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,R.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":g===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:g===`logs`?0:-1,className:`page-tab${g===`logs`?` page-tab--active`:``}`,onClick:()=>x(`logs`),onKeyDown:$c,children:t(`logs.tabLogs`)}),(0,R.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":g===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:g===`debug`?0:-1,className:`page-tab${g===`debug`?` page-tab--active`:``}`,onClick:()=>x(`debug`),onKeyDown:$c,children:t(`logs.tabDebug`)})]}),y&&(0,R.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:g!==`debug`,children:(0,R.jsx)(Xc,{apiBase:e,embedded:!0,active:g===`debug`})}),(0,R.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:g!==`logs`,children:[(0,R.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,R.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,R.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,R.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":c===e,className:`btn btn-sm${c===e?` btn-primary`:` btn-ghost`}`,style:{background:c===e?void 0:`transparent`,color:c===e?void 0:`var(--muted)`},onClick:()=>l(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,R.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,R.jsx)(`input`,{type:`search`,className:`input mono`,value:u,onChange:e=>d(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),N&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(``),children:t(`logs.filter.conversation.clear`)})]}),F&&(0,R.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,R.jsxs)(q,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:F.requests,tokens:Nt(F.totalTokens,h??n),cost:fl(F.estimatedCostUsd,h)}),` `,(0,R.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),F.unpricedRequests+F.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:F.unpricedRequests,unmetered:F.unmeteredRequests})}`:``]})]})}),w.kind===`failed-cold`&&(0,R.jsxs)(q,{tone:`err`,children:[w.error instanceof Error?`${t(`logs.loadError`)} ${w.error.message}`:t(`logs.loadError`),` `,(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E({forceLoading:!0}),disabled:w.refreshing,children:t(`common.retry`)})]}),C.loading&&T.length>0&&(0,R.jsx)(ha,{live:!1,children:t(`common.loading`)}),j&&T.length>0&&(0,R.jsxs)(q,{tone:`err`,children:[t(`logs.loadError`),` `,(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E({forceLoading:!0}),disabled:C.refreshing,children:t(`common.retry`)})]}),w.kind===`failed-cold`?null:w.showSkeleton&&T.length===0?(0,R.jsx)(ma,{label:t(`common.loading`),rows:6}):P.length===0?(0,R.jsx)(it,{title:t(`logs.noRequests`)}):(0,R.jsx)(R.Fragment,{children:(0,R.jsx)(`div`,{ref:m,className:`tbl-wrap logs-table-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:t(`logs.col.time`)}),(0,R.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,R.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,R.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,R.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,R.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,R.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,R.jsx)(`th`,{children:t(`logs.col.status`)}),(0,R.jsx)(`th`,{children:t(`logs.col.request`)}),(0,R.jsx)(`th`,{className:`num`,children:t(`logs.col.duration`)})]})}),(0,R.jsxs)(`tbody`,{children:[z>0&&(0,R.jsx)(`tr`,{children:(0,R.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:z}})}),L.map(e=>{let r=P[P.length-1-e.index],i=ll(r);return(0,R.jsxs)(`tr`,{"data-index":e.index,ref:I.measureElement,children:[(0,R.jsx)(`td`,{className:`muted mono`,children:bl(r.timestamp,h)}),(0,R.jsx)(`td`,{className:`num mono log-col-tokens`,title:il(r,t),children:(()=>{let e=ol(r),{read:i,write:a}=sl(r);return e===void 0?(0,R.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,R.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,R.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Nt(e,n)]}),i!==void 0&&i>0&&(0,R.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Nt(i,n)]}),a!==void 0&&a>0&&(0,R.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Nt(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,R.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(rl(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,R.jsx)(`td`,{className:`num mono log-col-rate`,children:ul(r.displayMetrics?.tokPerSecond,h)}),(0,R.jsx)(`td`,{className:`num mono log-col-cost`,children:dl(r.displayMetrics?.cost,h)}),(0,R.jsx)(`td`,{className:`mono log-col-model`,title:Sl(r),children:(0,R.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,R.jsx)(`span`,{children:Io(r.resolvedModel??r.model)}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,R.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,R.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),el(r)&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:el(r)})]})}),(0,R.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,R.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,R.jsx)(`span`,{children:cl(r)}),i&&(0,R.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,R.jsx)(`td`,{className:`muted`,children:r.provider}),(0,R.jsx)(`td`,{children:(0,R.jsxs)(`span`,{className:`log-status-cell`,children:[(0,R.jsx)(`span`,{className:`mono font-semibold`,style:{color:yl(r.status)},children:r.status}),(0,R.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>s(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,R.jsx)(`td`,{className:`muted mono`,children:(0,R.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,R.jsxs)(`td`,{className:`num`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),B>0&&(0,R.jsx)(`tr`,{children:(0,R.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:B}})})]})]})})}),o&&(0,R.jsx)(El,{detail:o,detailInfo:M,localeCode:n,localeTag:h,t,onClose:()=>s(null),onFilterConversation:e=>{d(e),s(null)}})]})]})}function Tl(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 El({detail:e,detailInfo:t,localeCode:n,localeTag:r,t:i,onClose:a,onFilterConversation:o}){let s=Tl(!0),[c,l]=(0,_.useState)(!1),u=sl(e),d=e.displayMetrics?.cost,f=ll(e),p=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),l(!0),window.setTimeout(()=>l(!1),1200)}catch{}};return(0,R.jsx)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),a()},children:(0,R.jsxs)(`div`,{className:`modal-card log-detail-card`,children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,R.jsx)(`span`,{className:`mono`,style:{color:yl(e.status)},children:e.status}),t&&(0,R.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:a,"aria-label":i(`common.cancel`),children:(0,R.jsx)(ae,{})})]}),t&&(0,R.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,R.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:i(`logs.detail.section.basic`)}),(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.time`)}),(0,R.jsx)(`span`,{className:`mono`,children:xl(e.timestamp,r)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.request`)}),(0,R.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,R.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void p(),children:i(c?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.conversation`)}),(0,R.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,R.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),o&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>o(e.conversationId),children:i(`logs.filter.conversation.apply`)})]})]}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.model`)}),(0,R.jsx)(`span`,{className:`mono`,children:Io(e.resolvedModel??e.model)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.provider`)}),(0,R.jsx)(`span`,{children:e.provider}),(e.requestedEffort||e.effectiveEffort)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.effort`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[cl(e),f?` (${f})`:``]})]}),e.errorCode&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.error`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.upstreamReason`)}),(0,R.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,R.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:i(`logs.detail.section.performance`)}),(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.duration`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.col.tokPerSec`)}),(0,R.jsx)(`span`,{className:`mono`,children:ul(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.ttft`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:i(gl(e.displayMetrics.tokPerSecond.reason))})]}),(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,R.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:i(`logs.detail.section.cost`)}),(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:i(`usage.cost.disclaimer`)}),d?.kind===`value`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.costTotal`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(d.estimate.cost.total,r)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.input`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(d.estimate.cost.input,r)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.cacheRead`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(d.estimate.cost.cacheRead,r)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.cacheWrite`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(d.estimate.cost.cacheWrite,r)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.output`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(d.estimate.cost.output,r)}),d.estimate.price&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.matchedKey`)}),(0,R.jsxs)(`span`,{className:`mono log-detail-break`,children:[d.estimate.price.jawcodeProvider??d.estimate.price.provider,`/`,d.estimate.price.modelId]}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.priceSource`)}),(0,R.jsxs)(`span`,{children:[i(`logs.detail.source.${d.estimate.price.source}`),` · `,i(vl(d.estimate.price.status))]})]})]}),d.estimateReasons.length>0&&(0,R.jsx)(`ul`,{className:`log-detail-notes`,children:d.estimateReasons.map(e=>(0,R.jsx)(`li`,{children:i(_l(e))},e))})]}):(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.costTotal`)}),(0,R.jsx)(`span`,{className:`mono`,children:`—`}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.unavailableReason`)}),(0,R.jsx)(`span`,{children:d?.kind===`unavailable`?i(gl(d.reason)):i(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,R.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:i(`logs.detail.section.attempts`)}),(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:i(`logs.detail.attempt.e2eNote`)}),(0,R.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{className:`num`,children:`#`}),(0,R.jsx)(`th`,{children:i(`logs.detail.attempt.target`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`logs.col.duration`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`logs.col.tokPerSec`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`logs.col.estimatedCost`)}),(0,R.jsx)(`th`,{children:i(`logs.detail.attempt.reason`)})]})}),(0,R.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=ll(e),a=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.join(`, `):void 0)??(t?.kind===`unavailable`?i(gl(t.reason)):i(`logs.detail.attempt.completed`));return(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,R.jsxs)(`td`,{children:[(0,R.jsx)(`span`,{children:e.provider}),(0,R.jsx)(`br`,{}),(0,R.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`br`,{}),(0,R.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[cl(e),n?` (${n})`:``]})]}),a&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`br`,{}),(0,R.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[a.jawcodeProvider??a.provider,`/`,a.modelId,` · `,i(`logs.detail.source.${a.source}`),` · `,i(vl(a.status))]})]})]}),(0,R.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,R.jsx)(`td`,{className:`num mono`,children:ul(e.displayMetrics?.tokPerSecond,r)}),(0,R.jsx)(`td`,{className:`num mono`,children:dl(t,r)}),(0,R.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,R.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:i(`logs.detail.section.usage`)}),(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.input`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.usage?Nt(e.usage.inputTokens,n):`—`}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.output`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.usage?Nt(e.usage.outputTokens,n):`—`}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.cacheRead`)}),(0,R.jsx)(`span`,{className:`mono`,children:u.read===void 0?`—`:Nt(u.read,n)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.cacheWrite`)}),(0,R.jsx)(`span`,{className:`mono`,children:u.write===void 0?`—`:Nt(u.write,n)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.reasoning`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Nt(e.usage.reasoningOutputTokens,n)}),(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.detail.totalTokens`)}),(0,R.jsx)(`span`,{className:`mono`,children:ol(e)===void 0?`—`:Nt(ol(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`logs.tokens.contextTotal`)}),(0,R.jsx)(`span`,{className:`mono`,children:Nt(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:i(`logs.tokens.estimatedNote`)})]}),(0,R.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,R.jsx)(`summary`,{children:i(`logs.detailRaw`)}),(0,R.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})})}function Dl(e){return`${Math.round(e*100)}%`}function Ol(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 kl(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 Al(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 jl(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Ml(e){let t=Al(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?jl(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 Nl({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,R.jsxs)(`div`,{className:`usage-filters`,children:[(0,R.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,R.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,R.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,R.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,R.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,R.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,R.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(`usage.range.${e}`);return(0,R.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 Pl({summary:e,activeDays:t,locale:n,t:r}){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Nt(e.totalTokens,n)})]}),(0,R.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Nt(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,R.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Nt(e.cacheCreationInputTokens??0,n)]})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Dl(e.coverageRatio)})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,R.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,R.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,R.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:ia(e.estimatedCostUsd,n)}),(0,R.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,R.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function Fl({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,R.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,R.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,R.jsx)(`div`,{className:`daybar-track`,children:(0,R.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,R.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Ol(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,R.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,R.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,R.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,R.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,R.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Ol(e.model,e.provider)}}),(0,R.jsx)(`span`,{className:`daybar-tip-name`,children:Io(e.model)}),(0,R.jsx)(`span`,{className:`daybar-tip-val`,children:Nt(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,R.jsx)(`span`,{className:`daybar-count`,children:Nt(e.totalTokens,t)}),(0,R.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function Z({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,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,R.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,R.jsx)(Fl,{weekBars:n,locale:r,t:i}):(0,R.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,R.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,R.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,R.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,R.jsxs)(`div`,{className:`heatmap-body`,children:[(0,R.jsxs)(`div`,{className:`heatmap-days`,children:[(0,R.jsx)(`span`,{}),(0,R.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,R.jsx)(`span`,{}),(0,R.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,R.jsx)(`span`,{}),(0,R.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,R.jsx)(`span`,{})]}),(0,R.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,R.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,R.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,R.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,R.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,R.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Nt(e.totalTokens,r)})}),(0,R.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,R.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,R.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,R.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,R.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function Q({title:e,titleId:t,children:n}){return(0,R.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,R.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function Il({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,R.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:i(`logs.col.model`)}),(0,R.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,R.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`mono`,children:Io(e.model)}),(0,R.jsx)(`td`,{className:`muted`,children:e.provider}),(0,R.jsx)(`td`,{className:`num`,children:e.requests}),(0,R.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,R.jsx)(`td`,{className:`num mono`,children:Nt(e.totalTokens,r)}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`div`,{className:`usage-bar`,children:(0,R.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,R.jsxs)(Q,{title:s,titleId:c,children:[(0,R.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function Ll({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,R.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`mono`,children:e.provider}),(0,R.jsx)(`td`,{className:`num`,children:e.requests}),(0,R.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,R.jsx)(`td`,{className:`num mono`,children:Nt(e.totalTokens,t)}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`div`,{className:`usage-bar`,children:(0,R.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,R.jsx)(Q,{title:i,titleId:a,children:o}):(0,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,R.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function Rl({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,R.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,R.jsx)(Q,{title:r,titleId:i,children:a}):(0,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,R.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function zl({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,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Pl,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,R.jsx)(Z,{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,R.jsx)(Il,{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,R.jsx)(Ll,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Dl(e.summary.coverageRatio):`—`,body:e?(0,R.jsx)(Rl,{summary:e.summary,t:u,workspace:!0}):null}];return(0,R.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,R.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,R.jsx)(tc,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,R.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,R.jsx)(it,{title:u(`usage.empty`)}):f.map(e=>(0,R.jsx)(`div`,{id:$s(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var Bl=new Map;function Vl(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function Hl(e,t,n){let r=Vl(e,t,n);return Bl.get(r)??sn(r)}function Ul(e,t,n,r){let i=Vl(e,t,n);Bl.set(i,r),J(i,r)}function Wl({apiBase:e}){let{t,locale:n}=G(),[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 Ul(e,r,a,i),i},[e,r,a]),u=Hl(e,r,a),d=ss(Vl(e,r,a),[e,r,a],l,{isEmpty:()=>!1}),{state:f}=d,p=f.data??u??null,m=(0,_.useMemo)(()=>Ml(p?.days??[]),[p?.days]),h=(0,_.useMemo)(()=>kl(p?.days??[]),[p?.days]),g=(0,_.useMemo)(()=>(p?.days??[]).filter(e=>e.requests>0).length,[p?.days]),v=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(p?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[p?.models,s]),y=(0,_.useMemo)(()=>(p?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[p?.providers]);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,R.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,R.jsx)(Nl,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),f.showSkeleton&&!p?(0,R.jsx)(ma,{label:t(`usage.loading`),rows:5}):f.kind===`failed-cold`?(0,R.jsxs)(q,{tone:`err`,children:[f.error instanceof Error?`${t(`usage.loadError`)} ${f.error.message}`:t(`usage.loadError`),` `,(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d.refresh(),children:t(`common.retry`)})]}):(0,R.jsxs)(R.Fragment,{children:[f.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`usage.loadError`)}),f.refreshing&&(0,R.jsx)(ha,{live:!f.showError,children:t(`usage.loading`)}),(0,R.jsx)(zl,{data:p,heatmap:m,weekBars:h,activeDays:g,filteredModels:v,modelQuery:s,onModelQuery:c,sortedProviders:y,range:r,locale:n,t})]})]})}function Gl(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 Kl={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 ql(e,t){let n=Kl[e.key];return n?t(n):e.label}function Jl(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function Yl(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function Xl({report:e,locale:t}){let n=K(),[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,R.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,R.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":n(`storage.section.buckets`),children:[(0,R.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,R.jsx)(`span`,{className:`storage-workspace-rail-title`,children:n(`storage.section.buckets`)}),(0,R.jsx)(`span`,{className:`storage-workspace-rail-count`,children:a.length})]}),(0,R.jsx)(`div`,{className:`storage-workspace-rail-list`,children:a.length===0?(0,R.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:n(`storage.empty`)}):a.map(e=>(0,R.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,R.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,R.jsx)(`span`,{className:`storage-workspace-rail-name`,children:ql(e,n)}),(0,R.jsx)(`span`,{className:`storage-workspace-rail-size`,children:Gl(e.bytes,t)})]}),(0,R.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,n(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,R.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":o?ql(o,n):n(`storage.section.largest`),children:o?(0,R.jsxs)(`div`,{className:`stw-detail`,children:[(0,R.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,R.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>i(null),children:[(0,R.jsx)(_e,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),n(`modal.back`)]})}),(0,R.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,R.jsx)(`h2`,{className:`stw-detail-title`,children:ql(o,n)}),(0,R.jsxs)(`dl`,{className:`stw-kv`,children:[(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.size`)}),(0,R.jsx)(`dd`,{className:`stw-kv-mono`,children:Gl(o.bytes,t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.files`)}),(0,R.jsx)(`dd`,{className:`stw-kv-mono`,children:o.fileCount.toLocaleString(t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.oldest`)}),(0,R.jsx)(`dd`,{children:Jl(o.oldest,t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.newest`)}),(0,R.jsx)(`dd`,{children:Jl(o.newest,t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,R.jsx)(`dd`,{className:`stw-kv-mono`,children:Yl(o,t,n)})]})]}),(o.largest?.length??0)>0&&(0,R.jsxs)(`div`,{className:`stw-section`,children:[(0,R.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),o.largest.map(e=>(0,R.jsxs)(`div`,{className:`stw-file-row`,children:[(0,R.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,R.jsx)(`span`,{className:`stw-file-size`,children:Gl(e.bytes,t)})]},e.path))]})]})]}):(0,R.jsxs)(`div`,{className:`stw-overview`,children:[(0,R.jsxs)(`div`,{className:`usage-cards`,children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:n(`storage.card.total`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Gl(e.total.bytes,t)})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:n(`storage.card.files`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:n(`storage.card.home`)}),(0,R.jsx)(`div`,{className:`stat-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),s.length>0?(0,R.jsxs)(`div`,{className:`stw-section`,children:[(0,R.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),s.map(e=>{let r=c.get(e.bucketKey);return(0,R.jsxs)(`div`,{className:`stw-file-row`,children:[(0,R.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),r&&(0,R.jsx)(`span`,{className:`stw-file-bucket`,children:ql(r,n)}),(0,R.jsx)(`span`,{className:`stw-file-size`,children:Gl(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,R.jsxs)(`p`,{className:`stw-hint`,children:[(0,R.jsx)(re,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),n(`storage.workspace.selectBucket`)]})]})})]})}var Zl=1024**3,Ql=[10,25,50],$l=(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 eu({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($l(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:Gl(a.bytes,t)})),r()}catch(e){v($l(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,R.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,R.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,R.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,R.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,R.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,R.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,R.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Ql.map(e=>(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,R.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,R.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:Gl(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,R.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,R.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,R.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,R.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,R.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,R.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,R.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,R.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,R.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,R.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 tu({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=ss(`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:Gl(a.bytes,t)})),r()}catch(e){p($l(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,R.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,R.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,R.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,R.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,R.jsx)(ha,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,R.jsx)(ma,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,R.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,R.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,R.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,R.jsx)(`th`,{})]})}),(0,R.jsx)(`tbody`,{children:x.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`muted`,children:w(e)}),(0,R.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,R.jsx)(`td`,{className:`num mono`,children:Gl(e.bytes,t)}),(0,R.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,R.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,R.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:Gl(c.bytes,t),id:c.id})}),f&&(0,R.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,R.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,R.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function nu(e){let{job:t,...n}=e;return n}function ru(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/Zl*100)/100));return e.target.reduceToBytes===void 0?{policy:nu(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:nu(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/Zl*100)/100))}}async function iu(e){await new Promise(t=>window.setTimeout(t,e))}function au({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=sn(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=ru(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,J(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*Zl)}}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*Zl)},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)}},z=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 iu(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=nu(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:Gl(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:Gl(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)}},B=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,R.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,R.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,R.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,R.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,R.jsx)(`div`,{className:`storage-policy-enable`,children:(0,R.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,R.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,R.jsx)(`span`,{className:`toggle-knob`})}),(0,R.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,R.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,R.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,R.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,R.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,R.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,R.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,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,R.jsx)(Fi,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(Pi(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(Pi(E,-.1,0,1e4,.1))}})]})]})]}),(0,R.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,R.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,R.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,R.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,R.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,R.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,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,R.jsx)(Fi,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(Pi(S,1,1,100))},onDecrement:()=>{N(),C(Pi(S,-1,1,100))}})]})]}),(0,R.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,R.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,R.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,R.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,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,R.jsx)(Fi,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(Pi(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(Pi(w,-.1,0,1e4,.1))}})]})]})]}),(0,R.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,R.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,R.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,R.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,R.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,R.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,R.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,R.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,R.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,R.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,R.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,R.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,R.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,R.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,R.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,R.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[B(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:Gl(s.lastRun.freedBytes,t)})}`:``]})]}),(0,R.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,R.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,R.jsx)(`span`,{className:`storage-policy-meta-value`,children:B(s.nextRun)})]})]}),(0,R.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void z(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,R.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,R.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,R.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function ou({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,R.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,R.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,R.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,R.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,R.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,R.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,R.jsx)(au,{apiBase:e,locale:t,t:n,onDone:o}),(0,R.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,R.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,R.jsx)(eu,{apiBase:e,locale:t,t:n,onDone:o}):(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,R.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,R.jsx)(tu,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function su({apiBase:e}){let{t,locale:n}=G(),r=`ocx.storage.report.v1:${e}`,i=sn(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 J(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=ss(`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,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,R.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,R.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,R.jsx)(se,{}),` `,t(`storage.refresh`)]})]})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,R.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,R.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,R.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,R.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,R.jsx)(ma,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,R.jsx)(R.Fragment,{children:(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,R.jsxs)(R.Fragment,{children:[m.showError&&(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,R.jsx)(it,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,R.jsx)(Xl,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,R.jsx)(ha,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,R.jsx)(ou,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}function cu(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 lu({state:e,busy:t,onEnable:n}){let r=K();return(0,R.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,R.jsxs)(`div`,{className:`row`,children:[(0,R.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===null?(0,R.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,R.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,R.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===null&&(0,R.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc openai-account-mode-banner__desc--pending`,"aria-hidden":`true`,children:`\xA0`}),e===`pool`&&(0,R.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,R.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,R.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,R.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,R.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,R.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,R.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]})]})}function uu(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 du({apiBase:e}){let t=K(),n=`ocx.codex-auth.config.v1:${e}`,r=sn(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()=>{try{let t=await fetch(`${e}/api/config`);if(!t.ok)throw Error(String(t.status));let r=await t.json(),i=Ua(uu(r));if(i===`absent`||i===`disabled`||i===`invalid`){a(i);let e=i===`disabled`?`disabled`:`absent`;s(e),J(n,{bannerState:i,accountModeState:e});return}let o=cu(r);a(o),s(o),J(n,{bannerState:o,accountModeState:o})}catch{}},[e,n]);(0,_.useEffect)(()=>{c.current!==e&&(c.current=e,Promise.resolve().then(()=>{p()}));let t=window.setInterval(()=>{p()},3e4);return()=>{window.clearInterval(t)}},[e,p]);let m=async()=>{u(!0),f(``);try{if(i!==`absent`&&i!==`disabled`)return;await Xa(e,i),await p()}catch(e){e instanceof Ya?f(t(e.i18nKey)):f(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{u(!1)}};return(0,R.jsx)(wa,{apiBase:e,accountModeState:o,banner:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(lu,{state:i,busy:l,onEnable:()=>{m()}}),d&&(0,R.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:d})]})})}function fu(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function pu(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 mu(e){return e.id}var hu={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 gu(e){let t=e||hu.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 _u(e,t){return new Date(e).toLocaleDateString(t)}function vu({url:e}){return(0,R.jsx)(yu,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,R.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}=G(),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,Ke.createPortal)((0,R.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,R.jsxs)(R.Fragment,{children:[(0,R.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 bu({text:e}){return(0,R.jsx)(yu,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,R.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}function xu({endpoints:e,claudeCodeEnabled:t}){let{t:n}=G();return(0,R.jsxs)(`div`,{className:`panel api-panel`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:n(`api.endpointsTitle`)}),(0,R.jsxs)(`div`,{className:`api-endpoints`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.baseUrl`)}),(0,R.jsx)(vu,{url:e.baseUrl})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.responsesEndpoint`)}),(0,R.jsx)(vu,{url:e.responses})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.chatCompletionsEndpoint`)}),(0,R.jsx)(vu,{url:e.chatCompletions})]}),t&&(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.messagesEndpoint`)}),(0,R.jsx)(vu,{url:e.messages})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.modelsEndpoint`)}),(0,R.jsx)(vu,{url:e.models})]})]}),(0,R.jsx)(`p`,{className:`muted small`,children:n(`api.endpointNote`)}),(0,R.jsxs)(`details`,{className:`awi-inline-fold`,children:[(0,R.jsx)(`summary`,{children:n(`api.authTitle`)}),(0,R.jsxs)(`div`,{className:`awi-inline-fold-body`,children:[(0,R.jsxs)(`ul`,{className:`api-auth-list muted small`,children:[(0,R.jsx)(`li`,{children:n(`api.authChatCompletions`)}),(0,R.jsx)(`li`,{children:n(`api.authResponses`)}),t&&(0,R.jsx)(`li`,{children:n(`api.authMessages`)}),(0,R.jsx)(`li`,{children:n(`api.authLoopback`)})]}),(0,R.jsx)(`p`,{className:`muted small`,children:n(`api.authBaseUrlNote`)})]})]})]})}function Su({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:_}=G();return(0,R.jsxs)(R.Fragment,{children:[a&&(0,R.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:_(`api.newKeyTitle`)}),(0,R.jsx)(`p`,{className:`muted small`,children:_(`api.newKeyNote`)}),(0,R.jsxs)(`div`,{className:`api-form-row`,children:[(0,R.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:a}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:p,children:o?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(ie,{}),` `,_(`api.copied`)]}):_(`api.copy`)})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:f,children:_(`api.dismiss`)})]}),(0,R.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:_(`api.generateTitle`)}),(0,R.jsxs)(`div`,{className:`api-form-row`,children:[(0,R.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:_(`api.keyNamePlaceholder`),"aria-label":_(`api.keyNamePlaceholder`),value:r,onChange:e=>u(e.target.value),className:`input`}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:d,disabled:i,children:[(0,R.jsx)(oe,{}),` `,_(i?`api.generating`:`api.generate`)]})]})]}),l&&(0,R.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:t?_(`api.activeKeysLoading`):_(`api.activeKeys`,{count:e.length})}),t?(0,R.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":_(`common.loading`)}):e.length>0?(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:_(`api.colName`)}),(0,R.jsx)(`th`,{children:_(`api.colKey`)}),(0,R.jsx)(`th`,{children:_(`api.colCreated`)}),(0,R.jsx)(`th`,{})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{children:e.name}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`code`,{children:e.prefix})}),(0,R.jsx)(`td`,{children:_u(e.createdAt,c)}),(0,R.jsx)(`td`,{children:s===e.id?(0,R.jsxs)(`span`,{className:`api-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>g(e.id),children:_(`api.confirm`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:h,children:_(`common.cancel`)})]}):(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":_(`api.deleteAria`),onClick:()=>m(e.id),children:(0,R.jsx)(ae,{})})})]},e.id))})]})}):n?(0,R.jsx)(`p`,{className:`muted`,children:_(`api.keysLoadFailed`)}):(0,R.jsx)(`p`,{className:`muted`,children:_(`api.noKeys`)})]})]})}function Cu({filteredModels:e,modelsLoading:t,modelsLoadFailed:n,modelQuery:r,copiedModelId:i,modelTests:a,claudeCodeEnabled:o,onModelQueryChange:s,onCopyModelId:c,onTestModel:l,sourceLabel:u,protocolLabel:d}){let{t:f}=G();return(0,R.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,R.jsxs)(`div`,{className:`api-panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:f(`api.modelsTitle`)}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:f(`api.modelsCount`,{count:e.length})})]}),(0,R.jsx)(`p`,{className:`muted small`,children:f(`api.modelsSubtitle`)}),(0,R.jsx)(`input`,{type:`search`,className:`input`,value:r,onChange:e=>s(e.target.value),placeholder:f(`api.modelsSearch`),"aria-label":f(`api.modelsSearch`)}),t?(0,R.jsx)(ma,{label:f(`api.modelsLoading`),rows:3}):n?null:e.length===0?(0,R.jsx)(`p`,{className:`muted small`,style:{marginTop:`0.75rem`},children:f(`api.modelsEmpty`)}):(0,R.jsx)(`div`,{className:`api-models-scroll`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:f(`api.colModel`)}),(0,R.jsx)(`th`,{children:f(`api.colSource`)}),(0,R.jsx)(`th`,{children:f(`api.colProtocols`)}),(0,R.jsx)(`th`,{})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>{let t=mu(e),n=a[t]?.state??`idle`;return(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{children:(0,R.jsxs)(`div`,{className:`api-model-cell`,children:[(0,R.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,R.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,R.jsx)(`td`,{children:u(e)}),(0,R.jsx)(`td`,{children:fu(o).map(d).join(`, `)}),(0,R.jsxs)(`td`,{children:[(0,R.jsxs)(`div`,{className:`api-model-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{c(t)},children:f(i===t?`api.modelCopied`:`api.copyModelId`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:n===`testing`,onClick:()=>{l(e)},children:f(n===`testing`?`api.testingModel`:`api.testModel`)})]}),n===`ok`&&(0,R.jsx)(`p`,{className:`muted small api-test-note api-test-note--ok`,children:f(`api.testSucceeded`)}),n===`error`&&(0,R.jsx)(`p`,{className:`muted small api-test-note api-test-note--error`,children:a[t]?.detail??f(`api.testFailed`)})]})]},t)})})]})})]})}function wu({endpoints:e,claudeCodeEnabled:t}){let{t:n}=G(),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,R.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,R.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,R.jsx)(ne,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?Kt(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??Wt(r):null,x=r?Gt(r):null,S=(()=>{let e=r?.watchdog?.warnThresholdBytes;if(y===null||y<=0||b===null||!e)return;let t=e-b;if(t<=0)return`danger`;let n=t/y;if(n<=1)return`danger`;if(n<=8)return`warn`})(),C=r?.responseState,w=r?.activeTurnCount,T=s===`draining`||s===`reconnecting`;return(0,R.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,R.jsxs)(`div`,{className:`mem-head`,children:[(0,R.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,R.jsx)(ne,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,R.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,R.jsxs)(`span`,{className:`mem-inflight`,children:[(0,R.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,R.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?Vt(t).format(w):`—`})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,R.jsx)(Jt,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,R.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,R.jsx)(qt,{label:n(`dash.mem.rss`),value:r?Ht(r.rss,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.jsHeap`),value:r?Ht(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:Ht(r.heapTotal,t)}):void 0}),(0,R.jsx)(qt,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?Ht(r.jscHeap.heapSize,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${Ht(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,R.jsxs)(`details`,{style:{marginTop:10},children:[(0,R.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,R.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,R.jsxs)(`div`,{className:`stat-row`,children:[(0,R.jsx)(qt,{label:n(`dash.mem.observed`),value:b===null?`—`:`${Ht(b,t)} (${x})`}),(0,R.jsx)(qt,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:Ht(r.external,t)}),(0,R.jsx)(qt,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:Ht(r.arrayBuffers,t)})]}),(0,R.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,R.jsxs)(`div`,{className:`stat-row`,children:[(0,R.jsx)(qt,{label:n(`dash.mem.storeEntries`),value:C?Vt(t).format(C.count):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.storeTotal`),value:C?Ht(C.totalBytes,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.storeLargest`),value:C?Ht(C.largestBytes,t):`—`}),(0,R.jsx)(qt,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:Ut(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,R.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,R.jsx)(qt,{label:n(`dash.mem.threshold`),value:Ht(r.watchdog.warnThresholdBytes,t)}),(0,R.jsx)(qt,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,R.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,R.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,R.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,R.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,R.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function $t({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,R.jsx)(`div`,{className:`panel`,children:(0,R.jsxs)(`div`,{className:`injection-head`,children:[(0,R.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,R.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,R.jsx)(fe,{width:13,height:13,"aria-hidden":`true`})})]}),(0,R.jsx)(rt,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...ht.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await mt(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,R.jsx)(rt,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...ht.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await mt(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 en({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,R.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,R.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,R.jsx)(rt,{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,R.jsx)(rt,{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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ge(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function tn({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,R.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,R.jsxs)(`div`,{className:`spread maintenance-head`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginTop:3},children:t(`dash.syncModelsHint`)})]}),(0,R.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,disabled:r,children:[(0,R.jsx)(se,{}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,R.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,R.jsxs)(`div`,{className:`notice ${c.nativeSubagentDefaultsWarning?`notice-warn`:`notice-ok`} maintenance-notice`,role:`status`,children:[c.nativeSubagentDefaultsWarning?(0,R.jsx)(de,{}):(0,R.jsx)(se,{}),(0,R.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,R.jsxs)(R.Fragment,{children:[` `,(0,R.jsx)(He,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]})]}),l&&(0,R.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`status`,children:[(0,R.jsx)(de,{}),(0,R.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})})]}),u&&(0,R.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,R.jsx)(de,{}):(0,R.jsx)(se,{}),(0,R.jsxs)(`span`,{children:[vt(u.status,t),u.latestVersion?` ${u.currentVersion} -> ${u.latestVersion}.`:``,d?` ${t(`dash.updateReconnecting`)}`:``,u.error?` ${u.error}`:``]})]})]})}function nn({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,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`panel`,children:(0,R.jsxs)(`div`,{className:`spread`,children:[(0,R.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,R.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,R.jsx)(`span`,{className:`knob`})})]})}),(0,R.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,R.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,R.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,R.jsx)(rt,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({webSearch:{model:e,backend:xt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,R.jsxs)(`div`,{className:`panel dash-sidecar-card`,"aria-busy":!a||void 0,children:[(0,R.jsxs)(`div`,{className:`dash-sidecar-card__row`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,R.jsx)(rt,{value:a?.vision.model??`gpt-5.6-luna`,options:s,onChange:e=>{l({vision:{model:e,backend:xt(c,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`)})]}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]})]}),(0,R.jsx)(`div`,{className:`panel`,"aria-busy":!u||void 0,children:(0,R.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,R.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,R.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,R.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,R.jsx)(fe,{width:13,height:13,"aria-hidden":`true`})}),(0,R.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${Ot(u?.sourceModels)}`})]}),(0,R.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,R.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,R.jsx)(`span`,{className:`knob`})}),(0,R.jsx)(rt,{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 rn(e){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)($t,{apiBase:e.apiBase,d:e}),(0,R.jsx)(en,{apiBase:e.apiBase,d:e}),(0,R.jsx)(tn,{d:e}),(0,R.jsx)(nn,{d:e}),(0,R.jsx)(Qt,{apiBase:e.apiBase})]})}function an(e){return(0,R.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,R.jsx)(It,{...e}),(0,R.jsx)(rn,{...e})]})}function on({t:e,providers:t}){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,R.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,R.jsx)(it,{title:(0,R.jsx)(He,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:e(`dash.col.name`)}),(0,R.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,R.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,R.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,R.jsx)(`tbody`,{children:t.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`font-semibold`,children:e.name}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`span`,{className:`chip`,children:e.adapter})}),(0,R.jsx)(`td`,{className:`muted mono text-label`,children:e.baseUrl}),(0,R.jsx)(`td`,{className:`muted`,children:e.defaultModel??`—`})]},e.name))})]})})]})}function sn(e){try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function J(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function cn(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function ln(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function un(e,t){return{request:++e.current,mutation:t.current}}var dn=2e3;function fn(e){let t=e.status;return t===`native`||t===`protected`||t===`at-risk`?t:null}function pn(e){return e?e.stale&&e.status!==`error`:!1}function mn(e,t){return!t||e!==null&&e!==`error`?e:t.status}var hn=3e4;function gn(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function _n(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function vn(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=fn(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(_n(e,t))throw e;return{status:`error`,stale:!1}}}async function yn(e,t){try{return(await lt(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function bn(e,t){return mt(await fetch(`${e}/api/models`,{signal:t}))}async function xn(e,t){return mt(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Sn(e,t,n){let{request:r,mutation:i}=un(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 mt(a),c;try{if(o.ok){let e=await o.json();ln({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else ln({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{ln({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 Cn(e,t,n){let{request:r,mutation:i}=un(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await mt(await fetch(`${e}/api/settings`,{signal:t})),o,s;return ln({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 wn(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(_n(e,t))throw e;return{maMode:`default`}}}async function Tn(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await mt(n),providers:await mt(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function En(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={...gn(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 Dn=`ocx.dash.controls.v1:`,On=`ocx.dash.overview.v1:`,kn=`ocx.dash.usage30d.v1:`,An=`ocx.dash.startup.v1:`,jn=`ocx.dash.maMode.v1:`;function Mn(e){return`${Dn}${e}`}function Nn(e){let{locale:t,t:n}=G(),[r,i]=(0,_.useState)(dt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>sn(Mn(e)),[e]),u=(0,_.useMemo)(()=>sn(`${On}${e}`),[e]),d=(0,_.useMemo)(()=>sn(`${kn}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=sn(`${An}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>sn(`${jn}${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),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(()=>p??`default`),[W,ee]=(0,_.useState)(!1),[te,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(!1),[ae,oe]=(0,_.useState)(!1),[se,ce]=(0,_.useState)(``),[le,ue]=(0,_.useState)(``),[de,fe]=(0,_.useState)([]),[pe,me]=(0,_.useState)([]),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(!0),[ye,be]=(0,_.useState)(!1),[xe,Se]=(0,_.useState)(``),[Ce,we]=(0,_.useState)(``),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)(null),[ke,Ae]=(0,_.useState)(null),[je,Me]=(0,_.useState)([]),[Ne,Pe]=(0,_.useState)(!1),[Fe,Ie]=(0,_.useState)(`latest`),[Le,Re]=(0,_.useState)(!0),[ze,Be]=(0,_.useState)(!1),K=(0,_.useRef)(0),Ve=(0,_.useRef)(null),He=(0,_.useRef)(0),Ue=(0,_.useRef)(0),Ge=(0,_.useRef)(0),Ke=(0,_.useRef)(!1),qe=(0,_.useRef)(0),Je=(0,_.useRef)(0),Ye=(0,_.useRef)(!1),[Xe,Ze]=(0,_.useState)(null),[Qe,$e]=(0,_.useState)(null),[et,tt]=(0,_.useState)(null),[nt,q]=(0,_.useState)(!1),[rt,it]=(0,_.useState)(!1),at=(0,_.useRef)(null),ot=(0,_.useRef)(null),st=(0,_.useRef)(null),ct=(0,_.useRef)(null),lt=wt(re,at),ut=wt(Ne,ot),pt=wt(te,st),ht=wt(ae,ct);(0,_.useEffect)(()=>{let e=()=>i(dt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{He.current+=1,Ve.current!==null&&(window.clearTimeout(Ve.current),Ve.current=null)},[]);let _t=(0,_.useRef)(f),vt=(0,_.useRef)(0),xt=(0,_.useRef)({settingsRequestEpochRef:Ue,settingsMutationEpochRef:Ge,settingsMutationInFlightRef:Ke,shadowCallRequestEpochRef:qe,shadowCallMutationEpochRef:Je,shadowCallMutationInFlightRef:Ye}).current,St=F(`dashboard-startup-health:${e}`,[e],t=>vn(e,t),{pollMs:3e4}),Ct=pn(St.data),Tt=St.refresh;(0,_.useEffect)(()=>{if(!Ct)return;let e=window.setTimeout(()=>{Tt()},dn);return()=>window.clearTimeout(e)},[Ct,Tt]);let Et=F(`dashboard-overview:${e}`,[e],t=>Tn(e,t),{pollMs:5e3}),Dt=m!==null||Et.data!==void 0,Ot=F(`dashboard-ma-mode:${e}`,[e],t=>wn(e,t),{pollMs:5e3}),kt=F(`dashboard-sidecars:${e}`,[e],async t=>{let n=vt.current;return{...await Sn(e,t,xt),startupHealthGeneration:n}},{pollMs:5e3}),At=F(`dashboard-settings:${e}`,[e],async t=>{let n=vt.current;return{...await Cn(e,t,xt),startupHealthGeneration:n}},{pollMs:5e3}),jt=F(`dashboard-multi-agent:${e}`,[e],t=>En(e,t),{pollMs:5e3,enabled:Dt}),Mt=F(`dashboard-usage:${e}`,[e],t=>xn(e,t),{pollMs:6e4,enabled:Dt}),Nt=F(`dashboard-diagnostics:${e}`,[e],t=>yn(e,t),{pollMs:hn,enabled:Dt}),Pt=F(`dashboard-models:${e}`,[e,rt],t=>bn(e,t),{enabled:Dt&&!rt});(0,_.useEffect)(()=>{if(St.data!==void 0){let t=St.data;vt.current+=1,v(t.status),_t.current=t.status,t.status!==`error`&&!t.stale&&J(`${An}${e}`,t.status)}},[St.data,e]),(0,_.useEffect)(()=>{let t=Et.data;t&&(t.health&&(h(t.health),b(t.providers),J(`${On}${e}`,{health:t.health,providers:t.providers})),it(t.error))},[Et.data,e]),(0,_.useEffect)(()=>{Ot.data!==void 0&&(U(Ot.data.maMode),J(`${jn}${e}`,Ot.data.maMode))},[Ot.data,e]);let Ft=Ot.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=jt.data;e&&(e.injection&&(ve(e.injection.multiAgentGuidanceEnabled),be(e.injection.syncCodexSubagentDefaults),ce(e.injection.injectionModel),ue(e.injection.injectionEffort),fe(e.injection.injectionEfforts),me(e.injection.injectionAvailable)),e.effortCaps&&(Se(e.effortCaps.effortCap),we(e.effortCaps.subagentEffortCap)))},[jt.data]),(0,_.useEffect)(()=>{let t=kt.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=sn(Mn(e))??{};J(Mn(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[kt.data,e]),(0,_.useEffect)(()=>{let t=At.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===vt.current){let n=mn(_t.current,t.startupHealthSeed);v(n),_t.current=n,n&&J(`${An}${e}`,n)}if(t.settings!==void 0){let n=sn(Mn(e))??{};J(Mn(e),{...n,settings:t.settings})}}},[At.data,e]),(0,_.useEffect)(()=>{Mt.data!==void 0&&(A(Mt.data),J(`${kn}${e}`,Mt.data))},[Mt.data,e]),(0,_.useEffect)(()=>{Nt.data&&Me(Nt.data)},[Nt.data]),(0,_.useEffect)(()=>{Pt.data&&S(Pt.data),L(Pt.loading)},[Pt.data,Pt.loading]),(0,_.useEffect)(()=>()=>{Ue.current+=1,qe.current+=1},[]);let It=F(et?.id&&et.restart?`update-job:${e}:${et.id}`:`update-job:idle:${e}`,[e,et?.id,et?.restart,et?.latestVersion],async t=>{if(!et?.id||!et.restart)return{reconnecting:!1};let n=et.latestVersion;try{let r=await mt(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(et.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await mt(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:!!(et?.id&&et.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=It.data;e&&(`job`in e&&e.job&&tt(e.job),q(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[It.data]);let Lt=(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]),Rt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return Lt;let t=[];for(let[n,r]of Lt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Lt,a]),zt=(0,_.useMemo)(()=>{let e=bt(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]),Bt=async t=>{if(!T||j)return;let n=T,r={webSearch:yt(T.webSearch,t.webSearch),vision:yt(T.vision,t.vision)};M(!0),E(r);try{let n=await mt(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=sn(Mn(e))??{};J(Mn(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision}})}catch{E(n)}finally{M(!1)}};async function Vt(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),Ye.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`);Je.current+=1}catch{O(n)}finally{Ye.current=!1,P(!1)}}let Ht=async t=>{if(!(W||H===t)){ee(!0);try{(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})})).ok&&(U(t),J(`${jn}${e}`,t))}catch{}finally{ee(!1)}}},Ut=async t=>{if(!he){ge(!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 mt(await fetch(`${e}/api/injection-model`)),r=gn(n);ve(r.multiAgentGuidanceEnabled),be(r.syncCodexSubagentDefaults),ce(r.injectionModel),ue(r.injectionEffort),Array.isArray(n.efforts)&&fe(n.efforts),Array.isArray(n.available)&&me(n.available)}catch{}finally{ge(!1)}}},Wt=async()=>{if(!C||R)return;let t=!C.codexAutoStart;z(!0),Ke.current=!0,w({...C,codexAutoStart:t});try{let n=await mt(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Ge.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),it(!0)}finally{Ke.current=!1,z(!1)}},Gt=async()=>{if(!B){V(!0),Oe(null),Ae(null);try{let t=await mt(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Oe(t),t.projectConfigGrouped&&Me(t.projectConfigGrouped)}catch(e){Ae(e instanceof Error?e.message:String(e))}finally{V(!1)}}},Kt=async(t,n=!1)=>{n&&(K.current=0),Ve.current!==null&&(window.clearTimeout(Ve.current),Ve.current=null);let r=++He.current;Be(!0),$e(null),Ze(null);try{let n=await mt(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==He.current)return;if(Ze(n),n.reason===`latest_unavailable`&&K.current<2){let e=++K.current;Ve.current=window.setTimeout(()=>{r===He.current&&(Ve.current=null,Kt(t))},800*e);return}n.reason!==`latest_unavailable`&&(K.current=0),Be(!1)}catch(e){if(r!==He.current)return;$e(e instanceof Error?e.message:String(e)),Be(!1)}},qt=()=>{He.current+=1,Ve.current!==null&&(window.clearTimeout(Ve.current),Ve.current=null),Be(!1),Pe(!1)},Jt=()=>{let e=gt(m?.version);Ie(e),Re(!0),Pe(!0),Kt(e,!0)},Yt=e=>{Ie(e),Kt(e,!0)},Xt=(0,_.useRef)(Jt);return(0,_.useEffect)(()=>{Xt.current=Jt}),(0,_.useEffect)(()=>{let e=()=>{ft()&&(We(`dashboard`),Xt.current())},t=ft()?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:Mt.loading&&!k,healthLoading:Et.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:I,settingsSaving:R,syncing:B,maMode:H,maModeResolved:Ft,maBusy:W,setMaHelpOpen:ne,maHelpOpen:te,effortCapHelpOpen:re,setEffortCapHelpOpen:ie,shadowCallHelpOpen:ae,setShadowCallHelpOpen:oe,injectionModel:se,injectionEffort:le,injectionEfforts:de,injectionAvailable:pe,injectionSaving:he,multiAgentGuidanceEnabled:_e,syncCodexSubagentDefaults:ye,saveInjection:Ut,effortCap:xe,subagentEffortCap:Ce,effortCapSaving:Te,setEffortCap:Se,setSubagentEffortCap:we,setEffortCapSaving:Ee,syncResult:De,syncError:ke,projectConfigWarnings:je,updateOpen:Ne,updateChannel:Fe,setUpdateRestart:Re,updateRestart:Le,updateLoading:ze,updateCheck:Xe,updateError:Qe,updateJob:et,reconnecting:nt,error:rt,effortCapHelpTriggerRef:at,updateTriggerRef:ot,maHelpTriggerRef:st,shadowCallHelpTriggerRef:ct,effortCapHelpDialogRef:lt,updateDialogRef:ut,maHelpDialogRef:pt,shadowCallHelpDialogRef:ht,filteredGroups:Rt,sidecarModels:zt,saveSidecar:Bt,saveShadowCall:Vt,switchMaMode:Ht,toggleCodexAutoStart:Wt,runSync:Gt,fetchUpdateCheck:Kt,closeUpdateDialog:qt,openUpdateDialog:Jt,changeUpdateChannel:Yt,runUpdate:async()=>{if(Xe?.canUpdate){$e(null);try{let t=await mt(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Fe,restart:Le})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);tt(t.job),q(!1),qt()}catch(e){$e(e instanceof Error?e.message:String(e))}}}}}function Pn(e){Ge(pt(e))}function Fn({apiBase:e}){let t=Nn(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,R.jsx)(it,{style:{marginTop:40},icon:(0,R.jsx)(de,{}),title:(0,R.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,R.jsx)(He,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,R.jsx)(an,{...t}),m=(0,R.jsx)(on,{t:n,providers:a}),h=(0,R.jsx)(At,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,R.jsx)(kt,{...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=Pn,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,R.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,R.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,R.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,R.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,R.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 In=`https://chatgpt.com/backend-api/codex`,Ln=`openai`;function Rn(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 Bn(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||zn(e.baseUrl)||e.hasApiKey===!0}function Vn(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Rn(e.baseUrl)===In}function Hn(e,t){return e===Ln&&Vn(t)}function Un(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||zn(e.baseUrl)}function Wn(e,t){return Hn(e,t)?`accounts`:Un(t)?`free`:`paid`}function Gn(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??Wn(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 Kn(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}Bn(a)?t.push({name:i,...a,tier:Wn(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function qn(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 Jn(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:Bn(e)?`ready`:`needs-setup`}function Yn(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!Hn(`openai`,t)||!Vn(n))return e;let r={...e};return delete r.chatgpt,r}function Xn(e){return e.authMode===`local`||zn(e.baseUrl)}var Zn=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function Qn(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(Xn(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return Zn.some(e=>n.includes(e))?`selfHosted`:`cloud`}function $n(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 er(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 tr(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 nr(e){let t={};for(let[n,r]of Object.entries($n(e)))t[n]=r.length;return t}function rr(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 ir={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function ar(e,t,n){let r=typeof t==`object`&&t?t:ir,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 or(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 sr(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 cr(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function lr(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 ur(e,t=`en`){return lr(e,t)}function dr(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var fr={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`},pr={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`};function mr(e){return fr[e.toLowerCase()]}function hr(e,t){let n=mr(e);return n?`/provider-icons/${n}`:void 0}function gr(e){let t=e.toLowerCase();return pr[t]?pr[t]:e===t&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)?e.split(`-`).map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(` `):e}function _r(e){return Object.prototype.hasOwnProperty.call(pr,e.toLowerCase())}function vr(e,t){let n=Jn(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 yr(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 br(e){let t=Jn(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 xr({name:e,adapter:t,baseUrl:n,cls:r}){let i=hr(e,{adapter:t,baseUrl:n});return(0,R.jsx)(`span`,{className:r,children:i?(0,R.jsx)(`img`,{src:i,alt:``,"aria-hidden":`true`}):(0,R.jsx)(V,{"aria-hidden":`true`})})}function Sr({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=K(),l=Un(e),u=Xn(e),d=vr(e,c),f=gr(e.name),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,R.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,R.jsx)(xr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,R.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,R.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,R.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,R.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,R.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,R.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,R.jsx)(Me,{width:17,height:17,"aria-hidden":`true`})}),(0,R.jsx)(`span`,{className:br(e),title:d,"aria-hidden":`true`})]})]})}function Cr(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}}]}):[],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 wr(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Tr(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 Er(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function Dr(e,t){return!e||!Er(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 Or(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function kr(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 Ar(e,t,n){let r=Dr(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=kr(e.label,n);i.push({rank:Or(e.label),row:{label:t,limitLabel:t,percent:e.percent,resetAt:e.resetAt}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function jr(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 Mr(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 Nr(e){return e>=99.5}function Pr(e,t){return t>0&&e>=t}function Fr(e,t){return Pr(e,t)||Nr(e)?`bar-warn`:`bar-green`}function Ir(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Lr(e){return{"--bar-scale":String(Ir(e)/100)}}function Rr({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1}){let{locale:s}=G(),c=Ar(e,t,r);return c.length===0?o?a===`stacked`?(0,R.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,R.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,R.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,R.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,R.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,R.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,R.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,R.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,R.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,R.jsx)(`span`,{className:`quota-skel quota-skel--val`})]},t)),(0,R.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,R.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:c.map(e=>(0,R.jsx)(Br,{row:e,threshold:n,t:r,locale:s},e.limitLabel))}):(0,R.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:c.map(e=>(0,R.jsx)(zr,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:s},e.label))})}function zr({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Nr(t),s=Pr(t,r),c=Fr(t,r),l=Vr(n,i,a);return(0,R.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,R.jsx)(`span`,{className:`quota-label`,children:e}),(0,R.jsx)(`span`,{className:`quota-reset-label`,children:i(`codexAuth.resets`)}),(0,R.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,R.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,R.jsx)(`div`,{className:`bar`,children:(0,R.jsx)(`div`,{className:`bar-fill ${c}`,style:Lr(t)})}),(0,R.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):void 0,children:[s&&(0,R.jsx)(de,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function Br({row:e,threshold:t,t:n,locale:r}){let i=Nr(e.percent),a=Pr(e.percent,t),o=Fr(e.percent,t),s=Hr(e.resetAt,n,r);return(0,R.jsxs)(`div`,{className:`quota-stacked-row${a?` quota-stacked-row--warn`:``}${i?` quota-stacked-row--exhausted`:``}`,children:[(0,R.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,R.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),(0,R.jsx)(`span`,{className:`quota-stacked-reset muted`,children:s})]}),(0,R.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,R.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,R.jsx)(`div`,{className:`bar-fill ${o}`,style:Lr(e.percent)})}),(0,R.jsx)(`span`,{className:`quota-stacked-used${a?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),i&&(0,R.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,R.jsx)(de,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function Vr(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=Mr(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 Hr(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=Mr(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 Ur({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=K(),{locale:c}=G(),l=or(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)(()=>sr(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?Cr(r):null;r&&i&&e.push({item:n,report:r,urgency:jr(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 rr(e).slice(0,4)},[n,d]),b=e=>{let t=cr(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,R.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,R.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,R.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,R.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,R.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,R.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,R.jsx)(Wr,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,R.jsx)(Wr,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,R.jsx)(Wr,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,R.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,R.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,R.jsx)(de,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,R.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,R.jsx)(xr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,R.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-name`,children:gr(e.name)}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,R.jsx)(_e,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,R.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,R.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,R.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,R.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,R.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,R.jsx)(xr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,R.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-name`,children:gr(e.name)}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:s(`pws.dashboard.checkedAgo`,{time:ar(t.updatedAt,l)})})]}),(0,R.jsx)(_e,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,R.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,R.jsx)(Rr,{quota:Cr(t),threshold:80,t:s,layout:`stacked`,pending:i&&!t.quota})})]},e.name))}):i?(0,R.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,R.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,R.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,R.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,R.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,R.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,R.jsx)(Rr,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,R.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,R.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,R.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,R.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,R.jsx)(xr,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-name`,children:gr(e.name)}),(0,R.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:lr(e.requests,c)})}),(0,R.jsx)(_e,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,R.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,R.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,R.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,R.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,R.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function Wr({count:e,label:t,tone:n}){return(0,R.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,R.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,R.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function Gr({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=K(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,R.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,R.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,R.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,R.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,R.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,R.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,R.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var Kr=[{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 qr({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=K(),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[x,S]=(0,_.useState)({free:!0,paid:!0}),[C,w]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[T,E]=(0,_.useState)(`az`),[D,O]=(0,_.useState)(!1),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)({}),[N,P]=(0,_.useState)({}),[F,I]=(0,_.useState)({}),[L,z]=(0,_.useState)({}),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(!1),W=`ocx.providers.quotas.v1:${t}`,ee=`ocx.providers.usage.v1:${t}`,[te,ne]=(0,_.useState)(()=>sn(ee)?.totals??{}),[re,ie]=(0,_.useState)(()=>sn(ee)?.models??{}),[ae,oe]=(0,_.useState)(()=>sn(W)??{}),[se,ce]=(0,_.useState)(()=>!sn(ee)),[le,de]=(0,_.useState)(()=>!sn(W)),[fe,me]=(0,_.useState)(0),he=(0,_.useRef)(null),ge=(0,_.useMemo)(()=>qn(Kn(Yn(e)),d??{}),[e,d]),_e=(0,_.useCallback)(()=>{me(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{V(!0),(async()=>{try{let n=await ct(await fetch(`${t}/api/selected-models`));if(e)return;M(nr(n)),P($n(n)),I(er(n)),z(tr(n)),U(!1)}catch{if(e)return;U(!0)}finally{e||V(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,fe]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{sn(ee)||ce(!0),fetch(`${t}/api/usage?range=30d`).then(e=>lt(e)).then(t=>{if(e||!t)return;let n={};for(let e of t.providers??[])n[e.provider]={requests:e.requests,totalTokens:e.totalTokens};ne(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}})}ie(r),J(ee,{totals:n,models:r})}).catch(()=>{}).finally(()=>{e||ce(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,ee]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{sn(W)||de(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>lt(e)).then(t=>{e||!t||oe(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 J(W,n),n})}).catch(()=>{}).finally(()=>{e||de(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,W]),(0,_.useEffect)(()=>{if(!D)return;let e=e=>{he.current&&!he.current.contains(e.target)&&O(!1)},t=e=>{e.key===`Escape`&&O(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[D]);let ve=(0,_.useMemo)(()=>[...ge.ready,...ge.needsSetup,...ge.disabled],[ge]),ye=(0,_.useMemo)(()=>ve.filter(Un).length,[ve]),be=ve.length-ye,xe=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of ve)e[Qn(t)]+=1;return e},[ve]),Se=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>Gn(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=Un(t);return!(n&&!x.free||!n&&!x.paid||!C[Qn(t)])}),T);return{ready:y.ready?t(ge.ready):[],needsSetup:y.needsSetup?t(ge.needsSetup):[],disabled:y.disabled?t(ge.disabled):[]}},[ge,g,y,x,C,T]),Ce=!y.ready||!y.needsSetup||!y.disabled||!x.free||!x.paid||!C.cloud||!C.local||!C.selfHosted||!C.login||T!==`az`,we=()=>{b({ready:!0,needsSetup:!0,disabled:!0}),S({free:!0,paid:!0}),w({cloud:!0,local:!0,selfHosted:!0,login:!0}),E(`az`)},Te=(0,_.useMemo)(()=>r?ve.find(e=>e.name===r)??null:null,[r,ve]),Ee=(0,_.useMemo)(()=>{let e=new Map;for(let t of ve){let n=gr(t.name);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},[ve]);if(ve.length===0)return(0,R.jsx)(Jr,{onAddProvider:o});let De=[{key:`ready`,label:h(`pws.status.ready`),count:ge.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:ge.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:ge.disabled.length}],Oe=[{id:`ready`,label:h(`pws.status.ready`),count:Se.ready.length,ariaLabel:h(`pws.groupReady`,{count:Se.ready.length}),items:Se.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:Se.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:Se.needsSetup.length}),items:Se.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:Se.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:Se.disabled.length}),items:Se.disabled}],ke=Oe.flatMap(e=>e.items.map(e=>e.name)),Ae=k&&ke.includes(k)?k:r&&ke.includes(r)?r:ke[0]??null;return(0,R.jsx)(`div`,{className:`pws-shell-container`,children:(0,R.jsxs)(`div`,{className:`pws-root`,children:[(0,R.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,R.jsxs)(`div`,{className:`pws-search-row`,children:[(0,R.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,R.jsx)(pe,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,R.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,R.jsxs)(`div`,{className:`pws-filter-wrap`,ref:he,children:[(0,R.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${Ce||D?` pws-filter-btn--active`:``}`,onClick:()=>O(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":D,"aria-controls":`pws-provider-filters`,children:[(0,R.jsx)(Ne,{width:18,height:18,"aria-hidden":`true`}),Ce&&(0,R.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),D&&(0,R.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,R.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),De.map(({key:e,label:t,count:n})=>(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:y[e],onChange:()=>b(t=>({...t,[e]:!t[e]}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:x.free,onChange:()=>S(e=>({...e,free:!e.free}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:ye})]}),(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:x.paid,onChange:()=>S(e=>({...e,paid:!e.paid}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:be})]}),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:xe.cloud},{key:`local`,label:h(`pws.type.local`),count:xe.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:xe.selfHosted},{key:`login`,label:h(`pws.type.login`),count:xe.login}].map(({key:e,label:t,count:n})=>(0,R.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:C[e],onChange:()=>w(t=>({...t,[e]:!t[e]}))}),(0,R.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,R.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,R.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,R.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:Kr.map(e=>(0,R.jsx)(`button`,{type:`button`,className:`pws-sort-btn${T===e.id?` pws-sort-btn--active`:``}`,onClick:()=>E(e.id),"aria-pressed":T===e.id,children:h(e.labelKey)},e.id))}),(0,R.jsx)(`div`,{className:`pws-filter-footer`,children:(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:we,disabled:!Ce,children:h(`pws.resetAll`)})})]})]})]}),(0,R.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(Se).every(e=>e.length===0)&&(0,R.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:Ce?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Oe.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,R.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,R.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,R.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,R.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,R.jsx)(Sr,{item:e,selected:r===e.name,tabbable:Ae===e.name,modelCount:j[e.name],isDefault:n===e.name,showConfigId:Ee.has(gr(e.name)),onClick:()=>i(e.name),onFocus:()=>A(e.name)}),a&&(0,R.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,R.jsx)(ue,{width:14,height:14})})]},e.name))]},e))]})]}),(0,R.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,R.jsx)(Gr,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):Te?m?.(Te,{usageTotals:te[Te.name],modelUsage:re[Te.name],quotaReport:ae[Te.name],availableModels:N[Te.name]??[],hasLiveModels:(F[Te.name]??0)>0,selectedModels:L[Te.name]??[],modelsLoading:B,modelsLoadFailed:H,onRetryModels:_e})??(0,R.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,R.jsx)(`h3`,{children:gr(Te.name)}),(0,R.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,R.jsx)(Ur,{sections:ge,quotaReports:ae,usageTotals:te,usageLoading:se,quotasLoading:le,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function Jr({onAddProvider:e}){let t=K();return(0,R.jsx)(`div`,{className:`pws-empty-root`,children:(0,R.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,R.jsx)(`div`,{"aria-hidden":`true`,children:(0,R.jsx)(H,{style:{width:64,height:64}})}),(0,R.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,R.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,R.jsx)(`span`,{"aria-hidden":`true`,children:(0,R.jsx)(Oe,{width:18,height:18})}),(0,R.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,R.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,R.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,R.jsx)(`span`,{"aria-hidden":`true`,children:(0,R.jsx)(Se,{width:18,height:18})}),(0,R.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,R.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,R.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,R.jsx)(`span`,{"aria-hidden":`true`,children:(0,R.jsx)(xe,{width:18,height:18})}),(0,R.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,R.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function Yr(e){if(Hn(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||Xn(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 Xr(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 Zr({item:e,usageTotals:t,quotaReport:n,oauthEmail:r,onEditSettings:i,onViewUsage:a,onUpdateProvider:o,onReauthenticate:s,onCancelLogin:c,reauthBusy:l=!1,accountPanel:u}){let d=K(),{locale:f}=G(),p=or(d),m=Jn(e),h=!!e.activeNeedsReauth,g=d(m===`ready`?`pws.status.connected`:m===`needs-setup`?h?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),_=t?.requests,v=t?.totalTokens,y=Cr(n);return(0,R.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,R.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,R.jsxs)(`section`,{className:`pws-section`,"aria-label":d(`pws.connection`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:d(`pws.connection`)}),(0,R.jsxs)(`dl`,{className:`pws-kv`,children:[(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`dash.status`)}),(0,R.jsxs)(`dd`,{className:m===`ready`?`pws-status-ok`:`pws-status-warn`,children:[m===`ready`?(0,R.jsx)(ie,{style:{width:13,height:13},"aria-hidden":`true`}):(0,R.jsx)(de,{style:{width:13,height:13},"aria-hidden":`true`}),g]})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`modal.baseUrl`)}),(0,R.jsx)(`dd`,{children:(0,R.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.cell.auth`)}),(0,R.jsx)(`dd`,{children:r?`${yr(e,d)} · ${r}`:yr(e,d)})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`modal.defaultModel`)}),(0,R.jsx)(`dd`,{children:e.defaultModel??(0,R.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.cell.note`)}),(0,R.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),i&&(0,R.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:i,children:d(`pws.editSettings`)})]}),u?(0,R.jsx)(`section`,{className:`pws-section`,"aria-label":d(`pws.availableAccounts`),children:u}):(0,R.jsxs)(`section`,{className:`pws-section`,"aria-label":d(`pws.authSummary`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:d(`pws.authSummary`)}),h?(0,R.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,R.jsx)(de,{style:{width:14,height:14},"aria-hidden":`true`}),(0,R.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,R.jsxs)(`span`,{children:[(0,R.jsx)(`strong`,{children:d(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?d(`pws.attention.reauthForward`):d(`pws.attention.reauth`)]}),s&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:l,onClick:()=>s(),children:d(l?`prov.waitingBrowser`:`pws.reauthenticate`)}),l&&c&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>c(),children:d(`common.cancel`)})]})]}):(0,R.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,R.jsx)(`span`,{className:`pws-auth-dot`}),(0,R.jsx)(`span`,{children:e.authMode===`forward`?d(`pws.passthrough`):e.authMode===`oauth`?r?d(`pws.loggedInAs`,{email:r}):d(`pws.notLoggedIn`):e.hasApiKey?d(`pws.apiKeyConfigured`):yr(e,d)})]})]})]}),(0,R.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,R.jsxs)(`section`,{className:`pws-section`,"aria-label":d(`pws.statsAria`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:d(`pws.statsTitle`)}),(0,R.jsxs)(`dl`,{className:`pws-kv`,children:[typeof _==`number`&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.stats.totalRequests`)}),(0,R.jsx)(`dd`,{className:`pws-kv-mono`,children:lr(_,f)})]}),typeof v==`number`&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.stats.totalTokens`)}),(0,R.jsx)(`dd`,{className:`pws-kv-mono`,children:ur(v,f)})]}),n&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:d(`pws.stats.quotaUpdated`)}),(0,R.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?wr(n.source):void 0,children:ar(n.updatedAt,p)})]}),typeof _!=`number`&&typeof v!=`number`&&!n&&(0,R.jsx)(`div`,{className:`muted`,children:d(`pws.usageUnavailable`)})]}),a&&(0,R.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:a,children:[d(`pws.viewUsage`),` →`]}),y&&(0,R.jsx)(`div`,{className:`muted pws-stats-note`,children:d(`pws.stats.quotaTracked`)})]}),(0,R.jsx)(Qr,{item:e,onUpdateProvider:o})]})]})}function Qr({item:e,onUpdateProvider:t}){let n=K(),[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,R.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,R.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,R.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,R.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,R.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,R.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function $r({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=K(),[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)(()=>Tr(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 z=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let B=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{}},V=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)}}},H=n.length===0&&P.length===0&&S.length===0&&!e.defaultModel,U=n.length===0&&P.length>0,W=L.length>300,ee=W?L.slice(0,300):L;return(0,R.jsxs)(`div`,{className:`pws-section`,children:[(0,R.jsxs)(`div`,{className:`pws-section-head`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),L.length>0&&(0,R.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:L.length})})]}),s&&(0,R.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,R.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),U&&!s&&(0,R.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,R.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,R.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,R.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&V()},placeholder:u(`models.customFieldModelIdPlaceholder`),"aria-label":u(`models.customAdd`),disabled:h}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{V()},disabled:h||I,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,R.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,R.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:z,style:{marginLeft:8},children:u(`common.retry`)})]}),!H&&(0,R.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&&H?(0,R.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&H?(0,R.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,R.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):H?(0,R.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):L.length===0?(0,R.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,R.jsx)(`ul`,{className:`pws-model-list`,children:ee.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,R.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,R.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:()=>{B(t)},title:t,"aria-label":u(A===t?`pws.modelCopied`:`pws.copyModelId`),children:(0,R.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,R.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,R.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),W&&(0,R.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(L.length)})})]})}function ei({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=K(),{locale:a}=G(),o=or(i),s=t?.requests!==void 0,c=Cr(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,R.jsxs)(`div`,{className:`pws-section`,children:[(0,R.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,R.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,R.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:dr(f,a)}),(0,R.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,R.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,R.jsx)(`span`,{className:`pws-usage-metric-value`,children:lr(t?.requests,a)}),(0,R.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,R.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,R.jsx)(`span`,{className:`pws-usage-metric-value`,children:ur(t?.totalTokens,a)}),(0,R.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,R.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,R.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,R.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`pws-model-table`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:i(`pws.col.model`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,R.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,R.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,R.jsxs)(_.Fragment,{children:[(0,R.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,R.jsx)(`td`,{className:`mono`,children:(0,R.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,R.jsx)(`td`,{className:`num mono`,children:dr(e.estimatedCostUsd,a)}),(0,R.jsx)(`td`,{className:`num mono`,children:ur(e.totalTokens,a)}),(0,R.jsx)(`td`,{className:`num`,children:e.requests}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`div`,{className:`pws-share-bar`,children:(0,R.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,R.jsx)(`tr`,{className:`pws-model-detail`,children:(0,R.jsx)(`td`,{colSpan:5,children:(0,R.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[` `,ur(e.inputTokens,a)]})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[` `,ur(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,R.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,R.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Rr,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,R.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,R.jsx)(`dd`,{children:wr(n.source)})]}),(0,R.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,R.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,R.jsx)(`dd`,{children:ar(n?.updatedAt,o)})]})]})]}):(0,R.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function ti(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function ni(e){return ti(e)??`account-…`}function ri(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function ii(e){let t=ri(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function ai(e){return e===`reauth_required`}function oi(e){return!!e?.needsReauth||ai(e?.health?.status)}function si(e){return e===`cooldown`}function ci(e){return e===`warning`||e===`reauth_required`}function li(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 ui(e,t){let n=li(t);return n?e(n):null}function di(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):ni(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 fi(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return pi(e)}function pi(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 hi=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function gi(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 _i({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,R.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,R.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,R.jsx)(Oe,{width:20}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,R.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,R.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var vi=2500;function yi(){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;fi(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)},vi))})},[i])}}function bi({url:e}){let t=K(),{outcomeFor:n,copy:r}=yi();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,R.jsxs)(`div`,{className:`login-url-block`,children:[(0,R.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,R.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,R.jsx)(we,{style:{width:13,height:13},"aria-hidden":`true`}),(0,R.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,R.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,R.jsx)(be,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function xi({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=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,R.jsx)(bi,{url:t}),(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,marginTop:12},children:[(0,R.jsx)(`div`,{className:`muted text-label`,children:f(`prov.pasteRedirectHint`)}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,R.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,R.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,R.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,R.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,R.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,R.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}function Si({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`,y=n.manualCodeState===`waiting`;(0,_.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,_.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let b=(0,_.useCallback)(()=>{c.current&&=(clearInterval(c.current),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),x=(0,_.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),S=(0,_.useCallback)(async()=>{x();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-auth-url`,authUrl:``}),b(),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,x,r,b]);(0,_.useEffect)(()=>(a.current=!0,()=>{x(),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}),b(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,x,r,b]);let C=(0,_.useCallback)((e,t)=>{h.current=e,g.current=t},[]),w=(0,_.useCallback)(()=>{n.step===`oauth-waiting`&&S(),g.current()},[n.step,S]),T=(0,_.useCallback)(async n=>{x(),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 y=await ct(v,i(`modal.networkError`));if(!a.current||!y)return;if(y.url){d.current=y.flowId??null,r({type:`set-flow-id`,flowId:y.flowId??null}),r({type:`set-auth-url`,authUrl:y.url}),r({type:`set-step`,step:`oauth-waiting`}),b();let n=y.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=setInterval(async()=>{if(s.current||v.signal.aborted)return;s.current=!0;let e=AbortSignal.any([v.signal,AbortSignal.timeout(1e4)]);try{let n=await lt(await fetch(_,{signal:e}));if(!a.current||v.signal.aborted)return;if(!n){o.current+=1,o.current>=3&&r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthStatusRetrying`),statusTone:`warn`});return}if(o.current=0,f.current===`waiting`?r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}):r({type:`set-status-notice`,statusNotice:``,statusTone:`ok`}),n.status===`done`){if(b(),x(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(),g.current()}else(n.status===`error`||n.status===`expired`)&&(b(),x(),d.current=null,r({type:`set-flow-id`,flowId:null}),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:n.error??i(`codexAuth.loginFailed`)})))}catch(e){if(!a.current||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{s.current=!1}},2e3),l.current=setTimeout(()=>{c.current&&(x(),S(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},3e5)}y.error&&!y.url&&r({type:`set-error`,error:y.error})}catch(e){a.current&&!(e instanceof Error&&e.name===`AbortError`)&&r({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[e,S,x,r,t,b,i]);return(0,_.useEffect)(()=>{if(!t){m.current=null;return}m.current!==t&&(m.current=t,T())},[t,T]),{manualCodeBusy:v,manualCodeWaiting:y,bindCallbacks:C,closeModal:w,startOAuth:T,submitManualCode:(0,_.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(!(!t||!s||v||y)){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,y,i,n.manualCode])}}function Ci({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=K(),[a,o]=(0,_.useReducer)(gi,r,hi),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=Si({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,R.jsx)(`dialog`,{ref:c,"aria-label":i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`),className:`modal-overlay`,onCancel:h,children:(0,R.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,R.jsx)(_i,{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,R.jsx)(xi,{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 wi=1e4;function Y(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Ti(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Ei(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Di(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Oi(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function ki(e,t,n){if(e<=0){let t=Ei(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Ti(t)??Ei(0,n)}}async function Ai(e,t,n=(e,t)=>fetch(e,t),r=wi){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 ji=3e4,Mi=new Map;function Ni(e,t=!0){let n=Mi.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,y]=(0,_.useState)(()=>n!=null),[b,x]=(0,_.useState)(0),S=(0,_.useRef)(new Set),C=(0,_.useRef)(null),w=(0,_.useRef)(0),T=(0,_.useRef)(null),E=(0,_.useRef)(new Set),D=(0,_.useRef)(null),O=(0,_.useRef)(null),k=(0,_.useRef)(!!n?.accounts.length),A=(0,_.useRef)(n!=null),j=(0,_.useRef)(null),M=(0,_.useCallback)(e=>(E.current.add(e),()=>{E.current.delete(e)}),[]),N=(0,_.useCallback)(()=>Oi(D.current?.value),[]),P=(0,_.useCallback)(()=>D.current?.value,[]),F=(0,_.useCallback)(async(t=!1)=>{let n=++w.current;g(e=>e+1);try{let r=[...E.current],a=new Map;for(let e of r)a.set(e,e.beginActiveRead());!t&&!A.current&&c(`loading`);let s=null,l,u=(async()=>{try{let r=await fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`);if(!r.ok)throw Error(`account load failed`);let a=await r.json();return w.current===n&&(s=a.accounts??[],i(s),k.current=s.length>0,A.current=!0,c(`ready`)),!0}catch{return!1}})(),d=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(w.current===n){let e=i.activeCodexAccountId??null,t=T.current;t&&e!==t.id||(T.current=null,l=e,o(e)),D.current={value:i};for(let e of r)e.acceptActiveRead(i,a.get(e))}return!0}catch{if(w.current===n)for(let e of r)e.rejectActiveRead();return!1}})(),[f,p]=await Promise.all([u,d]);if(w.current!==n)return!1;if(f){c(`ready`),A.current=!0;let t=Mi.get(e);return Mi.set(e,{accounts:s??t?.accounts??[],activeId:l===void 0?t?.activeId??null:l}),p}return A.current||c(`error`),!1}finally{g(e=>Math.max(0,e-1)),y(!0)}},[e]);(0,_.useEffect)(()=>{t&&C.current!==e&&(C.current=e,Promise.resolve().then(()=>{F()}))},[e,t,F]);let I=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!I||b>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{F(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,I,b,F]),(0,_.useEffect)(()=>{if(!t||b>0)return;let e=window.setInterval(()=>{F()},ji);return()=>window.clearInterval(e)},[t,F,b]);let L=(0,_.useCallback)(()=>{let e={};return S.current.add(e),x(S.current.size),e},[]),R=(0,_.useCallback)(e=>{S.current.delete(e)&&x(S.current.size)},[]),z=(0,_.useCallback)(async t=>{if(O.current)return{ok:!1,reason:`busy`};O.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 T.current={id:r??null},o(r??null),F(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{O.current=null,u(null)}},[e,F]),B=(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 F(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,F]),V=(0,_.useCallback)(async(t,n)=>{if(j.current)return{ok:!1,reason:`busy`};j.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;T.current={id:e},o(e)}return F(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{j.current=null,f(null)}},[e,F]),H=(0,_.useCallback)(async()=>{if(j.current)return{ok:!1,reason:`busy`};j.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;T.current={id:e},o(e)}return F(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{j.current=null,m(!1)}},[e,F]),U=(0,_.useCallback)(async t=>{try{return(await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(await F(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,F]),W=(0,_.useCallback)(async()=>await F()?{ok:!0}:{ok:!1,reason:`reload`},[F]),ee=a&&a!==`__main__`?r.find(e=>e.id===a):null,te=r.find(e=>e.isMain),ne=ee??te,re=!ne?.paused&&oi(ne);return{accounts:r,activeId:a,loadState:s,refreshing:h>0,initialLoading:!v,switchingId:l,pauseUpdatingId:d,pausingExhausted:p,activeNeedsReauth:re,load:F,switchAccount:z,setAccountPaused:V,pauseExhaustedAccounts:H,saveAlias:B,removeAccount:U,syncAfterAccountAdded:W,pauseRefresh:L,resumeRefresh:R,subscribeLoadObserver:M,readLastThreshold:N,readLastActive:P}}function Pi(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 Fi({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,R.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,R.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,R.jsx)(me,{width:10,height:10,"aria-hidden":`true`})}),(0,R.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,R.jsx)(he,{width:10,height:10,"aria-hidden":`true`})})]})}function Ii({threshold:e,draft:t,hydrated:n=!0,saving:r,loadError:i,feedback:a,onDraftChange:o,onEditingChange:s,onCommit:c,onCancel:l,onToggle:u,onRetry:d}){let f=K(),p=(0,_.useRef)(!1),m=e>0,h=r||!n,g=r?f(`common.saving`):a?.message??``,v=r?`pending`:a?.tone,y=g?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,R.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":r||!n&&!i||void 0,children:[(0,R.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,R.jsx)(`strong`,{children:f(`codexAuth.autoSwitch`)}),(0,R.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:i?`alert`:void 0,children:i?f(`codexAuth.autoSwitchLoadFailed`):m?f(`codexAuth.autoSwitchDesc`,{threshold:e}):f(`codexAuth.autoSwitchOffDesc`)})]}),(0,R.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(s(!1),p.current){p.current=!1;return}m&&!h&&c()}},children:[i&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:d,children:f(`pws.retryAccounts`)}),m&&(0,R.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:f(`codexAuth.autoSwitchThreshold`)}),(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,R.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:h,"aria-disabled":h,"aria-label":f(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":y,onChange:e=>o(e.target.value),onFocus:()=>{h||s(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||h||(e.key===`Enter`?(e.preventDefault(),c()):e.key===`Escape`&&(e.preventDefault(),l()))}}),(0,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,R.jsx)(Fi,{disabled:h,incrementLabel:f(`codexAuth.autoSwitchThresholdInc`),decrementLabel:f(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{s(!0),o(Pi(t,1,1,100))},onDecrement:()=>{s(!0),o(Pi(t,-1,1,100))}})]})]}),(0,R.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,R.jsx)(`button`,{type:`button`,className:`toggle ${m?`on`:``}`,onPointerDownCapture:()=>{p.current=!0},onPointerUp:()=>{p.current=!1},onPointerCancel:()=>{p.current=!1},onClick:()=>{p.current=!1,u()},disabled:h,"aria-pressed":m,"aria-label":f(`codexAuth.autoSwitch`),"aria-describedby":y,title:f(`codexAuth.autoSwitch`),children:(0,R.jsx)(`span`,{className:`toggle-knob`})})})]}),g&&(0,R.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${v===`err`?` is-error`:``}`,role:v===`err`?`alert`:`status`,"aria-atomic":`true`,children:g})]})}var Li=[`quota`,`round-robin`,`fill-first`],Ri=`quota`,zi=new Set(Li);function Bi(e){return typeof e==`string`&&zi.has(e)?e:Ri}function Vi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Hi(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function Ui(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:Bi(i.accountPoolStrategy??t.strategy),stickyLimit:Vi(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var Wi={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`};function Gi({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=K(),l=Li.map(e=>({value:e,label:c(Wi[e])}));return(0,R.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,R.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,R.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyHint`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,R.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,R.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,R.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,R.jsx)(Fi,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=Pi(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=Pi(t,-1,1,100);o(e),s(e)}})]})})]})]})}function Ki(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:Bi(t.accountPoolStrategy),stickyLimit:Vi(t.accountPoolStickyLimit)}}function qi({apiBase:e,subscribeLoadObserver:t,readLastActive:n}){let r=K(),[i,a]=(0,_.useState)(Ri),[o,s]=(0,_.useState)(1),[c,l]=(0,_.useState)(`1`),[u,d]=(0,_.useState)(!1),f=(0,_.useRef)(!1),[p,m]=(0,_.useState)(!1),h=(0,_.useRef)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(0),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(null),C=(0,_.useCallback)(e=>{let t=Bi(e.accountPoolStrategy),n=Vi(e.accountPoolStickyLimit);a(t),s(n),l(String(n)),f.current=!0,d(!0),b(!1),S(null)},[]),w=(0,_.useCallback)(e=>{let t=Ki(e);t&&C({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[C]),T=(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(h.current){g.current=!0;return}C(n)}catch{h.current||b(!0)}},[e,C]),E=(0,_.useCallback)(()=>{g.current&&(g.current=!1,queueMicrotask(()=>{if(h.current){g.current=!0;return}T()}))},[T]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>v.current,acceptActiveRead:(e,t)=>{if(t===v.current){if(h.current){g.current=!0;return}w(e)}},rejectActiveRead:()=>{f.current||b(!0)}});return!h.current&&n&&w(n()),e},[t,w,n]),(0,_.useEffect)(()=>{!n||t||h.current||w(n())},[n,w,t]),(0,_.useEffect)(()=>{t||T()},[T,t]);let D=(0,_.useCallback)(async t=>{if(h.current)return;let n=i,c=o;t.strategy!==void 0&&a(t.strategy),t.stickyLimit!==void 0&&(s(t.stickyLimit),l(String(t.stickyLimit))),h.current=!0,m(!0),S(null),v.current+=1;let u=await Ui(e,t);v.current+=1,u.ok?(a(u.strategy),s(u.stickyLimit),l(String(u.stickyLimit)),f.current=!0,d(!0)):(S(r(`accountPool.strategyUpdateFailed`)),a(n),s(c),l(String(c))),h.current=!1,m(!1),E()},[e,E,o,i,r]),O=p||y||!u;return(0,R.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":p||!u&&!y,children:[y&&(0,R.jsx)(`div`,{className:`card-sub`,role:`alert`,children:r(`accountPool.strategyLoadFailed`)}),y&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{T()},children:r(`common.retry`)}),!y&&(0,R.jsx)(Gi,{strategy:i,stickyDraft:c,disabled:O,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{O||e===i||D({strategy:e})},onStickyDraftChange:l,onStickyCommit:e=>{if(O)return;let t=Hi(e??c);if(t===null){l(String(o)),S(r(`accountPool.stickyLimitInvalid`));return}if(t===o){l(String(t));return}D({stickyLimit:t})}}),x&&(0,R.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:x})]})}function Ji(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=Oi(e),r=Di(v.current,y.current,t,x.current);r===`defer`?S.current=Y(n):r===`apply`&&T(Y(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(Y(Oi(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 Ai(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=Ti(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=ki(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 Yi=new Map;function Xi(e,t){return`${e??``}\0${JSON.stringify(t)}`}function Zi(e,t){let n=Xi(e,t??{}),r=Yi.get(n);return r||(r=new Intl.NumberFormat(e,t),Yi.set(n,r)),r}var Qi={month:`short`,day:`numeric`,year:`numeric`},$i={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},ea=new Map;function ta(e,t){let n=Xi(e,t),r=ea.get(n);return r||(r=new Intl.DateTimeFormat(e,t),ea.set(n,r)),r}function na(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:ta(t,Qi).format(n)}function ra(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:ta(t,$i).format(n)}function ia(e,t){return!Number.isFinite(e)||e<0?`—`:`~${Zi(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function aa(e,t){return na(e,t)}function oa(e,t){return ra(e,t)}function sa(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function ca({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=sa(n),s=o<=7;return(0,R.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,R.jsxs)(`div`,{className:`credit-item-head`,children:[(0,R.jsx)(Ce,{width:13}),(0,R.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,R.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,R.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,R.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:aa(t,i)})}),(0,R.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:oa(n,i),days:String(o)})})]})]})}function la({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,R.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,R.jsx)(Ce,{width:12}),`0`]}):r===void 0?null:(0,R.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,R.jsx)(Ce,{width:12}),r]})}function ua({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,R.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${Math.max(r.length,i.length,a.length)}ch`},children:o})}function da({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=K(),g=e=>!e.paused&&t===e.id;return(0,R.jsx)(R.Fragment,{children:e.map(e=>{let t=e.health?.status,_=!!e.needsReauth||ai(t),v=si(t),y=ui(h,e.health),b=di(h,`codex`,e.id,e.health);return(0,R.jsxs)(`div`,{className:`card ${g(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,R.jsxs)(`div`,{className:`card-head`,children:[(0,R.jsx)(`span`,{className:`dot ${_?`dot-amber`:g(e)?`dot-blue`:`dot-muted`}`}),(0,R.jsx)(`strong`,{children:e.alias??e.email}),(0,R.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,R.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,R.jsx)(`span`,{className:`badge badge-muted`,title:h(`codexAuth.pausedHint`),children:h(`codexAuth.paused`)}),(0,R.jsx)(la,{t:h,account:e,onClick:()=>a(e)}),y&&(0,R.jsx)(`span`,{className:ii(t),children:y}),_&&!y&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:h(`codexAuth.needsReauth`)}),g(e)&&!_&&!v&&(0,R.jsx)(`span`,{className:`badge badge-primary`,children:h(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!g(e)&&!_&&!v&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),_&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>u(e.id),children:h(`codexAuth.reauthenticate`)}),p&&ci(t)&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>p(e.id),children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:mi(h,m?.(e.id))})}),(0,R.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,R.jsx)(le,{width:14}):(0,R.jsx)(ce,{width:14}),(0,R.jsx)(ua,{t:h,paused:e.paused,saving:c===e.id})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void d(e),children:h(`prov.editAlias`)}),(0,R.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,R.jsx)(ae,{width:14})})]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,h(`prov.accountId`),`: `,ni(e.id)]}),b&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:b}),v&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:h(`pws.healthCooldownHint`)}),_?(0,R.jsx)(`div`,{className:`card-sub faint`,children:h(`codexAuth.tokenExpired`)}):!v&&(0,R.jsx)(Rr,{quota:e.quota,plan:e.plan,threshold:i,t:h,pending:e.quota==null})]},e.id)})})}function fa({onReauth:e}){let t=K();return(0,R.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,R.jsxs)(`span`,{children:[(0,R.jsx)(de,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function pa({className:e,style:t}){return(0,R.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function ma({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,R.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,R.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,R.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,R.jsx)(pa,{})},t))]})}function ha({children:e,busy:t=!0,live:n=!0,className:r}){return(0,R.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,R.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,R.jsx)(`span`,{children:e})]})}function ga({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,onCancel:i,onConfirm:a}){let o=K(),s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,R.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?o(`codexAuth.preparePoolTitle`):e.id===`__main__`?o(`codexAuth.switchBack`):o(`codexAuth.switchTitle`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?o(`codexAuth.preparePoolDesc`):e.id===`__main__`?o(`codexAuth.switchBackDesc`):o(`codexAuth.switchDesc`)}),(0,R.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,R.jsx)(`strong`,{children:e.id===`__main__`?t||o(`codexAuth.codexApp`):e.email}),e.plan&&(0,R.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,R.jsxs)(`div`,{className:`notice-warn`,children:[(0,R.jsx)(de,{width:14}),` `,o(`codexAuth.cacheWarning`)]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`codexAuth.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r,onClick:a,children:o(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function _a({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=G(),d=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,R.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,R.jsx)(`div`,{className:`confirm-icon`,children:(0,R.jsx)(de,{width:22})}),(0,R.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,R.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:aa(n[0].granted_at,l)})}),(0,R.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,R.jsx)(Ce,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,R.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,R.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,R.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,R.jsx)(ca,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,R.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,R.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function va({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||ai(t?.health?.status),_=si(t?.health?.status),v=ui(e,t?.health),y=t?di(e,`codex`,m,t.health):null;return(0,R.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,R.jsxs)(`div`,{className:`card-head`,children:[(0,R.jsx)(`span`,{className:`dot ${g?`dot-amber`:`dot-green`}`}),(0,R.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,R.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,R.jsx)(la,{t:e,account:{...t,id:`__main__`},onClick:()=>u({...t,id:`__main__`})}),t?.paused&&(0,R.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),v&&(0,R.jsx)(`span`,{className:ii(t?.health?.status),children:v}),g&&!v&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(h),children:a}),d&&ci(t?.health?.status)&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>d(m),children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:mi(e,f?.(m))})}),t&&(0,R.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,R.jsx)(le,{width:14}):(0,R.jsx)(ce,{width:14}),(0,R.jsx)(ua,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,R.jsxs)(`span`,{className:`card-right`,children:[(0,R.jsx)(Se,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),y&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:y}),_&&(0,R.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),g?(0,R.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!_&&(0,R.jsx)(Rr,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function ya({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,R.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,R.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,R.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,R.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,R.jsx)(ce,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,R.jsx)(se,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function ba({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,R.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,R.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,R.jsxs)(`div`,{className:`card-head`,children:[(0,R.jsx)(`span`,{className:`dot dot-muted`}),(0,R.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,R.jsxs)(`span`,{className:`card-badges`,children:[(0,R.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,R.jsx)(Ce,{width:12}),`0`]}),(0,R.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,R.jsx)(ce,{width:14}),` `,e(`codexAuth.pause`)]}),(0,R.jsxs)(`span`,{className:`card-right`,children:[(0,R.jsx)(Se,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,R.jsxs)(`div`,{className:`card-sub`,children:[(0,R.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,R.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,R.jsx)(Rr,{quota:null,threshold:0,t:e,pending:!0})]}),(0,R.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,R.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,R.jsx)(`div`,{className:`sep-line`}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,R.jsx)(oe,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,R.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,R.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,R.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,R.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,R.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function xa(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Sa(e,t,n,r){try{let i=await lt(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:xa(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 Ca=`ocx doctor`;function wa({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a}){let o=K(),s=Ji(e,{updated:o(`codexAuth.autoSwitchUpdated`),updateFailed:o(`codexAuth.autoSwitchUpdateFailed`),invalid:o(`codexAuth.autoSwitchThresholdInvalid`)}),{beginServerRead:c,acceptServerRead:l,rejectServerRead:u,hydrateServerValue:d}=s,f=Ni(e,!a),p=a??f,{accounts:m,activeId:h,loadState:g,switchingId:v,pauseUpdatingId:y,pausingExhausted:b,load:x}=p,{refreshing:S}=p,[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)(null),N=(0,_.useRef)(null),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(null),[ee,te]=(0,_.useState)(!1),ne=yi(),re=(0,_.useCallback)((e,t=!1)=>{N.current&&clearTimeout(N.current),A(e),M(t?`err`:`ok`),N.current=setTimeout(()=>{A(null),M(null),N.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let ie=(0,_.useCallback)(e=>{ne.copy(Ca,e)},[ne]),{subscribeLoadObserver:ae,readLastThreshold:se}=p;(0,_.useEffect)(()=>ae({beginActiveRead:c,acceptActiveRead:l,rejectActiveRead:u}),[ae,c,l,u]),(0,_.useEffect)(()=>{let e=se();e!==void 0&&d(e)},[se,d]),(0,_.useEffect)(()=>{if(!T)return;let e=p.pauseRefresh();return()=>p.resumeRefresh(e)},[p,T]);let ce=h&&h!==`__main__`?m.find(e=>e.id===h):null,le=!ce?.paused&&oi(ce);(0,_.useEffect)(()=>{i?.(le)},[le,i]);let ue=(0,_.useCallback)(e=>{O(e),E(!0)},[]),de=(0,_.useCallback)(()=>{E(!1),O(null)},[]),fe=(0,_.useCallback)(()=>{p.syncAfterAccountAdded(),re(o(`codexAuth.accountAdded`)),de()},[de,p,re,o]),pe=async e=>{let n=await p.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;re(o(`codexAuth.switchFailed`),!0);return}w(null);let r=n.activeId,i=r&&r!==`__main__`?m.find(e=>e.id===r)?.email??o(`pws.accountOrdinal`,{count:`1`}):o(`codexAuth.mainAccount`);re(o(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},me=async e=>{let t=window.prompt(o(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await p.saveAlias(e.id,t);re(o(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),!n.ok)},he=async e=>{let t=!e.paused,n=await p.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(w(t=>t?.id===e.id?null:t),re(o(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),!n.ok))},ge=async e=>{let t=m.find(t=>t.id===e)?.email??o(`pws.accountOrdinal`,{count:`1`});window.confirm(o(`codexAuth.removeConfirm`,{id:t}))&&((await p.removeAccount(e)).ok||re(o(`codexAuth.removeFailed`),!0))},_e=async()=>{F(!0);try{let e=await x(!0);re(o(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),!e)}finally{F(!1)}},ve=async()=>{let e=await p.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||re(e.ok?e.pausedCount>0?o(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):o(`codexAuth.pauseExhaustedNone`):o(`codexAuth.pauseExhaustedFailed`),!e.ok)},ye=async t=>{L(t),B(!1),W(null),te(!0);try{let n=await lt(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{te(!1)}},be=async t=>{H(!0);try{let n=await Sa(e,t,o,x);n.close&&(L(null),B(!1)),n.toast&&re(n.toast,!n.ok)}finally{H(!1)}},xe=m.find(e=>e.isMain),Se=m.filter(e=>!e.isMain),Ce=!xe?.paused&&(!h||h===`__main__`),we=o(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Te=y!==null||b,Ee=s.threshold??0;return(0,R.jsxs)(`div`,{children:[(0,R.jsx)(ya,{t:o,embedded:r,refreshingQuota:P,actionFeedback:k,actionFeedbackTone:j,pausingExhausted:b,pauseBusy:Te,onRefresh:()=>{_e()},onPauseExhausted:()=>{ve()}}),n,(0,R.jsx)(ba,{t:o,loadState:g,accountsCount:m.length,onRetry:()=>{x()}}),S&&m.length>0&&(0,R.jsx)(ha,{live:g!==`error`,children:o(`common.loading`)}),!(g===`loading`&&m.length===0)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(va,{t:o,main:xe,isMainActive:Ce,accountModeState:t,threshold:Ee,switchActionLabel:we,onSwitch:w,onTogglePause:he,pauseUpdatingId:y,pauseBusy:Te,onOpenReset:ye,onCopyDoctor:ie,doctorCopyOutcomeFor:ne.outcomeFor}),(0,R.jsxs)(`div`,{className:`section-sep`,children:[(0,R.jsx)(`span`,{className:`section-label`,children:o(`codexAuth.accountPool`)}),(0,R.jsx)(`div`,{className:`sep-line`}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>E(!0),children:[(0,R.jsx)(oe,{width:14}),` `,o(`codexAuth.add`)]})]}),le&&ce&&(0,R.jsx)(fa,{onReauth:()=>ue(ce.id)}),Se.length===0&&(0,R.jsx)(it,{title:o(`codexAuth.noPool`)}),(0,R.jsx)(da,{pool:Se,activeId:h,accountModeState:t,switchActionLabel:we,threshold:Ee,onOpenReset:ye,onSwitch:w,onTogglePause:he,pauseUpdatingId:y,pauseBusy:Te,onReauth:ue,onEditAlias:me,onRemove:ge,onCopyDoctor:ie,doctorCopyOutcomeFor:ne.outcomeFor})]}),(0,R.jsx)(Ii,{threshold:s.threshold,draft:s.draft,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(),x()}}),(0,R.jsx)(qi,{apiBase:e,subscribeLoadObserver:p.subscribeLoadObserver,readLastActive:p.readLastActive}),C&&(0,R.jsx)(ga,{confirm:C,mainEmail:xe?.email,accountModeState:t,switchingId:v,onCancel:()=>w(null),onConfirm:()=>{pe(C.id===`__main__`?`__main__`:C.id)}}),I&&(0,R.jsx)(_a,{resetPopup:I,resetConfirm:z,creditDetails:U,creditDetailsLoading:ee,redeeming:V,onClose:()=>{L(null),B(!1),W(null)},onShowConfirm:()=>B(!0),onCancelConfirm:()=>B(!1),onRedeem:()=>{be(I.id)}}),T&&(0,R.jsx)(Ci,{apiBase:e,reauthAccountId:D??void 0,onClose:de,onAdded:fe})]})}function Ta({apiBase:e,accountCount:t}){let n=K(),[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=Vi(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:Bi(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=Bi(r?.strategy??t.strategy),s=Vi(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,R.jsxs)(`div`,{className:`card`,style:{marginTop:12},"aria-busy":x||l,children:[(0,R.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,R.jsxs)(`div`,{style:{flex:1},children:[(0,R.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,R.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,R.jsxs)(`label`,{className:`toggle`,style:{display:`inline-flex`,alignItems:`center`,gap:8},children:[(0,R.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,R.jsx)(`span`,{children:n(g?`anthropicPool.on`:`anthropicPool.off`)})]})]}),(0,R.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,R.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`label`,{className:`field`,style:{display:`block`,marginTop:12},children:[(0,R.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,R.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,R.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,R.jsx)(Gi,{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=Hi(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,R.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}var Ea=`ocx doctor`,Da=4e3,Oa=[],ka=[];function Aa({item:e,apiBase:t,oauth:n,accounts:r=Oa,keys:i=ka,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d}){let f=K(),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(!1),S=yi(),C=yi();(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),Da);return()=>window.clearTimeout(e)},[r]);let w=Yr({...e,hasApiKey:e.hasApiKey||i.length>0}),T=w===`oauth-accounts`,E=w===`api-keys`;if(w===`codex-accounts`)return(0,R.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(`pws.availableAccounts`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:f(`pws.availableAccounts`)}),(0,R.jsx)(`div`,{className:`pwi-auth-body`,children:(0,R.jsx)(wa,{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,R.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(T?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:f(T?`pws.availableAccounts`:`pws.apiKeys`)}),(0,R.jsxs)(`div`,{className:`pwi-auth-body`,children:[T&&(0,R.jsxs)(R.Fragment,{children:[e.name===`anthropic`&&(0,R.jsx)(Ta,{apiBase:t,accountCount:r.length}),(0,R.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,R.jsx)(`span`,{className:`pwi-auth-dot ${N?`pwi-auth-dot--warn`:j?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,R.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,R.jsxs)(`span`,{className:`pwi-auth-actions`,children:[M&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:f(`prov.logout`)}):(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,R.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,R.jsx)(Se,{style:{width:13,height:13},"aria-hidden":`true`}),f(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),s&&D&&(0,R.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,R.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,R.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,R.jsx)(`div`,{className:`pwi-auth-wait-title`,children:f(`prov.waitingBrowser`)}),D.deviceCode&&(0,R.jsxs)(`div`,{className:`pwi-device-code-wrap`,children:[(0,R.jsx)(`span`,{children:f(`prov.deviceCode`)}),(0,R.jsx)(`code`,{className:`pwi-device-code`,children:D.deviceCode}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>S.copy(O,O),children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:A})})]}),(0,R.jsx)(bi,{url:D.url??``}),l.onCancelLogin&&(0,R.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,R.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,R.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),f(`pws.accountsLoading`)]}),a===`error`&&(0,R.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,R.jsx)(`span`,{children:f(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:f(`pws.retryAccounts`)})]}),r.length>0&&(0,R.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=Xr(r,t,f),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||ai(a),u=ci(a),d=si(a),p=ni(t.id),m=ui(f,t.health),h=di(f,e.name,t.id,t.health);return(0,R.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,R.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,R.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,R.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,R.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,R.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,R.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${f(`prov.accountId`)}: ${p}`].filter(Boolean).join(` · `)}),h&&(0,R.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:h}),d&&(0,R.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:f(`pws.healthCooldownHint`)})]}),m&&(0,R.jsx)(`span`,{className:ii(a),children:m}),c&&!m&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:f(`pws.reauth`)}),t.active&&(0,R.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)}),i&&(0,R.jsx)(`span`,{className:`badge badge-muted`,children:f(`pws.accountSwitching`)})]}),c&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{C.copy(Ea,t.id)},children:(0,R.jsx)(`span`,{"aria-live":`polite`,children:mi(f,C.outcomeFor(t.id))})}),(0,R.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,R.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,R.jsx)(ue,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||b&&t.quota==null)&&(0,R.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,R.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:f(`pws.accountQuotaUnavailable`)}):(0,R.jsx)(Rr,{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,R.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:f(`pws.noAccounts`)}),j&&(0,R.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,R.jsxs)(R.Fragment,{children:[i.length>0&&(0,R.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,R.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,R.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,R.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,R.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,R.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,f(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,R.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)})]}),(0,R.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,R.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,R.jsx)(ue,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),p?(0,R.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,R.jsx)(`input`,{className:`input`,type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:v}),(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m(!1),g(``)},children:f(`common.cancel`)})]}):(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>m(!0),children:f(`pws.addKey`)})]})]})]})}function ja(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 Ma(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 Na(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Pa=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],Fa=[];function Ia({item:e,availableModels:t=Fa,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=K(),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(Ma(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=>lt(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(Ma(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=[...Pa];return c&&!e.includes(c)&&e.unshift(c),e},[c]),z=_r(e.name),B=j===`ready`&&!!(k&&k.length>0),V=c.trim()===`anthropic`&&m===`key`,H=z&&j!==`error`,U=async()=>{if(!r)return O({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;let t=B?Na(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,liveModels:C};V?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)}},W=(0,_.useRef)(U);(0,_.useEffect)(()=>{W.current=U}),(0,_.useEffect)(()=>{if(a)return a(()=>W.current()),()=>a(null)},[a]);let ee=()=>{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(Ma(k,e.baseUrl))},te=(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,R.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,R.jsx)(Se,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,R.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),z?(0,R.jsx)(`input`,{className:`input`,value:c,readOnly:!0,disabled:!0}):(0,R.jsx)(`select`,{className:`input`,value:c,onChange:e=>l(e.target.value),children:L.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))})]}),B?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,R.jsx)(`select`,{className:`input`,value:N,onChange:e=>{let t=e.target.value;P(t),d(ja(k,t,u))},children:k.map(e=>(0,R.jsx)(`option`,{value:e.id,children:te(e.id,e.label)},e.id))})]}),N===`custom`&&(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,R.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,R.jsx)(`input`,{className:`input`,value:u,onChange:e=>d(e.target.value),readOnly:H,disabled:H})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),I.length>0?(0,R.jsxs)(`select`,{className:`input`,value:f,onChange:e=>p(e.target.value),children:[(0,R.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),I.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))]}):(0,R.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),z?(0,R.jsx)(`input`,{className:`input`,value:yr(e,o),readOnly:!0,disabled:!0}):(0,R.jsxs)(`select`,{className:`input`,value:m,onChange:e=>h(e.target.value),children:[(0,R.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,R.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,R.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,R.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),V&&(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,R.jsxs)(`select`,{className:`input`,value:g,onChange:e=>v(e.target.value),children:[(0,R.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,R.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,R.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:y,onChange:e=>b(e.target.value),rows:2})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,R.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,R.jsxs)(`span`,{children:[(0,R.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,R.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),F&&(0,R.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,R.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,R.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ee,disabled:T,children:o(`pws.discardSettings`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void U(),disabled:T,children:o(T?`pws.saving`:`pws.saveSettings`)})]})]}),D&&(0,R.jsx)(`div`,{className:D.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:D.text})]})}function La({providerName:e,onConfirm:t,onCancel:n}){let r=K();return(0,R.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,R.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":r(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{children:r(`pws.removeConfirmTitle`)}),(0,R.jsx)(`p`,{children:r(`pws.removeConfirmBody`,{name:e})}),(0,R.jsxs)(`div`,{className:`dialog-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:r(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:t,children:r(`pws.removeConfirm`)})]})]})})}function Ra({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=K();return(0,R.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,R.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,R.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,R.jsxs)(`div`,{className:`dialog-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function za({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}){let O=K(),[k,A]=(0,_.useState)(`overview`),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(null),[F,I]=(0,_.useState)(!1),L=(0,_.useRef)(null),z=(0,_.useCallback)(e=>{L.current=e},[]),B=e.disabled===!0,V=(0,_.useMemo)(()=>Un(e),[e]),H=(0,_.useMemo)(()=>Xn(e),[e]),U=(0,_.useMemo)(()=>Yr(e),[e]),W=(0,_.useMemo)(()=>[{id:`overview`,label:O(`pws.tab.overview`)},{id:`models`,label:O(`pws.tab.models`)},{id:`usage`,label:O(`pws.tab.usage`)},...U?[{id:`accounts`,label:O(U===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:O(`pws.tab.settings`)}],[U,O]),ee=(0,_.useCallback)(e=>{if(j&&k===`settings`&&e!==`settings`){P(e);return}A(e)},[k,j]),te=(0,_.useCallback)(()=>{if(j&&k===`settings`){P(`deselect`);return}d()},[j,k,d]),ne=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%W.length;else if(e.key===`ArrowLeft`)n=(t-1+W.length)%W.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=W.length-1;else return;e.preventDefault(),ee(W[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ee,W]),re=`pws-tab-${k}`,ie=`pws-panel-${k}`;return(0,R.jsxs)(`div`,{className:`pws-detail`,children:[(0,R.jsx)(`div`,{className:`pws-detail-head`,children:(0,R.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:te,children:[(0,R.jsx)(_e,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),O(`pws.allProviders`)]})}),(0,R.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,R.jsx)(xr,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,R.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,R.jsxs)(`h2`,{className:`pws-detail-title`,children:[gr(e.name),H&&(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:O(`modal.badge.local`)}),!H&&V&&(0,R.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:O(`modal.badge.free`)})]})}),(0,R.jsxs)(`div`,{className:`pws-detail-actions`,children:[E&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>E(e.name),"aria-label":O(`pws.removeConfirmTitle`),title:O(`pws.removeConfirmTitle`),children:(0,R.jsx)(ue,{style:{width:15,height:15},"aria-hidden":`true`})}),D&&(0,R.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,R.jsx)(`span`,{className:`pws-detail-toggle-label`,children:O(`pws.enabledLabel`)}),(0,R.jsx)(nt,{on:!B,onClick:()=>D(e.name,!B),disabled:T,label:O(`pws.enabledLabel`)})]})]})]}),(0,R.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:W.map((e,t)=>(0,R.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":k===e.id,tabIndex:k===e.id?0:-1,className:`pws-detail-tab${k===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ee(e.id),onKeyDown:e=>ne(e,t),children:e.label},e.id))}),(0,R.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:ie,"aria-labelledby":re,tabIndex:0,children:[k===`overview`&&(0,R.jsx)(Zr,{accountPanel:U?(0,R.jsx)(Aa,{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,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}),k===`models`&&(0,R.jsx)($r,{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),k===`usage`&&(0,R.jsx)(ei,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),k===`accounts`&&(0,R.jsx)(Aa,{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}),k===`settings`&&(0,R.jsx)(Ia,{item:e,apiBase:f,availableModels:i,onUpdateProvider:w,onDirtyChange:M,onRegisterSave:z},e.name)]}),N&&(0,R.jsx)(Ra,{saving:F,onCancel:()=>{F||P(null)},onDiscard:()=>{if(F)return;let e=N;P(null),M(!1),e===`deselect`?d():A(e)},onSave:()=>{(async()=>{if(!F){I(!0);try{if(!(await L.current?.()??!1))return;let e=N;P(null),M(!1),e===`deselect`?d():e&&A(e)}finally{I(!1)}}})()}})]})}var Ba=`https://chatgpt.com/backend-api/codex`;function Va(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 Ha(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 Ua(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Va(e.baseUrl)!==Ba?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function Wa(e){return e.id===`openai`}function Ga(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Ka(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return(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 qa(e,t){return Wa(e)?Ja(e):{name:t.name.trim(),provider:Ka(t)}}function Ja(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Ya=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function Xa(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 Ya(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Ya(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Ya(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ja(i))})).ok)throw new Ya(`codexAuth.enableOpenaiFailed`)}var Za=new Set([`anthropic`,`google-antigravity`]),Qa=new Set([`github-copilot`,`cursor`]);function $a(e){let t=e.trim().toLowerCase();return Za.has(t)?`high`:Qa.has(t)?`elevated`:null}function eo(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function to(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function no(e,t=!1){let n={};for(let[t,r]of Object.entries(e))oi(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function X(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=Xr(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=Xr(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)(()=>no(u,l),[u,l])}}function ro(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 io={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},ao=e=>io[e]??e;function oo({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:ao(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:ao(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 lt(a)??null:null;if(o){if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:ao(d)}):t(`prov.loginError`,{provider:ao(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:ao(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),_=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:ao(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),_=!0;break}l(t(`prov.loginOk`,{provider:ao(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:ao(d)}),!1),s(null))}catch{r.current.get(d)===v&&l(t(`prov.loginRequestFail`,{provider:ao(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:ao(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:ao(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:ao(n)}),!1)}}}}async function so(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function co({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l}){return{removeProvider:(0,_.useCallback)(async e=>{a(e)},[a]),confirmRemoveProvider:(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`});n.ok?(o(t(`prov.removed`,{name:d}),!0),r===d&&i(null),s(),c(),l(!0)):o(await so(n,f),!1)}catch{o(f,!1)}finally{n.current=!1}},[e,s,c,l,o,n,a,i,t,r]),setProviderDisabled:(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 i.json().catch(()=>({}))).error||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]),updateProvider:(0,_.useCallback)(async(t,n)=>{try{let r=await fetch(`${e}/api/providers?name=${encodeURIComponent(t)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});return r.ok?(await s(),{ok:!0}):{ok:!1,error:(await r.json().catch(()=>({}))).error||`Update failed`}}catch{return{ok:!1,error:`Network error`}}},[e,s])}}function lo({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await ct(await fetch(`${e}/api/config`));n(t??null),s&&t&&J(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await ct(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 lt(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function uo({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=K(),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=$a(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`:to(p),v=h===`anthropic`||h===`google-antigravity`;return(0,R.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,R.jsx)(`h3`,{id:a,children:i(eo(p),{provider:t})}),(0,R.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,R.jsx)(de,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,R.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,R.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,R.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,R.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,R.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 fo(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function po(e){return Wn(e.id,fo(e))}function mo(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[po(n)].push(n);return t}function ho(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}var go={},_o=[],vo={};function yo({presets:e,usageRank:t=go,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=_o,accountStatus:s=vo,busyProvider:c=null,onLogin:l,onCancelLogin:u,onLogout:d}){let f=K(),[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)(()=>mo(y),[y])[p],x=(0,_.useMemo)(()=>ho(b,h),[b,h]),S=e=>{let t=e.codexAccountMode===`direct`?(0,R.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,R.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.pool`)}):e.auth===`oauth`?(0,R.jsx)(`span`,{className:`badge badge-accent`,children:f(`modal.badge.oauth`)}):e.auth===`forward`?(0,R.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.codexLogin`)}):e.auth===`local`?(0,R.jsx)(`span`,{className:`badge badge-amber`,children:f(`modal.badge.local`)}):e.keyOptional?null:(0,R.jsx)(`span`,{className:`badge badge-muted`,children:f(`modal.badge.apiKey`)});return(0,R.jsxs)(R.Fragment,{children:[(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,R.jsx)(`span`,{className:`badge badge-green`,children:f(`modal.badge.free`)}):null,t]})};return(0,R.jsxs)(`div`,{className:`provider-catalog`,children:[(0,R.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,R.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,R.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:f(`modal.accountsHint`)}),(0,R.jsx)(`input`,{className:`input provider-catalog-search`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.search`)}),(0,R.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&x.length===0&&(0,R.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.catalogLoading`)}),p!==`accounts`&&x.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`title`,children:e.label}),(0,R.jsxs)(`div`,{className:`sub`,children:[(0,R.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,R.jsx)(`div`,{className:`provider-catalog-badges`,children:S(e)})]},e.id)),p!==`accounts`&&!n&&x.length===0&&(0,R.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,R.jsxs)(`div`,{className:`list-row provider-catalog-account-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`title`,children:e.label}),(0,R.jsx)(`div`,{className:`sub`,children:i})]}),(0,R.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,R.jsxs)(R.Fragment,{children:[r&&(0,R.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-auth`,children:f(`modal.accountManage`)}),l&&(0,R.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,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(e.id),children:f(`modal.accountLogout`)}):n?u&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:f(`common.cancel`)}):l&&(0,R.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,R.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:f(`modal.noMatch`)})]}),(0,R.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,R.jsx)(`div`,{style:{flex:1}}),p!==`accounts`&&(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:f(`modal.notListed`)})]})]})}function bo({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=K();return(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,R.jsx)(`div`,{className:`muted text-control`,children:e.note??h(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>u(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,R.jsx)(Se,{}),n?h(`modal.waitingBrowser`):h(`modal.logInWith`,{label:e.label})]}):(0,R.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,R.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,R.jsx)(bi,{url:a}),n&&(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,R.jsx)(`div`,{className:`muted text-label`,children:h(`prov.pasteRedirectHint`)}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,R.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,R.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,R.jsx)(`div`,{className:`text-label`,style:{color:l?`var(--accent-hover)`:`var(--amber)`},children:c})]}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:d,children:h(`modal.useApiKeyInstead`)}),(0,R.jsx)(`div`,{style:{flex:1}}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}function xo({label:e,children:t}){return(0,R.jsxs)(`label`,{style:{display:`block`},children:[(0,R.jsx)(`span`,{className:`field-label`,children:e}),t]})}function So({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=K();return(0,R.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,R.jsxs)(`details`,{className:`setup-guide`,children:[(0,R.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,R.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,R.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,R.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,R.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,R.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,R.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,R.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,R.jsx)(xo,{label:h(`modal.providerName`),children:(0,R.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,R.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(xo,{label:h(`modal.adapter`),children:(0,R.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,R.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(xo,{label:h(`modal.endpoint`),children:(0,R.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:ja(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,R.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,R.jsx)(xo,{label:h(`modal.baseUrl`),children:(0,R.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,R.jsx)(xo,{label:h(`modal.baseUrl`),children:(0,R.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,R.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,R.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,R.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,R.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,R.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,R.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,R.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,R.jsxs)(R.Fragment,{children:[e.dashboardUrl&&(0,R.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,R.jsx)(xe,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,R.jsx)(be,{style:{width:13,height:13}})]}),(0,R.jsx)(xo,{label:h(`modal.apiKey`),children:(0,R.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,R.jsx)(xo,{label:h(`modal.apiKeyTransport`),children:(0,R.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,R.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,R.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,R.jsx)(xo,{label:h(`modal.defaultModel`),children:(0,R.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,R.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,R.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,R.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,R.jsx)(`div`,{style:{flex:1}}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Co=2e3;function wo({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,Co)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await lt(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 To(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 Eo(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 Do({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=K(),m=(0,_.useMemo)(()=>[{id:`custom`,label:p(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[p]),[h,g]=(0,_.useReducer)(Eo,a,e=>To(e,p(`modal.customProvider`))),v=(0,_.useRef)(!0),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=F(`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=F(`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=F(`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}),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:I,oauthUrlProvider:L,manualCode:z,manualCodeBusy:B,manualCodeMsg:V,manualCodeOk:H,endpointChoice:U,oauthTosPending:W}=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`&&!W&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,W]);let ee=e=>{let t=Ga(e);return t?p(t):e.note},te=e=>{let t=Ma(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?ja(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},ne=async()=>{if(!k)return;let t=O?Wa(O):!1,n=O?.baseUrlChoices?.length?Na(O.baseUrlChoices,U,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=qa(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:re,submitManualCode:ie}=wo({apiBase:e,t:p,aliveRef:v,onAdded:r}),oe={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:V,ok:e})},se=k?t.includes(k.name.trim())&&k.name.trim()!==``:!1,ce=e=>{if(!M){if($a(e)){g({type:`set-oauth-tos-pending`,providerId:e});return}re(e,oe)}},le=e=>{ie(e,z,B,{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:V,ok:e}),setManualCodeMsg:e=>g({type:`set-manual-code-msg`,msg:e})})},ue=O?.id===`custom`,de=k?.authMode===`local`,fe=O?Wa(O):!1;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":p(`modal.add`),className:`modal-overlay`,onClick:n,children:(0,R.jsxs)(`div`,{ref:b,className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{children:O?p(`modal.addNamed`,{label:O.label}):p(`modal.add`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":p(`common.close`),onClick:n,children:(0,R.jsx)(ae,{})})]}),O?k&&(O.auth===`oauth`&&k.authMode===`oauth`?(0,R.jsx)(bo,{preset:O,oauthSupported:w,oauthBusy:M,oauthMsg:N,oauthMsgTone:P,oauthUrl:L===O.oauthProvider?I:``,manualCode:z,manualCodeBusy:B,manualCodeMsg:V,manualCodeOk:H,onRequestLogin:ce,onUseApiKeyInstead:()=>{g({type:`use-api-key-instead`,form:{...k,authMode:`key`}})},onManualCodeChange:e=>g({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{le(e)},onBack:()=>g({type:`back`})}):(0,R.jsx)(So,{preset:O,form:k,endpointChoice:U,error:j,saving:A,dup:se,isCustom:ue,isLocal:de,isReservedForward:fe,presetDescription:ee,onFormChange:e=>g({type:`set-form`,form:e}),onEndpointChoiceChange:e=>g({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{ne()},onUseOauthLogin:()=>g({type:`use-oauth-login`,form:{...k,authMode:`oauth`}}),onBack:()=>g({type:`back`})})):(0,R.jsx)(yo,{presets:T,usageRank:D,presetsLoading:E,initialTier:i,onSelectPreset:e=>te(e),onSelectCustom:()=>te(m[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:l,onCancelLogin:u,onLogout:d})]})}),W&&(0,R.jsx)(uo,{providerId:W,providerLabel:O?.label??W,onCancel:()=>g({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=W;e&&(g({type:`set-oauth-tos-pending`,providerId:null}),re(e,oe))}},W)]})}function Oo({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,removeConfirmName:s,codexLoginOpen:c,jsonLeaveOpen:l,jsonSaving:u,oauthTosPending:d,onCloseAdd:f,onAdded:p,onAccountLogin:m,onAccountCancelLogin:h,onAccountLogout:g,onOpenAdd:_,onCloseCodexLogin:v,onCodexAdded:y,onCancelRemove:b,onConfirmRemove:x,onCancelJsonLeave:S,onDiscardJson:C,onSaveJson:w,onCancelOauthTos:T,onContinueOauthTos:E}){return(0,R.jsxs)(R.Fragment,{children:[n&&(0,R.jsx)(Do,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:f,onAdded:p,accountRows:a,accountStatus:o,accountBusy:i,onAccountLogin:m,onAccountCancelLogin:h,onAccountLogout:g,onOpen:_}),c&&(0,R.jsx)(Ci,{apiBase:e,onClose:v,onAdded:y}),s&&(0,R.jsx)(La,{providerName:s,onCancel:b,onConfirm:x}),l&&S&&C&&w&&(0,R.jsx)(Ra,{saving:u??!1,onCancel:S,onDiscard:C,onSave:w}),d&&(0,R.jsx)(uo,{providerId:d.provider,providerLabel:ao(d.provider),onCancel:T,onContinue:E},`${d.provider}:${d.addAccount?`add`:`login`}`)]})}function ko(e,t){return[...Ha(e.providers).map(e=>({id:e,label:gr(e),kind:`codex`,href:`#codex-auth`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:ao(e),kind:`oauth`}))]}function Ao(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 jo({apiBase:e}){let t=K(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>sn(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),I=(0,_.useRef)(new Map),L=(0,_.useCallback)((e,t=!0)=>{c(e),u(t)},[]);(0,_.useEffect)(()=>(M.current=!0,()=>{M.current=!1}),[]),F(`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}),F(`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});let[z,B]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:V,fetchOauth:H,fetchProviderQuotas:U}=lo({apiBase:e,t,setConfig:i,setOauthProviders:f,setOauthStatus:m,notify:L,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{B(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),W=Ni(e),ee=W.activeNeedsReauth,te=(0,_.useMemo)(()=>{let e=W.accounts;if(e.length===0&&W.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}:{},...ee?{needsReauth:!0}:{}}}},[p,W.accounts,W.loadState,ee]),{accountSets:ne,accountLoadStates:re,switchingAccount:ie,keyPools:ae,fetchAccountSets:se,switchAccount:ce,switchApiKey:le,removeApiKey:ue,addApiKeyValue:de,editCredentialAlias:fe,removeAccount:pe,activeAccountNeedsReauth:me}=X({apiBase:e,t,config:r,oauthStatus:te,aliveRef:M,notify:L,fetchConfig:V,fetchOauth:H,fetchProviderQuotas:U,codexActiveNeedsReauth:ee}),{draft:he,setDraft:ge,jsonEditorOpen:_e,jsonSaving:ve,jsonLeaveOpen:ye,saveConfig:be,openJsonEditor:xe,discardJsonEditor:Se,requestCloseJsonEditor:Ce,restoreJsonEditor:we,jsonIsDirty:Te,setJsonLeaveOpen:Ee}=ro({apiBase:e,config:r,notify:L,fetchConfig:V,fetchProviderQuotas:U,onSaved:()=>k(e=>e+1),t});(0,_.useEffect)(()=>{N.current!==e&&(N.current=e,Promise.resolve().then(()=>{V(),H()}))},[e,V,H]);let De=()=>k(e=>e+1),{cancelLoginOAuth:Oe,loginOAuth:ke,logoutOAuth:Ae}=oo({apiBase:e,t,aliveRef:M,oauthLoginGenerationRef:I,accountSets:ne,setBusy:g,setStatus:c,setLoginInfo:y,setOauthStatus:m,notify:L,fetchConfig:V,fetchOauth:H,fetchAccountSets:se,fetchProviderQuotas:U,bumpModelsRefresh:De}),{removeProvider:je,confirmRemoveProvider:Me,setProviderDisabled:Ne,updateProvider:Pe}=co({apiBase:e,t,removeBusyRef:P,workspaceSelected:b,setWorkspaceSelected:x,setRemoveConfirmName:T,notify:L,fetchConfig:V,fetchOauth:H,fetchProviderQuotas:U}),Fe=(e,t=!1)=>{if(h!==e){if($a(e)){j({provider:e,addAccount:t});return}ke(e,t)}};if(!r)return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,R.jsx)(q,{tone:`err`,children:s}):(0,R.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,R.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,R.jsx)(`div`,{className:`providers-workspace-main`,children:(0,R.jsxs)(`p`,{className:`muted`,children:[(0,R.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let Ie=ko(r,d),Le=Ao(r,te),Re=e=>r.providers[e]?.authMode===`forward`;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:t(`nav.providers`)}),(0,R.jsx)(`div`,{className:`row`,children:(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,R.jsx)(oe,{}),t(`prov.add`)]})})]}),s&&(0,R.jsx)(q,{tone:l?`ok`:`err`,children:s}),(0,R.jsx)(qr,{onRemoveProvider:je,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:b,onSelect:x,onAddProvider:e=>{C(e??null),o(!0)},onEditConfig:xe,jsonEditor:{open:_e,draft:he,isDirty:Te,onDraftChange:ge,onSave:()=>be(),onClose:Ce,onRestore:we},jsonSaving:ve,modelsRefreshToken:O,activeAccountNeedsReauth:me,quotaRefreshEpoch:z.epoch,quotaForceRefresh:z.force,detail:(t,n)=>{let i=Le[t.name]??p[t.name];return(0,R.jsx)(za,{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:ne[t.name]?.accounts??[],keys:ae[t.name]??[],accountLoadState:re[t.name]??(t.authMode===`oauth`?`idle`:`ready`),switchingAccountId:ie?.provider===t.name?ie.accountId:null,busyProvider:h,loginHint:v,authHandlers:{onLogin:Fe,onCancelLogin:Oe,onLogout:Ae,onReauth:(e,t)=>ke(e,!0,t),onSwitchAccount:ce,onRemoveAccount:pe,onRetryAccounts:async e=>{await se([e])},onAddApiKey:de,onSwitchApiKey:le,onRemoveApiKey:ue,onEditAlias:fe},isDefault:t.name===r.defaultProvider,onRemoveProvider:je,onSetDisabled:Ne,onUpdateProvider:Pe,codexController:W},t.name)}}),(0,R.jsx)(Oo,{apiBase:e,config:r,adding:a,addIntent:S,busy:h,addModalAccountRows:Ie,accountLoginStatus:Le,removeConfirmName:w,codexLoginOpen:E,jsonLeaveOpen:ye,jsonSaving:ve,oauthTosPending:A,onCloseAdd:()=>{h&&Oe(h),o(!1),C(null)},onAdded:e=>{o(!1),C(null),L(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),V(),H(),U(!0),De()},onAccountLogin:async n=>{if(n===`openai`){if(h===`openai`)return;let n=r.providers.openai,i=Ua(n);if(i===`invalid`){L(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){g(`openai`);try{await Xa(e,i),await V()}catch(e){e instanceof Ya?L(t(e.i18nKey),!1):L(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{M.current&&g(e=>e===`openai`?null:e)}}D(!0);return}if(Re(n)){D(!0);return}(r.providers[n]?.authMode===`oauth`||d.includes(n))&&Fe(n)},onAccountCancelLogin:e=>{Oe(e)},onAccountLogout:e=>{Ae(e)},onOpenAdd:H,onCloseCodexLogin:()=>D(!1),onCodexAdded:()=>{D(!1),L(t(`prov.loginOk`,{provider:gr(`openai`),cmd:`ocx sync`}),!0),V(),H(),U(!0),De()},onCancelRemove:()=>T(null),onConfirmRemove:()=>{Me(w)},onCancelJsonLeave:()=>{ve||Ee(!1)},onDiscardJson:Se,onSaveJson:()=>{be()},onCancelOauthTos:()=>j(null),onContinueOauthTos:()=>{let e=A;e&&(j(null),ke(e.provider,e.addAccount))}})]})}var Mo={"gpt-5.6-sol":Te,"gpt-5.6-terra":Oe,"gpt-5.6-luna":Ee},No={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function Po(e){return e.slice(e.lastIndexOf(`/`)+1)}function Fo(e){return Mo[e]??Mo[Po(e)]??null}function Io(e){let t=Fo(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:No,"aria-hidden":!0}),e):e}var Lo=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function Ro(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...Lo];let r=new Set(Lo),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 Lo.filter(e=>a.has(e))}var zo=0;function Bo(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++zo}`}}var Vo=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Ho=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,Uo=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Wo(e){return Vo.test(e.trim())}function Go(e){return`combo/${e.trim()}`}function Ko(e,t){return(typeof t==`string`?t.trim():``)||Go(e)}function qo(e){return typeof e==`string`&&e.trim()?e.trim():null}function Jo(e){return e===`round-robin`?`round-robin`:`failover`}function Yo(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Xo(e){return typeof e==`string`&&Lo.includes(e)?e:null}function Zo(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Qo(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=Zo(t.weight);a.push(Bo(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():Ko(r,qo(t.alias)),alias:qo(t.alias),strategy:Jo(t.strategy),stickyLimit:Yo(t.stickyLimit),defaultEffort:Xo(t.defaultEffort),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function $o(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 es(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 ts(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 ns(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 rs(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 is(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Wo(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(!Ho.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&Uo.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 as(e=``){return{id:e,model:e?Go(e):`combo/`,alias:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,targets:[Bo()]}}function os(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 ss(e,t,n,r){let{isEmpty:i,...a}=r,o=F(e,t,n,a);return{...o,state:os(o,i,r.enabled!==!1)}}function cs(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 ls(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function us(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function ds(e){if(!ls(e))throw Error(`invalid selected models response`);let t=e.selected;if(!ls(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,us(t)]))}async function fs(e,t=fetch){let n=await t(`${e}/api/selected-models`);if(!n.ok)throw Error(`selected models HTTP ${n.status}`);return ds(await n.json())}function ps(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function ms(e,t,n,r,i){return ps(e,t,n,r)&&!i}async function hs(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 gs(e,t){return e===t}function _s(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 vs=Array.from({length:18},(e,t)=>1e5+t*5e4),ys=new Set(vs),bs=`custom`,xs=[4,8,16,32,64,128,256,500,1e3],Ss=new Set(xs),Cs=`ocx-models-collapsed:v2`,ws=`ocx-models-combos-open:v1`;function Ts(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function Es(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ds(e,t,n){let r=[];for(let i of e){let e=t.has(i.id)||t.has(i.namespaced);ms(n,i.provider,i.id,i.native===!0,e)&&r.push({value:i.namespaced,label:i.namespaced})}return r}function Os(e=localStorage){try{let t=e.getItem(Cs);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 ks(e,t=localStorage){try{t.setItem(Cs,JSON.stringify([...e]))}catch{}}function As(e=localStorage){try{return(e.getItem(`ocx-models-combos-open:v1`)??e.getItem(`ocx-models-combos-open`))===`1`}catch{return!1}}function js(e,t=localStorage){try{t.setItem(ws,e?`1`:`0`)}catch{}}function Ms({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=K(),i=e&&t?.status===`failed`?t:void 0;return(0,R.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,R.jsx)(fe,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,R.jsxs)(`span`,{children:[i&&n&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${_s(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,R.jsx)(`a`,{href:`#providers`,children:r(`models.openProviderSettings`)})]})]})}function Ns({apiBase:e}){let t=K(),n=`ocx.models.catalog.v1:${e}`,r=(0,_.useMemo)(()=>sn(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??{}),[y,b]=(0,_.useState)(()=>r?.contextCapValue??35e4),[x,S]=(0,_.useState)(``),[C,w]=(0,_.useState)(!1),T=Os(),[E,D]=(0,_.useState)(()=>T??new Set),O=(0,_.useRef)(T===null),[k,A]=(0,_.useState)(``),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),F=(0,_.useRef)(!1),L=(0,_.useRef)(0),z=(0,_.useRef)(!1),[B,V]=(0,_.useState)(null),[U,W]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(``),ne=(0,_.useRef)(!1),[re,ie]=(0,_.useState)(``),[ae,oe]=(0,_.useState)(!1),[se,ce]=(0,_.useState)(!1),[le,ue]=(0,_.useState)(!1),[de,pe]=(0,_.useState)(`add`),[me,he]=(0,_.useState)(``),[ge,ve]=(0,_.useState)(``),[ye,be]=(0,_.useState)(``),[xe,Se]=(0,_.useState)(``),[Ce,we]=(0,_.useState)(``),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)([`text`]),[ke,je]=(0,_.useState)(!1),[Me,Ne]=(0,_.useState)(``),[Pe,Fe]=(0,_.useState)(null),Ie=(0,_.useRef)(null),[Le,Re]=(0,_.useState)(null),[ze,Be]=(0,_.useState)(!1),[G,Ve]=(0,_.useState)(null),[He,Ue]=(0,_.useState)(!1),[We,Ge]=(0,_.useState)(As),[Ke,qe]=(0,_.useState)(null),Je=()=>{let e=!We;js(e),Ge(e)};(0,_.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await ct(await fetch(`${e}/api/combos`));t||(Ve(Qo(n)),Ue(!1))}catch{t||(Ve(null),Ue(!0))}})(),()=>{t=!0}},[e]),(0,_.useEffect)(()=>()=>{Ie.current&&clearTimeout(Ie.current)},[]);let Ye=(0,_.useMemo)(()=>Ds(i,c,u??{}),[i,c,u]),Xe=(0,_.useCallback)(async()=>{try{let t=await lt(await fetch(`${e}/api/shadow-call-settings`));t&&Re(t)}catch{}},[e]),Ze=(0,_.useCallback)(async()=>{if(!ne.current)try{let t=await fetch(`${e}/api/v2`);if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){V(null);return}let n=await lt(t);if(!n||typeof n.enabled!=`boolean`){V(null);return}V({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`})}catch{V(null)}},[e]),Qe=(0,_.useCallback)(async t=>{let[r,i,a,o]=await Promise.all([fetch(`${e}/api/models`),fetch(`${e}/api/provider-context-caps`),fetch(`${e}/api/providers`),fs(e)]),[s,c,l]=await Promise.all([ct(r),ct(i),ct(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=Es(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 J(n,p),p},[e,n]),$e=(0,_.useCallback)(e=>{let t=cs(e.models,e.providers);qe(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),b(e.contextCapValue),v(e.contextCaps)},[]),et=ss(n,[e],async e=>{let t=await Qe(e);if(e.aborted)throw Error(`models request aborted`);return $e(t),t},{isEmpty:()=>!1,pollMs:1e4}),tt=et.state,ot=et.refresh;(0,_.useLayoutEffect)(()=>{r&&(I(n,r),ot())},[n,r,ot]);let st=(0,_.useCallback)(async(e=!1)=>{if(z.current&&!e)return!1;z.current=!0;let t=++L.current;try{let e=await Qe(new AbortController().signal);return gs(t,L.current)?($e(e),I(n,e),!0):!1}catch{return!1}finally{gs(t,L.current)&&(z.current=!1)}},[$e,n,Qe]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{Xe(),Ze()},0),t=window.setInterval(()=>{ne.current||Ze()},1e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[Xe,Ze]);let ut=(0,_.useMemo)(()=>cs(i,o),[i,o]);(0,_.useEffect)(()=>{if(!O.current||ut.length===0)return;O.current=!1;let e=new Set(ut.map(e=>e.provider));D(e),ks(e)},[ut]);let dt=(0,_.useMemo)(()=>u?i.filter(e=>ms(u,e.provider,e.id,e.native===!0,c.has(e.namespaced))).length:0,[c,i,u]),ft=async(n,r,i,a)=>{++L.current,P(!0),F.current=!0,A(``);let o=null;try{(await hs(e,n,r,i,a)).ok||(o=`models.saveFailed`)}catch{o=`models.networkError`}finally{let e=await st(!0);o?(M(!1),A(t(o))):e&&(M(!0),A(t(`models.applied`))),P(!1),F.current=!1}},pt=async n=>{P(!0),F.current=!0,A(``);let r=g[n]!==y;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 ct(i,t(`models.capSaveFailed`)))?.caps??{}),M(!0),A(t(`models.capApplied`)),await st(!0)}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{P(!1),F.current=!1}},mt=e=>{D(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),ks(n),n})},ht=e=>{D(()=>{let t=e?new Set(ut.map(e=>e.provider)):new Set;return ks(t),t})},gt=async n=>{P(!0),F.current=!0,A(``);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 ct(r,t(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&b(e.value),v(e?.caps??{}),M(!0),A(t(`models.capApplied`)),await st(!0)}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.capSaveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{P(!1),F.current=!1}},_t=e=>{!Number.isFinite(e)||e<=0||gt({value:Math.floor(e)})},vt=e=>{if(e===`custom`){w(!0),S(String(y));return}w(!1);let t=Number(e);Number.isFinite(t)&&t>0&&t!==y&&_t(t)},yt=()=>{let e=Number(x.replace(/[_,\s]/g,``));if(!Number.isFinite(e)||e<=0){M(!1),A(t(`models.capSaveFailed`));return}w(!1),_t(e)},bt=(0,_.useMemo)(()=>{let e=ut.filter(e=>!e.native&&e.rows.length>0);return e.length>0&&e.every(e=>g[e.provider]===y)},[ut,g,y]),xt=()=>{gt({setAll:!bt})},St=async t=>{if(!(!Le||ze)){Be(!0),Re({...Le,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Be(!1)}}},Ct=async n=>{if(!(!B||ne.current)&&B.multiAgentMode!==n){W(!0),ne.current=!0,te(``),A(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:n})});try{let e=await ct(r,t(`models.saveFailed`));Ze(),M(!0),A(t(`models.v2Applied`)),te((e?.warnings??[]).join(` `))}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{W(!1),ne.current=!1}}},wt=async n=>{if(!(!B||ne.current)){if(!Number.isInteger(n)||n<1){M(!1),A(t(`models.v2ThreadsInvalid`));return}if(B.maxConcurrentThreadsPerSession!==n){W(!0),ne.current=!0,te(``),A(``);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await ct(r,t(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){M(!1),A(t(`models.saveFailed`));return}V({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`}),M(!0),A(t(`models.v2ThreadsApplied`)),oe(!1)}catch(e){M(!1),A(e instanceof Error?e.message:t(`models.saveFailed`))}}catch{M(!1),A(t(`models.networkError`))}finally{W(!1),ne.current=!1}}}},Tt=e=>{if(e===`custom`){oe(!0),ie(String(B?.maxConcurrentThreadsPerSession??``));return}oe(!1),wt(Number(e))},Et=(e,t)=>{Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{Fe({namespaced:e,rect:t.getBoundingClientRect()})},300)},kt=(e,t)=>{Ie.current&&clearTimeout(Ie.current),Fe({namespaced:e,rect:t.getBoundingClientRect()})},At=()=>{Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>Fe(null),120)},jt=()=>{Ie.current&&clearTimeout(Ie.current)},Mt=async(n,r,i,a,o)=>{je(!0),Ne(``);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 ct(s,t(`models.customSaveFailed`)),ue(!1),M(!0),A(t(`models.customAdded`)),await st(!0)}catch(e){Ne(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Ne(t(`models.networkError`))}finally{je(!1)}},Nt=async(n,r)=>{je(!0),Ne(``);try{let i=await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});try{await ct(i,t(`models.customSaveFailed`)),ue(!1),M(!0),A(t(`models.customUpdated`)),await st(!0)}catch(e){Ne(e instanceof Error?e.message:t(`models.customSaveFailed`))}}catch{Ne(t(`models.networkError`))}finally{je(!1)}},Pt=async n=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(n)}`,{method:`DELETE`})).ok?(M(!0),A(t(`models.customDeleted`)),await st(!0)):(M(!1),A(t(`models.customSaveFailed`)))}catch{M(!1),A(t(`models.networkError`))}},Ft=tt.data??r;if(tt.showSkeleton&&!Ft)return(0,R.jsx)(ma,{label:t(`models.loading`),rows:5});if(tt.kind===`failed-cold`)return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:tt.error instanceof Error?tt.error.message:t(`models.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>et.refresh(),children:t(`common.retry`)})]});let It=u??{},Lt=e=>{let{provider:n,rows:r,native:i,liveModels:a,discovery:o}=e,s=E.has(n),l=e=>ms(It,n,e.id,e.native===!0,c.has(e.namespaced)),u=r.filter(l).length,d=g[n]===y,_=i,v=a&&o?.status===`failed`?o:void 0,b=(f[n]??``).trim().toLowerCase(),x=b?r.filter(e=>e.id.toLowerCase().includes(b)):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,D=r.length>0,O=!D||r.every(l),k=!D||r.every(e=>!l(e)),A=e=>{D&&ft(`provider`,n,r.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,R.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,R.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>mt(n),"aria-expanded":!s,style:{flex:1,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,R.jsx)(_e,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,R.jsx)(`span`,{className:`text-body font-semibold`,children:n}),_&&(0,R.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.nativeGroupLabel`)}),v&&(0,R.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:_s(t,v),children:t(`models.discoveryFailedBadge`)}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:u,total:r.length})})]}),(0,R.jsxs)(`div`,{className:`row models-provider-actions`,children:[!_&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),pe(`add`),he(n),ve(``),be(``),Se(``),we(``),Ee(!1),Oe([`text`]),Ne(``),ue(!0)},"aria-label":t(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:N||O,onClick:()=>A(!0),children:t(`models.allOn`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:N||k,onClick:()=>A(!1),children:t(`models.allOff`)}),!_&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(nt,{on:d,onClick:()=>pt(n),disabled:N,label:t(`models.capValue`,{value:Ts(y)})}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.capValue`,{value:Ts(y)})})]})]})]}),!s&&(0,R.jsxs)(`div`,{className:`models-provider-body`,children:[_&&(0,R.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:t(`models.nativeHint`)}),r.length===0&&(0,R.jsx)(Ms,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>60/2&&(0,R.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,R.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Et(e.namespaced,t.currentTarget),onMouseLeave:At,onFocus:t=>kt(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||Fe(null)},children:[(0,R.jsxs)(`div`,{className:`row models-model-row`,children:[(0,R.jsx)(nt,{on:!r,onClick:()=>void ft(`models`,n,[{id:e.id,native:e.native===!0}],r),disabled:N,label:e.native?e.id:e.namespaced}),(0,R.jsx)(`code`,{className:`mono text-control`,style:{color:r?`var(--faint)`:`var(--text)`,textDecoration:r?`line-through`:`none`},children:e.native?Io(e.id):e.namespaced}),e.custom&&(0,R.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.customBadge`)}),e.contextCapped&&(0,R.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:t(`models.contextCappedValue`,{value:Ts(e.contextCap??y)})})]}),Pe?.namespaced===e.namespaced&&(()=>{let n=Pe.rect,i=n.bottom+4,a=i+360>window.innerHeight;return(0,R.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:jt,onMouseLeave:At,children:[(0,R.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,R.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,R.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:t(`models.customBadge`)}),(0,R.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipProvider`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:e.provider}),(e.contextWindow||e.contextCap)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipContext`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:Ts(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipModalities`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,R.jsx)(`span`,{className:`model-tip-key`,children:t(`models.tipStatus`)}),(0,R.jsx)(`span`,{className:`model-tip-val`,children:t(r?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,R.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{pe(`edit`),he(e.provider),ve(e.customId),be(e.id),Se(e.displayName??``),we(e.contextWindow?String(e.contextWindow):``),Ee(!1),Oe(e.inputModalities??[`text`]),Ne(``),ue(!0),Fe(null)},children:t(`models.customEdit`)}),(0,R.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}))&&Pt(e.customId),Fe(null)},children:t(`models.customDelete`)})]})]})})()]},e.namespaced)}),T>0&&(0,R.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)},Rt=Ke?ut.filter(e=>e.provider===Ke):ut,zt=(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`models-control-top-row`,children:[(0,R.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!Le||void 0,children:[(0,R.jsxs)(`span`,{className:`models-shadow-label`,children:[t(`models.shadowCallIntercept`),` `,(0,R.jsx)(at,{content:t(`models.shadowCallInterceptHint`,{models:Dt(Le?.sourceModels)}),side:`top`,maxWidth:320,children:(0,R.jsx)(`span`,{style:{cursor:`help`},"aria-label":t(`models.shadowCallInterceptHint`,{models:Dt(Le?.sourceModels)}),children:`ⓘ`})})]}),(0,R.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:t(`models.shadowCallOriginal`,{models:Ot(Le?.sourceModels)})}),(0,R.jsx)(nt,{on:Le?.enabled??!1,onClick:()=>void St({enabled:!Le?.enabled}),disabled:!Le||ze,label:t(`models.shadowCallIntercept`)}),(0,R.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,R.jsx)(rt,{value:Le?.model??``,options:[{value:``,label:`—`},...Ye],onChange:e=>{Re(t=>t&&{...t,model:e}),St({model:e})},disabled:!Le||ze||!Le.enabled,label:t(`models.shadowCallIntercept`)})})]}),B&&(0,R.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2Label`)}),(0,R.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":t(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,R.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(B.multiAgentMode??`default`)===e,className:`btn btn-sm${(B.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(B.multiAgentMode??`default`)===e?void 0:`transparent`,color:(B.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:U,onClick:()=>void Ct(e),children:t(`models.v2Mode_${e}`)},e))}),(0,R.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:()=>ce(!0),"aria-label":t(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,R.jsx)(fe,{width:14,height:14,"aria-hidden":`true`})})]})]}),B&&(B.enabled||B.agentsMaxThreadsConflict||ee)&&(0,R.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[B.enabled&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`models.v2ThreadsLabel`)}),(0,R.jsx)(rt,{value:ae?`custom`:B.maxConcurrentThreadsPerSession!==null&&B.maxConcurrentThreadsPerSession!==void 0?Ss.has(B.maxConcurrentThreadsPerSession)?String(B.maxConcurrentThreadsPerSession):`custom`:``,options:[...B.maxConcurrentThreadsPerSession===null||B.maxConcurrentThreadsPerSession===void 0?[{value:``,label:t(`models.v2ThreadsDefault`)}]:[],...B.maxConcurrentThreadsPerSession!==null&&B.maxConcurrentThreadsPerSession!==void 0&&!Ss.has(B.maxConcurrentThreadsPerSession)&&!ae?[{value:`custom`,label:String(B.maxConcurrentThreadsPerSession)}]:[],...xs.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:t(`models.custom`)}],onChange:e=>Tt(e),disabled:U,label:t(`models.v2ThreadsLabel`)}),ae&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:re,onChange:e=>ie(e.target.value),onKeyDown:e=>{e.key===`Enter`&&wt(Number(re.replace(/[_,\s]/g,``)))},disabled:U,"aria-label":t(`models.v2ThreadsLabel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:U,onClick:()=>{wt(Number(re.replace(/[_,\s]/g,``)))},children:t(`models.v2ThreadsApply`)})]})]}),B.enabled&&B.agentsMaxThreadsConflict&&(0,R.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:t(`models.v2Conflict`)}),ee&&(0,R.jsx)(`span`,{className:`muted text-label`,children:ee})]}),(0,R.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`models.contextCapLabel`)}),(0,R.jsx)(rt,{value:C?bs:ys.has(y)?String(y):bs,options:[...!ys.has(y)&&!C?[{value:String(y),label:Ts(y)}]:[],...vs.map(e=>({value:String(e),label:Ts(e)})),{value:bs,label:t(`models.custom`)}],onChange:e=>vt(e),disabled:N,label:t(`models.contextCapLabel`)}),C&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:t(`models.customPlaceholder`),value:x,onChange:e=>S(e.target.value),onKeyDown:e=>{e.key===`Enter`&&yt()},disabled:N,"aria-label":t(`models.customPlaceholder`)}),(0,R.jsx)(`button`,{type:`button`,onClick:yt,disabled:N,className:`btn btn-ghost btn-sm`,children:t(`models.customApply`)})]}),(0,R.jsx)(nt,{on:bt,onClick:xt,disabled:N,label:t(`models.setAll`)}),(0,R.jsx)(`span`,{className:`muted text-label leading-body`,children:t(`models.setAllHint`,{value:Ts(y)})})]}),(()=>{let e=i.filter(e=>e.custom).length;return e===0?null:(0,R.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,R.jsx)(`span`,{className:`models-chip mono text-caption`,children:t(`models.customSummary`,{count:e})})})})(),(0,R.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,R.jsx)(fe,{width:15,height:15,"aria-hidden":`true`}),(0,R.jsx)(`span`,{children:t(`models.orderHint`)})]})]}),Bt=(0,R.jsxs)(R.Fragment,{children:[G!==null&&!He&&G.length===0&&(0,R.jsx)(`div`,{className:`card models-combos-card`,children:(0,R.jsxs)(`div`,{className:`row models-combos-empty-head`,children:[(0,R.jsxs)(`div`,{className:`row models-field-row`,style:{minWidth:0},children:[(0,R.jsx)(Ae,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,R.jsx)(`strong`,{children:t(`nav.combos`)}),(0,R.jsx)(`span`,{className:`muted text-label`,children:t(`models.combosEmpty`)})]}),(0,R.jsx)(`a`,{className:`btn btn-sm`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]})}),G!==null&&!He&&G.length>0&&(0,R.jsxs)(`div`,{className:`card models-combos-card`,children:[(0,R.jsxs)(`div`,{className:`row group-head models-field-row${We?` open`:``}`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`row models-field-row`,"aria-expanded":We,onClick:Je,style:{flex:1,background:`none`,border:`none`,padding:0,cursor:`pointer`,font:`inherit`,color:`inherit`,textAlign:`left`,minWidth:0},children:[(0,R.jsx)(_e,{style:{width:14,height:14,color:`var(--muted)`,flexShrink:0,transform:We?`rotate(90deg)`:`none`,transition:`transform .12s`}}),(0,R.jsx)(Ae,{width:14,height:14,"aria-hidden":`true`,style:{flexShrink:0}}),(0,R.jsx)(`strong`,{children:t(`nav.combos`)}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.combosActive`,{count:G.length})})]}),(0,R.jsx)(`a`,{className:`btn btn-sm btn-ghost`,href:`#combos`,style:{flexShrink:0},children:t(`models.combosSetup`)})]}),We&&(0,R.jsxs)(`div`,{children:[G.map(e=>(0,R.jsxs)(`div`,{className:`row models-combo-row`,children:[(0,R.jsx)(`span`,{className:`mono leading-ui`,children:e.model}),(0,R.jsxs)(`span`,{className:`muted text-label`,children:[e.strategy,` · `,e.targets.length]})]},e.id)),(0,R.jsxs)(`a`,{className:`row muted models-combos-add`,href:`#combos`,children:[`+ `,t(`models.combosAdd`)]})]})]})]}),Vt=(0,R.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ht(!0),disabled:N,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>ht(!1),disabled:N,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),Ht=(0,R.jsx)(R.Fragment,{children:ut.length===0&&(0,R.jsx)(it,{icon:(0,R.jsx)(H,{}),title:t(`models.noRouted`),children:t(`models.noRoutedHint`)})}),Ut=(0,R.jsxs)(R.Fragment,{children:[se&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.v2Label`),onClick:()=>ce(!1),onKeyDown:e=>{e.key===`Escape`&&ce(!1)},children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{children:t(`models.v2Label`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ce(!1),"aria-label":t(`common.close`),children:`×`})]}),(0,R.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,R.jsx)(`div`,{className:`models-help-link`,children:(0,R.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,R.jsx)(`div`,{className:`modal-actions`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>ce(!1),children:t(`common.ok`)})})]})}),le&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`models.customAdd`),onClick:()=>{ke||ue(!1)},onKeyDown:e=>{e.key===`Escape`&&!ke&&ue(!1)},children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsx)(`h3`,{children:t(de===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:me})}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ue(!1),disabled:ke,"aria-label":t(`common.close`),children:`×`})]}),Me&&(0,R.jsx)(q,{tone:`err`,children:Me}),(0,R.jsxs)(`div`,{className:`models-field-stack`,children:[(0,R.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldModelId`),(0,R.jsx)(`input`,{className:`input`,value:ye,onChange:e=>be(e.target.value),disabled:ke,placeholder:t(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,R.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldDisplayName`),(0,R.jsx)(`input`,{className:`input`,value:xe,onChange:e=>Se(e.target.value),disabled:ke,placeholder:t(`models.customFieldDisplayNamePlaceholder`)})]}),(0,R.jsxs)(`label`,{className:`text-label models-field`,children:[t(`models.customFieldContext`),(0,R.jsxs)(`div`,{className:`row models-field-row`,children:[(0,R.jsx)(rt,{value:Te?`custom`:Ce,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`){Ee(!0);return}Ee(!1),we(e)},disabled:ke,label:t(`models.customFieldContext`)}),Te&&(0,R.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:Ce,onChange:e=>we(e.target.value),disabled:ke,placeholder:t(`models.customPlaceholder`),"aria-label":t(`models.customFieldContext`)})]})]}),(0,R.jsxs)(`div`,{className:`text-label models-field`,children:[t(`models.customFieldModalities`),(0,R.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,R.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:De.includes(e),onChange:t=>{Oe(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:ke}),(0,R.jsx)(`span`,{className:`text-control`,children:e})]},e))})]})]}),(0,R.jsxs)(`div`,{className:`modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ue(!1),disabled:ke,children:t(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:ke||!ye.trim(),onClick:()=>{let e=ye.trim(),t=xe.trim(),n=Ce?Number(Ce.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;de===`add`?Mt(me,e,t||void 0,r,De.length>0?De:void 0):Nt(ge,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:De})},children:t(ke?`models.customSaving`:de===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]});return(0,R.jsxs)(`div`,{className:`models-workspace-shell`,children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:t(`nav.models`)}),(0,R.jsx)(`div`,{className:`row`,children:(0,R.jsx)(`span`,{className:`muted mono text-label`,children:t(`models.active`,{active:dt,total:i.length})})})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`models.subtitle`)}),k&&(0,R.jsx)(q,{tone:j?`ok`:`err`,children:k}),tt.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`models.loadFail`)}),tt.refreshing&&(0,R.jsx)(ha,{live:!tt.showError,children:t(`models.loading`)}),(0,R.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":tt.refreshing||void 0,children:[(0,R.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":t(`nav.models`),children:[(0,R.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,R.jsx)(`span`,{className:`models-workspace-rail-title`,children:t(`models.workspace.providers`)}),(0,R.jsx)(`span`,{className:`models-workspace-rail-count`,children:ut.length})]}),(0,R.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,R.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ke===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>qe(null),"aria-current":Ke===null?`true`:void 0,children:[(0,R.jsx)(`span`,{className:`models-workspace-rail-name`,children:t(`models.workspace.allProviders`)}),(0,R.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:dt,total:i.length})})]}),ut.map(e=>{let{provider:n,rows:r}=e,i=r.filter(e=>ms(It,n,e.id,e.native===!0,c.has(e.namespaced))).length;return(0,R.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ke===n?` models-workspace-rail-row--selected`:``}`,onClick:()=>qe(n),"aria-current":Ke===n?`true`:void 0,children:[(0,R.jsx)(`span`,{className:`models-workspace-rail-name`,children:n}),(0,R.jsx)(`span`,{className:`models-workspace-rail-meta`,children:t(`models.active`,{active:i,total:r.length})})]},n)})]})]}),(0,R.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":t(`models.workspace.mainAria`),children:[zt,Bt,Vt,(0,R.jsx)(`div`,{className:`models-provider-list`,children:Rt.map(e=>Lt(e))}),ut.length===0&&Ht]})]}),Ut]})}function Ps(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function Fs(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function Is(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 Ls(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||Is(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 Rs({value:e,onChange:t,disabled:n}){let r=K();return(0,R.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,R.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 zs({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=K(),o=i??Lo,s=t!==null&&!o.includes(t);return(0,R.jsxs)(R.Fragment,{children:[(0,R.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,R.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,R.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))]}),s?(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function Bs({targets:e,strategy:t,providers:n,models:r,onChange:i}){let a=K(),o=Ps(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,R.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,_=Ls(r,p.provider,n),v=p.model&&!_.includes(p.model)?[p.model,..._]:_,y=!p.provider;return(0,R.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,R.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,R.jsx)(je,{width:14,height:14,"aria-hidden":`true`})}),(0,R.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,R.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,R.jsx)(me,{width:14,height:14,"aria-hidden":`true`})}),(0,R.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,R.jsx)(he,{width:14,height:14,"aria-hidden":`true`})})]}),(0,R.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:Ls(r,t,n)[0]??``})},children:[(0,R.jsx)(`option`,{value:``,children:a(`cws.target.pickProvider`)}),g.map(e=>(0,R.jsx)(`option`,{value:e.name,children:e.disabled?a(`cws.target.disabled`,{name:e.name}):e.name},e.name))]}),(0,R.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,R.jsx)(`option`,{value:``,children:y?a(`cws.target.pickProviderFirst`):v.length===0?a(`cws.target.noModels`):a(`cws.target.pickModel`)}),v.map(e=>(0,R.jsx)(`option`,{value:e,children:e},e))]}),t===`round-robin`&&(0,R.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=Fs(e.target.value,1,1e4);t!==void 0&&d(m,{weight:t})}}),(0,R.jsx)(`div`,{className:`cwi-target-actions`,children:(0,R.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,R.jsx)(ue,{width:14,height:14})})})]},p.clientKey??`${p.provider}:${p.model}`)}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>i([...e,Bo()]),children:[(0,R.jsx)(oe,{width:14,height:14}),` `,a(`cws.target.add`)]})]})}function Vs({existingIds:e,existingAliases:t,providerMap:n,providers:r,models:i,onClose:a,onSubmit:o}){let s=K(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(()=>as()),[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)(()=>Ro(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=is(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:Ko(i,a)});if(!e.ok){m(e.error||s(`cws.saveFailed`));return}}finally{f(!1)}};return(0,R.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:y,children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:v}),(0,R.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,R.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,R.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:s(`cws.addTitle`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:d,"aria-label":s(`common.close`),children:(0,R.jsx)(ae,{width:16,height:16})})]}),(0,R.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:s(`cws.addSubtitle`)}),p&&(0,R.jsx)(q,{tone:`err`,children:p}),(0,R.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-id`,children:s(`cws.field.id`)}),(0,R.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:l.id,disabled:d,onChange:e=>u(t=>({...t,id:e.target.value,model:Ko(e.target.value,t.alias)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idInternalHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:s(`cws.field.alias`)}),(0,R.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:Ko(t.id,e.target.value)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.aliasHint`)}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.idHint`,{model:l.id.trim()?Ko(l.id,l.alias):`…`})})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:s(`cws.strategy`)}),(0,R.jsx)(Rs,{value:l.strategy,disabled:d,onChange:e=>u(t=>({...t,strategy:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:l.strategy===`failover`?s(`cws.strategy.failoverHint`):s(`cws.strategy.roundRobinHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:s(`cws.field.defaultEffort`)}),(0,R.jsx)(zs,{id:`cwi-new-effort`,value:l.defaultEffort,disabled:d,allowedEfforts:g,onChange:e=>u(t=>({...t,defaultEffort:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.defaultEffortHint`)})]}),l.strategy===`round-robin`&&(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:s(`cws.field.stickyLimit`)}),(0,R.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:l.stickyLimit,disabled:d,onChange:e=>{let t=Fs(e.target.value,1,100);t!==void 0&&u(e=>({...e,stickyLimit:t}))}}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:s(`cws.field.stickyLimitHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:s(`cws.targets`)}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:l.strategy===`failover`?s(`cws.targets.failoverHint`):s(`cws.targets.roundRobinHint`)}),(0,R.jsx)(Bs,{targets:l.targets,strategy:l.strategy,providers:r,models:i,onChange:e=>u(t=>({...t,targets:e}))})]})]}),(0,R.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,disabled:d,children:s(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{b()},disabled:d,children:s(d?`common.saving`:`cws.create`)})]})]})]})}function Hs({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=K(),[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=!ns(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)(()=>Ro(h.targets,E),[h.targets,E]),O=(0,_.useCallback)(t=>{let n=t(h);g(n),d(!ns(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=is(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:Ko(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()?Ko(h.id,h.alias):f(`cws.addTitle`):e.model;return(0,R.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,R.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[s&&(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:s,"aria-label":f(`cws.backToAll`),children:[(0,R.jsx)(_e,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),f(`cws.allCombos`)]}),(0,R.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:j}),!t&&(0,R.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{k()},title:f(`cws.copyModel`),children:f(S?`cws.copied`:`cws.copyModel`)}),(0,R.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&l&&(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,R.jsx)(ue,{width:14,height:14}),` `,f(`common.remove`)]}),(0,R.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,R.jsx)(q,{tone:b.ok?`ok`:`err`,children:b.text}),(0,R.jsxs)(`div`,{className:`combos-workspace-tabs`,role:`tablist`,children:[(0,R.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,R.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,R.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,children:p===`config`?(0,R.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:f(`cws.field.id`)}),(0,R.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:h.id,disabled:v,onChange:e=>O(t=>({...t,id:e.target.value,model:Ko(e.target.value,t.alias)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:t?f(`cws.field.idInternalHint`):f(`cws.field.idHintEdit`,{model:Ko(h.id,h.alias)})})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:f(`cws.field.alias`)}),(0,R.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:h.alias??``,placeholder:Go(h.id.trim()||`…`),disabled:v,onChange:e=>O(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:Ko(t.id,e.target.value)}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.aliasHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,R.jsx)(Rs,{value:h.strategy,disabled:v,onChange:e=>O(t=>({...t,strategy:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`6px 0 0`},children:h.strategy===`failover`?f(`cws.strategy.failoverHint`):f(`cws.strategy.roundRobinHint`)})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-effort`,children:f(`cws.field.defaultEffort`)}),(0,R.jsx)(zs,{id:`cwi-effort`,value:h.defaultEffort,disabled:v,allowedEfforts:D,onChange:e=>O(t=>({...t,defaultEffort:e}))}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),h.strategy===`round-robin`&&(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`label`,{htmlFor:`cwi-sticky`,children:f(`cws.field.stickyLimit`)}),(0,R.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:h.stickyLimit,disabled:v,onChange:e=>{let t=Fs(e.target.value,1,100);t!==void 0&&O(e=>({...e,stickyLimit:t}))}})]}),(0,R.jsxs)(`div`,{className:`cwi-field`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,R.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`0 0 8px`},children:h.strategy===`failover`?f(`cws.targets.failoverHint`):f(`cws.targets.roundRobinHint`)}),(0,R.jsx)(Bs,{targets:h.targets,strategy:h.strategy,providers:a,models:o,onChange:e=>O(t=>({...t,targets:e}))})]})]}):(0,R.jsxs)(`section`,{className:`pwi-section`,children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:f(`cws.aboutTitle`)}),(0,R.jsx)(`p`,{className:`muted`,style:{margin:0},children:f(`cws.aboutBody`)})]})})]})}function Us({model:e,onCancel:t,onConfirm:n}){let r=K(),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,R.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,R.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,R.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function Ws({onKeep:e,onDiscard:t}){let n=K(),r=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]),(0,R.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]),children:[(0,R.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,R.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,R.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,R.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function Gs(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:`cws.attention.few`)}function Ks({combos:e,cataloguedComboIds:t,onSelect:n,onAdd:r}){let i=K(),a=$o(e),o=ts(e,{cataloguedComboIds:t});return(0,R.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,R.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,R.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:i(`cws.overviewTitle`)}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,children:[(0,R.jsx)(oe,{width:14,height:14}),` `,i(`cws.add`)]})]}),(0,R.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:i(`cws.overviewBlurb`)}),(0,R.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,R.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,R.jsx)(`strong`,{children:e.length}),(0,R.jsx)(`span`,{children:i(`cws.count.total`)})]}),(0,R.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,R.jsx)(`strong`,{children:a.failover.length}),(0,R.jsx)(`span`,{children:i(`cws.count.failover`)})]}),(0,R.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,R.jsx)(`strong`,{children:a.roundRobin.length}),(0,R.jsx)(`span`,{children:i(`cws.count.roundRobin`)})]})]}),(0,R.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.howTitle`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.howTitle`)}),(0,R.jsx)(`p`,{className:`muted`,style:{margin:0},children:i(`cws.howBody`)})]}),o.length>0&&(0,R.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.attentionTitle`),children:[(0,R.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.attentionTitle`)}),(0,R.jsx)(`div`,{className:`cwi-attention-list`,children:o.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>n(e.id),children:[(0,R.jsx)(de,{width:14,height:14,"aria-hidden":`true`}),(0,R.jsx)(`code`,{className:`chip`,children:e.model}),(0,R.jsx)(`span`,{className:`muted`,children:Gs(e.reason,i)}),(0,R.jsx)(_e,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function qs({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=K(),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)(()=>as(),[]),E=(0,_.useMemo)(()=>es(e,m),[e,m]),D=(0,_.useMemo)(()=>$o(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))},z=()=>b(void 0),B=y!==void 0&&M,V=!i&&e.length===0;return(0,R.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,R.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":f(`cws.railAria`),children:[(0,R.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`div`,{className:`combos-workspace-rail-title`,children:f(`nav.combos`)}),(0,R.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(V){document.getElementById(`cwi-edit-id`)?.focus();return}c()},"aria-label":f(`cws.add`),children:[(0,R.jsx)(oe,{width:14,height:14}),` `,f(`cws.add`)]})]}),(0,R.jsx)(`div`,{className:`cwi-search-row`,children:(0,R.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,R.jsx)(pe,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,R.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,R.jsx)(`div`,{className:`combos-workspace-rail-list`,children:E.length===0&&e.length>0?(0,R.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:f(`cws.noSearchResults`)}):(0,R.jsx)(R.Fragment,{children:[[`failover`,D.failover,`cws.group.failover`],[`round-robin`,D.roundRobin,`cws.group.roundRobin`]].map(([e,t,n])=>t.length>0?(0,R.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,R.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,R.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),f(n),(0,R.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,R.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,R.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,R.jsx)(Ae,{width:16,height:16})}),(0,R.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,R.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?f(`cws.targetCountOne`):f(`cws.targetCount`,{count:e.targets.length})}),(0,R.jsx)(_e,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,R.jsx)(`div`,{className:`combos-workspace-main`,children:j?(0,R.jsx)(Hs,{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):V?(0,R.jsx)(Hs,{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,R.jsx)(Ks,{combos:e,cataloguedComboIds:r,onSelect:e=>I(e),onAdd:c})}),l&&!V&&(0,R.jsx)(Vs,{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,R.jsx)(Us,{model:e.find(e=>e.id===x)?.model??Go(x),onCancel:()=>S(null),onConfirm:()=>{(async()=>{let e=await s(x);S(null),e.ok&&(k===x&&(v(null),w(null)),a())})()}}),B&&(0,R.jsx)(Ws,{onKeep:z,onDiscard:L})]})}function Js(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function Ys(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Xs(e){return sn(e)}function Zs({apiBase:e}){let t=K(),n=`ocx.combos.workspace.v1:${e}`,r=Xs(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=Qo(a),u=o.providers??{},d=Yn(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 J(n,h),h},[e,n]),f=ss(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,R.jsx)(ma,{label:t(`cws.loading`),rows:5}):p.kind===`failed-cold`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:p.error instanceof Error?p.error.message:t(`cws.loadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,R.jsxs)(`div`,{className:`combos-workspace-shell`,children:[i&&(0,R.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,R.jsx)(q,{tone:o?`ok`:`err`,children:i})}),p.showError&&(0,R.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,R.jsx)(q,{tone:`err`,children:t(`cws.loadFailed`)})}),p.refreshing&&(0,R.jsx)(ha,{live:!p.showError,children:t(`cws.loading`)}),(0,R.jsx)(`div`,{className:`combos-workspace-shell-body`,children:(0,R.jsx)(qs,{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(rs(n,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=Js(o);if(!a.ok||s||!Ys(o)){let e=s||t(`cws.saveFailed`);return u(e,!1),{ok:!1,error:e}}return f.refresh(),u(i?t(`cws.renamed`,{from:Go(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=Js(i);if(!r.ok||a||!Ys(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 Qs=`section`;function $s(e,t){return[e,Qs,t].join(`-`)}function ec(e){return[e,Qs,``].join(`-`)}function tc({scope:e,items:t,ariaLabel:n}){let[r,i]=(0,_.useState)(t[0]?.id??``),a=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById($s(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!n)return;let r=n.target.id.slice(ec(e).length);i(e=>e===r?e:r)},{rootMargin:`-72px 0px -60% 0px`,threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[t,e]);let o=t=>{let n=document.getElementById($s(e,t));n&&(i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,R.jsx)(`div`,{ref:a,className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,R.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":$s(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>o(t.id),children:[t.label,t.meta?(0,R.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function nc({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s}){let c=K();return(0,R.jsxs)(`div`,{className:`swi-delegation`,children:[(0,R.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,R.jsxs)(`div`,{className:`setting-copy`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:c(`sub.delegation.model`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:c(`sub.delegation.modelHint`)})]}),(0,R.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,R.jsx)(rt,{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,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,R.jsxs)(`div`,{className:`setting-copy`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:c(`dash.syncCodexSubagentDefaults`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,R.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,R.jsx)(`span`,{className:`knob`})})]}),(0,R.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,R.jsxs)(`div`,{className:`setting-copy`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,children:c(`dash.multiAgentGuidance`)}),(0,R.jsx)(`div`,{className:`muted setting-hint`,children:c(`dash.multiAgentGuidanceHint`)})]}),(0,R.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":c(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,R.jsx)(`span`,{className:`knob`})})]})]})}function rc({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=K(),[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,R.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,R.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,R.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,R.jsxs)(`section`,{id:$s(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,R.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,R.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,R.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,R.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,R.jsx)(fe,{width:15,height:15,"aria-hidden":`true`}),(0,R.jsx)(`span`,{children:(0,R.jsx)(He,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,R.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,R.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,R.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,R.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,R.jsx)(`span`,{className:`swi-featured-name`,children:Io(e)}),(0,R.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,R.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,R.jsx)(me,{})}),(0,R.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,R.jsx)(he,{})}),(0,R.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,R.jsx)(ae,{})})]})]},e))}),(0,R.jsx)(`div`,{className:`swi-save-row`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,R.jsxs)(`section`,{id:$s(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,R.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,R.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,R.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,R.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,R.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,R.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,R.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,R.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,R.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,R.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,R.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,R.jsx)(U,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,R.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:Io(e)})]}),(0,R.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,R.jsx)(ie,{style:{width:14,height:14}}):(0,R.jsx)(oe,{style:{width:14,height:14}})})]},e)})})]})]}),(0,R.jsxs)(`section`,{id:$s(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,R.jsx)(`div`,{className:`swi-featured-head`,children:(0,R.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,R.jsx)(nc,{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 ic(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=gn(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 mt(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 mt(await fetch(`${e}/api/injection-model`)))}catch{}finally{i(!1)}}},[e,v,r])}}function ac(e){return sn(e)}function oc({apiBase:e}){let t=K(),n=`ocx.subagents.v1:${e}`,r=ac(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=ic(e),m=(0,_.useCallback)(async()=>{let r=await ct(await fetch(`${e}/api/subagent-models`),t(`sub.loadFail`));if(!r)throw Error(t(`sub.loadFail`));let i=r.available??[],o=new Set(i),s={available:i,chosen:(r.chosen??[]).filter(e=>o.has(e))};return a(s.chosen),J(n,s),s},[e,n,t]),h=ss(n,[e],m,{isEmpty:()=>!1}),{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 ct(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),J(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,R.jsx)(ma,{label:t(`sub.loading`),rows:4}):g.kind===`failed-cold`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:g.error instanceof Error?g.error.message:t(`sub.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,R.jsx)(q,{tone:c?`ok`:`err`,children:o}),g.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`sub.loadFail`)}),g.refreshing&&(0,R.jsx)(ha,{live:!g.showError,children:t(`sub.loading`)}),(0,R.jsx)(rc,{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 sc(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 cc(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 lc(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var uc=(e,t)=>Math.abs(e-t)<1.01,dc=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},fc,pc=()=>{if(fc!==void 0)return fc;if(typeof navigator>`u`)return fc=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return fc=!0;let e=navigator.maxTouchPoints;return fc=navigator.platform===`MacIntel`&&e!==void 0&&e>0},mc=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},hc=e=>e,gc=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},_c=(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(mc(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(mc(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},vc={passive:!0},yc=typeof window>`u`?!0:`onscrollend`in window,bc=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&yc,o=0,s=a?null:dc(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,vc),a&&r.addEventListener(`scrollend`,u,vc),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},xc=(e,t)=>bc(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Sc=(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`]},Cc=(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})},wc=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:hc,rangeExtractor:gc,onChange:()=>{},measureElement:Sc,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=cc(()=>(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,!(!pc()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,vc),e.addEventListener(`touchend`,n,vc),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&&(pc()&&(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=cc(()=>[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=cc(()=>[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=sc(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=cc(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Dc(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=cc(()=>{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=cc(()=>[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 lc(t[Tc(0,t.length-1,r?e=>n[e*2]:e=>lc(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&&(pc()&&(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&&uc(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()}},Tc=(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 Ec(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 Dc(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=Ec(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=Tc(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 Oc=typeof document<`u`?_.useLayoutEffect:_.useEffect;function kc({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,Ke.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[c]=_.useState(()=>{let e=new wc(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),Oc(()=>c._didMount(),[]),Oc(()=>c._willUpdate()),Oc(()=>{o(c)}),c}function Ac(e){return kc({observeElementRect:_c,observeElementOffset:xc,scrollToFn:Cc,...e})}var jc=32;function Mc(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Nc(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 Pc(e){let t=e.trim();if(t&&!Nc(t)&&!(t.length>4096))return Mc(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,jc)}function Fc(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r?!0:n!==void 0&&e===n:!1}var Ic={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:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`}}},Lc={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 Rc(e){return e===`de`||e===`ko`||e===`zh`||e===`ru`||e===`ja`?e:`en`}function zc(e,t){if(e<400)return null;let n=Rc(t);return(Ic[Math.trunc(e)]??(e<500?Lc.client:Lc.server))[n]}var Bc=[`provider`,`usage`,`injection`];function Vc(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function Hc(e){return new Date(e).toLocaleTimeString()}function Uc(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function Wc(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function Gc({entries:e}){let{t}=G();return(0,R.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,R.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,R.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,R.jsx)(`div`,{style:{overflowX:`auto`},children:(0,R.jsxs)(`table`,{className:`table text-label`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,R.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,R.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,R.jsx)(`th`,{children:`thinking`}),(0,R.jsx)(`th`,{children:`effort`}),(0,R.jsx)(`th`,{children:`beta`}),(0,R.jsx)(`th`,{children:`metadata`}),(0,R.jsx)(`th`,{children:`system`})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`muted mono`,children:Hc(e.at)}),(0,R.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,R.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,R.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,R.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,R.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,R.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,R.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,R.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,R.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function Kc({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=G();return e?n?r.length===0?(0,R.jsxs)(`div`,{className:`empty`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,R.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,R.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,R.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Vc(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,R.jsxs)(`div`,{className:`empty`,children:[(0,R.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,R.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function qc({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=G();return(0,R.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,R.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,R.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=Wc(e,n);return(0,R.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,R.jsx)(nt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,R.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,R.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,R.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function Jc({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=G();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,R.jsx)(`h2`,{children:o(`debug.title`)}),(0,R.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,R.jsx)(se,{}),` `,o(`debug.refresh`)]}),(0,R.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function Yc(e){return`debug-settings:${e}`}function Xc({apiBase:e,embedded:t,active:n=!0}){let{t:r}=G(),i=`ocx.debug.settings.v1:${e}`,a=sn(i),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(`provider`),[u,d]=(0,_.useState)([]),[f,p]=(0,_.useState)(!0),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(0),v=(0,_.useRef)(0),y=(0,_.useRef)(0),b=(0,_.useRef)(null),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=ss(Yc(e),[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 J(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1}),w=C.state,T=C.data??a??null,E=F(`debug-claude-inbound:${e}`,[e,T?.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&&!!T?.claude}).data??[],D=Ac({count:u.length,getScrollElement:()=>x.current,estimateSize:()=>20,overscan:30,getItemKey:e=>u[e].seq}),O=(0,_.useCallback)(e=>Uc(T,e),[T]);(0,_.useEffect)(()=>{if(!T||O(c))return;let e=Bc.find(O);if(!e)return;let t=window.setTimeout(()=>l(e),0);return()=>window.clearTimeout(t)},[T,c,O]);let k=O(c),A=c===`provider`?`${e}/api/debug/logs`:c===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,j=(0,_.useCallback)(async(e,t)=>{let n=++y.current;if(!k){n===y.current&&(d([]),g.current=0);return}h(!0);try{let r=new URLSearchParams({limit:`500`});!e&&g.current>0&&r.set(`after`,String(g.current));let i=await fetch(`${A}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==y.current)return;let a=await i.json();if(t?.aborted||n!==y.current||a.length===0)return;d(t=>(e?a:[...t,...a]).slice(-2e3)),g.current=a[a.length-1].seq}catch{}finally{n===y.current&&h(!1)}},[A,k]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${c}:${k}`,r=S.current!==t;if(S.current=t,!r&&u.length>0)return;g.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&d([]),j(!0,i.signal)},0);return()=>{window.clearTimeout(a),y.current+=1,i.abort()}},[n,e,c,k]);let M=(0,_.useEffectEvent)(e=>{j(e)});(0,_.useEffect)(()=>{if(!n||!f||!k)return;let e=setInterval(()=>M(!1),1e3);return()=>clearInterval(e)},[n,f,k]),(0,_.useEffect)(()=>{f&&u.length>0&&D.scrollToIndex(u.length-1,{align:`end`})},[u,f,D]);let N=async t=>{let n=++v.current;s(!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!==v.current)return;J(i,a),I(Yc(e),a)}catch{}},a=(b.current??Promise.resolve()).then(r,r);b.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===v.current&&s(!1)}},P=async(e,t)=>{await N({[e]:t})},L=async()=>{await N({reset:!0})};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Jc,{embedded:t,refreshing:m,streamEnabled:k,follow:f,onRefresh:()=>void j(!0),onFollowChange:p}),!T&&w.showError?(0,R.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,R.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>C.refresh(),children:r(`common.retry`)})]}):w.showSkeleton&&!T?(0,R.jsx)(ma,{label:r(`debug.loading`),rows:3}):T?(0,R.jsx)(qc,{debug:T,debugBusy:o,stream:c,onSetFlag:(e,t)=>{P(e,t)},onReset:()=>{L()},onStreamChange:l}):null,T&&w.refreshing&&(0,R.jsx)(ha,{live:!w.showError,children:r(`debug.loading`)}),T&&w.showError&&(0,R.jsx)(q,{tone:`err`,children:r(`debug.loadFailed`)}),T?.claude&&(0,R.jsx)(Gc,{entries:E}),(0,R.jsx)(Kc,{debug:!!T,stream:c,streamEnabled:k,entries:u,scrollContainerRef:x,lineVirtualizer:D})]})}function Zc(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function Qc(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function $c(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),Qc(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),Qc(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function el(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 nl(e){return`ocx.logs.list.v1:${e}`}function rl(e){return e===`cursor`||e.startsWith(`cursor-`)}function il(e,t){if(!e.usage)return;let n=sl(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(rl(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 ol(e){let t=al(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function sl(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 cl(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 ll(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function ul(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 dl(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 fl(e,t){return!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var pl=3,ml={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`},hl={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 gl(e){return ml[e]}function _l(e){return hl[e]}function vl(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function yl(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function bl(e,t,n){try{return new Date(e).toLocaleTimeString(t,n?{timeZone:n}:void 0)}catch{return new Date(e).toLocaleTimeString(t)}}function xl(e,t,n){try{return new Date(e).toLocaleString(t,n?{timeZone:n}:void 0)}catch{return new Date(e).toLocaleString(t)}}function Sl(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 Cl(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 wl({apiBase:e}){let{t,locale:n}=G(),r=sn(nl(e)),[i,a]=(0,_.useState)(!0),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(`all`),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(),m=(0,_.useRef)(null),h=Ie.find(e=>e.code===n)?.htmlLang,[g,v]=(0,_.useState)();(0,_.useEffect)(()=>{let t=new AbortController;return(async()=>{try{let n=await fetch(`${e}/api/settings`,{signal:t.signal});if(!n.ok)return;let r=await n.json();typeof r.timeZone==`string`&&r.timeZone.trim()&&v(r.timeZone.trim())}catch{}})(),()=>t.abort()},[e]);let[y,b]=(0,_.useState)(Zc),[x,S]=(0,_.useState)(()=>Zc()===`debug`);(0,_.useEffect)(()=>{let e=()=>b(Zc());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{y===`debug`&&S(!0)},[y]);let C=Qc,w=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/logs`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let r=await n.json();return J(nl(e),r),r},[e]),T=ss(nl(e),[e],w,{isEmpty:e=>e.length===0,enabled:y===`logs`,pollMs:i?2e3:void 0}),E=T.state,D=E.data??r??[],O=T.refresh,k=!T.refreshing&&E.showError,A=!T.refreshing&&!E.showError&&E.data!==void 0,[j,M]=(0,_.useState)({error:null,count:0});A&&j.count!==0?M({error:null,count:0}):k&&j.error!==E.error&&M(e=>({error:E.error,count:e.count+1}));let N=j.count>=pl,P=o?zc(o.status,n):null,F=u.trim();(0,_.useEffect)(()=>{let e=!1;if(!F){p(void 0);return}return Pc(F).then(t=>{e||p(t)}),()=>{e=!0}},[F]);let I=D.filter(e=>tl(e,c)&&(!F||Fc(e.conversationId,F,f))),L=F?Cl(I):null,z=Ac({count:I.length,getScrollElement:()=>m.current,estimateSize:()=>44,overscan:15}),B=z.getVirtualItems(),V=B.length>0?B[0].start:0,H=B.length>0?z.getTotalSize()-B[B.length-1].end:0;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:t(`nav.logs`)}),y===`logs`&&(0,R.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,R.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,R.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":y===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:y===`logs`?0:-1,className:`page-tab${y===`logs`?` page-tab--active`:``}`,onClick:()=>C(`logs`),onKeyDown:$c,children:t(`logs.tabLogs`)}),(0,R.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":y===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:y===`debug`?0:-1,className:`page-tab${y===`debug`?` page-tab--active`:``}`,onClick:()=>C(`debug`),onKeyDown:$c,children:t(`logs.tabDebug`)})]}),x&&(0,R.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:y!==`debug`,children:(0,R.jsx)(Xc,{apiBase:e,embedded:!0,active:y===`debug`})}),(0,R.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:y!==`logs`,children:[(0,R.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,R.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,R.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,R.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,R.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":c===e,className:`btn btn-sm${c===e?` btn-primary`:` btn-ghost`}`,style:{background:c===e?void 0:`transparent`,color:c===e?void 0:`var(--muted)`},onClick:()=>l(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,R.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,R.jsx)(`input`,{type:`search`,className:`input mono`,value:u,onChange:e=>d(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),F&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(``),children:t(`logs.filter.conversation.clear`)})]}),L&&(0,R.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,R.jsxs)(q,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:L.requests,tokens:Nt(L.totalTokens,h??n),cost:fl(L.estimatedCostUsd,h)}),` `,(0,R.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),L.unpricedRequests+L.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:L.unpricedRequests,unmetered:L.unmeteredRequests})}`:``]})]})}),E.kind===`failed-cold`&&(0,R.jsxs)(q,{tone:`err`,children:[E.error instanceof Error?`${t(`logs.loadError`)} ${E.error.message}`:t(`logs.loadError`),` `,(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>O({forceLoading:!0}),disabled:E.refreshing,children:t(`common.retry`)})]}),T.loading&&D.length>0&&(0,R.jsx)(ha,{live:!1,children:t(`common.loading`)}),N&&D.length>0&&(0,R.jsxs)(q,{tone:`err`,children:[t(`logs.loadError`),` `,(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>O({forceLoading:!0}),disabled:T.refreshing,children:t(`common.retry`)})]}),E.kind===`failed-cold`?null:E.showSkeleton&&D.length===0?(0,R.jsx)(ma,{label:t(`common.loading`),rows:6}):I.length===0?(0,R.jsx)(it,{title:t(`logs.noRequests`)}):(0,R.jsx)(R.Fragment,{children:(0,R.jsx)(`div`,{ref:m,className:`tbl-wrap logs-table-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:t(`logs.col.time`)}),(0,R.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,R.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,R.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,R.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,R.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,R.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,R.jsx)(`th`,{children:t(`logs.col.status`)}),(0,R.jsx)(`th`,{children:t(`logs.col.request`)}),(0,R.jsx)(`th`,{className:`num`,children:t(`logs.col.duration`)})]})}),(0,R.jsxs)(`tbody`,{children:[V>0&&(0,R.jsx)(`tr`,{children:(0,R.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:V}})}),B.map(e=>{let r=I[I.length-1-e.index],i=ll(r);return(0,R.jsxs)(`tr`,{"data-index":e.index,ref:z.measureElement,children:[(0,R.jsx)(`td`,{className:`muted mono`,children:bl(r.timestamp,h,g)}),(0,R.jsx)(`td`,{className:`num mono log-col-tokens`,title:il(r,t),children:(()=>{let e=ol(r),{read:i,write:a}=sl(r);return e===void 0?(0,R.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,R.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,R.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Nt(e,n)]}),i!==void 0&&i>0&&(0,R.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Nt(i,n)]}),a!==void 0&&a>0&&(0,R.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Nt(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,R.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(rl(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,R.jsx)(`td`,{className:`num mono log-col-rate`,children:ul(r.displayMetrics?.tokPerSecond,h)}),(0,R.jsx)(`td`,{className:`num mono log-col-cost`,children:dl(r.displayMetrics?.cost,h)}),(0,R.jsx)(`td`,{className:`mono log-col-model`,title:Sl(r),children:(0,R.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,R.jsx)(`span`,{children:Io(r.resolvedModel??r.model)}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,R.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,R.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),el(r)&&(0,R.jsx)(`span`,{className:`badge badge-amber`,children:el(r)})]})}),(0,R.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,R.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,R.jsx)(`span`,{children:cl(r)}),i&&(0,R.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,R.jsx)(`td`,{className:`muted`,children:r.provider}),(0,R.jsx)(`td`,{children:(0,R.jsxs)(`span`,{className:`log-status-cell`,children:[(0,R.jsx)(`span`,{className:`mono font-semibold`,style:{color:yl(r.status)},children:r.status}),(0,R.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>s(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,R.jsx)(`td`,{className:`muted mono`,children:(0,R.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,R.jsxs)(`td`,{className:`num`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),H>0&&(0,R.jsx)(`tr`,{children:(0,R.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:H}})})]})]})})}),o&&(0,R.jsx)(El,{detail:o,detailInfo:P,localeCode:n,localeTag:h,serverTimeZone:g,t,onClose:()=>s(null),onFilterConversation:e=>{d(e),s(null)}})]})]})}function Tl(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 El({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Tl(!0),[l,u]=(0,_.useState)(!1),d=sl(e),f=e.displayMetrics?.cost,p=ll(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,R.jsx)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:(0,R.jsxs)(`div`,{className:`modal-card log-detail-card`,children:[(0,R.jsxs)(`div`,{className:`modal-head`,children:[(0,R.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,R.jsx)(`span`,{className:`mono`,style:{color:yl(e.status)},children:e.status}),t&&(0,R.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,R.jsx)(ae,{})})]}),t&&(0,R.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,R.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,R.jsx)(`span`,{className:`mono`,children:xl(e.timestamp,r,i)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,R.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,R.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,R.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,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,R.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,R.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,R.jsx)(`span`,{className:`mono`,children:Io(e.resolvedModel??e.model)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,R.jsx)(`span`,{children:e.provider}),(e.requestedEffort||e.effectiveEffort)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[cl(e),p?` (${p})`:``]})]}),e.errorCode&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,R.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,R.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,R.jsx)(`span`,{className:`mono`,children:ul(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,R.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(gl(e.displayMetrics.tokPerSecond.reason))})]}),(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,R.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(f.estimate.cost.total,r)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(f.estimate.cost.input,r)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(f.estimate.cost.cacheRead,r)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(f.estimate.cost.cacheWrite,r)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,R.jsx)(`span`,{className:`mono`,children:fl(f.estimate.cost.output,r)}),f.estimate.price&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,R.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,R.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(vl(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,R.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,R.jsx)(`li`,{children:a(_l(e))},e))})]}):(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,R.jsx)(`span`,{className:`mono`,children:`—`}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,R.jsx)(`span`,{children:f?.kind===`unavailable`?a(gl(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,R.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,R.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{className:`num`,children:`#`}),(0,R.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,R.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,R.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,R.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,R.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,R.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=ll(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(gl(t.reason)):a(`logs.detail.attempt.completed`));return(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,R.jsxs)(`td`,{children:[(0,R.jsx)(`span`,{children:e.provider}),(0,R.jsx)(`br`,{}),(0,R.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`br`,{}),(0,R.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[cl(e),n?` (${n})`:``]})]}),i&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`br`,{}),(0,R.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(vl(i.status))]})]})]}),(0,R.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,R.jsx)(`td`,{className:`num mono`,children:ul(e.displayMetrics?.tokPerSecond,r)}),(0,R.jsx)(`td`,{className:`num mono`,children:dl(t,r)}),(0,R.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,R.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,R.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,R.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.usage?Nt(e.usage.inputTokens,n):`—`}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.usage?Nt(e.usage.outputTokens,n):`—`}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,R.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Nt(d.read,n)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,R.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Nt(d.write,n)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,R.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Nt(e.usage.reasoningOutputTokens,n)}),(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,R.jsx)(`span`,{className:`mono`,children:ol(e)===void 0?`—`:Nt(ol(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,R.jsx)(`span`,{className:`mono`,children:Nt(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,R.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,R.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,R.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,R.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})})}function Dl(e){return`${Math.round(e*100)}%`}function Ol(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 kl(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 Al(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 jl(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Ml(e){let t=Al(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?jl(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 Nl({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,R.jsxs)(`div`,{className:`usage-filters`,children:[(0,R.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,R.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,R.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,R.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,R.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,R.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,R.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(`usage.range.${e}`);return(0,R.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 Pl({summary:e,activeDays:t,locale:n,t:r}){return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Nt(e.totalTokens,n)})]}),(0,R.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Nt(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,R.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Nt(e.cacheCreationInputTokens??0,n)]})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Dl(e.coverageRatio)})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,R.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,R.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,R.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:ia(e.estimatedCostUsd,n)}),(0,R.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,R.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function Fl({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,R.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,R.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,R.jsx)(`div`,{className:`daybar-track`,children:(0,R.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,R.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Ol(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,R.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,R.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,R.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,R.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,R.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Ol(e.model,e.provider)}}),(0,R.jsx)(`span`,{className:`daybar-tip-name`,children:Io(e.model)}),(0,R.jsx)(`span`,{className:`daybar-tip-val`,children:Nt(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,R.jsx)(`span`,{className:`daybar-count`,children:Nt(e.totalTokens,t)}),(0,R.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function Z({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,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,R.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,R.jsx)(Fl,{weekBars:n,locale:r,t:i}):(0,R.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,R.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,R.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,R.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,R.jsxs)(`div`,{className:`heatmap-body`,children:[(0,R.jsxs)(`div`,{className:`heatmap-days`,children:[(0,R.jsx)(`span`,{}),(0,R.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,R.jsx)(`span`,{}),(0,R.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,R.jsx)(`span`,{}),(0,R.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,R.jsx)(`span`,{})]}),(0,R.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,R.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,R.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,R.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,R.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,R.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Nt(e.totalTokens,r)})}),(0,R.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,R.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,R.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,R.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,R.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function Q({title:e,titleId:t,children:n}){return(0,R.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,R.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function Il({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,R.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:i(`logs.col.model`)}),(0,R.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,R.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,R.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`mono`,children:Io(e.model)}),(0,R.jsx)(`td`,{className:`muted`,children:e.provider}),(0,R.jsx)(`td`,{className:`num`,children:e.requests}),(0,R.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,R.jsx)(`td`,{className:`num mono`,children:Nt(e.totalTokens,r)}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`div`,{className:`usage-bar`,children:(0,R.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,R.jsxs)(Q,{title:s,titleId:c,children:[(0,R.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function Ll({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,R.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`mono`,children:e.provider}),(0,R.jsx)(`td`,{className:`num`,children:e.requests}),(0,R.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,R.jsx)(`td`,{className:`num mono`,children:Nt(e.totalTokens,t)}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`div`,{className:`usage-bar`,children:(0,R.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,R.jsx)(Q,{title:i,titleId:a,children:o}):(0,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,R.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function Rl({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,R.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,R.jsx)(Q,{title:r,titleId:i,children:a}):(0,R.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,R.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function zl({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,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Pl,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,R.jsx)(Z,{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,R.jsx)(Il,{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,R.jsx)(Ll,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Dl(e.summary.coverageRatio):`—`,body:e?(0,R.jsx)(Rl,{summary:e.summary,t:u,workspace:!0}):null}];return(0,R.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,R.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,R.jsx)(tc,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,R.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,R.jsx)(it,{title:u(`usage.empty`)}):f.map(e=>(0,R.jsx)(`div`,{id:$s(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var Bl=new Map;function Vl(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function Hl(e,t,n){let r=Vl(e,t,n);return Bl.get(r)??sn(r)}function Ul(e,t,n,r){let i=Vl(e,t,n);Bl.set(i,r),J(i,r)}function Wl({apiBase:e}){let{t,locale:n}=G(),[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 Ul(e,r,a,i),i},[e,r,a]),u=Hl(e,r,a),d=ss(Vl(e,r,a),[e,r,a],l,{isEmpty:()=>!1}),{state:f}=d,p=f.data??u??null,m=(0,_.useMemo)(()=>Ml(p?.days??[]),[p?.days]),h=(0,_.useMemo)(()=>kl(p?.days??[]),[p?.days]),g=(0,_.useMemo)(()=>(p?.days??[]).filter(e=>e.requests>0).length,[p?.days]),v=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(p?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[p?.models,s]),y=(0,_.useMemo)(()=>(p?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[p?.providers]);return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,R.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,R.jsx)(Nl,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),f.showSkeleton&&!p?(0,R.jsx)(ma,{label:t(`usage.loading`),rows:5}):f.kind===`failed-cold`?(0,R.jsxs)(q,{tone:`err`,children:[f.error instanceof Error?`${t(`usage.loadError`)} ${f.error.message}`:t(`usage.loadError`),` `,(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d.refresh(),children:t(`common.retry`)})]}):(0,R.jsxs)(R.Fragment,{children:[f.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`usage.loadError`)}),f.refreshing&&(0,R.jsx)(ha,{live:!f.showError,children:t(`usage.loading`)}),(0,R.jsx)(zl,{data:p,heatmap:m,weekBars:h,activeDays:g,filteredModels:v,modelQuery:s,onModelQuery:c,sortedProviders:y,range:r,locale:n,t})]})]})}function Gl(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 Kl={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 ql(e,t){let n=Kl[e.key];return n?t(n):e.label}function Jl(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function Yl(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function Xl({report:e,locale:t}){let n=K(),[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,R.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,R.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":n(`storage.section.buckets`),children:[(0,R.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,R.jsx)(`span`,{className:`storage-workspace-rail-title`,children:n(`storage.section.buckets`)}),(0,R.jsx)(`span`,{className:`storage-workspace-rail-count`,children:a.length})]}),(0,R.jsx)(`div`,{className:`storage-workspace-rail-list`,children:a.length===0?(0,R.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:n(`storage.empty`)}):a.map(e=>(0,R.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,R.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,R.jsx)(`span`,{className:`storage-workspace-rail-name`,children:ql(e,n)}),(0,R.jsx)(`span`,{className:`storage-workspace-rail-size`,children:Gl(e.bytes,t)})]}),(0,R.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,n(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,R.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":o?ql(o,n):n(`storage.section.largest`),children:o?(0,R.jsxs)(`div`,{className:`stw-detail`,children:[(0,R.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,R.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>i(null),children:[(0,R.jsx)(_e,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),n(`modal.back`)]})}),(0,R.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,R.jsx)(`h2`,{className:`stw-detail-title`,children:ql(o,n)}),(0,R.jsxs)(`dl`,{className:`stw-kv`,children:[(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.size`)}),(0,R.jsx)(`dd`,{className:`stw-kv-mono`,children:Gl(o.bytes,t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.files`)}),(0,R.jsx)(`dd`,{className:`stw-kv-mono`,children:o.fileCount.toLocaleString(t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.oldest`)}),(0,R.jsx)(`dd`,{children:Jl(o.oldest,t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.newest`)}),(0,R.jsx)(`dd`,{children:Jl(o.newest,t)})]}),(0,R.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,R.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,R.jsx)(`dd`,{className:`stw-kv-mono`,children:Yl(o,t,n)})]})]}),(o.largest?.length??0)>0&&(0,R.jsxs)(`div`,{className:`stw-section`,children:[(0,R.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),o.largest.map(e=>(0,R.jsxs)(`div`,{className:`stw-file-row`,children:[(0,R.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,R.jsx)(`span`,{className:`stw-file-size`,children:Gl(e.bytes,t)})]},e.path))]})]})]}):(0,R.jsxs)(`div`,{className:`stw-overview`,children:[(0,R.jsxs)(`div`,{className:`usage-cards`,children:[(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:n(`storage.card.total`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:Gl(e.total.bytes,t)})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:n(`storage.card.files`)}),(0,R.jsx)(`div`,{className:`stat-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,R.jsxs)(`div`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`muted`,children:n(`storage.card.home`)}),(0,R.jsx)(`div`,{className:`stat-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),s.length>0?(0,R.jsxs)(`div`,{className:`stw-section`,children:[(0,R.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),s.map(e=>{let r=c.get(e.bucketKey);return(0,R.jsxs)(`div`,{className:`stw-file-row`,children:[(0,R.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),r&&(0,R.jsx)(`span`,{className:`stw-file-bucket`,children:ql(r,n)}),(0,R.jsx)(`span`,{className:`stw-file-size`,children:Gl(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,R.jsxs)(`p`,{className:`stw-hint`,children:[(0,R.jsx)(re,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),n(`storage.workspace.selectBucket`)]})]})})]})}var Zl=1024**3,Ql=[10,25,50],$l=(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 eu({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($l(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:Gl(a.bytes,t)})),r()}catch(e){v($l(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,R.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,R.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,R.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,R.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,R.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,R.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,R.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Ql.map(e=>(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,R.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,R.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:Gl(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,R.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,R.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,R.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,R.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,R.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,R.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,R.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,R.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,R.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,R.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 tu({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=ss(`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:Gl(a.bytes,t)})),r()}catch(e){p($l(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,R.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,R.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,R.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,R.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,R.jsx)(ha,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,R.jsx)(ma,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,R.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,R.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,R.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,R.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,R.jsx)(`th`,{})]})}),(0,R.jsx)(`tbody`,{children:x.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{className:`muted`,children:w(e)}),(0,R.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,R.jsx)(`td`,{className:`num mono`,children:Gl(e.bytes,t)}),(0,R.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,R.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,R.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,R.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,R.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,R.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:Gl(c.bytes,t),id:c.id})}),f&&(0,R.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,R.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,R.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function nu(e){let{job:t,...n}=e;return n}function ru(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/Zl*100)/100));return e.target.reduceToBytes===void 0?{policy:nu(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:nu(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/Zl*100)/100))}}async function iu(e){await new Promise(t=>window.setTimeout(t,e))}function au({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=sn(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=ru(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,J(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*Zl)}}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*Zl)},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)}},z=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 iu(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=nu(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:Gl(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:Gl(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)}},B=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,R.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,R.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,R.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,R.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,R.jsx)(`div`,{className:`storage-policy-enable`,children:(0,R.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,R.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,R.jsx)(`span`,{className:`toggle-knob`})}),(0,R.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,R.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,R.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,R.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,R.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,R.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,R.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,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,R.jsx)(Fi,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(Pi(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(Pi(E,-.1,0,1e4,.1))}})]})]})]}),(0,R.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,R.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,R.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,R.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,R.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,R.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,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,R.jsx)(Fi,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(Pi(S,1,1,100))},onDecrement:()=>{N(),C(Pi(S,-1,1,100))}})]})]}),(0,R.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,R.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,R.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,R.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,R.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,R.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,R.jsx)(Fi,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(Pi(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(Pi(w,-.1,0,1e4,.1))}})]})]})]}),(0,R.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,R.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,R.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,R.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,R.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,R.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,R.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,R.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,R.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,R.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,R.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,R.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,R.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,R.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,R.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,R.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,R.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[B(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:Gl(s.lastRun.freedBytes,t)})}`:``]})]}),(0,R.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,R.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,R.jsx)(`span`,{className:`storage-policy-meta-value`,children:B(s.nextRun)})]})]}),(0,R.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void z(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,R.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,R.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,R.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function ou({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,R.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,R.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,R.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,R.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,R.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,R.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,R.jsx)(au,{apiBase:e,locale:t,t:n,onDone:o}),(0,R.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,R.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,R.jsx)(eu,{apiBase:e,locale:t,t:n,onDone:o}):(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,R.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,R.jsx)(tu,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,R.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function su({apiBase:e}){let{t,locale:n}=G(),r=`ocx.storage.report.v1:${e}`,i=sn(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 J(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=ss(`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,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,R.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,R.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,R.jsx)(se,{}),` `,t(`storage.refresh`)]})]})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,R.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,R.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,R.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,R.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,R.jsx)(ma,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,R.jsx)(R.Fragment,{children:(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,R.jsxs)(R.Fragment,{children:[m.showError&&(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,R.jsx)(it,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,R.jsx)(Xl,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,R.jsx)(ha,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,R.jsx)(ou,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}function cu(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 lu({state:e,busy:t,onEnable:n}){let r=K();return(0,R.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,R.jsxs)(`div`,{className:`row`,children:[(0,R.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===null?(0,R.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,R.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,R.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===null&&(0,R.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc openai-account-mode-banner__desc--pending`,"aria-hidden":`true`,children:`\xA0`}),e===`pool`&&(0,R.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,R.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,R.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,R.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,R.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,R.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,R.jsx)(`a`,{href:`#providers`,children:r(`codexAuth.openProviders`)})]})]})}function uu(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 du({apiBase:e}){let t=K(),n=`ocx.codex-auth.config.v1:${e}`,r=sn(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()=>{try{let t=await fetch(`${e}/api/config`);if(!t.ok)throw Error(String(t.status));let r=await t.json(),i=Ua(uu(r));if(i===`absent`||i===`disabled`||i===`invalid`){a(i);let e=i===`disabled`?`disabled`:`absent`;s(e),J(n,{bannerState:i,accountModeState:e});return}let o=cu(r);a(o),s(o),J(n,{bannerState:o,accountModeState:o})}catch{}},[e,n]);(0,_.useEffect)(()=>{c.current!==e&&(c.current=e,Promise.resolve().then(()=>{p()}));let t=window.setInterval(()=>{p()},3e4);return()=>{window.clearInterval(t)}},[e,p]);let m=async()=>{u(!0),f(``);try{if(i!==`absent`&&i!==`disabled`)return;await Xa(e,i),await p()}catch(e){e instanceof Ya?f(t(e.i18nKey)):f(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{u(!1)}};return(0,R.jsx)(wa,{apiBase:e,accountModeState:o,banner:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(lu,{state:i,busy:l,onEnable:()=>{m()}}),d&&(0,R.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:d})]})})}function fu(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function pu(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 mu(e){return e.id}var hu={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 gu(e){let t=e||hu.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 _u(e,t){return new Date(e).toLocaleDateString(t)}function vu({url:e}){return(0,R.jsx)(yu,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,R.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}=G(),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,Ke.createPortal)((0,R.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,R.jsxs)(R.Fragment,{children:[(0,R.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 bu({text:e}){return(0,R.jsx)(yu,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,R.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}function xu({endpoints:e,claudeCodeEnabled:t}){let{t:n}=G();return(0,R.jsxs)(`div`,{className:`panel api-panel`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:n(`api.endpointsTitle`)}),(0,R.jsxs)(`div`,{className:`api-endpoints`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.baseUrl`)}),(0,R.jsx)(vu,{url:e.baseUrl})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.responsesEndpoint`)}),(0,R.jsx)(vu,{url:e.responses})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.chatCompletionsEndpoint`)}),(0,R.jsx)(vu,{url:e.chatCompletions})]}),t&&(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.messagesEndpoint`)}),(0,R.jsx)(vu,{url:e.messages})]}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`span`,{className:`muted small`,children:n(`api.modelsEndpoint`)}),(0,R.jsx)(vu,{url:e.models})]})]}),(0,R.jsx)(`p`,{className:`muted small`,children:n(`api.endpointNote`)}),(0,R.jsxs)(`details`,{className:`awi-inline-fold`,children:[(0,R.jsx)(`summary`,{children:n(`api.authTitle`)}),(0,R.jsxs)(`div`,{className:`awi-inline-fold-body`,children:[(0,R.jsxs)(`ul`,{className:`api-auth-list muted small`,children:[(0,R.jsx)(`li`,{children:n(`api.authChatCompletions`)}),(0,R.jsx)(`li`,{children:n(`api.authResponses`)}),t&&(0,R.jsx)(`li`,{children:n(`api.authMessages`)}),(0,R.jsx)(`li`,{children:n(`api.authLoopback`)})]}),(0,R.jsx)(`p`,{className:`muted small`,children:n(`api.authBaseUrlNote`)})]})]})]})}function Su({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:_}=G();return(0,R.jsxs)(R.Fragment,{children:[a&&(0,R.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:_(`api.newKeyTitle`)}),(0,R.jsx)(`p`,{className:`muted small`,children:_(`api.newKeyNote`)}),(0,R.jsxs)(`div`,{className:`api-form-row`,children:[(0,R.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:a}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:p,children:o?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(ie,{}),` `,_(`api.copied`)]}):_(`api.copy`)})]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:f,children:_(`api.dismiss`)})]}),(0,R.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:_(`api.generateTitle`)}),(0,R.jsxs)(`div`,{className:`api-form-row`,children:[(0,R.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:_(`api.keyNamePlaceholder`),"aria-label":_(`api.keyNamePlaceholder`),value:r,onChange:e=>u(e.target.value),className:`input`}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:d,disabled:i,children:[(0,R.jsx)(oe,{}),` `,_(i?`api.generating`:`api.generate`)]})]})]}),l&&(0,R.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:t?_(`api.activeKeysLoading`):_(`api.activeKeys`,{count:e.length})}),t?(0,R.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":_(`common.loading`)}):e.length>0?(0,R.jsx)(`div`,{className:`tbl-wrap`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:_(`api.colName`)}),(0,R.jsx)(`th`,{children:_(`api.colKey`)}),(0,R.jsx)(`th`,{children:_(`api.colCreated`)}),(0,R.jsx)(`th`,{})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{children:e.name}),(0,R.jsx)(`td`,{children:(0,R.jsx)(`code`,{children:e.prefix})}),(0,R.jsx)(`td`,{children:_u(e.createdAt,c)}),(0,R.jsx)(`td`,{children:s===e.id?(0,R.jsxs)(`span`,{className:`api-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>g(e.id),children:_(`api.confirm`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:h,children:_(`common.cancel`)})]}):(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":_(`api.deleteAria`),onClick:()=>m(e.id),children:(0,R.jsx)(ae,{})})})]},e.id))})]})}):n?(0,R.jsx)(`p`,{className:`muted`,children:_(`api.keysLoadFailed`)}):(0,R.jsx)(`p`,{className:`muted`,children:_(`api.noKeys`)})]})]})}function Cu({filteredModels:e,modelsLoading:t,modelsLoadFailed:n,modelQuery:r,copiedModelId:i,modelTests:a,claudeCodeEnabled:o,onModelQueryChange:s,onCopyModelId:c,onTestModel:l,sourceLabel:u,protocolLabel:d}){let{t:f}=G();return(0,R.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,R.jsxs)(`div`,{className:`api-panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:f(`api.modelsTitle`)}),(0,R.jsx)(`span`,{className:`muted mono text-label`,children:f(`api.modelsCount`,{count:e.length})})]}),(0,R.jsx)(`p`,{className:`muted small`,children:f(`api.modelsSubtitle`)}),(0,R.jsx)(`input`,{type:`search`,className:`input`,value:r,onChange:e=>s(e.target.value),placeholder:f(`api.modelsSearch`),"aria-label":f(`api.modelsSearch`)}),t?(0,R.jsx)(ma,{label:f(`api.modelsLoading`),rows:3}):n?null:e.length===0?(0,R.jsx)(`p`,{className:`muted small`,style:{marginTop:`0.75rem`},children:f(`api.modelsEmpty`)}):(0,R.jsx)(`div`,{className:`api-models-scroll`,children:(0,R.jsxs)(`table`,{className:`tbl`,children:[(0,R.jsx)(`thead`,{children:(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`th`,{children:f(`api.colModel`)}),(0,R.jsx)(`th`,{children:f(`api.colSource`)}),(0,R.jsx)(`th`,{children:f(`api.colProtocols`)}),(0,R.jsx)(`th`,{})]})}),(0,R.jsx)(`tbody`,{children:e.map(e=>{let t=mu(e),n=a[t]?.state??`idle`;return(0,R.jsxs)(`tr`,{children:[(0,R.jsx)(`td`,{children:(0,R.jsxs)(`div`,{className:`api-model-cell`,children:[(0,R.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,R.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,R.jsx)(`td`,{children:u(e)}),(0,R.jsx)(`td`,{children:fu(o).map(d).join(`, `)}),(0,R.jsxs)(`td`,{children:[(0,R.jsxs)(`div`,{className:`api-model-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{c(t)},children:f(i===t?`api.modelCopied`:`api.copyModelId`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:n===`testing`,onClick:()=>{l(e)},children:f(n===`testing`?`api.testingModel`:`api.testModel`)})]}),n===`ok`&&(0,R.jsx)(`p`,{className:`muted small api-test-note api-test-note--ok`,children:f(`api.testSucceeded`)}),n===`error`&&(0,R.jsx)(`p`,{className:`muted small api-test-note api-test-note--error`,children:a[t]?.detail??f(`api.testFailed`)})]})]},t)})})]})})]})}function wu({endpoints:e,claudeCodeEnabled:t}){let{t:n}=G(),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,R.jsxs)(`details`,{className:`awi-usage-fold`,children:[(0,R.jsx)(`summary`,{children:n(`api.workspace.usageExamples`)}),(0,R.jsxs)(`div`,{className:`awi-usage-fold-body`,children:[(0,R.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,R.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageChatTitle`)}),(0,R.jsx)(bu,{text:i})]}),(0,R.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,R.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageResponsesTitle`)}),(0,R.jsx)(bu,{text:a})]}),t&&(0,R.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,R.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageMessagesTitle`)}),(0,R.jsx)(bu,{text:o})]})]})]})}function Tu({keys:e,keysLoading:t,keysLoadFailed:n,endpoints:r,claudeCodeEnabled:i,localeTag:a,newName:o,creating:s,newKey:c,copied:l,filteredModels:u,modelsLoading:d,modelsLoadFailed:f,modelQuery:p,copiedModelId:m,modelTests:h,onNewNameChange:g,onCreate:v,onDismissNewKey:y,onCopyKey:b,onDelete:x,onModelQueryChange:S,onCopyModelId:C,onTestModel:w,sourceLabel:T,protocolLabel:E}){let D=K(),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),P=O?e.find(e=>e.id===O)??null:null,F=()=>{j(!1),N(!1)},I=()=>{k(null),F()};return(0,_.useEffect)(()=>{if(!A)return;let e=window.setTimeout(()=>N(!0),300);return()=>window.clearTimeout(e)},[A]),(0,R.jsx)(`div`,{className:`apikeys-workspace-shell`,children:(0,R.jsxs)(`div`,{className:`apikeys-workspace-root`,children:[(0,R.jsxs)(`aside`,{className:`apikeys-workspace-rail`,"aria-label":D(`api.title`),children:[(0,R.jsx)(`div`,{className:`apikeys-workspace-rail-header`,children:(0,R.jsx)(`span`,{className:`apikeys-workspace-rail-title`,children:t?D(`api.activeKeysLoading`):D(`api.activeKeys`,{count:e.length})})}),(0,R.jsxs)(`div`,{className:`apikeys-workspace-rail-list`,children:[(0,R.jsx)(`button`,{type:`button`,className:`apikeys-workspace-rail-row${O===null?` apikeys-workspace-rail-row--selected`:``}`,onClick:I,"aria-current":O===null?`page`:void 0,children:(0,R.jsx)(`span`,{className:`apikeys-workspace-rail-name`,children:D(`api.workspace.overview`)})}),t?(0,R.jsx)(`span`,{className:`apikeys-workspace-rail-empty`,children:D(`common.loading`)}):e.length===0?(0,R.jsx)(`span`,{className:`apikeys-workspace-rail-empty`,children:D(n?`api.keysLoadFailed`:`api.workspace.noKeysHint`)}):e.map(e=>(0,R.jsxs)(`button`,{type:`button`,className:`apikeys-workspace-rail-row${O===e.id?` apikeys-workspace-rail-row--selected`:``}`,onClick:()=>{k(e.id),F()},"aria-current":O===e.id?`page`:void 0,children:[(0,R.jsx)(`span`,{className:`apikeys-workspace-rail-name`,children:e.name}),(0,R.jsxs)(`span`,{className:`apikeys-workspace-rail-meta`,children:[e.prefix,` · `,_u(e.createdAt,a)]})]},e.id))]})]}),(0,R.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":D(`api.workspace.details`),children:P?(0,R.jsxs)(`div`,{className:`awi-detail`,children:[(0,R.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,R.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:I,children:[(0,R.jsx)(_e,{className:`awi-back-chevron`,"aria-hidden":`true`}),D(`modal.back`)]})}),(0,R.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,R.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,R.jsx)(`h2`,{className:`awi-detail-title`,children:P.name}),(0,R.jsx)(`span`,{className:`awi-detail-actions`,children:A?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{!P||!M||(x(P.id),F(),k(null))},disabled:!M,children:[(0,R.jsx)(ue,{}),` `,D(`api.confirm`)]},`confirm-delete`),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,children:D(`common.cancel`)})]}):(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:()=>{P&&j(!0)},"aria-label":D(`api.deleteAria`),children:[(0,R.jsx)(ue,{}),` `,D(`api.workspace.deleteKey`)]},`request-delete`)})]}),A&&(0,R.jsx)(`p`,{className:`muted awi-delete-hint`,children:D(`api.workspace.deleteConfirm`)}),(0,R.jsxs)(`div`,{className:`awi-section`,children:[(0,R.jsx)(`h3`,{className:`awi-section-title`,children:D(`api.workspace.keyDetails`)}),(0,R.jsxs)(`dl`,{className:`awi-kv`,children:[(0,R.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,R.jsx)(`dt`,{children:D(`api.colName`)}),(0,R.jsx)(`dd`,{children:P.name})]}),(0,R.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,R.jsx)(`dt`,{children:D(`api.workspace.keyPrefix`)}),(0,R.jsx)(`dd`,{children:(0,R.jsx)(`code`,{children:P.prefix})})]}),(0,R.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,R.jsx)(`dt`,{children:D(`api.colCreated`)}),(0,R.jsx)(`dd`,{children:_u(P.createdAt,a)})]})]})]})]})]}):(0,R.jsxs)(`div`,{className:`awi-overview`,children:[(0,R.jsxs)(`div`,{className:`awi-overview-left`,children:[(0,R.jsx)(Su,{keys:e,keysLoading:t,keysLoadFailed:n,newName:o,creating:s,newKey:c,copied:l,confirmDelete:null,localeTag:a,showKeyList:!1,onNewNameChange:g,onCreate:v,onDismissNewKey:y,onCopyKey:b,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,R.jsx)(xu,{endpoints:r,claudeCodeEnabled:i}),(0,R.jsx)(wu,{endpoints:r,claudeCodeEnabled:i})]}),(0,R.jsx)(`div`,{className:`awi-overview-right`,children:(0,R.jsx)(Cu,{filteredModels:u,modelsLoading:d,modelsLoadFailed:f,modelQuery:p,copiedModelId:m,modelTests:h,claudeCodeEnabled:i,onModelQueryChange:S,onCopyModelId:C,onTestModel:w,sourceLabel:T,protocolLabel:E})})]})})]})})}var Eu=[];function Du(e){let t=e.replace(/\/$/,``);if(!t)return hu;try{return new URL(t).host?gu(`${t}/v1/responses`):hu}catch{return hu}}function Ou({apiBase:e}){let{t,locale:n}=G(),r=Ie.find(e=>e.code===n)?.htmlLang,i=`ocx.apikeys.list.v1:${e}`,a=`ocx.apikeys.models.v1:${e}`,o=sn(i),s=sn(a),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)({}),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(!1),T=(0,_.useRef)(!1),E=(0,_.useCallback)(async n=>{let r=await lt(await fetch(`${e}/api/keys`,{signal:n}));if(!r)throw Error(t(`api.keysLoadFailed`));let a=gu(r.endpoint??``),o={keys:r.keys??[],endpoints:{baseUrl:r.baseUrl??a.baseUrl,responses:r.responsesEndpoint??r.endpoint??hu.responses,chatCompletions:r.chatCompletionsEndpoint??a.chatCompletions,messages:r.messagesEndpoint??a.messages,models:r.modelsEndpoint??a.models},claudeCodeEnabled:r.claudeCodeEnabled!==!1};return J(i,o),o},[e,i,t]),D=(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=>pu(e)).sort((e,t)=>mu(e).localeCompare(mu(t)));return J(a,s),s},[e,a,t]),O=ss(`api-keys:${e}`,[e],E,{isEmpty:e=>e.keys.length===0}),k=ss(`api-models:${e}`,[e],D,{isEmpty:e=>e.length===0}),A=O.state,j=k.state,M=A.data??o,N=j.data??s??Eu,P=M?.keys??[],F=M?.endpoints??Du(e),I=M?.claudeCodeEnabled??!0,L=O.refresh,z=(0,_.useMemo)(()=>{let e=u.trim().toLowerCase();return e?N.filter(t=>mu(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):N},[u,N]),B=async n=>{if(T.current)return!1;T.current=!0,b(!0),l(null);try{let r=n??g,i=await ct(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?(l(t(`api.createFailed`)),!1):(S(i.key),v(``),L(),!0)}catch{return l(t(`api.createFailed`)),!1}finally{T.current=!1,b(!1)}},V=async n=>{l(null);try{if(!(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n})})).ok){l(t(`api.deleteFailed`));return}L()}catch{l(t(`api.deleteFailed`))}},H=()=>{x&&(navigator.clipboard.writeText(x),w(!0),setTimeout(()=>w(!1),2e3))},U=async e=>{try{await navigator.clipboard.writeText(e),p(e),window.setTimeout(()=>p(t=>t===e?null:t),2e3)}catch{}},W=e=>e.native?t(`api.sourceNative`):e.provider===`combo`?t(`api.sourceCombo`):e.custom?t(`api.sourceCustom`):e.provider,ee=e=>t(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),te=async e=>{let n=mu(e);h(e=>({...e,[n]:{state:`testing`}}));try{let e=await fetch(F.chatCompletions,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:n,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1})});if(!e.ok){let t=await e.text();h(r=>({...r,[n]:{state:`error`,detail:t.slice(0,160)||String(e.status)}}));return}h(e=>({...e,[n]:{state:`ok`}}))}catch(e){h(r=>({...r,[n]:{state:`error`,detail:e instanceof Error?e.message:t(`api.testFailed`)}}))}},ne=t(`api.subtitle`).split(/\{authHeader\}|\{altHeader\}/);return(0,R.jsxs)(`section`,{className:`api-page`,children:[(0,R.jsx)(`div`,{className:`page-head`,children:(0,R.jsx)(`h2`,{children:t(`api.title`)})}),(0,R.jsxs)(`p`,{className:`page-sub`,children:[ne[0],(0,R.jsx)(`code`,{children:`Authorization: Bearer ocx_...`}),ne[1],(0,R.jsx)(`code`,{children:`x-opencodex-api-key`}),ne[2]]}),c&&(0,R.jsx)(q,{tone:`err`,children:c}),A.showError&&M&&(0,R.jsx)(q,{tone:`err`,children:t(`api.keysLoadFailed`)}),j.showError&&M&&(0,R.jsx)(q,{tone:`err`,children:t(`api.modelsLoadFailed`)}),A.showSkeleton&&!M?(0,R.jsx)(ma,{label:t(`api.activeKeysLoading`),rows:4}):A.kind===`failed-cold`&&!M?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(q,{tone:`err`,children:A.error instanceof Error?A.error.message:t(`api.keysLoadFailed`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>L(),children:t(`common.retry`)})]}):(0,R.jsxs)(R.Fragment,{children:[A.refreshing&&M&&(0,R.jsx)(ha,{live:!A.showError,children:t(`api.activeKeysLoading`)}),j.refreshing&&j.data&&(0,R.jsx)(ha,{live:!j.showError&&!(A.refreshing&&M),children:t(`api.modelsLoading`)}),(0,R.jsx)(Tu,{keys:P,keysLoading:!1,keysLoadFailed:A.showError,endpoints:F,claudeCodeEnabled:I,localeTag:r,newName:g,creating:y,newKey:x,copied:C,filteredModels:z,modelsLoading:j.showSkeleton&&!j.data&&!s,modelsLoadFailed:j.showError,modelQuery:u,copiedModelId:f,modelTests:m,onNewNameChange:v,onCreate:()=>{B()},onDismissNewKey:()=>S(null),onCopyKey:H,onDelete:e=>{V(e)},onModelQueryChange:d,onCopyModelId:e=>{U(e)},onTestModel:e=>{te(e)},sourceLabel:W,protocolLabel:ee})]})]})}function ku(e,t){let n=(e??[]).map(e=>({value:e,label:Io(e)}));return[{value:``,label:t},...n]}function Au(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}var ju=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`];function Mu(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=ju.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 Nu(e){return e?e.backend??`auto`:`inherit`}function Pu(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function Fu(e,t){return{...e,model:t}}function Iu(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 Lu({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,R.jsxs)(`label`,{className:`toggle`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,R.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function Ru({supported:e,checked:t,onChange:n}){let r=K(),i=e?void 0:`claude-system-env-unsupported`;return(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,R.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,R.jsx)(`span`,{className:`desc`,id:i,children:(0,R.jsx)(He,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,R.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,R.jsx)(Lu,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function zu({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=K(),a=t??e;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`h-section`,children:i(`claude.smallFastModel`)}),(0,R.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,R.jsx)(rt,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,R.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function Bu(){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 Vu(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 Hu(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 Uu({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=K();return(0,R.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.enabledLabel`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.enabledHint`)})]}),(0,R.jsx)(Lu,{label:i(`claude.enabledLabel`),checked:e.enabled,onChange:t=>r({...e,enabled:t})})]}),(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,R.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,R.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:Hu(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,R.jsx)(Ru,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,R.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,R.jsx)(Lu,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,R.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,R.jsx)(Lu,{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,R.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,R.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,R.jsx)(`span`,{className:`title`,children:i(o)}),(0,R.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,R.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,R.jsx)(rt,{value:Nu(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]:Pu(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,R.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:Fu(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,R.jsx)(`datalist`,{id:c,children:n.map(e=>(0,R.jsx)(`option`,{value:e},e))})]})]},t)})]})}function Wu({manualEnv:e}){let t=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`h-section`,children:t(`claude.quickstart`)}),(0,R.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,R.jsx)(He,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,R.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,R.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,R.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,R.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function Gu({rows:e,onRowsChange:t}){let n=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[n(`claude.modelMap`),` `,(0,R.jsx)(`span`,{className:`count`,children:e.length})]}),(0,R.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,R.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,R.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,R.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,R.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,R.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,R.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,R.jsx)(ae,{})})]},r.id))}),(0,R.jsx)(`div`,{style:{marginTop:8},children:(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:Bu(),from:``,to:``}]),children:[(0,R.jsx)(oe,{}),` `,n(`claude.addMapping`)]})})]})}var Ku=`etc`;function qu(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:Ku,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function Ju({aliases:e}){let t=K();return(0,R.jsxs)(`div`,{className:`claude-aliases`,children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[t(`claude.aliases`),` `,(0,R.jsx)(`span`,{className:`count`,children:e.length})]}),(0,R.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,R.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,R.jsx)(`div`,{className:`claude-aliases-scroll`,children:qu(e).map(([e,n])=>(0,R.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,R.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===Ku?t(`claude.aliasProviderOther`):e,(0,R.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,R.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,R.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,R.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,R.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function Yu(e){return sn(e)}function Xu({apiBase:e,active:t=!0}){let n=K(),{locale:r}=G(),i=Ie.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=(0,_.useMemo)(()=>Yu(a),[a]),[s,c]=(0,_.useState)(()=>o?.state??null),[l,u]=(0,_.useState)(()=>o?.rows??[]),[d,f]=(0,_.useState)(!!o),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(`settings`),b=(0,_.useCallback)(async t=>{let r=await ct(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`,...Au(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:Bu(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return c(i),u(o),f(!0),J(a,s),s},[e,a,n]),x=ss(`claude-code:${e}`,[e],b,{isEmpty:()=>!1,enabled:t}),S=x.state,C=S.data??o,w=s??C?.state??null,T=d?l:C?.rows??l,E=(0,_.useMemo)(()=>ku(w?.available,n(`claude.smallFastModelUnsetOption`)),[w?.available,n]),D=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,9e5,1e6],t=w?.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:Vu(e,i)}))]},[w?.autoCompactWindow,n,i]),O=async()=>{if(!w)return;m(``);let t={};for(let e of T)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await ct(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:w.enabled,authMode:w.authMode,systemEnv:w.systemEnv,fastMode:w.fastMode,autoContext:w.autoContext,autoCompactWindow:w.autoCompactWindow,injectAgents:w.injectAgents,smallFastModel:w.smallFastModel,modelMap:t,webSearchSidecar:Iu(w.webSearchSidecar),visionSidecar:Iu(w.visionSidecar)})}),n(`claude.saveFailed`)),g(!0),m(n(`claude.saved`)),x.refresh()}catch(e){g(!1),m(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(S.kind===`disabled`&&!C)return null;if(S.showSkeleton&&!C)return(0,R.jsx)(ma,{label:n(`claude.loading`),rows:3});if(S.kind===`failed-cold`)return(0,R.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,R.jsx)(q,{tone:`err`,children:S.error instanceof Error?S.error.message:n(`claude.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x.refresh(),children:n(`common.retry`)})]});if(!w)return null;let k=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,R.jsx)(Uu,{state:w,autoCompactOptions:D,availableModels:w.available??[],onStateChange:c})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,R.jsx)(Wu,{manualEnv:Mu(w)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,R.jsx)(zu,{value:w.smallFastModel,tierHaikuModel:w.tierModels?.haiku,options:E,onChange:e=>c({...w,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),body:(0,R.jsx)(Gu,{rows:T,onRowsChange:e=>{f(!0),u(e)}})},{id:`aliases`,label:n(`claude.aliases`),body:(0,R.jsx)(Ju,{aliases:w.aliases})}],A=k.find(e=>e.id===v)??k[0],j=v===`settings`||v===`smallFast`||v===`modelMap`;return(0,R.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:n(`claude.pageTitle`)}),j&&(0,R.jsx)(`div`,{className:`claudecode-workspace-save`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{O()},children:n(`common.save`)})})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:n(`claude.subtitle`)}),p&&(0,R.jsx)(q,{tone:h?`ok`:`err`,children:p}),S.showError&&(0,R.jsx)(q,{tone:`err`,children:n(`claude.loadFail`)}),S.refreshing&&(0,R.jsx)(ha,{live:!S.showError,children:n(`claude.loading`)}),(0,R.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,R.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,R.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:k.map(e=>(0,R.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${v===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>y(e.id),"aria-current":v===e.id?`true`:void 0,children:(0,R.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,R.jsx)(`section`,{className:`claudecode-workspace-main`,"aria-label":A.label,children:(0,R.jsx)(`div`,{className:`ccw-body`,children:A.body})})]})]})}function Zu(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 Qu(e){return new Set(Object.keys(e))}function $u(e,t){return t!==null&&e===t}function ed(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function td(e){return{read(t){let n=ed(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=ed(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function nd(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var rd=[`opus`,`fable`,`sonnet`,`haiku`],id=td(`ocx.claudeDesktop.collapsedFamilies.v2`),ad={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function od(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 sd(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:rd.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 cd(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function ld(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 ud(e){return sn(e)}function dd(e){let t=ud(e);return{data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?od(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{},hasCache:!!t?.data}}function fd({apiBase:e,active:t=!0}){let n=K(),r=`ocx.claude-desktop.v1:${e}`,i=(0,_.useMemo)(()=>dd(r),[r]),[a,o]=(0,_.useState)(()=>i.profile),[s,c]=(0,_.useState)(()=>i.savedProfile),[l,u]=(0,_.useState)(()=>i.destinations),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)({}),[b,x]=(0,_.useState)({}),[S,C]=(0,_.useState)(()=>id.read()??new Set(rd)),[w,T]=(0,_.useState)({}),E=(0,_.useRef)(null),D=(0,_.useCallback)(async t=>{let i=await ct(await fetch(`${e}/api/claude-desktop`,{signal:t}),n(`claudeDesktop.loadFail`));if(!i||!(`profile`in i)||!(`models`in i))throw Error(cd(i,n(`claudeDesktop.loadFail`)));let a=sd(i),s={data:i,profile:a};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(o(a),c(od(a)),u(Object.fromEntries(i.models.map(e=>[e.route,a.assignments[e.route]?.family??`opus`]))),id.read()===null){let e=Object.fromEntries(rd.map(e=>[e,0]));for(let t of i.models)e[a.assignments[t.route]?.family??`opus`]+=1;C(Qu(e))}return J(r,s),s},[e,r,n]),O=ss(`claude-desktop:${e}`,[e],D,{isEmpty:()=>!1,enabled:t}),k=O.state,A=k.data??(i.data&&i.profile?{data:i.data,profile:i.profile}:null),j=A?.data??null,M=a??A?.profile??null,N=s??A?.profile??null,P=A?Object.fromEntries(A.data.models.map(e=>[e.route,A.profile.assignments[e.route]?.family??`opus`])):{},F=Object.keys(l).length>0?l:P,I=(0,_.useMemo)(()=>M!==null&&N!==null&&JSON.stringify(M)!==JSON.stringify(N),[M,N]),L=(0,_.useMemo)(()=>{let e=Object.fromEntries(rd.map(e=>[e,[]]));if(!j||!M)return e;for(let t of j.models)e[M.assignments[t.route]?.family??`opus`].push(t);return e},[j,M]),z=(0,_.useMemo)(()=>{let e={};for(let t of rd){let n=L[t].filter(e=>e.available).map(e=>e.route).sort(),r=M?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[L,M]),B=ss(`claude-desktop-status:${e}`,[e],async t=>{let n=await lt(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return n},{isEmpty:()=>!1,pollMs:5e3,enabled:t}).state.data??null,V=(e,t)=>{!M||M.assignments[e]?.family===t||(o(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}}),u(n=>({...n,[e]:t})),m(n(`claudeDesktop.moved`,{route:e,family:n(ad[t])})))},H=e=>{let t=nd(S,e);id.write(t),C(t)},U=async t=>{if(!(!M||h)){g(`save`),f(null);try{await ct(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:M})}),n(`claudeDesktop.saveFailed`)),c(od(M)),t?(g(`apply`),await ct(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`}),n(`claudeDesktop.applyFailed`)),f({tone:`ok`,text:n(`claudeDesktop.savedApplied`)}),m(n(`claudeDesktop.savedAppliedAnnounce`))):(f({tone:`ok`,text:n(`claudeDesktop.saved`)}),m(n(`claudeDesktop.savedAnnounce`)))}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.updateFailed`);f({tone:`err`,text:t}),m(t)}finally{g(null)}}},W=()=>{if(!M)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(M,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),m(n(`claudeDesktop.exported`))},ee=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(n(`claudeDesktop.importExpected`));o(sd({...j,profile:e})),f({tone:`ok`,text:n(`claudeDesktop.importReady`)}),m(n(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.importInvalid`);f({tone:`err`,text:t}),m(n(`claudeDesktop.importFailed`,{error:t}))}},te=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&V(n,t)};return k.kind===`disabled`&&!A?null:k.showSkeleton&&!A?(0,R.jsx)(ma,{label:n(`claudeDesktop.loading`),rows:4}):k.kind===`failed-cold`?(0,R.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,R.jsx)(q,{tone:`err`,children:k.error instanceof Error?k.error.message:n(`claudeDesktop.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>O.refresh(),children:n(`claudeDesktop.retry`)})]}):!j||!M?null:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head claude-desktop-head`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h2`,{children:n(`claudeDesktop.title`)}),(0,R.jsx)(`p`,{className:`page-sub`,children:n(`claudeDesktop.subtitle`,{port:j.port})})]}),(0,R.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,R.jsx)(`input`,{ref:E,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ee(e)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E.current?.click(),children:n(`claudeDesktop.importJson`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:W,children:n(`claudeDesktop.exportJson`)})]})]}),B&&(0,R.jsxs)(`div`,{className:`claude-status-bar ${B.activeProfile===!1?`not-applied`:B.stale?`stale`:B.applied?`applied`:`not-applied`}`,children:[(0,R.jsx)(`span`,{className:`claude-status-dot`}),(0,R.jsx)(`span`,{children:B.activeProfile===!1?n(`claudeDesktop.status.notActiveProfile`):B.stale?n(`claudeDesktop.status.stale`):B.applied?n(`claudeDesktop.status.applied`):n(`claudeDesktop.status.notApplied`)}),B.health.lastRequestAt&&(0,R.jsxs)(`span`,{className:`claude-status-health`,children:[n(`claudeDesktop.health.lastRequest`),`: `,new Date(B.health.lastRequestAt).toLocaleTimeString()]}),B.health.requestCount>0&&(0,R.jsx)(`span`,{className:`claude-status-health`,children:n(`claudeDesktop.health.stats`,{count:B.health.requestCount,errors:B.health.errorCount})})]}),(0,R.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:p}),d&&(0,R.jsx)(q,{tone:d.tone,children:d.text}),k.showError&&(0,R.jsx)(q,{tone:`err`,children:n(`claudeDesktop.loadFail`)}),k.refreshing&&(0,R.jsx)(ha,{live:!k.showError,children:n(`claudeDesktop.loading`)}),(0,R.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,R.jsx)(`span`,{className:`claude-dirty${I?` active`:``}`,children:n(I?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,R.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!I||h!==null,onClick:()=>void U(!1),children:n(h===`save`?`claudeDesktop.saving`:`common.save`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:h!==null,onClick:()=>void U(!0),children:n(h===`apply`?`claudeDesktop.applying`:h===`save`?`claudeDesktop.saving`:`claudeDesktop.saveApply`)})]})]}),j.models.length===0&&(0,R.jsx)(it,{title:n(`claudeDesktop.emptyTitle`),children:n(`claudeDesktop.emptyHint`)}),(0,R.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":n(`claudeDesktop.assignmentsLabel`),children:rd.map(e=>{let t=L[e],r=Zu(t,v[e]??``,b[e]??6),i=S.has(e),a=z[e];return(0,R.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>te(t,e),children:[(0,R.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,R.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,R.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>H(e),children:[(0,R.jsx)(_e,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,R.jsx)(`span`,{className:`ocx-group-name`,children:n(ad[e])}),(0,R.jsx)(`span`,{className:`ocx-group-count`,children:n(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,R.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&M.defaults[e]===null&&(0,R.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.chooseDefault`)}),a&&a!==M.defaults[e]&&(0,R.jsx)(`span`,{className:`claude-default-needed`,title:a,children:n(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,R.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[r.showSearch&&(0,R.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:n(`models.search`),"aria-label":n(`models.search`),value:v[e]??``,onChange:t=>{let n=t.target.value;y(t=>({...t,[e]:n})),x(t=>({...t,[e]:6}))}}),(0,R.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,R.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneEmpty`)}):r.noMatch?(0,R.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneNoMatch`)}):r.shown.map(t=>{let r=M.assignments[t.route],i=ld(t.contextWindow,n),a=F[t.route]??`opus`,s=w[t.route]??$u(t.route,z[e]);return(0,R.jsxs)(`article`,{className:`claude-model-card${s?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,R.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":s,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>T(e=>({...e,[t.route]:!s})),children:[(0,R.jsx)(_e,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:s?`rotate(90deg)`:`none`}}),(0,R.jsxs)(`span`,{className:`claude-model-names`,children:[(0,R.jsx)(`strong`,{title:t.label,children:t.label}),(0,R.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,R.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,R.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:n(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,R.jsx)(`span`,{className:`claude-1m-chip`,children:n(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,R.jsx)(`span`,{className:`claude-effort-badge off`,children:n(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,R.jsx)(`span`,{className:`claude-effort-badge on`,children:n(`claudeDesktop.effort.supported`)}),M.defaults[e]===t.route&&(0,R.jsx)(`span`,{className:`claude-row-default`,children:n(`claudeDesktop.defaultBadge`)}),(0,R.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?n(`claudeDesktop.available`):n(`claudeDesktop.unavailable`)})]}),s&&(0,R.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[z[e]===t.route&&M.defaults[e]!==t.route&&(0,R.jsx)(`span`,{className:`claude-effective-default`,children:n(`claudeDesktop.temporaryDefault`)}),(0,R.jsxs)(`div`,{className:`claude-field`,children:[(0,R.jsx)(`span`,{children:n(`claudeDesktop.alias`)}),(0,R.jsx)(`code`,{className:`claude-alias`,title:r.alias,children:r.alias})]}),(0,R.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,R.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:M.defaults[e]===t.route,disabled:!t.available,onChange:()=>o(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),n(`claudeDesktop.useAsDefault`,{family:n(ad[e])})]}),(0,R.jsxs)(`div`,{className:`claude-move-row`,children:[(0,R.jsx)(`label`,{htmlFor:`move-${t.route}`,children:n(`claudeDesktop.moveTo`)}),(0,R.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>u(n=>({...n,[t.route]:e.target.value})),children:rd.map(e=>(0,R.jsx)(`option`,{value:e,children:n(ad[e])},e))}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>V(t.route,a),children:n(`claudeDesktop.move`)})]})]})]},t.route)}),r.hidden>0&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>x(t=>({...t,[e]:(t[e]??6)+6})),children:n(`models.showMore`,{n:r.hidden})})]})]})]},e)})})]})}function pd({apiBase:e}){let[t,n]=(0,_.useState)(`code`),r=K(),i=(0,_.useRef)(null),a=(0,_.useRef)(null),o=e=>{n(e),window.requestAnimationFrame(()=>(e===`code`?i:a).current?.focus())},s=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),o(t===`code`?`desktop`:`code`)):e.key===`Home`?(e.preventDefault(),o(`code`)):e.key===`End`&&(e.preventDefault(),o(`desktop`))};return(0,R.jsxs)(`section`,{className:`claude-page`,children:[(0,R.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":r(`claude.tabsLabel`),children:[(0,R.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:s,onClick:()=>o(`code`),children:r(`claude.tabCode`)}),(0,R.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:s,onClick:()=>o(`desktop`),children:r(`claude.tabDesktop`)})]}),(0,R.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:t!==`code`,children:(0,R.jsx)(Xu,{apiBase:e,active:t===`code`},e)}),(0,R.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:t!==`desktop`,children:(0,R.jsx)(fd,{apiBase:e,active:t===`desktop`},e)})]})}function md(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 hd=td(`ocx.grok.collapsedGroups.v2`),gd=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],_d=new Set(gd.map(e=>e.id));function vd(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 $({apiBase:e}){let t=K(),n=`ocx.grok.status.v1:${e}`,r=sn(n),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(()=>hd.read()??new Set(_d)),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(``),m=(0,_.useCallback)(async()=>{let r=await ct(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 J(n,i),i},[e,n,t]),h=`grok-status:${e}`,g=ss(h,[e],m,{isEmpty:()=>!1}),{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=nd(o,e);hd.write(t),s(t)},E=e=>{let t=e?new Set(gd.map(e=>e.id)):new Set;hd.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 ct(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&&I(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&&J(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,R.jsx)(`section`,{className:`grok-page`,children:(0,R.jsx)(ma,{label:t(`grok.loading`),rows:4})}):v.kind===`failed-cold`?(0,R.jsxs)(`section`,{className:`grok-page`,children:[(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:v.error instanceof Error?v.error.message:t(`grok.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>y(),children:t(`common.retry`)})]}):(0,R.jsxs)(`section`,{className:`grok-page`,children:[(0,R.jsx)(`h2`,{className:`page-title`,children:t(`grok.title`)}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`grok.subtitle`)}),(0,R.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:f}),u&&(0,R.jsx)(q,{tone:u.tone,children:u.text}),v.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`grok.loadFail`)}),v.refreshing&&(0,R.jsx)(ha,{live:!v.showError,children:t(`grok.loading`)}),b&&b.candidates.length>0&&(0,R.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,R.jsx)(`span`,{className:`claude-dirty${C?` active`:``}`,children:t(C?`grok.unsaved`:`grok.upToDate`)}),(0,R.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,R.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,R.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,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,R.jsx)(`span`,{children:t(`grok.endpoint`)}),(0,R.jsx)(`code`,{children:b.baseUrl??`—`})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:(0,R.jsx)(`code`,{children:b.configPath})})]}):(0,R.jsxs)(it,{title:t(`grok.notConfiguredTitle`),children:[t(`grok.notConfiguredHint`),(0,R.jsx)(`br`,{}),(0,R.jsx)(`code`,{children:b?.configPath})]}),b&&b.candidates.length>0&&(0,R.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,R.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!0),disabled:c!==null,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!1),disabled:c!==null,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),gd.map(e=>{let n=md(b.candidates,w,S,e.id);if(n.total===0)return null;let r=o.has(e.id);return(0,R.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,R.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,R.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,R.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>T(e.id),children:[(0,R.jsx)(_e,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,R.jsx)(`span`,{className:`ocx-group-name`,children:t(e.tkey)}),(0,R.jsx)(`span`,{className:`ocx-group-count`,children:t(`grok.enabledCount`,{on:n.enabled,total:n.total})})]})})}),!r&&(0,R.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:n.rows.map(e=>(0,R.jsxs)(`div`,{className:`grok-model-row`,children:[(0,R.jsx)(nt,{on:e.enabled,onClick:()=>D(e.id,!e.enabled),disabled:c!==null,label:t(`grok.toggleModel`,{id:e.id})}),(0,R.jsxs)(`span`,{className:`grok-model-names`,children:[(0,R.jsx)(`strong`,{title:e.id,children:e.id}),(0,R.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,R.jsx)(`span`,{className:`claude-model-context`,children:vd(e.contextWindow,t)})]},e.id))})]},e.id)})]})]})}function yd(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 bd={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},xd={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},Sd={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function Cd({ok:e,yes:t,no:n}){return(0,R.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function wd({failed:e,data:t}){let{t:n}=G(),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`?de:ie,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,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,R.jsx)(`div`,{className:`startup-hero-icon`,children:(0,R.jsx)(i,{})}),(0,R.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,R.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:bd[t.status])}),(0,R.jsx)(`h3`,{children:n(e?`startup.error`:xd[t.status])}),(0,R.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(cn(t)):n(`startup.safeDetail`)})]})]}),(0,R.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,R.jsxs)(`section`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,R.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,R.jsxs)(`section`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,R.jsx)(`div`,{className:`value`,children:n(Sd[t.protection])})]}),(0,R.jsxs)(`section`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,R.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function Td({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=G(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,R.jsxs)(`section`,{className:`panel startup-details`,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,R.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,R.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:o(`startup.service`)}),(0,R.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,R.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,R.jsx)(Cd,{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,R.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,R.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,R.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:o(`startup.shim`)}),(0,R.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,R.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,R.jsx)(Cd,{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,R.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,R.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,R.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 Ed({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=G();return(0,R.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,R.jsx)(ye,{})]}),(0,R.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,R.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,R.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,R.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,R.jsx)(Cd,{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,R.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,R.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,R.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,R.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,R.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,R.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function Dd({data:e,copied:t,onCopy:n}){let{t:r}=G();return(0,R.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,R.jsx)(te,{})]}),(0,R.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,R.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,R.jsxs)(`div`,{className:`startup-command-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,R.jsx)(`code`,{children:e.commands.installService})]}),(0,R.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,R.jsxs)(`div`,{className:`startup-command-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,R.jsx)(`code`,{children:e.commands.installShim})]}),(0,R.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,R.jsxs)(`div`,{className:`startup-command-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,R.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,R.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,R.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,R.jsx)(ye,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var Od=`ocx.startup.page.v1:`;function kd(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function Ad(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=kd([`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 jd({apiBase:e}){let{t}=G(),n=`${Od}${e}`,r=(0,_.useMemo)(()=>sn(n),[n]),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(()=>r?.tray??null),[c,l]=(0,_.useState)(()=>!r?.data),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(()=>r?.warning??null),[x,S]=(0,_.useState)(()=>r?.fix??null),[C,w]=(0,_.useState)(()=>!r?.data),T=(0,_.useRef)(!!r?.data),E=(0,_.useCallback)(async r=>{let i=T.current;i||(l(!0),w(!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();T.current=!0;let c=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(!yd(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,c]).then(([e,i])=>{if(r.aborted)return;let a=o.platform===`win32`?i.tray:null;if(o.platform===`win32`?(s(a),p(i.error)):(s(null),p(!1)),l(!1),w(!1),e){let r=Ad(e.codexRuntime,t,o.platform);b(r.warning),S(r.fix),J(n,{data:o,warning:r.warning,fix:r.fix,tray:a});return}let c=sn(n);J(n,{data:o,warning:c?.warning??null,fix:c?.fix??null,tray:a})}),o}catch(e){throw r.aborted?e:(i||(s(null),p(!0),b(null),S(null)),w(!1),l(!1),e)}},[e,n,t]),D=ss(`startup-page:${e}`,[e],E,{isEmpty:()=>!1}),O=D.state,k=D.refresh,A=O.data??r?.data??null,j=O.refreshing,M=!!A?.diagnosticStale||O.showError;(0,_.useEffect)(()=>{if(!A?.diagnosticStale)return;let e=window.setTimeout(k,2e3);return()=>window.clearTimeout(e)},[A,k]);let N=async e=>{try{await navigator.clipboard.writeText(e),a(e),window.setTimeout(()=>a(t=>t===e?null:t),1600)}catch{a(null)}},P=async t=>{d(!0),p(!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(!yd(r.status))throw Error(`invalid tray action status`);s(r.status),p(!1)}catch{s(null),p(!0)}finally{d(!1)}},F=async(t,n)=>{h(t),v(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`)}v({kind:`success`,action:t,repair:n?.repair===!0}),k()}catch(e){v({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e)})}finally{h(null)}};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h2`,{children:t(`startup.title`)}),(0,R.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,R.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,R.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`#dashboard`,children:t(`startup.backToDashboard`)}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),disabled:j,children:[(0,R.jsx)(se,{}),` `,t(`startup.refresh`)]})]})]}),O.showSkeleton&&!A?(0,R.jsx)(ma,{label:t(`startup.loading`),rows:5}):O.kind===`failed-cold`?(0,R.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,R.jsx)(q,{tone:`err`,children:O.error instanceof Error?O.error.message:t(`startup.error`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:t(`common.retry`)})]}):A?(0,R.jsxs)(R.Fragment,{children:[O.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`startup.error`)}),O.refreshing&&(0,R.jsx)(ha,{live:!O.showError,children:t(`startup.loading`)}),M&&(0,R.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(C||y)&&(0,R.jsx)(`div`,{className:`startup-runtime-notice-slot${C&&!y?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":C&&!y?!0:void 0,children:y&&(0,R.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,R.jsx)(`p`,{className:`startup-runtime-notice__text`,children:y}),x&&(0,R.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,R.jsx)(`code`,{children:x}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void N(x),children:t(i===x?`startup.copied`:`startup.copy`)})]})]})}),(0,R.jsx)(wd,{failed:M,data:A}),(0,R.jsx)(Td,{data:A,failed:M,loading:j,installBusy:m,installResult:g,onInstall:(e,t)=>{F(e,t)}}),A.platform===`win32`&&(0,R.jsx)(Ed,{tray:o,trayLoading:c,trayError:f,trayBusy:u,onTrayAction:e=>{P(e)}}),(0,R.jsx)(Dd,{data:A,copied:i,onCopy:e=>{N(e)}})]}):null]})}var Md=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,R.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,R.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,R.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,R.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,R.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},Nd=5*6e4,Pd=10*6e4,Fd=`https://github.com/lidge-jun/opencodex`;async function Id(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Ld({apiBase:e,onOpenUpdate:t}){let n=K(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=F(`sidebar-star:${e}`,[e],t=>Id(`${e}/api/github/star`,t),{pollMs:Nd}),c=F(`sidebar-update-badge:${e}`,[e],t=>Id(`${e}/api/update/badge`,t),{pollMs:Pd}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??Fd,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,R.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,R.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,R.jsx)(ve,{}),` `,n(`common.github`)]}),(0,R.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,R.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,R.jsx)(Me,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,R.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,R.jsx)(ge,{"aria-hidden":`true`}),m&&(0,R.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Rd=!1,zd=null,Bd=null,Vd=!1,Hd=`/`;function Ud(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 Wd=`opencodex-api-token`,Gd=null,Kd=null,qd=null;function Jd(){return Gd}function Yd(e){Gd=e}function Xd(){Gd=null,Kd=null,qd=null}function Zd(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function Qd(){ef(Zd(`opencodex-session-token`),Zd(`opencodex-session-csrf`),Zd(`opencodex-session-origin`))}function $d(e){e!=null&&Jd()===e&&Xd()}function ef(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(Gd=e,Kd=t,qd=n,!0)}function tf(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 nf(){if(!Bd)return null;try{let e=await Bd(Hd,{cache:`no-store`});if(!e.ok)return null;let t=await e.text();return ef(tf(t,`opencodex-session-token`),tf(t,`opencodex-session-csrf`),tf(t,`opencodex-session-origin`))?Jd():null}catch{return null}}function rf(){try{sessionStorage.removeItem(Wd)}catch{}}function af(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),qd&&Kd&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,qd);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,Kd)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function of(e){return Vd?null:zd||(zd=(async()=>{if(Vd)return null;let t=Jd();if(t&&t!==e)return t;let n=await nf();if(n)return n;let r=window.prompt(`OpenCodex admin token (OPENCODEX_ADMIN_AUTH_TOKEN)`)?.trim()||null;return r?(Yd(r),r):(Vd=!0,null)})().finally(()=>{zd=null}),zd)}function sf(){if(Rd)return;Rd=!0,rf(),Qd();let e=window.fetch.bind(window);Bd=e,window.fetch=async(t,n)=>{if(!Ud(t))return e(t,n);let r=Jd(),[i,a]=r?af(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;let s=Jd();if(s&&s!==r){let[r,i]=af(t,n,s),a=await e(r,i);if(a.status!==401)return a;$d(s)}else $d(r);let c=await of(r);if(!c)return o;let[l,u]=af(t,n,c),d=await e(l,u);return d.status===401&&$d(c),d}}var cf=new Set([`dashboard`,`startup`,`providers`,`models`,`combos`,`subagents`,`logs`,`usage`,`storage`,`codex-auth`,`api`,`claude`,`grok`]);function lf(e){let t=Ue(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:cf.has(t)?t:`dashboard`}var uf=[`dashboard/providers`,`dashboard/models`];function df(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`dashboard`&&(e===`dashboard/update`||uf.includes(e))}function ff(e){let t=lf(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:df(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var pf=[`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 mf(){try{for(let e of pf)localStorage.removeItem(e)}catch{}}function hf(){let[e,t]=(0,_.useState)(lf);(0,_.useEffect)(()=>{mf()},[]);let n=(0,_.useCallback)(e=>{let n=ff(e);n.replaceTo&&We(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(Ue(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=Ue(window.location.hash);if(t===`debug`||t.startsWith(`debug/`)){We(`logs/debug`);return}if(t===`providers/workspace`){We(`providers`);return}df(t,e)||We(e)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{Ge(n?`${e}/${n}`:e),t(e)}}}var gf=15e3;function _f(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 vf(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function yf(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=gf,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 vf(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:_f(o,a.status,i)}:{accepted:!0}}sf();var bf={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`},xf=``,Sf=`ocx-theme`,Cf=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:B},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:xe},{id:`providers`,tkey:`nav.providers`,Icon:V},{id:`models`,tkey:`nav.models`,Icon:H},{id:`subagents`,tkey:`nav.subagents`,Icon:U},{id:`logs`,tkey:`nav.logs`,Icon:W},{id:`usage`,tkey:`nav.usage`,Icon:ne},{id:`storage`,tkey:`nav.storage`,Icon:re},{id:`api`,tkey:`nav.api`,Icon:Oe},{id:`claude`,tkey:`nav.claude`,Icon:ke},{id:`grok`,tkey:`nav.grok`,Icon:H}],wf={light:Te,dark:Ee,system:De},Tf={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function Ef(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 Df(){let e=localStorage.getItem(Sf);return e===`light`||e===`dark`?e:`system`}function Of(){let{page:e,navigateToPage:t}=hf(),[n,r]=(0,_.useState)(Df),{locale:i,setLocale:a}=G(),o=K(),[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(Sf)):(e.setAttribute(`data-theme`,n),localStorage.setItem(Sf,n))},[n]);let f=F(`app-healthz:${xf}`,[],async e=>{let t=await fetch(`${xf}/healthz`,{signal:e});return t.ok?Ef(await t.json()):null},{pollMs:3e4}),p=()=>r(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),m=wf[n],h=f.data??`2.8.0`,[g,v]=(0,_.useState)(!1),y=(0,_.useCallback)(async e=>{let t=await lt(await fetch(`${xf}/api/claude-code`,{signal:e}));return t&&typeof t.enabled==`boolean`?t.enabled:null},[]),b=F(`app-claude-code:${xf}`,[],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;I(`app-claude-code:${xf}`,e);try{(await fetch(`${xf}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:e})})).ok||I(`app-claude-code:${xf}`,!e)}catch{I(`app-claude-code:${xf}`,!e)}finally{x.current=!1,C(!1)}},T=async()=>{if(!confirm(o(`dash.stopConfirm`)))return;v(!0);let e=await yf(xf,{formatFailure:e=>o(`dash.stopFailed`,{status:String(e)})});e.accepted||(v(!1),alert(e.message))},E=(0,R.jsxs)(`div`,{className:`brand`,children:[(0,R.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":o(`app.logoAria`)}),(0,R.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,R.jsxs)(`span`,{className:`ver`,children:[`v`,h]})]});return(0,R.jsxs)(`div`,{className:`app`,children:[(0,R.jsxs)(`header`,{className:`mobile-topbar`,inert:s,children:[(0,R.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,R.jsx)(ee,{})}),E,(0,R.jsx)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:(0,R.jsx)(ye,{})})]}),s&&(0,R.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>c(!1),"aria-hidden":`true`}),(0,R.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${s?` open`:``}`,ref:u,tabIndex:-1,children:[(0,R.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,R.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>c(!1),"aria-label":o(`nav.closeMenu`),title:o(`nav.closeMenu`),children:(0,R.jsx)(ae,{})})]}),(0,R.jsx)(`nav`,{children:Cf.map(({id:n,tkey:r,Icon:i})=>(0,R.jsxs)(`div`,{className:`nav-entry${n===`claude`?` nav-entry-claude${e===n?` active`:``}`:``}`,children:[(0,R.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,R.jsx)(i,{}),` `,o(r)]}),n===`claude`&&b!==null&&(0,R.jsx)(nt,{on:b,onClick:()=>void w(),disabled:S,label:o(`claude.toggleAria`)})]},n))}),(0,R.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,R.jsxs)(`div`,{className:`lang-toggle`,children:[(0,R.jsx)(Oe,{"aria-hidden":!0}),(0,R.jsx)(rt,{value:i,options:Ie.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,R.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:p,"aria-label":`${o(`theme.label`)}: ${o(Tf[n])}`,title:`${o(`theme.label`)}: ${o(Tf[n])}`,children:[(0,R.jsx)(m,{}),` `,(0,R.jsx)(`span`,{className:`mode`,children:o(Tf[n])})]}),(0,R.jsxs)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:[(0,R.jsx)(ye,{}),` `,(0,R.jsx)(`span`,{className:`mode`,children:o(g?`dash.stopping`:`dash.stop`)})]}),(0,R.jsx)(Ld,{apiBase:xf,onOpenUpdate:()=>{c(!1),t(`dashboard`,`update`)}})]})]}),(0,R.jsx)(`main`,{className:`main`,inert:s,children:(0,R.jsx)(`div`,{className:`main-inner${e===`combos`?` main-inner--combos`:``}`,children:(0,R.jsxs)(Md,{pageName:o(bf[e]),title:o(`errorBoundary.title`),message:o(`errorBoundary.message`),detailsLabel:o(`errorBoundary.details`),reloadLabel:o(`errorBoundary.reload`),children:[e===`dashboard`&&(0,R.jsx)(Fn,{apiBase:xf}),e===`startup`&&(0,R.jsx)(jd,{apiBase:xf}),e===`providers`&&(0,R.jsx)(jo,{apiBase:xf}),e===`models`&&(0,R.jsx)(Ns,{apiBase:xf}),e===`combos`&&(0,R.jsx)(Zs,{apiBase:xf},xf),e===`subagents`&&(0,R.jsx)(oc,{apiBase:xf},xf),e===`logs`&&(0,R.jsx)(wl,{apiBase:xf}),e===`usage`&&(0,R.jsx)(Wl,{apiBase:xf}),e===`storage`&&(0,R.jsx)(su,{apiBase:xf}),e===`codex-auth`&&(0,R.jsx)(du,{apiBase:xf}),e===`api`&&(0,R.jsx)(Ou,{apiBase:xf}),e===`claude`&&(0,R.jsx)(pd,{apiBase:xf}),e===`grok`&&(0,R.jsx)($,{apiBase:xf})]},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,R.jsx)(_.StrictMode,{children:(0,R.jsx)(Ve,{children:(0,R.jsx)(Of,{})})}));
67
+ `)}function Nu(e){return e?e.backend??`auto`:`inherit`}function Pu(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function Fu(e,t){return{...e,model:t}}function Iu(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 Lu({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,R.jsxs)(`label`,{className:`toggle`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,R.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function Ru({supported:e,checked:t,onChange:n}){let r=K(),i=e?void 0:`claude-system-env-unsupported`;return(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,R.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,R.jsx)(`span`,{className:`desc`,id:i,children:(0,R.jsx)(He,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,R.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,R.jsx)(Lu,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function zu({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=K(),a=t??e;return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`h-section`,children:i(`claude.smallFastModel`)}),(0,R.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,R.jsx)(rt,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,R.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function Bu(){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 Vu(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 Hu(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 Uu({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=K();return(0,R.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.enabledLabel`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.enabledHint`)})]}),(0,R.jsx)(Lu,{label:i(`claude.enabledLabel`),checked:e.enabled,onChange:t=>r({...e,enabled:t})})]}),(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,R.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,R.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:Hu(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,R.jsx)(Ru,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,R.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,R.jsx)(Lu,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,R.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,R.jsx)(`div`,{className:`setting-controls`,children:(0,R.jsx)(rt,{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,R.jsxs)(`div`,{className:`setting-row`,children:[(0,R.jsxs)(`div`,{className:`setting-label`,children:[(0,R.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,R.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,R.jsx)(Lu,{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,R.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,R.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,R.jsx)(`span`,{className:`title`,children:i(o)}),(0,R.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,R.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,R.jsx)(rt,{value:Nu(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]:Pu(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,R.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:Fu(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,R.jsx)(`datalist`,{id:c,children:n.map(e=>(0,R.jsx)(`option`,{value:e},e))})]})]},t)})]})}function Wu({manualEnv:e}){let t=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`h-section`,children:t(`claude.quickstart`)}),(0,R.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,R.jsx)(He,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,R.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,R.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,R.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,R.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function Gu({rows:e,onRowsChange:t}){let n=K();return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[n(`claude.modelMap`),` `,(0,R.jsx)(`span`,{className:`count`,children:e.length})]}),(0,R.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,R.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,R.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,R.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,R.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,R.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,R.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,R.jsx)(ae,{})})]},r.id))}),(0,R.jsx)(`div`,{style:{marginTop:8},children:(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:Bu(),from:``,to:``}]),children:[(0,R.jsx)(oe,{}),` `,n(`claude.addMapping`)]})})]})}var Ku=`etc`;function qu(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:Ku,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function Ju({aliases:e}){let t=K();return(0,R.jsxs)(`div`,{className:`claude-aliases`,children:[(0,R.jsxs)(`div`,{className:`h-section`,children:[t(`claude.aliases`),` `,(0,R.jsx)(`span`,{className:`count`,children:e.length})]}),(0,R.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,R.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,R.jsx)(`div`,{className:`claude-aliases-scroll`,children:qu(e).map(([e,n])=>(0,R.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,R.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===Ku?t(`claude.aliasProviderOther`):e,(0,R.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,R.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,R.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,R.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,R.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function Yu(e){return sn(e)}function Xu({apiBase:e,active:t=!0}){let n=K(),{locale:r}=G(),i=Ie.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=(0,_.useMemo)(()=>Yu(a),[a]),[s,c]=(0,_.useState)(()=>o?.state??null),[l,u]=(0,_.useState)(()=>o?.rows??[]),[d,f]=(0,_.useState)(!!o),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(`settings`),b=(0,_.useCallback)(async t=>{let r=await ct(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`,...Au(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:Bu(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return c(i),u(o),f(!0),J(a,s),s},[e,a,n]),x=ss(`claude-code:${e}`,[e],b,{isEmpty:()=>!1,enabled:t}),S=x.state,C=S.data??o,w=s??C?.state??null,T=d?l:C?.rows??l,E=(0,_.useMemo)(()=>ku(w?.available,n(`claude.smallFastModelUnsetOption`)),[w?.available,n]),D=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,9e5,1e6],t=w?.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:Vu(e,i)}))]},[w?.autoCompactWindow,n,i]),O=async()=>{if(!w)return;m(``);let t={};for(let e of T)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await ct(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:w.enabled,authMode:w.authMode,systemEnv:w.systemEnv,fastMode:w.fastMode,autoContext:w.autoContext,autoCompactWindow:w.autoCompactWindow,injectAgents:w.injectAgents,smallFastModel:w.smallFastModel,modelMap:t,webSearchSidecar:Iu(w.webSearchSidecar),visionSidecar:Iu(w.visionSidecar)})}),n(`claude.saveFailed`)),g(!0),m(n(`claude.saved`)),x.refresh()}catch(e){g(!1),m(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(S.kind===`disabled`&&!C)return null;if(S.showSkeleton&&!C)return(0,R.jsx)(ma,{label:n(`claude.loading`),rows:3});if(S.kind===`failed-cold`)return(0,R.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,R.jsx)(q,{tone:`err`,children:S.error instanceof Error?S.error.message:n(`claude.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x.refresh(),children:n(`common.retry`)})]});if(!w)return null;let k=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,R.jsx)(Uu,{state:w,autoCompactOptions:D,availableModels:w.available??[],onStateChange:c})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,R.jsx)(Wu,{manualEnv:Mu(w)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,R.jsx)(zu,{value:w.smallFastModel,tierHaikuModel:w.tierModels?.haiku,options:E,onChange:e=>c({...w,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),body:(0,R.jsx)(Gu,{rows:T,onRowsChange:e=>{f(!0),u(e)}})},{id:`aliases`,label:n(`claude.aliases`),body:(0,R.jsx)(Ju,{aliases:w.aliases})}],A=k.find(e=>e.id===v)??k[0],j=v===`settings`||v===`smallFast`||v===`modelMap`;return(0,R.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsx)(`h2`,{children:n(`claude.pageTitle`)}),j&&(0,R.jsx)(`div`,{className:`claudecode-workspace-save`,children:(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{O()},children:n(`common.save`)})})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:n(`claude.subtitle`)}),p&&(0,R.jsx)(q,{tone:h?`ok`:`err`,children:p}),S.showError&&(0,R.jsx)(q,{tone:`err`,children:n(`claude.loadFail`)}),S.refreshing&&(0,R.jsx)(ha,{live:!S.showError,children:n(`claude.loading`)}),(0,R.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,R.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,R.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:k.map(e=>(0,R.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${v===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>y(e.id),"aria-current":v===e.id?`true`:void 0,children:(0,R.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,R.jsx)(`section`,{className:`claudecode-workspace-main`,"aria-label":A.label,children:(0,R.jsx)(`div`,{className:`ccw-body`,children:A.body})})]})]})}function Zu(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 Qu(e){return new Set(Object.keys(e))}function $u(e,t){return t!==null&&e===t}function ed(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function td(e){return{read(t){let n=ed(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=ed(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function nd(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var rd=[`opus`,`fable`,`sonnet`,`haiku`],id=td(`ocx.claudeDesktop.collapsedFamilies.v2`),ad={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function od(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 sd(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:rd.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 cd(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function ld(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 ud(e){return sn(e)}function dd(e){let t=ud(e);return{data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?od(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{},hasCache:!!t?.data}}function fd({apiBase:e,active:t=!0}){let n=K(),r=`ocx.claude-desktop.v1:${e}`,i=(0,_.useMemo)(()=>dd(r),[r]),[a,o]=(0,_.useState)(()=>i.profile),[s,c]=(0,_.useState)(()=>i.savedProfile),[l,u]=(0,_.useState)(()=>i.destinations),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)({}),[b,x]=(0,_.useState)({}),[S,C]=(0,_.useState)(()=>id.read()??new Set(rd)),[w,T]=(0,_.useState)({}),E=(0,_.useRef)(null),D=(0,_.useCallback)(async t=>{let i=await ct(await fetch(`${e}/api/claude-desktop`,{signal:t}),n(`claudeDesktop.loadFail`));if(!i||!(`profile`in i)||!(`models`in i))throw Error(cd(i,n(`claudeDesktop.loadFail`)));let a=sd(i),s={data:i,profile:a};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(o(a),c(od(a)),u(Object.fromEntries(i.models.map(e=>[e.route,a.assignments[e.route]?.family??`opus`]))),id.read()===null){let e=Object.fromEntries(rd.map(e=>[e,0]));for(let t of i.models)e[a.assignments[t.route]?.family??`opus`]+=1;C(Qu(e))}return J(r,s),s},[e,r,n]),O=ss(`claude-desktop:${e}`,[e],D,{isEmpty:()=>!1,enabled:t}),k=O.state,A=k.data??(i.data&&i.profile?{data:i.data,profile:i.profile}:null),j=A?.data??null,M=a??A?.profile??null,N=s??A?.profile??null,P=A?Object.fromEntries(A.data.models.map(e=>[e.route,A.profile.assignments[e.route]?.family??`opus`])):{},F=Object.keys(l).length>0?l:P,I=(0,_.useMemo)(()=>M!==null&&N!==null&&JSON.stringify(M)!==JSON.stringify(N),[M,N]),L=(0,_.useMemo)(()=>{let e=Object.fromEntries(rd.map(e=>[e,[]]));if(!j||!M)return e;for(let t of j.models)e[M.assignments[t.route]?.family??`opus`].push(t);return e},[j,M]),z=(0,_.useMemo)(()=>{let e={};for(let t of rd){let n=L[t].filter(e=>e.available).map(e=>e.route).sort(),r=M?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[L,M]),B=ss(`claude-desktop-status:${e}`,[e],async t=>{let n=await lt(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return n},{isEmpty:()=>!1,pollMs:5e3,enabled:t}).state.data??null,V=(e,t)=>{!M||M.assignments[e]?.family===t||(o(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}}),u(n=>({...n,[e]:t})),m(n(`claudeDesktop.moved`,{route:e,family:n(ad[t])})))},H=e=>{let t=nd(S,e);id.write(t),C(t)},U=async t=>{if(!(!M||h)){g(`save`),f(null);try{await ct(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:M})}),n(`claudeDesktop.saveFailed`)),c(od(M)),t?(g(`apply`),await ct(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`}),n(`claudeDesktop.applyFailed`)),f({tone:`ok`,text:n(`claudeDesktop.savedApplied`)}),m(n(`claudeDesktop.savedAppliedAnnounce`))):(f({tone:`ok`,text:n(`claudeDesktop.saved`)}),m(n(`claudeDesktop.savedAnnounce`)))}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.updateFailed`);f({tone:`err`,text:t}),m(t)}finally{g(null)}}},W=()=>{if(!M)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(M,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),m(n(`claudeDesktop.exported`))},ee=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(n(`claudeDesktop.importExpected`));o(sd({...j,profile:e})),f({tone:`ok`,text:n(`claudeDesktop.importReady`)}),m(n(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.importInvalid`);f({tone:`err`,text:t}),m(n(`claudeDesktop.importFailed`,{error:t}))}},te=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&V(n,t)};return k.kind===`disabled`&&!A?null:k.showSkeleton&&!A?(0,R.jsx)(ma,{label:n(`claudeDesktop.loading`),rows:4}):k.kind===`failed-cold`?(0,R.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,R.jsx)(q,{tone:`err`,children:k.error instanceof Error?k.error.message:n(`claudeDesktop.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>O.refresh(),children:n(`claudeDesktop.retry`)})]}):!j||!M?null:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head claude-desktop-head`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h2`,{children:n(`claudeDesktop.title`)}),(0,R.jsx)(`p`,{className:`page-sub`,children:n(`claudeDesktop.subtitle`,{port:j.port})})]}),(0,R.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,R.jsx)(`input`,{ref:E,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ee(e)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E.current?.click(),children:n(`claudeDesktop.importJson`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:W,children:n(`claudeDesktop.exportJson`)})]})]}),B&&(0,R.jsxs)(`div`,{className:`claude-status-bar ${B.activeProfile===!1?`not-applied`:B.stale?`stale`:B.applied?`applied`:`not-applied`}`,children:[(0,R.jsx)(`span`,{className:`claude-status-dot`}),(0,R.jsx)(`span`,{children:B.activeProfile===!1?n(`claudeDesktop.status.notActiveProfile`):B.stale?n(`claudeDesktop.status.stale`):B.applied?n(`claudeDesktop.status.applied`):n(`claudeDesktop.status.notApplied`)}),B.health.lastRequestAt&&(0,R.jsxs)(`span`,{className:`claude-status-health`,children:[n(`claudeDesktop.health.lastRequest`),`: `,new Date(B.health.lastRequestAt).toLocaleTimeString()]}),B.health.requestCount>0&&(0,R.jsx)(`span`,{className:`claude-status-health`,children:n(`claudeDesktop.health.stats`,{count:B.health.requestCount,errors:B.health.errorCount})})]}),(0,R.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:p}),d&&(0,R.jsx)(q,{tone:d.tone,children:d.text}),k.showError&&(0,R.jsx)(q,{tone:`err`,children:n(`claudeDesktop.loadFail`)}),k.refreshing&&(0,R.jsx)(ha,{live:!k.showError,children:n(`claudeDesktop.loading`)}),(0,R.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,R.jsx)(`span`,{className:`claude-dirty${I?` active`:``}`,children:n(I?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,R.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!I||h!==null,onClick:()=>void U(!1),children:n(h===`save`?`claudeDesktop.saving`:`common.save`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:h!==null,onClick:()=>void U(!0),children:n(h===`apply`?`claudeDesktop.applying`:h===`save`?`claudeDesktop.saving`:`claudeDesktop.saveApply`)})]})]}),j.models.length===0&&(0,R.jsx)(it,{title:n(`claudeDesktop.emptyTitle`),children:n(`claudeDesktop.emptyHint`)}),(0,R.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":n(`claudeDesktop.assignmentsLabel`),children:rd.map(e=>{let t=L[e],r=Zu(t,v[e]??``,b[e]??6),i=S.has(e),a=z[e];return(0,R.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>te(t,e),children:[(0,R.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,R.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,R.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>H(e),children:[(0,R.jsx)(_e,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,R.jsx)(`span`,{className:`ocx-group-name`,children:n(ad[e])}),(0,R.jsx)(`span`,{className:`ocx-group-count`,children:n(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,R.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&M.defaults[e]===null&&(0,R.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.chooseDefault`)}),a&&a!==M.defaults[e]&&(0,R.jsx)(`span`,{className:`claude-default-needed`,title:a,children:n(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,R.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[r.showSearch&&(0,R.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:n(`models.search`),"aria-label":n(`models.search`),value:v[e]??``,onChange:t=>{let n=t.target.value;y(t=>({...t,[e]:n})),x(t=>({...t,[e]:6}))}}),(0,R.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,R.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneEmpty`)}):r.noMatch?(0,R.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneNoMatch`)}):r.shown.map(t=>{let r=M.assignments[t.route],i=ld(t.contextWindow,n),a=F[t.route]??`opus`,s=w[t.route]??$u(t.route,z[e]);return(0,R.jsxs)(`article`,{className:`claude-model-card${s?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,R.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":s,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>T(e=>({...e,[t.route]:!s})),children:[(0,R.jsx)(_e,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:s?`rotate(90deg)`:`none`}}),(0,R.jsxs)(`span`,{className:`claude-model-names`,children:[(0,R.jsx)(`strong`,{title:t.label,children:t.label}),(0,R.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,R.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,R.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:n(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,R.jsx)(`span`,{className:`claude-1m-chip`,children:n(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,R.jsx)(`span`,{className:`claude-effort-badge off`,children:n(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,R.jsx)(`span`,{className:`claude-effort-badge on`,children:n(`claudeDesktop.effort.supported`)}),M.defaults[e]===t.route&&(0,R.jsx)(`span`,{className:`claude-row-default`,children:n(`claudeDesktop.defaultBadge`)}),(0,R.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?n(`claudeDesktop.available`):n(`claudeDesktop.unavailable`)})]}),s&&(0,R.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[z[e]===t.route&&M.defaults[e]!==t.route&&(0,R.jsx)(`span`,{className:`claude-effective-default`,children:n(`claudeDesktop.temporaryDefault`)}),(0,R.jsxs)(`div`,{className:`claude-field`,children:[(0,R.jsx)(`span`,{children:n(`claudeDesktop.alias`)}),(0,R.jsx)(`code`,{className:`claude-alias`,title:r.alias,children:r.alias})]}),(0,R.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,R.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:M.defaults[e]===t.route,disabled:!t.available,onChange:()=>o(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),n(`claudeDesktop.useAsDefault`,{family:n(ad[e])})]}),(0,R.jsxs)(`div`,{className:`claude-move-row`,children:[(0,R.jsx)(`label`,{htmlFor:`move-${t.route}`,children:n(`claudeDesktop.moveTo`)}),(0,R.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>u(n=>({...n,[t.route]:e.target.value})),children:rd.map(e=>(0,R.jsx)(`option`,{value:e,children:n(ad[e])},e))}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>V(t.route,a),children:n(`claudeDesktop.move`)})]})]})]},t.route)}),r.hidden>0&&(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>x(t=>({...t,[e]:(t[e]??6)+6})),children:n(`models.showMore`,{n:r.hidden})})]})]})]},e)})})]})}function pd({apiBase:e}){let[t,n]=(0,_.useState)(`code`),r=K(),i=(0,_.useRef)(null),a=(0,_.useRef)(null),o=e=>{n(e),window.requestAnimationFrame(()=>(e===`code`?i:a).current?.focus())},s=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),o(t===`code`?`desktop`:`code`)):e.key===`Home`?(e.preventDefault(),o(`code`)):e.key===`End`&&(e.preventDefault(),o(`desktop`))};return(0,R.jsxs)(`section`,{className:`claude-page`,children:[(0,R.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":r(`claude.tabsLabel`),children:[(0,R.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:s,onClick:()=>o(`code`),children:r(`claude.tabCode`)}),(0,R.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:s,onClick:()=>o(`desktop`),children:r(`claude.tabDesktop`)})]}),(0,R.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:t!==`code`,children:(0,R.jsx)(Xu,{apiBase:e,active:t===`code`},e)}),(0,R.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:t!==`desktop`,children:(0,R.jsx)(fd,{apiBase:e,active:t===`desktop`},e)})]})}function md(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 hd=td(`ocx.grok.collapsedGroups.v2`),gd=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],_d=new Set(gd.map(e=>e.id));function vd(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 $({apiBase:e}){let t=K(),n=`ocx.grok.status.v1:${e}`,r=sn(n),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(()=>hd.read()??new Set(_d)),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(``),m=(0,_.useCallback)(async()=>{let r=await ct(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 J(n,i),i},[e,n,t]),h=`grok-status:${e}`,g=ss(h,[e],m,{isEmpty:()=>!1}),{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=nd(o,e);hd.write(t),s(t)},E=e=>{let t=e?new Set(gd.map(e=>e.id)):new Set;hd.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 ct(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&&I(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&&J(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,R.jsx)(`section`,{className:`grok-page`,children:(0,R.jsx)(ma,{label:t(`grok.loading`),rows:4})}):v.kind===`failed-cold`?(0,R.jsxs)(`section`,{className:`grok-page`,children:[(0,R.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:v.error instanceof Error?v.error.message:t(`grok.loadFail`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>y(),children:t(`common.retry`)})]}):(0,R.jsxs)(`section`,{className:`grok-page`,children:[(0,R.jsx)(`h2`,{className:`page-title`,children:t(`grok.title`)}),(0,R.jsx)(`p`,{className:`page-sub`,children:t(`grok.subtitle`)}),(0,R.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:f}),u&&(0,R.jsx)(q,{tone:u.tone,children:u.text}),v.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`grok.loadFail`)}),v.refreshing&&(0,R.jsx)(ha,{live:!v.showError,children:t(`grok.loading`)}),b&&b.candidates.length>0&&(0,R.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,R.jsx)(`span`,{className:`claude-dirty${C?` active`:``}`,children:t(C?`grok.unsaved`:`grok.upToDate`)}),(0,R.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,R.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,R.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,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,R.jsx)(`span`,{children:t(`grok.endpoint`)}),(0,R.jsx)(`code`,{children:b.baseUrl??`—`})]}),(0,R.jsx)(`p`,{className:`page-sub`,children:(0,R.jsx)(`code`,{children:b.configPath})})]}):(0,R.jsxs)(it,{title:t(`grok.notConfiguredTitle`),children:[t(`grok.notConfiguredHint`),(0,R.jsx)(`br`,{}),(0,R.jsx)(`code`,{children:b?.configPath})]}),b&&b.candidates.length>0&&(0,R.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,R.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!0),disabled:c!==null,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),` `,t(`models.collapseAll`)]}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>E(!1),disabled:c!==null,children:[(0,R.jsx)(_e,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,t(`models.expandAll`)]})]}),gd.map(e=>{let n=md(b.candidates,w,S,e.id);if(n.total===0)return null;let r=o.has(e.id);return(0,R.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,R.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,R.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,R.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>T(e.id),children:[(0,R.jsx)(_e,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,R.jsx)(`span`,{className:`ocx-group-name`,children:t(e.tkey)}),(0,R.jsx)(`span`,{className:`ocx-group-count`,children:t(`grok.enabledCount`,{on:n.enabled,total:n.total})})]})})}),!r&&(0,R.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:n.rows.map(e=>(0,R.jsxs)(`div`,{className:`grok-model-row`,children:[(0,R.jsx)(nt,{on:e.enabled,onClick:()=>D(e.id,!e.enabled),disabled:c!==null,label:t(`grok.toggleModel`,{id:e.id})}),(0,R.jsxs)(`span`,{className:`grok-model-names`,children:[(0,R.jsx)(`strong`,{title:e.id,children:e.id}),(0,R.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,R.jsx)(`span`,{className:`claude-model-context`,children:vd(e.contextWindow,t)})]},e.id))})]},e.id)})]})]})}function yd(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 bd={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},xd={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},Sd={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function Cd({ok:e,yes:t,no:n}){return(0,R.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function wd({failed:e,data:t}){let{t:n}=G(),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`?de:ie,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,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,R.jsx)(`div`,{className:`startup-hero-icon`,children:(0,R.jsx)(i,{})}),(0,R.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,R.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:bd[t.status])}),(0,R.jsx)(`h3`,{children:n(e?`startup.error`:xd[t.status])}),(0,R.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(cn(t)):n(`startup.safeDetail`)})]})]}),(0,R.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,R.jsxs)(`section`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,R.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,R.jsxs)(`section`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,R.jsx)(`div`,{className:`value`,children:n(Sd[t.protection])})]}),(0,R.jsxs)(`section`,{className:`stat`,children:[(0,R.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,R.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function Td({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=G(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,R.jsxs)(`section`,{className:`panel startup-details`,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,R.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,R.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:o(`startup.service`)}),(0,R.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,R.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,R.jsx)(Cd,{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,R.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,R.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,R.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:o(`startup.shim`)}),(0,R.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,R.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,R.jsx)(Cd,{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,R.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,R.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,R.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 Ed({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=G();return(0,R.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,R.jsx)(ye,{})]}),(0,R.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,R.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,R.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,R.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,R.jsx)(Cd,{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,R.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,R.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,R.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,R.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,R.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,R.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function Dd({data:e,copied:t,onCopy:n}){let{t:r}=G();return(0,R.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,R.jsxs)(`div`,{className:`panel-head`,children:[(0,R.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,R.jsx)(te,{})]}),(0,R.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,R.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,R.jsxs)(`div`,{className:`startup-command-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,R.jsx)(`code`,{children:e.commands.installService})]}),(0,R.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,R.jsxs)(`div`,{className:`startup-command-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,R.jsx)(`code`,{children:e.commands.installShim})]}),(0,R.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,R.jsxs)(`div`,{className:`startup-command-row`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,R.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,R.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,R.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,R.jsx)(ye,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var Od=`ocx.startup.page.v1:`;function kd(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function Ad(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=kd([`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 jd({apiBase:e}){let{t}=G(),n=`${Od}${e}`,r=(0,_.useMemo)(()=>sn(n),[n]),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(()=>r?.tray??null),[c,l]=(0,_.useState)(()=>!r?.data),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(()=>r?.warning??null),[x,S]=(0,_.useState)(()=>r?.fix??null),[C,w]=(0,_.useState)(()=>!r?.data),T=(0,_.useRef)(!!r?.data),E=(0,_.useCallback)(async r=>{let i=T.current;i||(l(!0),w(!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();T.current=!0;let c=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(!yd(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,c]).then(([e,i])=>{if(r.aborted)return;let a=o.platform===`win32`?i.tray:null;if(o.platform===`win32`?(s(a),p(i.error)):(s(null),p(!1)),l(!1),w(!1),e){let r=Ad(e.codexRuntime,t,o.platform);b(r.warning),S(r.fix),J(n,{data:o,warning:r.warning,fix:r.fix,tray:a});return}let c=sn(n);J(n,{data:o,warning:c?.warning??null,fix:c?.fix??null,tray:a})}),o}catch(e){throw r.aborted?e:(i||(s(null),p(!0),b(null),S(null)),w(!1),l(!1),e)}},[e,n,t]),D=ss(`startup-page:${e}`,[e],E,{isEmpty:()=>!1}),O=D.state,k=D.refresh,A=O.data??r?.data??null,j=O.refreshing,M=!!A?.diagnosticStale||O.showError;(0,_.useEffect)(()=>{if(!A?.diagnosticStale)return;let e=window.setTimeout(k,2e3);return()=>window.clearTimeout(e)},[A,k]);let N=async e=>{try{await navigator.clipboard.writeText(e),a(e),window.setTimeout(()=>a(t=>t===e?null:t),1600)}catch{a(null)}},P=async t=>{d(!0),p(!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(!yd(r.status))throw Error(`invalid tray action status`);s(r.status),p(!1)}catch{s(null),p(!0)}finally{d(!1)}},F=async(t,n)=>{h(t),v(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`)}v({kind:`success`,action:t,repair:n?.repair===!0}),k()}catch(e){v({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e)})}finally{h(null)}};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`page-head`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`h2`,{children:t(`startup.title`)}),(0,R.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,R.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,R.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`#dashboard`,children:t(`startup.backToDashboard`)}),(0,R.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),disabled:j,children:[(0,R.jsx)(se,{}),` `,t(`startup.refresh`)]})]})]}),O.showSkeleton&&!A?(0,R.jsx)(ma,{label:t(`startup.loading`),rows:5}):O.kind===`failed-cold`?(0,R.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,R.jsx)(q,{tone:`err`,children:O.error instanceof Error?O.error.message:t(`startup.error`)}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:t(`common.retry`)})]}):A?(0,R.jsxs)(R.Fragment,{children:[O.showError&&(0,R.jsx)(q,{tone:`err`,children:t(`startup.error`)}),O.refreshing&&(0,R.jsx)(ha,{live:!O.showError,children:t(`startup.loading`)}),M&&(0,R.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(C||y)&&(0,R.jsx)(`div`,{className:`startup-runtime-notice-slot${C&&!y?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":C&&!y?!0:void 0,children:y&&(0,R.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,R.jsx)(`p`,{className:`startup-runtime-notice__text`,children:y}),x&&(0,R.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,R.jsx)(`code`,{children:x}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void N(x),children:t(i===x?`startup.copied`:`startup.copy`)})]})]})}),(0,R.jsx)(wd,{failed:M,data:A}),(0,R.jsx)(Td,{data:A,failed:M,loading:j,installBusy:m,installResult:g,onInstall:(e,t)=>{F(e,t)}}),A.platform===`win32`&&(0,R.jsx)(Ed,{tray:o,trayLoading:c,trayError:f,trayBusy:u,onTrayAction:e=>{P(e)}}),(0,R.jsx)(Dd,{data:A,copied:i,onCopy:e=>{N(e)}})]}):null]})}var Md=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,R.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,R.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,R.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,R.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,R.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,R.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},Nd=5*6e4,Pd=10*6e4,Fd=`https://github.com/lidge-jun/opencodex`;async function Id(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Ld({apiBase:e,onOpenUpdate:t}){let n=K(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=F(`sidebar-star:${e}`,[e],t=>Id(`${e}/api/github/star`,t),{pollMs:Nd}),c=F(`sidebar-update-badge:${e}`,[e],t=>Id(`${e}/api/update/badge`,t),{pollMs:Pd}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??Fd,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,R.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,R.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,R.jsx)(ve,{}),` `,n(`common.github`)]}),(0,R.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,R.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,R.jsx)(Me,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,R.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,R.jsx)(ge,{"aria-hidden":`true`}),m&&(0,R.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Rd=!1,zd=null,Bd=null,Vd=!1,Hd=`/`;function Ud(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 Wd=`opencodex-api-token`,Gd=null,Kd=null,qd=null;function Jd(){return Gd}function Yd(e){Gd=e}function Xd(){Gd=null,Kd=null,qd=null}function Zd(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function Qd(){ef(Zd(`opencodex-session-token`),Zd(`opencodex-session-csrf`),Zd(`opencodex-session-origin`))}function $d(e){e!=null&&Jd()===e&&Xd()}function ef(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(Gd=e,Kd=t,qd=n,!0)}function tf(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 nf(){if(!Bd)return null;try{let e=await Bd(Hd,{cache:`no-store`});if(!e.ok)return null;let t=await e.text();return ef(tf(t,`opencodex-session-token`),tf(t,`opencodex-session-csrf`),tf(t,`opencodex-session-origin`))?Jd():null}catch{return null}}function rf(){try{sessionStorage.removeItem(Wd)}catch{}}function af(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),qd&&Kd&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,qd);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,Kd)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function of(e){return Vd?null:zd||(zd=(async()=>{if(Vd)return null;let t=Jd();if(t&&t!==e)return t;let n=await nf();if(n)return n;let r=window.prompt(`OpenCodex admin token (OPENCODEX_ADMIN_AUTH_TOKEN)`)?.trim()||null;return r?(Yd(r),r):(Vd=!0,null)})().finally(()=>{zd=null}),zd)}function sf(){if(Rd)return;Rd=!0,rf(),Qd();let e=window.fetch.bind(window);Bd=e,window.fetch=async(t,n)=>{if(!Ud(t))return e(t,n);let r=Jd(),[i,a]=r?af(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;let s=Jd();if(s&&s!==r){let[r,i]=af(t,n,s),a=await e(r,i);if(a.status!==401)return a;$d(s)}else $d(r);let c=await of(r);if(!c)return o;let[l,u]=af(t,n,c),d=await e(l,u);return d.status===401&&$d(c),d}}var cf=new Set([`dashboard`,`startup`,`providers`,`models`,`combos`,`subagents`,`logs`,`usage`,`storage`,`codex-auth`,`api`,`claude`,`grok`]);function lf(e){let t=Ue(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:cf.has(t)?t:`dashboard`}var uf=[`dashboard/providers`,`dashboard/models`];function df(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`dashboard`&&(e===`dashboard/update`||uf.includes(e))}function ff(e){let t=lf(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:df(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var pf=[`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 mf(){try{for(let e of pf)localStorage.removeItem(e)}catch{}}function hf(){let[e,t]=(0,_.useState)(lf);(0,_.useEffect)(()=>{mf()},[]);let n=(0,_.useCallback)(e=>{let n=ff(e);n.replaceTo&&We(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(Ue(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=Ue(window.location.hash);if(t===`debug`||t.startsWith(`debug/`)){We(`logs/debug`);return}if(t===`providers/workspace`){We(`providers`);return}df(t,e)||We(e)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{Ge(n?`${e}/${n}`:e),t(e)}}}var gf=15e3;function _f(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 vf(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function yf(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=gf,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 vf(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:_f(o,a.status,i)}:{accepted:!0}}sf();var bf={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`},xf=``,Sf=`ocx-theme`,Cf=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:B},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:xe},{id:`providers`,tkey:`nav.providers`,Icon:V},{id:`models`,tkey:`nav.models`,Icon:H},{id:`subagents`,tkey:`nav.subagents`,Icon:U},{id:`logs`,tkey:`nav.logs`,Icon:W},{id:`usage`,tkey:`nav.usage`,Icon:ne},{id:`storage`,tkey:`nav.storage`,Icon:re},{id:`api`,tkey:`nav.api`,Icon:Oe},{id:`claude`,tkey:`nav.claude`,Icon:ke},{id:`grok`,tkey:`nav.grok`,Icon:H}],wf={light:Te,dark:Ee,system:De},Tf={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function Ef(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 Df(){let e=localStorage.getItem(Sf);return e===`light`||e===`dark`?e:`system`}function Of(){let{page:e,navigateToPage:t}=hf(),[n,r]=(0,_.useState)(Df),{locale:i,setLocale:a}=G(),o=K(),[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(Sf)):(e.setAttribute(`data-theme`,n),localStorage.setItem(Sf,n))},[n]);let f=F(`app-healthz:${xf}`,[],async e=>{let t=await fetch(`${xf}/healthz`,{signal:e});return t.ok?Ef(await t.json()):null},{pollMs:3e4}),p=()=>r(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),m=wf[n],h=f.data??`2.8.2-preview.20260731`,[g,v]=(0,_.useState)(!1),y=(0,_.useCallback)(async e=>{let t=await lt(await fetch(`${xf}/api/claude-code`,{signal:e}));return t&&typeof t.enabled==`boolean`?t.enabled:null},[]),b=F(`app-claude-code:${xf}`,[],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;I(`app-claude-code:${xf}`,e);try{(await fetch(`${xf}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:e})})).ok||I(`app-claude-code:${xf}`,!e)}catch{I(`app-claude-code:${xf}`,!e)}finally{x.current=!1,C(!1)}},T=async()=>{if(!confirm(o(`dash.stopConfirm`)))return;v(!0);let e=await yf(xf,{formatFailure:e=>o(`dash.stopFailed`,{status:String(e)})});e.accepted||(v(!1),alert(e.message))},E=(0,R.jsxs)(`div`,{className:`brand`,children:[(0,R.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":o(`app.logoAria`)}),(0,R.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,R.jsxs)(`span`,{className:`ver`,children:[`v`,h]})]});return(0,R.jsxs)(`div`,{className:`app`,children:[(0,R.jsxs)(`header`,{className:`mobile-topbar`,inert:s,children:[(0,R.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,R.jsx)(ee,{})}),E,(0,R.jsx)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:(0,R.jsx)(ye,{})})]}),s&&(0,R.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>c(!1),"aria-hidden":`true`}),(0,R.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${s?` open`:``}`,ref:u,tabIndex:-1,children:[(0,R.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,R.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>c(!1),"aria-label":o(`nav.closeMenu`),title:o(`nav.closeMenu`),children:(0,R.jsx)(ae,{})})]}),(0,R.jsx)(`nav`,{children:Cf.map(({id:n,tkey:r,Icon:i})=>(0,R.jsxs)(`div`,{className:`nav-entry${n===`claude`?` nav-entry-claude${e===n?` active`:``}`:``}`,children:[(0,R.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,R.jsx)(i,{}),` `,o(r)]}),n===`claude`&&b!==null&&(0,R.jsx)(nt,{on:b,onClick:()=>void w(),disabled:S,label:o(`claude.toggleAria`)})]},n))}),(0,R.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,R.jsxs)(`div`,{className:`lang-toggle`,children:[(0,R.jsx)(Oe,{"aria-hidden":!0}),(0,R.jsx)(rt,{value:i,options:Ie.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,R.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:p,"aria-label":`${o(`theme.label`)}: ${o(Tf[n])}`,title:`${o(`theme.label`)}: ${o(Tf[n])}`,children:[(0,R.jsx)(m,{}),` `,(0,R.jsx)(`span`,{className:`mode`,children:o(Tf[n])})]}),(0,R.jsxs)(`button`,{type:`button`,className:`theme-toggle stop-toggle`,onClick:T,disabled:g,"aria-label":o(`dash.stop`),title:o(`dash.stop`),children:[(0,R.jsx)(ye,{}),` `,(0,R.jsx)(`span`,{className:`mode`,children:o(g?`dash.stopping`:`dash.stop`)})]}),(0,R.jsx)(Ld,{apiBase:xf,onOpenUpdate:()=>{c(!1),t(`dashboard`,`update`)}})]})]}),(0,R.jsx)(`main`,{className:`main`,inert:s,children:(0,R.jsx)(`div`,{className:`main-inner${e===`combos`?` main-inner--combos`:``}`,children:(0,R.jsxs)(Md,{pageName:o(bf[e]),title:o(`errorBoundary.title`),message:o(`errorBoundary.message`),detailsLabel:o(`errorBoundary.details`),reloadLabel:o(`errorBoundary.reload`),children:[e===`dashboard`&&(0,R.jsx)(Fn,{apiBase:xf}),e===`startup`&&(0,R.jsx)(jd,{apiBase:xf}),e===`providers`&&(0,R.jsx)(jo,{apiBase:xf}),e===`models`&&(0,R.jsx)(Ns,{apiBase:xf}),e===`combos`&&(0,R.jsx)(Zs,{apiBase:xf},xf),e===`subagents`&&(0,R.jsx)(oc,{apiBase:xf},xf),e===`logs`&&(0,R.jsx)(wl,{apiBase:xf}),e===`usage`&&(0,R.jsx)(Wl,{apiBase:xf}),e===`storage`&&(0,R.jsx)(su,{apiBase:xf}),e===`codex-auth`&&(0,R.jsx)(du,{apiBase:xf}),e===`api`&&(0,R.jsx)(Ou,{apiBase:xf}),e===`claude`&&(0,R.jsx)(pd,{apiBase:xf}),e===`grok`&&(0,R.jsx)($,{apiBase:xf})]},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,R.jsx)(_.StrictMode,{children:(0,R.jsx)(Ve,{children:(0,R.jsx)(Of,{})})}));