@bitkyc08/opencodex 2.20.0 → 2.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/gui/dist/assets/{index-DSK3S5HY.js → index-BOFeam5a.js} +2 -2
- package/gui/dist/assets/{index-DF_UFrGS.css → index-Xq49CY8F.css} +1 -1
- package/gui/dist/index.html +2 -2
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +2 -28
- package/src/adapters/google.ts +31 -3
- package/src/adapters/openai-chat.ts +25 -8
- package/src/adapters/responses-tool-schema.ts +67 -0
- package/src/bridge.ts +15 -2
- package/src/claude/gateway-cache.ts +41 -4
- package/src/cli/claude.ts +1 -1
- package/src/generated/compatibility-version.json +24 -16
- package/src/images/loop.ts +15 -5
- package/src/providers/registry.ts +7 -1
- package/src/responses/custom-tool-compat.ts +4 -1
- package/src/responses/parser.ts +7 -1
- package/src/responses/provider-opaque-metadata.ts +73 -0
- package/src/responses/schema.ts +6 -0
- package/src/server/auth-cors.ts +42 -6
- package/src/server/system-env.ts +1 -1
- package/src/types.ts +18 -1
- package/src/web-search/loop.ts +21 -5
|
@@ -50,7 +50,7 @@ v2: spawn_agent を備えたマルチスレッドエージェント。すべて
|
|
|
50
50
|
|
|
51
51
|
変更は新規セッションに適用されます。`,"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.contextSettings":`コンテキストウィンドウ`,"models.contextSettingsTitle":`コンテキストウィンドウ — {provider}`,"models.contextDefault":`プロバイダーのデフォルト`,"models.contextModel":`モデル`,"models.contextModelOverride":`モデル別の上書き`,"models.contextHint":`上流メタデータがない場合に使われ、メタデータがある場合は報告値の上限になります。自動検出に戻すには空欄にします。`,"models.contextAutomatic":`自動検出`,"models.contextSaved":`コンテキストウィンドウを更新しました — 次回の Codex ターンから有効です。`,"models.contextUnchanged":`保存するコンテキストウィンドウの変更はありません。`,"models.contextSaveFailed":`コンテキストウィンドウを保存できませんでした`,"models.contextInvalid":`コンテキストウィンドウは正の整数で指定してください`,"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":`公開セレクター`,"sub.ultraMode":`ウルトラモード`,"sub.ultraModeHint":`すべてのモデルと reasoning effort で Proactive マルチエージェント委任ポリシーを有効にします(reasoning effort 自体は変更しません)。config.toml に features.multi_agent_v2.multi_agent_mode_hint_text を書き込みます。`,"sub.ultraModeV2Required":`v2 マルチエージェントサーフェスが必要です — 先に multi_agent_v2 を有効にし、サブエージェントモードで v2 を選択してください。`,"sub.ultraModeText":`ウルトラモード委任テキスト`,"sub.ultraModePreset":`プリセットを復元`,"sub.ultraModeLoadFail":`ウルトラモード設定を読み込めませんでした — プロキシは実行中ですか?`,"sub.ultraModeSaveFail":`ウルトラモード設定の保存に失敗しました`,"sub.ultraModeSaved":`ウルトラモードを保存しました。新しい Codex セッションから適用されます。`,"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.route.section":`ルート決定`,"logs.detail.route.kind":`ルート種別`,"logs.detail.route.profile":`プロファイル`,"logs.detail.route.selected":`選択済み`,"logs.detail.route.candidates":`候補`,"logs.detail.route.unknown":`このリクエストにはルートトレースが記録されていません(トレース前の行)。`,"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":`一致した価格キー`,"logs.detail.priceSource":`価格ソース`,"logs.detail.unavailableReason":`利用不可の理由`,"logs.detail.copyRequestId":`リクエスト ID をコピー`,"logs.detail.copied":`コピーしました`,"logs.detail.source.jawcode":`jawcode カタログ`,"logs.detail.source.expected":`予想価格オーバーレイ`,"logs.detail.source.user":`プロバイダー設定の価格オーバーレイ`,"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.attempt.recovery.transient5xx":`一時的な5xxエラー`,"logs.detail.attempt.recovery.connectionReset":`接続がリセットされました`,"logs.detail.attempt.recovery.oauth401":`OAuth 再認証`,"logs.detail.attempt.recovery.key429":`キーがレート制限 (429)`,"logs.detail.attempt.recovery.rateLimit429":`レート制限 (429)`,"logs.detail.attempt.recovery.anthropicOauth429":`Anthropic OAuth レート制限 (429)`,"logs.detail.attempt.recovery.image413":`画像ペイロードが大きすぎます (413)`,"logs.detail.attempt.recovery.emptyCompletion":`空の完了を再試行`,"logs.detail.attempt.recovery.unknown":`不明なリカバリ理由`,"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":`一致する価格が見つかりませんでした。`,"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.detail.estimate.provider_cost_overlay":`プロバイダー設定の価格オーバーレイが使用されました。`,"logs.col.error":`エラー`,"logs.col.upstreamReason":`上流の理由`,"logs.col.duration":`所要時間`,"logs.tokens.reported":`報告済み`,"logs.tokens.unreported":`未報告`,"logs.tokens.unsupported":`非対応`,"logs.tokens.estimated":`推定`,"logs.tokens.input":`入力`,"logs.tokens.output":`出力`,"logs.tokens.cacheRead":`キャッシュ読み取り (c)`,"logs.tokens.cacheWrite":`キャッシュ書き込み (w)`,"logs.tokens.reasoning":`推論`,"logs.tokens.noCache":`キャッシュデータなし`,"logs.tokens.contextTotal":`アクティブコンテキスト`,"logs.tokens.noCacheNote":`このプロバイダーはキャッシュトークンを報告しません`,"logs.tokens.noCacheCursor":`Cursor のキャッシュ詳細は未報告`,"logs.tokens.noCacheCursorNote":`Cursor はキャッシュ read/write トークン数を公開しません。これは不明という意味で、キャッシュミスの確定ではありません`,"logs.tokens.estimatedNote":`推定(プロバイダーは正確な使用量を報告しません)`,"logs.details":`詳細`,"logs.detailTitle":`リクエストの詳細`,"logs.detailRaw":`生のログエントリ`,"debug.title":`デバッグ`,"debug.subtitle":`オプトインのプロバイダートランスポートおよび使用量抽出診断です。リクエストエラーと 502 はログタブに残ります。`,"debug.debug":`プロバイダーデバッグ`,"debug.usage":`使用量抽出`,"debug.injection":`インジェクションログ`,"debug.claude":`Claude インバウンド`,"debug.claudeInbound.title":`Claude インバウンドリクエスト`,"debug.claudeInbound.sub":`Claude Code/Desktop が実際に送信する内容(thinking、effort、metadata) — プロンプトテキストは保存されません。`,"debug.claudeInbound.empty":`まだキャプチャされたリクエストはありません。これがオンの状態で Claude からメッセージを送信してください。`,"debug.claudeInbound.time":`時刻`,"debug.claudeInbound.endpoint":`エンドポイント`,"debug.claudeInbound.model":`モデル`,"debug.claudeInbound.none":`なし`,"debug.reset":`ランタイムオーバーライドをクリア`,"debug.refresh":`更新`,"debug.follow":`追従`,"debug.streamProvider":`プロバイダー`,"debug.streamUsage":`使用量`,"debug.streamInjection":`インジェクション`,"debug.loading":`デバッグ設定を読み込み中…`,"debug.loadFailed":`デバッグ設定を読み込めませんでした。`,"debug.emptyTitle":`デバッグログはオフです`,"debug.empty":`上のカードでプロバイダーデバッグまたは使用量抽出をオンにしてください。プロキシ経由でリクエストを送信すると、ここに行が表示されます。`,"debug.noLinesTitle":`行を待機中`,"debug.noLines.provider":`プロバイダーデバッグはオンですが、トランスポートの異常(欠落または不正なフレーム、Cursor のダイヤル/再試行イベント)のみを記録します。Anthropic のようなプロバイダーでの正常なリクエストは行を生成しないことがあります。`,"debug.noLines.usage":`使用量抽出はオンですが、まだ何もキャプチャされていません。Codex 経由でチャット/リクエストを送信するとここに表示されます。`,"debug.noLines.injection":`インジェクションログはオンですが、まだ何もキャプチャされていません。コラボおよびサブエージェントのターンでのマルチエージェントガイダンスインジェクションと負荷上限の決定を記録します。`,"usage.title":`使用量`,"usage.subtitle":`プロキシからのローカルトークン会計です。欠損した使用量はゼロとして表示されることはありません。`,"usage.loading":`使用量データを読み込み中…`,"usage.empty":`まだ使用量が記録されていません。プロキシ経由でリクエストを送信するとここにアクティビティが表示されます。`,"usage.loadError":`使用量データを読み込めませんでした。`,"usage.range.all":`すべて`,"usage.range.available":`利用可能な履歴`,"usage.historyTruncated":`古い利用履歴が読み込まれていないため、合計は利用可能な履歴のみを対象とします。`,"usage.historyTruncatedWindow":`読み込まれた行のリクエスト開始時刻は {start} から {end} の範囲です。読み取り上限によりファイル前方の記録が除外されているため、選択した期間は不完全な場合があります。`,"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.cockpitImportDescription":`このデバイスから Cockpit Tools Antigravity JSON エクスポートをインポートします。ファイル内容は表示されません。`,"pws.cockpitImportFileLabel":`Cockpit Tools Antigravity JSON エクスポート`,"pws.cockpitImportChooseFile":`JSON ファイルを選択`,"pws.cockpitImporting":`インポート中…`,"pws.cockpitImportInvalid":`選択したファイルは有効な JSON エクスポートではないか、大きすぎます。`,"pws.cockpitImportFailed":`アカウントのインポートを完了できませんでした。`,"pws.cockpitImportComplete":`インポート完了: インポート {imported}、更新 {updated}、失敗 {failed}、未対応 {unsupported}。`,"pws.accountSwitching":`切り替え中…`,"pws.accountCurrent":`現在のアカウント`,"pws.defaultModelNone":`なし(プロバイダーのデフォルトを使用)`,"pws.discardSettings":`破棄`,"pws.jsonEditorDesc":`生のプロバイダー JSON 設定を編集します。変更はすぐに保存されます。`,"pws.jsonEditorTitle":`JSON エディタ — {name}`,"pws.jsonRestore":`復元`,"pws.jsonSave":`保存`,"pws.loggedInTitle":`ログイン済み`,"pws.notLoggedInTitle":`未ログイン`,"pws.note":`メモ`,"pws.allowPrivateNetwork":`ローカル/プライベートネットワークを許可`,"pws.liveModels":`プロバイダーからモデルを検出`,"pws.liveModelsDesc":`プロバイダーのライブモデルカタログを取得します。オフにすると設定済みの静的モデルのみを使用します。`,"pws.optionalPlaceholder":`任意`,"pws.providerId":`プロバイダー ID`,"pws.reauth":`再認証が必要`,"pws.reauthenticate":`再認証`,"pws.copyDoctor":`ocx doctor をコピー`,"pws.doctorCopied":`コピー済み`,"pws.healthCooldownHint":`クールダウンが終わるまで待ってください。まだこのアカウントをプローブしないでください。`,"pws.doctorCopyUnavailable":`クリップボードを利用できません`,"pws.healthLabel.rateLimited":`レート制限中`,"pws.healthLabel.quotaLimited":`クォータ制限中`,"pws.healthLabel.reauthRequired":`再認証が必要です`,"pws.healthLabel.refreshFailed":`更新に失敗しました`,"pws.healthLabel.metadataMismatch":`メタデータの不一致`,"pws.healthLabel.credentialConflict":`資格情報の競合`,"pws.healthSummary.rateLimited":`{provider} {account}: {until} までレート制限中です。それまでこのアカウントのルーティングは停止します。`,"pws.healthSummary.quotaLimited":`{provider} {account}: {until} までクォータ制限中です。それまでこのアカウントのルーティングは停止します。`,"pws.healthSummary.reauthRequired":`{provider} {account}: 再認証が必要です。`,"pws.healthSummary.credentialConflict":`{provider} {account}: 資格情報の競合があります。`,"pws.healthSummary.metadataMismatch":`{provider} {account}: メタデータが一致しません。`,"pws.healthSummary.staleCredentials":`{provider} {account}: 資格情報が不完全です。`,"pws.removeConfirm":`削除`,"pws.removeConfirmBody":`プロバイダー "{name}" を削除しますか? これは元に戻せません。`,"pws.removeDefaultConfirmBody":`既定のプロバイダー "{name}" を削除しますか? "{defaultProvider}" が既定のプロバイダーになります。この操作は元に戻せません。`,"pws.removeConfirmTitle":`プロバイダーを削除`,"pws.saveSettings":`保存`,"pws.pacingTitle":`リクエスト間隔調整`,"pws.pacingDesc":`このプロバイダーへの送信開始を均等に遅延します。ストリーミング応答は重複できます。`,"pws.pacingEnabled":`有効`,"pws.pacingRpm":`1分あたりのリクエスト数`,"pws.pacingRpmUnit":`RPM`,"pws.pacingDelay":`最小間隔 (ms)`,"pws.pacingSlowerWins":`より遅いプロバイダー制限が優先され、モデル設定は遅延を増やす場合のみ適用されます。`,"pws.pacingQueued":`待機中`,"pws.pacingNextSlot":`次のスロットまで`,"pws.pacingLastModel":`最後のモデル`,"pws.pacingNone":`なし`,"pws.pacingModelOverrides":`モデル別設定`,"pws.pacingModel":`モデル`,"pws.pacingAdd":`設定を追加`,"pws.pacingRemove":`削除`,"pws.pacingRemoveModel":`{model} のリクエスト間隔設定を削除`,"pws.pacingRuleRequired":`プロバイダー制限またはモデル別設定を追加してから有効にしてください。`,"pws.saving":`保存中…`,"pws.settingsSaved":`設定を保存しました。`,"pws.accountModeSaved":`アカウントモードを保存しました。`,"pws.accountModeFailed":`アカウントモードを切り替えられませんでした。`,"pws.accountModeConfirm":`OpenAI のアカウントモードを切り替えますか?実行中の会話はもう一方のモードのアカウントセットに再割り当てされ、クォータ使用量は新しいモードで計上されます。`,"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.capacity.estimate":`設定済み重みによるプール推定`,"pws.capacity.currentAccount":`現在の有効アカウント`,"pws.capacity.nextRecovery":`次の容量回復`,"pws.capacity.recoveryShare":`+{percent}% のプール容量`,"pws.capacity.incomplete":`対象範囲が不完全です: {excluded} 件を除外(不明なプラン {unknown} 件)`,"pws.capacity.partial":`一部の期間の対象範囲が不完全です: {count} 件のアカウントでは表示中のすべての制限期間を取得できません`,"pws.capacity.windowPartial":`一部のみ`,"pws.capacity.windowPartialA11y":`{window}: アカウントの対象範囲が不完全です`,"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.connectionNotApplicable":`対象外 — このプロバイダーは静的モデルカタログを使用します。`,"pws.editSettings":`設定を編集`,"pws.viewUsage":`詳細な使用量を表示`,"pws.allSystemsOk":`すべてのシステムが稼働中`,"pws.apiKeyConfigured":`API キー設定済み`,"pws.addApiKey":`API キーを追加`,"pws.loggedInAs":`{email} としてログイン中`,"pws.notLoggedIn":`未ログイン`,"pws.passthrough":`Codex パススルー`,"pws.notes":`メモ`,"pws.notePlaceholder":`このプロバイダーについてのメモを追加...`,"pws.noteSaved":`メモを保存しました`,"pws.authSummary":`認証`,"time.justNow":`たった今`,"time.notChecked":`未確認`,"time.minutesAgo":`{n}分前`,"time.hoursAgo":`{n}時間前`,"time.daysAgo":`{n}日前`,"modal.noMatch":`一致なし。`,"modal.oauthDefaultNote":`アカウントでログイン — API キー不要です。`,"modal.oauthComingSoon":`{label} の OAuth ログインは次回の更新で対応予定です。今は API キーをお使いください。`,"modal.oauthComingSoonShort":`このプロバイダーの OAuth ログインは次回の更新で対応予定です — 今は API キーをお使いください。`,"modal.useApiKeyInstead":`代わりに API キーを使用`,"modal.setupGuide":`セットアップガイド`,"modal.setupStep1Prefix":`にアクセスし`,"modal.setupDashboardLink":`{label} ダッシュボード`,"modal.setupStep1Suffix":`から API キーをコピー`,"modal.setupStep2":`下の API キー欄に貼り付け`,"modal.setupStep3":`プロバイダーを追加をクリック — モデルは自動検出されます`,"modal.namePlaceholder":`例: openrouter`,"modal.duplicateWarn":`プロバイダー "{name}" は既存で、上書きされます。`,"modal.forwardHintPrefix":`キー不要 — プロキシはあなたの`,"modal.forwardCredentials":`codex ログイン`,"modal.forwardHintSuffix":`資格情報をこのプロバイダーに転送します。`,"modal.localHint":`API キーは保存されません。Cursor の静的な公開モデルカタログを Codex に追加しますが、ライブの Cursor トランスポートとネイティブのファイル/シェル実行は監査されるまで無効のままです。`,"modal.getApiKey":`{label} の API キーを取得`,"modal.apiKey":`API キー`,"modal.apiKeyTransport":`API キーヘッダー`,"modal.apiKeyTransportNative":`x-api-key (Anthropic 標準)`,"modal.apiKeyTransportBearer":`Authorization: Bearer`,"modal.apiKeyPlaceholder":`sk-… (または $ENV_VAR)`,"modal.defaultModelPlaceholder":`例: gpt-5.5`,"modal.baseUrlPlaceholder":`https://...`,"modal.baseUrlPlaceholderError":`ベース URL に未解決の {placeholder} が含まれています。実際の値に置き換えてください。`,"modal.baseUrlPlaceholderHint":`プロバイダーを追加する前に、ベース URL の {placeholder} を実際の Account ID に置き換えてください。`,"modal.adding":`追加中…`,"modal.useOauthLogin":`← OAuth ログインを使用`,"nav.codexAuth":`Codex 認証`,"nav.api":`API`,"nav.integrations":`連携`,"nav.openMenu":`メニューを開く`,"nav.closeMenu":`メニューを閉じる`,"integrations.subtitle":`クライアントを opencodex に接続し、認証情報の管理とクライアント設定の復元を行います。`,"integrations.tabsLabel":`連携画面`,"integrations.tab.overview":`概要`,"integrations.tab.keys":`API キー`,"integrations.tab.codex":`Codex CLI`,"integrations.tab.claude":`Claude`,"integrations.tab.grok":`Grok Build`,"integrations.tab.opencode":`OpenCode`,"integrations.tab.pi":`Pi`,"integrations.tab.omp":`OMP`,"integrations.tab.hermes":`Hermes`,"integrations.tab.openclaw":`OpenClaw`,"integrations.tab.kimi":`Kimi Code`,"integrations.tab.gajae":`Gajae Code`,"integrations.tab.dsh":`DeepSeek Harness (DSH)`,"integrations.tab.mcode":`MiniMax Code`,"integrations.codex.title":`Codex CLI`,"integrations.codex.body":`Codex の接続はプロキシサービスが管理します。opencodex を起動すると適用され、サービスを停止するとネイティブのルーティングに戻ります。`,"integrations.codex.openService":`サービス制御を開く`,"integrations.state.notInstalled":`未インストール`,"integrations.state.unknown":`確認中`,"integrations.detail.codexRouted":`Codex のリクエストはこのプロキシを経由します`,"integrations.detail.codexAbsent":`Codex はまだこのプロキシを経由していません`,"integrations.detail.keyCount":`キー {count} 個を発行済み`,"integrations.detail.keyNone":`発行済みのキーはありません`,"integrations.detail.keyChecking":`確認中…`,"integrations.detail.keyUnavailable":`キーの状態を取得できません`,"integrations.detail.claudeOff":`接続がオフです`,"integrations.detail.desktopCurrent":`Desktop はこのプロファイルで動作しています`,"integrations.detail.desktopStale":`適用後にプロファイルが変更されました`,"integrations.detail.desktopNotServed":`プロファイルはありますが Desktop は別のものを使用中です`,"integrations.detail.desktopAbsent":`適用されたプロファイルはありません`,"integrations.detail.desktopDesiredOff":`Claude Desktop 連携はオフです`,"integrations.detail.desktopDesiredOnNotApplied":`連携はオンですが、Desktop はゲートウェイプロファイルを使用していません`,"integrations.detail.desktopSelectedElsewhere":`Desktop は別のプロファイルを使用しています`,"integrations.detail.desktopProfileDrift":`選択された Desktop プロファイルが変更されました`,"integrations.detail.desktopObservedUnsafe":`選択された Desktop プロファイルは安全に変更できません`,"integrations.detail.desktopNotInstalled":`Claude Desktop の設定ライブラリがインストールされていません`,"integrations.dialog.desktop.title":`Claude Desktop 連携を無効にしますか?`,"integrations.dialog.desktop.changes":`{path} に opencodex 管理のゲートウェイプロファイルがある場合、Desktop は先に認証情報のない標準プロファイルを選択し、その後で古いプロファイルとバックアップを削除します。`,"integrations.dialog.desktop.breakage":`Claude Desktop は opencodex 経由のモデルではなく、標準の Claude に戻ります。`,"integrations.dialog.desktop.undo":`再度有効にすると、保存済みのモデル割り当てから opencodex プロファイルを再生成します。`,"integrations.dialog.desktop.restart":`Claude Desktop は起動時にのみこの設定を読み取ります。変更を反映するには完全に終了して再起動してください。`,"integrations.dialog.desktop.confirm":`無効にする`,"integrations.native.error.desktopUnsafeMetadata":`{path} の Claude Desktop メタデータを安全に読み取れなかったため、ライブラリは変更されませんでした。`,"integrations.native.error.desktopCleanupIncomplete":`Claude Desktop は標準モードを指していますが、古い opencodex 認証情報ファイルが残っています: {paths}。`,"integrations.native.msg.desktopDisabled":`Claude Desktop 連携を無効にしました。`,"integrations.native.msg.desktopEnabled":`Claude Desktop 連携を有効にしました。`,"integrations.detail.grokModels":`モデル {count} 個を接続済み`,"integrations.detail.grokAbsent":`設定に opencodex ブロックがありません`,"integrations.dialog.grok.title":`Grok Build 連携を解除しますか?`,"integrations.dialog.grok.changes":`{path} から、opencodex が印を付けたブロックだけを削除します。ブロック外に直接書いた内容はそのまま残します。`,"integrations.dialog.grok.breakage":`解除すると、Grok Build から opencodex のモデルエイリアスが消えます。xAI アカウントで使用していたモデルはそのままです。`,"integrations.dialog.grok.undo":`opencodex が loopback アドレスで実行中なら、再び有効にしたとき、現在利用できるモデル一覧からブロックを新しく書き込みます。`,"integrations.dialog.grok.confirm":`解除`,"integrations.native.msg.nonLoopbackRemoved":`Grok Build を自動登録できるのは、opencodex が loopback アドレスで実行中の場合だけです。loopback アドレスを指していた以前のブロックを削除しました。`,"integrations.native.msg.nonLoopbackRemovedNoop":`Grok Build を自動登録できるのは、opencodex が loopback アドレスで実行中の場合だけです。削除する以前のブロックはありませんでした。`,"integrations.native.msg.nonLoopbackSuperseded":`Grok Build を自動登録できるのは、opencodex が loopback アドレスで実行中の場合だけです。その間に別の場所から設定へ新しいブロックが書かれたため、現在ファイルにあるブロックはこのリクエストが作成したものではありません。`,"integrations.native.error.orphanedMarker":`{path} に opencodex の開始マーカーはありますが、終了マーカーがありません。ブロックの終端を特定できないため、ファイルは変更していません。`,"integrations.native.error.homeMismatch":`インストール済みサービスのホームと現在のホームが一致しないため、ファイルは変更していません。`,"integrations.native.error.notInstalled":`Grok Build がインストールされていないため、変更できません。`,"integrations.native.error.configBusy":`別の場所で設定を保存中のため、変更できませんでした。しばらくしてから再試行してください。`,"integrations.state.absent":`未適用`,"integrations.state.current":`適用済み`,"integrations.state.stale":`更新が必要`,"integrations.state.conflict":`競合`,"integrations.state.unsafe":`確認不可`,"integrations.summary.detected":`検出されたクライアント`,"integrations.summary.applied":`設定済みクライアント`,"integrations.summary.stale":`更新が必要`,"integrations.summary.lastChange":`最終変更`,"integrations.summary.disableAll":`すべて無効にする…`,"integrations.onboarding":`適用時は、先にバックアップを保存してから opencodex プロバイダーブロックを 1 つだけ書き込みます。無効化時はそのブロックだけを削除し、保存されたスナップショットから復元できます。`,"integrations.empty.title":`インストール済みのクライアントが検出されませんでした`,"integrations.empty.body":`対応クライアントをインストールしてから、ここに戻って opencodex を適用してください。`,"integrations.action.apply":`適用`,"integrations.action.disable":`無効にする`,"integrations.action.refresh":`更新`,"integrations.action.settings":`設定`,"integrations.action.manageKeys":`キーを管理`,"integrations.action.restore":`復元…`,"integrations.action.undo":`元に戻す`,"integrations.action.restorePoint":`この時点に復元…`,"integrations.action.snapshotExpired":`バックアップ期限切れ`,"integrations.rollback.title":`復元センター`,"integrations.rollback.empty":`適用履歴はまだありません`,"integrations.rollback.emptyBody":`書き込みが成功するたびに、変更前のスナップショットが先に保存されます。`,"integrations.restore.title":`このスナップショットを復元しますか?`,"integrations.restore.body":`現在のファイルを先にバックアップしてから、選択したスナップショットで置き換えます。`,"integrations.restore.driftTitle":`新しい編集が検出されました`,"integrations.restore.driftBody":`このスナップショット以降の変更をバックアップしてから、ファイルを置き換えます。`,"integrations.restore.confirm":`復元`,"integrations.restore.confirmDrift":`新しい編集をバックアップして復元`,"integrations.restore.pending":`復元中…`,"integrations.restore.manual":`自動復元に失敗しました: {reason}。{path} から手動で復元してください。`,"integrations.error.load":`連携状態を読み込めませんでした。`,"integrations.error.stale":`最新の更新に失敗しました。以下の値は古い可能性があります。`,"integrations.error.busy":`このクライアントに対する別の変更が実行中です。しばらくしてから再試行してください。`,"integrations.error.conflict":`opencodex の書き込み後に設定が変更されました。何も削除していません。`,"integrations.error.unsafe":`設定を安全に変更できません。`,"integrations.error.generic":`連携の変更に失敗しました。以前の状態は保持されています。`,"integrations.error.nonLoopback":`{client} は localhost のプロキシにしか接続できません。リモートバインドに必要な認証ヘッダーを置く場所が設定ファイルになく、手動で書いても同じです。トンネルやローカルフォワーダーで loopback 経路を用意してください。`,"integrations.status.installed":`インストール済み`,"integrations.status.notInstalled":`未インストール`,"integrations.status.appliedAt":`適用`,"integrations.status.backup":`バックアップ`,"integrations.status.lastRestore":`最終復元`,"integrations.status.unknown":`不明`,"integrations.bulk.title":`適用済みのクライアント連携を無効にしますか?`,"integrations.bulk.body":`opencodex が所有するブロックだけを削除します。各クライアントについて、変更前のスナップショットを保存します。`,"integrations.bulk.partial":`一部のクライアントを無効にできませんでした: {clients}`,"integrations.bulk.success":`適用済みのクライアント連携を無効にしました。`,"integrations.retention.degraded":`バックアップの整理が遅れています。古いバックアップがディスクに残っている可能性があります。`,"integrations.error.residual":`ファイルが中間状態のままの可能性があります: {message} {path} から復元してください。`,"integrations.error.recover":`{message} バックアップは {path} にあります。`,"integrations.kind.apply":`適用`,"integrations.kind.disable":`解除`,"integrations.kind.refresh":`更新`,"integrations.kind.restore":`復元`,"integrations.semantics.opencode":`ディスクから直接起動した場合にのみ適用されます。ocx opencode の環境注入が優先されます。`,"integrations.semantics.pi":`新しいセッションから適用されます。`,"integrations.semantics.omp":`カタログを読み込むには OMP を再起動してください。`,"integrations.semantics.hermes":`新しいセッションから適用されます。`,"integrations.semantics.openclaw":`実行中のゲートウェイにすぐ適用されます。`,"integrations.semantics.kimi":`再起動するか /reload を実行すると適用されます(v2 はファイルを監視します)。`,"integrations.semantics.gajae":`新しいセッション、または /model を開いたときに適用されます。`,"integrations.semantics.dsh":`OpenCodex が管理するのは $DSH_HOME/settings.yaml 内の llm-pi-ai.providers.opencodex だけです。DSH はこのプロバイダーをホットリロードし、既定のモデルと deepseek-official は変更しません。現在はループバック専用で、実際の認証情報は書き込みません。`,"integrations.semantics.mcode":`custom_provider.opencodex のみを管理します。既定モデルと MiniMax ログインは変更しません。`,"codexAuth.mainAccount":`メインアカウント`,"codexAuth.logLabel":`ログラベル`,"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.pinned":`固定中`,"codexAuth.pinnedHint":`手動で選択したアカウントなので、これより高い選択順序が先に使われることはありません。固定はこのアカウントを使い切るか、別のアカウントを選ぶか、いずれかの選択順序を変更するまで続きます。`,"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":`すぐに反映されます。アカウントに紐付いた既存スレッドと処理中のリクエストは現在のアカウントを維持し、新規または未紐付けのリクエストは選択したアカウントの順序ティアを使います。同じ選択順序のアカウントは引き続き交代で使われます。`,"codexAuth.cacheWarning":`アカウント切り替えでプロンプトキャッシュはリセットされます。新規セッションは空のキャッシュで開始します。`,"codexAuth.setAsNext":`このアカウントを次に使う`,"codexAuth.cancel":`キャンセル`,"codexAuth.switchBack":`メインに戻しますか?`,"codexAuth.switchBackDesc":`すぐに反映されます。アカウントに紐付いた既存スレッドと処理中のリクエストは現在のアカウントを維持し、新規または未紐付けのリクエストはアプリログインアカウントの順序ティアを使います。同じ選択順序のアカウントは引き続き交代で使われます。`,"codexAuth.autoSwitch":`使用量ベースのプロアクティブ切り替え`,"codexAuth.autoSwitchQuotaDesc":`クォータ: 使用率が {threshold}% 以上になると、既に紐付いたタスクを含む次のリクエストが、使用率の低い適格アカウントへ移る場合があります。Go/Free は 30 日枠のみを使用します。`,"codexAuth.autoSwitchQuotaOffDesc":`使用量ベースのプロアクティブ切り替えはオフです。新規/未紐付けタスクの割り当てと障害回復は引き続き適用されます。`,"codexAuth.autoSwitchRoundRobinDesc":`ラウンドロビン割り当てはこのしきい値を使用せず、新規/未紐付けタスクを引き続きローテーションします。`,"codexAuth.autoSwitchFillFirstDesc":`フィルファースト: {threshold}% は新規/未紐付けタスクの使い切り基準です。正常な紐付け済みタスクはアカウントを維持します。`,"codexAuth.autoSwitchFillFirstOffDesc":`フィルファーストには新規/未紐付けタスクの使用量基準がありません。クールダウン、再認証、障害回復では引き続きルーティングが変わる場合があります。`,"codexAuth.failureRecoveryNote":`障害回復は別です。出力前の 429/402 拒否、クールダウン、再認証、除外、または設定済みの一時障害フェイルオーバーにより、別の適格アカウントが選ばれる場合があります。`,"codexAuth.autoSwitchThreshold":`使用量しきい値`,"codexAuth.autoSwitchThresholdAria":`使用量しきい値(パーセント)`,"codexAuth.autoSwitchThresholdInc":`使用量しきい値を上げる`,"codexAuth.autoSwitchThresholdDec":`使用量しきい値を下げる`,"codexAuth.autoSwitchLoadFailed":`使用量ベースの切り替え設定を読み込めませんでした。`,"codexAuth.autoSwitchThresholdInvalid":`1 から 100 までの整数を入力してください`,"codexAuth.autoSwitchUpdated":`使用量ベースのプロアクティブ切り替え設定を更新しました`,"codexAuth.autoSwitchUpdateFailed":`使用量ベースの切り替え更新を確認できませんでした。最後に確認された値を表示しています。`,"codexAuth.requestUserInput":`Default モードで入力を求める`,"codexAuth.requestUserInputDesc":`Default モードのセッションで Codex が一時停止し、request_user_input ツールで質問できるようにします。`,"codexAuth.requestUserInputUpdated":`機能フラグを更新しました - 新しいセッションから適用されます。`,"codexAuth.requestUserInputUpdatedRestart":`機能フラグを更新しました - 新しいセッションから適用されます。Codex アプリを再起動してください。`,"codexAuth.requestUserInputUpdateFailed":`機能フラグを更新できませんでした。変更はありません。`,"codexAuth.requestUserInputLoadFailed":`config.toml から機能フラグを読み込めませんでした。`,"codexAuth.accountPickerTitle":`モデルピッカーで使用する Codex アカウントを指定`,"codexAuth.accountPickerOffDesc":`有効にすると、通常の GPT ピッカー項目がアカウントセレクターごとの項目に置き換わり、ログアウトせずに会話で使うアカウントを明示的に選べます。無効にしてもアカウントは削除されません。`,"codexAuth.accountPickerOnDesc":`各セレクターは保存済みアカウント 1 つに対応する公開ラベルです。選択した会話はそのアカウントに固定され、Pool のローテーションやフォールバックは行われず、現在の Pool アカウントも変更されません。`,"codexAuth.accountPickerCompatibility":`組み込みの Codex App ログインには専用セレクターがあります。生成されたマップでは通常 main と呼ばれ、必要に応じて main-2 のような衝突を避けるサフィックスが使われます。追加アカウントには安定したプライバシー保護ラベルが割り当てられ、カスタムセレクター名は保持されます。既存の会話と保存済みのモデル選択は引き続きルーティングされます。無効にすると生成された項目だけが非表示になり、セレクターと完全一致ルートは保持されます。通常の GPT モデル ID は従来どおり Pool または Direct で動作します。`,"codexAuth.accountPickerUpdated":`アカウント指定を更新しました。`,"codexAuth.accountPickerUpdateFailed":`アカウント指定を更新できませんでした。最後に確認された設定を表示しています。`,"codexAuth.accountPickerLoadFailed":`アカウント指定の設定を読み込めませんでした。`,"codexAuth.accountPickerRefreshFailed":`この設定を更新できませんでした。最後に確認された値を引き続き表示しています。`,"codexAuth.advancedSettings":`詳細設定`,"codexAuth.advancedSettingsAria":`高度な Codex 認証設定を表示または非表示`,"codexAuth.catalogRefreshPending":`変更は保存されましたが、Codex モデルカタログの更新が保留中です。ocx sync を実行して再試行してください。`,"anthropicPool.title":`Claude アカウントプール(実験的)`,"anthropicPool.enabledDesc":`429 時にアカウントをクールダウンしてフェイルオーバーします。新規セッションは 5 時間使用率が {threshold}% 未満のアカウントを優先します。`,"anthropicPool.disabledDesc":`アクティブな Claude アカウントのみを使用します。実験的ルーティングを受け入れる場合のみ有効にしてください。`,"anthropicPool.experimentalWarning":`実験的で十分に検証されていません。自動的な複数アカウント回転に見える行為は Anthropic により制限される可能性があります。同一組織はクォータを共有することがあり、その場合プールしても効果がありません。リスクを理解していない場合はオフのままにしてください。`,"anthropicPool.needTwoAccounts":`プールを有効にする前に、Claude OAuth アカウントを 2 つ以上追加してください。`,"anthropicPool.threshold":`新規セッションの使用率しきい値`,"anthropicPool.thresholdAria":`新規セッションの使用率しきい値(パーセント)`,"anthropicPool.thresholdHelp":`0 はクォータに基づく選択を無効にします(アフィニティ + アクティブアカウントのみ)。デフォルト 80。`,"anthropicPool.thresholdInvalid":`0 から 100 までの整数を入力してください`,"anthropicPool.loadFailed":`Claude プール設定を読み込めませんでした。`,"anthropicPool.saveFailed":`Claude プール設定を保存できませんでした。`,"anthropicPool.on":`オン`,"anthropicPool.off":`オフ`,"accountPool.strategy":`ローテーション戦略`,"accountPool.strategyDesc":`OpenCodex が新規/未紐付けタスクへアカウントを割り当てる方法です。`,"accountPool.strategyQuota":`クォータ`,"accountPool.strategyRoundRobin":`ラウンドロビン`,"accountPool.strategyFillFirst":`フィルファースト`,"accountPool.strategyHintQuota":`クォータ戦略は使用量しきい値を超えると、既存タスクの次のリクエストも別アカウントへ再紐付けできます。`,"accountPool.strategyHintRoundRobin":`ラウンドロビンは有効な紐付けがないタスクだけをローテーションし、使用量しきい値は通常のローテーションを変えません。`,"accountPool.strategyHintFillFirst":`フィルファーストはしきい値を未紐付けタスクの使い切り基準として使用し、正常な紐付け済みタスクは親和性を維持します。`,"accountPool.unboundDefinition":`新規/未紐付けタスクとは、現在のアカウント紐付けがないリクエストです。既存の表示中タスクも、プロキシまたは親和性のリセット後は未紐付けになる場合があります。`,"accountPool.stickyLimit":`ローテーション前の新規/未紐付け割り当て数`,"accountPool.stickyLimitAria":`ローテーション前の新規/未紐付け割り当て数`,"accountPool.stickyLimitInc":`スティッキー上限を上げる`,"accountPool.stickyLimitDec":`スティッキー上限を下げる`,"accountPool.stickyLimitHelp":`次へ進む前に、この回数の新規/未紐付けタスクを選択アカウントへ割り当てます。カウンターは上流の成功後ではなく、タスクを紐付けた時点で増えます。`,"accountPool.stickyLimitInvalid":`1 から 100 までの整数を入力してください`,"accountPool.strategyLoadFailed":`ローテーション戦略を読み込めませんでした。`,"accountPool.strategyUpdateFailed":`ローテーション戦略を保存できませんでした。`,"accountPool.priority":`選択順序`,"accountPool.priorityAria":`このアカウントの選択順序`,"accountPool.priorityHint":`数値が大きいほど先に使われます。上位のアカウントがすべて使い切られるか利用できなくなったときにのみ、より小さい数値へ移ります。`,"accountPool.priorityFirst":`最初`,"accountPool.priorityEarlier":`早め`,"accountPool.priorityNormal":`標準`,"accountPool.priorityLater":`遅め`,"accountPool.priorityLast":`最後`,"accountPool.priorityOption":`{name}({value})`,"accountPool.priorityCustom":`カスタム`,"accountPool.priorityUpdated":`{email} の選択順序を更新しました`,"accountPool.priorityUpdateFailed":`{email} の選択順序を保存できませんでした。最後に確認された値を表示しています。`,"codexAuth.switched":`次のリクエストでは {email} を使用します`,"codexAuth.loadFailed":`Codex アカウント設定を読み込めませんでした。`,"codexAuth.switchFailed":`アカウントを切り替えられませんでした。以前の選択はそのままです。`,"codexAuth.removeConfirm":`{id} を削除しますか?`,"codexAuth.removeFailed":`アカウントを削除できませんでした。何も変更されていません。`,"codexAuth.addTitle":`Codex アカウントを追加`,"codexAuth.addIdLabel":`アカウント ID (スラッグ)`,"codexAuth.addIdPlaceholder":`codex-work、codex-alt、team...`,"codexAuth.resetCreditsAria":`{count} 個のリセットクレジット`,"codexAuth.addJsonLabel":`auth.json の内容`,"codexAuth.addHelp":`別のマシンの ~/.codex/auth.json からコピー、または codex-auth export を使用。`,"codexAuth.importBtn":`インポート`,"codexAuth.importInvalidJson":`無効な JSON です`,"codexAuth.importMissingTokens":`JSON に access_token または refresh_token がありません`,"codexAuth.importMissingId":`アカウント ID は必須です`,"codexAuth.accountAdded":`アカウントをプールに追加しました`,"codexAuth.addPickDesc":`別の ChatGPT アカウントでログインしてプールに追加します。`,"codexAuth.oauthLogin":`OAuth ログイン`,"codexAuth.oauthDesc":`ブラウザで ChatGPT ログインを開きます`,"codexAuth.importAuthJson":`auth.json をインポート`,"codexAuth.importAuthJsonDesc":`別の Codex インストールまたは codex-auth export から`,"codexAuth.back":`戻る`,"codexAuth.oauthAlreadyInProgress":`ログインは既に進行中です。ブラウザで完了してください。`,"codexAuth.oauthWaiting":`ブラウザで ChatGPT ログインが完了するのを待機中...`,"codexAuth.oauthSubmittingCode":`コードを送信中…`,"codexAuth.oauthCodeSubmitted":`コードを送信しました — ログイン完了を待っています…`,"codexAuth.oauthStatusRetrying":`ログイン状態の確認中にネットワークまたはプロキシ エラーが発生しました — 再試行中…`,"codexAuth.oauthCancelled":`ログインはキャンセルされました。`,"codexAuth.loginFailed":`ログインに失敗しました`,"codexAuth.needsReauth":`再ログイン`,"codexAuth.reauthenticate":`再認証`,"codexAuth.tokenExpired":`トークンが期限切れ — このアカウントを再認証してください`,"codexAuth.mainTokenExpired":`トークンが期限切れ — Codex アプリログインから再度サインインしてください`,"codexAuth.emailCollision":`このアカウントはメインの Codex ログインと一致します。別のアカウントを使用してください。`,"codexAuth.resetCreditsTitle":`リセットクレジット`,"codexAuth.resetCreditsAvailable":`{count} 個のリセットクレジットが利用可能です。`,"codexAuth.resetCreditsDesc":`各クレジットは現在の時間別・週間使用量上限を即座にリセットします。`,"codexAuth.noResetCredits":`リセットクレジットはありません。`,"codexAuth.earnCreditsHint":`クレジットは毎月および紹介プログラム経由で獲得できます。`,"codexAuth.creditsExpireNote":`クレジットは獲得から 30 日で失効します。`,"codexAuth.useOneCredit":`1 クレジットを使用`,"codexAuth.confirmResetTitle":`リセットクレジットを使用しますか?`,"codexAuth.confirmResetDesc":`現在のレート制限を即座にリセットします。残り {count} クレジットです。`,"codexAuth.irreversible":`この操作は元に戻せません。`,"codexAuth.useCredit":`クレジットを使用`,"codexAuth.redeeming":`リセット中...`,"codexAuth.resetSuccess":`レート制限をリセットしました! 残り {remaining} クレジット。`,"codexAuth.resetSuccessGeneric":`レート制限をリセットしました!`,"codexAuth.resetAlreadyRedeemed":`このクレジットは既に引き換え済みです。クレジットは変わりません。`,"codexAuth.resetNothingToReset":`今リセットが必要なレート制限枠はありません。`,"codexAuth.resetNoCredit":`利用可能なリセットクレジットはありません。`,"codexAuth.resetError":`リセットクレジットの引き換えに失敗しました。もう一度お試しください。`,"codexAuth.fifoNote":`最も古いクレジットが先に使用されます。`,"codexAuth.confirmWhichCredit":`{date} のクレジットが使用されます。`,"codexAuth.creditNext":`次に使用`,"codexAuth.creditLabel":`クレジット #{n}`,"codexAuth.creditNextBadge":`次`,"codexAuth.creditGranted":`付与 {date}`,"codexAuth.creditExpires":`失効 {date} (残り {days}日)`,"api.title":`API アクセス`,"api.subtitle":`生成した API キーで外部アプリから opencodex プロキシに接続します。認証は {authHeader} ヘッダーで行い、エンドポイントごとに受け付けるヘッダーは下の表のとおりです。`,"api.endpointNote":`ベース URL を OpenAI 互換クライアントで使ってください。Responses と Chat Completions は /v1 配下で公開されます。`,"api.endpointsTitle":`エンドポイント`,"api.baseUrl":`ベース URL`,"api.responsesEndpoint":`Responses API`,"api.chatCompletionsEndpoint":`Chat Completions API`,"api.messagesEndpoint":`Messages API`,"api.modelsEndpoint":`Models API`,"api.authTitle":`認証`,"api.authBaseUrlNote":`クライアントにはベース URL を設定し、下のプロトコル別エンドポイントを選んでください。`,"api.authLoopback":`ループバック (127.0.0.1 または ::1) は認証を省略します。リモートでは生成した ocx_ キーまたは OPENCODEX_API_AUTH_TOKEN が必要です。`,"api.modelsTitle":`外部モデルカタログ`,"api.modelsCount":`{count} 件が利用可能`,"api.modelsSearch":`モデルを検索`,"api.modelsSubtitle":`これらの ID を /v1/models と選択したプロトコルで使用してください。`,"api.modelsLoading":`モデルを読み込み中…`,"api.modelsLoadFailed":`外部モデルカタログを読み込めませんでした。`,"api.modelsEmpty":`外部から呼び出せるモデルはまだありません。`,"api.modelsNoMatch":`「{query}」に一致するモデルはありません。`,"api.colModel":`モデル`,"api.colSource":`ソース`,"api.colProtocols":`プロトコル`,"api.copyModelId":`ID をコピー`,"api.modelCopied":`コピーしました`,"api.testModel":`テスト`,"api.testingModel":`テスト中…`,"api.testSucceeded":`OK`,"api.testFailed":`失敗`,"api.protocolResponses":`Responses`,"api.protocolChatCompletions":`Chat Completions`,"api.protocolMessages":`Messages`,"api.sourceNative":`ChatGPT プール`,"api.sourceCombo":`コンボ`,"api.sourceCustom":`カスタム`,"api.usageResponsesTitle":`Responses の例`,"api.usageChatTitle":`Chat Completions の例`,"api.usageMessagesTitle":`Messages の例`,"api.newKeyTitle":`新しいキーを作成しました`,"api.newKeyNote":`今すぐこのキーをコピーしてください — 再表示されません。`,"api.copy":`コピー`,"api.copied":`コピーしました`,"api.dismiss":`閉じる`,"api.generateTitle":`キーを生成`,"api.keyNamePlaceholder":`キー名(任意)`,"api.generate":`生成`,"api.generating":`作成中…`,"api.activeKeys":`アクティブなキー ({count})`,"api.activeKeysLoading":`有効なキー`,"api.noKeys":`まだ API キーがありません。上で生成してください。`,"api.workspace.sections":`API セクション`,"api.section.keys":`キー`,"api.section.connect":`接続`,"api.section.endpoints":`エンドポイント`,"api.section.models":`モデル`,"api.section.examples":`例`,"api.workspace.details":`APIキーの詳細`,"api.workspace.keyDetails":`キーの詳細`,"api.workspace.keyPrefix":`キーのプレフィックス`,"api.workspace.deleteKey":`キーを削除`,"api.workspace.deleteConfirm":`このキーを削除しますか?この操作は元に戻せません。`,"api.workspace.usageExamples":`使用例`,"api.copyUrlHint":`クリックして URL をコピー`,"api.urlCopied":`URL をコピーしました`,"api.copyExampleHint":`クリックして例をコピー`,"api.exampleCopied":`例をコピーしました`,"api.colName":`名前`,"api.colKey":`キー`,"api.colCreated":`作成日`,"api.confirm":`確認`,"api.deleteAria":`API キーを削除`,"api.usageSampleInput":`こんにちは、世界!`,"api.clientConfig.title":`クライアント設定`,"api.clientConfig.rowsLabel":`クライアントを接続`,"api.clientConfig.details":`詳細`,"api.clientConfig.detailsAria":`{client} 設定の詳細`,"api.clientConfig.copyAria":`{client} 設定をコピー`,"api.clientConfig.downloadAria":`{client} 設定をダウンロード`,"api.clientConfig.rowMeta":`{destination} · モデル {count} 件`,"api.clientConfig.rowError":`{client} の設定を生成できませんでした。`,"api.clientConfig.copiedAnnounceClient":`{client} の設定をクリップボードにコピーしました。`,"api.clientConfig.clientOpencode":`OpenCode`,"api.clientConfig.clientPi":`Pi`,"api.clientConfig.clientOmp":`OMP`,"api.clientConfig.clientHermes":`Hermes`,"api.clientConfig.clientOpenclaw":`OpenClaw`,"api.clientConfig.clientKimi":`Kimi Code`,"api.clientConfig.clientGajae":`Gajae Code`,"api.clientConfig.clientDsh":`DeepSeek Harness (DSH)`,"api.clientConfig.clientMcode":`MiniMax Code`,"api.clientConfig.copy":`設定をコピー`,"api.clientConfig.download":`ダウンロード`,"api.clientConfig.loading":`クライアント設定を生成中…`,"api.clientConfig.jsonLabel":`{client} 設定`,"api.clientConfig.destination":`配置先ファイル`,"api.clientConfig.envHint":`起動前にキーを設定`,"api.clientConfig.mergeWarning":`配置先ファイルにマージしてください。置き換えると既存のプロバイダーや MCP 設定が失われます。`,"api.clientConfig.modelCount":`{count} 件のモデルを書き出しました`,"api.clientConfig.missingLimits":`{total} 件中 {count} 件のモデルにコンテキスト上限がないため、クライアント側の既定値が使われます。`,"api.clientConfig.noKeyYet":`{env} に対応するキーがまだありません。ループバック外で使う前に上でキーを発行してください。`,"api.clientConfig.loadFailed":`モデル一覧を読み取れなかったため、クライアント設定を生成できませんでした。`,"api.clientConfig.copiedAnnounce":`クライアント設定をクリップボードにコピーしました。`,"api.clientConfig.copyFailed":`クライアント設定をコピーできませんでした。`,"api.clientConfig.downloadedAnnounce":`{filename} をダウンロードしました。まだ何も変わっていません。{destination} に自分でマージしてください。`,"api.clientConfig.whereDisclosure":`このファイルの置き場所`,"api.clientConfig.whereBody":`上のパスはグローバル設定の場所です。作業ディレクトリのプロジェクト設定ファイルが優先され、キーは設定に書かれた環境変数から読み込まれ、このファイルには保存されません。`,"api.keysLoadFailed":`APIキーを読み込めませんでした。`,"api.createFailed":`APIキーを作成できませんでした。`,"api.deleteFailed":`APIキーを削除できませんでした。`,"api.auth.endpoint":`エンドポイント`,"api.auth.required":`必須`,"api.auth.accepted":`利用可`,"api.auth.rejected":`不可`,"api.auth.testProtocol":`{protocol} をテスト`,"api.auth.testNeedsFreshKey":`認証付きテストを実行するには、キーを新しく作成し、一度だけ表示される値を画面に残したままにしてください。`,"api.key.name":`キー名`,"api.key.rename":`名前を変更`,"api.key.saveName":`名前を保存`,"api.key.renaming":`保存中…`,"api.key.renameFailed":`名前を変更できませんでした。入力内容はそのまま残しています。`,"api.key.deleting":`削除中…`,"api.key.copyFailed":`キーをコピーできませんでした。このパネルを閉じる前に手動で選択してコピーしてください。`,"api.attribution.title":`キー別の使用状況`,"api.attribution.requests7d":`直近 7 日のリクエスト`,"api.attribution.totalRequests":`集計済みリクエスト総数`,"api.attribution.totalRequestsAvailable":`利用可能な履歴のリクエスト`,"api.attribution.sinceAvailable":`利用可能な集計開始日`,"api.attribution.lastUsed":`最終使用`,"api.attribution.since":`集計開始`,"api.attribution.neverUsed":`集計開始以降は未使用`,"api.attribution.unavailable":`使用状況なし`,"api.attribution.unavailableDetail":`まだ集計された使用状況がありません。集計開始前のリクエストは遡って割り当てられません。`,"api.attribution.ambiguous":`2 つのキーが同じ ID を共有しているため、どちらの使用状況か判別できません。設定ファイルでキーごとに一意の ID を指定してください。`,"api.attribution.railAmbiguous":`ID 重複`,"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.appliedMarkerUnsaved":`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.status.disabled":`Claude Desktop 連携はオフです。有効にした後、Desktop を完全に終了して再起動してください。`,"claudeDesktop.enableApply":`有効にして適用`,"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.tabsLabel":`コンボ詳細セクション`,"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.nativeAlias":`ネイティブ OpenAI エイリアス`,"cws.field.nativeAliasHint":`このコンボがサポート対象の修飾なし OpenAI ネイティブモデル ID を所有します。アカウント修飾・プロバイダー修飾ルートは別のままです。`,"cws.field.displayName":`表示名`,"cws.field.displayNameHint":`モデルピッカーに表示するラベルです。ネイティブ OpenAI エイリアスでは必須です。`,"cws.field.stickyLimit":`ローテーション前の固定成功数`,"cws.field.stickyLimitHint":`重み付きセレクタが進む前に、選んだターゲットをこの回数の成功リクエスト分保持します。`,"cws.field.defaultEffort":`デフォルトの推論`,"cws.field.defaultEffortNone":`なし(ターゲットのデフォルト)`,"cws.field.defaultEffortHint":`クライアントが推論負荷を省略した場合のみ使用されます。選択肢は選択ターゲットが広告する負荷の交差です。`,"cws.capability.imageInputUnavailable":`選択した全ターゲットが画像入力に対応すると有効になります。`,"cws.capability.imageInputHint":`全ターゲットが画像対応なら既定でオン。オフにするとテキストのみ。`,"cws.capability.imageInput":`画像 / マルチモーダル`,"cws.capabilities":`能力`,"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.unsupportedNativeAlias":`ネイティブエイリアスには、現在サポートされている OpenAI の bare model id を指定してください。`,"cws.err.missingNativeAliasDisplayName":`ネイティブエイリアスには表示名が必要です。`,"cws.err.invalidDisplayName":`表示名は 128 文字以内で、制御文字を含めることはできません。`,"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.customFieldReasoning":`推論努力`,"models.customFieldReasoningOverride":`推論努力を上書き`,"models.reasoningEffort.none":`なし`,"models.reasoningEffort.minimal":`最小`,"models.reasoningEffort.low":`低`,"models.reasoningEffort.medium":`中`,"models.reasoningEffort.high":`高`,"models.reasoningEffort.xhigh":`非常に高`,"models.reasoningEffort.max":`最大`,"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":`今すぐ同期`,"lab.title":`Compatibility Lab`,"lab.subtitle":`Read-only compatibility verdict matrix from lab projection evidence.`,"lab.loadFailed":`Could not load compatibility lab data`,"lab.projectionUnavailable":`Lab projection is not available. Run conformance or live probes first.`,"lab.projectionIncompatible":`Lab projection schema is incompatible. Rebuild the projection.`,"lab.statusTitle":`Projection status`,"lab.matrixTitle":`Compatibility matrix`,"lab.verdictsTitle":`Verdict records`,"lab.filter.layer":`Evidence layer`,"lab.filter.verdict":`Verdict`,"lab.filter.subject":`Subject ID`,"lab.filter.all":`All`,"lab.col.subject":`Subject`,"lab.col.layer":`Layer`,"lab.col.suite":`Suite`,"lab.col.verdict":`Verdict`,"lab.col.asOf":`As of`,"lab.col.protocol":`Protocol conformance`,"lab.col.live":`Live route compatibility`,"lab.col.task":`Task effectiveness`,"lab.empty":`No compatibility verdicts in the projection yet.`,"lab.subjectKind":`Kind`,"lab.observationCount":`Observations`,"lab.eventCount":`Events`,"lab.verdictCount":`Verdicts`,"lab.subjectCount":`Subjects`,"lab.builtAt":`Built`,"lab.loading":`Loading compatibility evidence…`,"lab.loadMore":`Load more`,"lab.detailTitle":`Verdict detail`,"lab.detailClose":`Close`,"lab.detailSubject":`Subject`,"lab.detailObservations":`Observations`,"lab.detailEvents":`Contributing events`,"lab.detailArtifacts":`Artifact metadata`,"lab.production.title":`観測された本番トラフィック`,"lab.production.notVerification":`ラボ検証ではありません`,"lab.production.attempts":`試行`,"lab.production.successes":`成功`,"lab.production.routeErrors":`ルートエラー`,"lab.production.lastObserved":`最終観測`,"lab.detailLoadFailed":`Could not load verdict detail`,"lab.refresh":`Refresh`,"lab.verdict.UNKNOWN":`Unknown`,"lab.verdict.CLAIMED":`Claimed`,"lab.verdict.PROBED":`Probed`,"lab.verdict.VERIFIED":`Verified`,"lab.verdict.DEGRADED":`Degraded`,"lab.verdict.BLOCKED":`Blocked`,"lab.verdict.UNSUPPORTED":`Unsupported`,"lab.layer.protocol_conformance":`Protocol conformance`,"lab.layer.live_route_compatibility":`Live route compatibility`,"lab.layer.task_effectiveness":`Task effectiveness`,"dash.visionAdvanced":`詳細設定`,"dash.visionMaxDescriptions":`1 ターンあたりの最大説明数`,"dash.visionMaxDescriptionsInvalid":`正の整数を入力してください。`,"dash.visionTimeout":`タイムアウト`,"dash.visionTimeoutInvalid":`{min} から {max} ミリ秒の整数を入力してください。`,"dash.visionAdvancedPopover":`詳細なビジョン設定`},Fe={"nav.dashboard":`Gösterge Paneli`,"uptime.day":` gün`,"uptime.hour":` saat`,"uptime.minute":` dk`,"uptime.second":` sn`,"nav.startup":`Başlatma Güvenliği`,"nav.providers":`Sağlayıcılar`,"nav.models":`Modeller`,"nav.combos":`Kombolar`,"nav.subagents":`Alt Ajanlar`,"nav.logs":`Günlükler & Hata Ayıklama`,"nav.usage":`Kullanım`,"common.github":`GitHub`,"sidebar.star":`GitHub'da Yıldız Ver`,"sidebar.starred":`GitHub'da Yıldız Verildi`,"sidebar.starUnauthenticated":`Yıldız vermek için GitHub'ı açın (gh CLI oturum açmamış)`,"sidebar.starFailed":`gh üzerinden yıldız verilemedi. Bunun yerine GitHub açılıyor.`,"sidebar.updateAvailable":`Güncelleme mevcut: {version}`,"sidebar.checkUpdate":`Güncellemeleri kontrol et`,"common.save":`Kaydet`,"common.saving":`Kaydediliyor…`,"common.cancel":`İptal`,"common.discard":`Vazgeç`,"common.close":`Kapat`,"common.ok":`Tamam`,"common.remove":`Kaldır`,"common.loading":`Yükleniyor…`,"common.retry":`Tekrar Dene`,"auth.adminTokenTitle":`OpenCodex yönetici jetonu (OPENCODEX_ADMIN_AUTH_TOKEN)`,"auth.adminAccountLabel":`Hesap`,"auth.adminTokenFieldLabel":`Yönetici jetonu`,"auth.adminTokenRejected":`Bu yönetici jetonu reddedildi. Kontrol edip tekrar deneyin.`,"auth.adminTokenUnavailable":`Yönetici jetonu doğrulanamadı. Tekrar deneyin.`,"app.logoAria":`opencodex logosu`,"app.claudeOn":`Claude AÇIK`,"app.claudeOff":`Claude KAPALI`,"theme.label":`Tema`,"theme.light":`Açık`,"theme.dark":`Koyu`,"theme.system":`Sistem`,"lang.label":`Dil`,"lang.nativeName":`Türkçe`,"provider.name.commandCodeAuth":`Command Code - Auth`,"provider.name.commandCodeApi":`Command Code - API`,"provider.name.volcengine":`Volcengine Ark`,"provider.name.volcengineCodingPlan":`Volcengine Ark Coding Plan`,"provider.name.volcengineAgentPlan":`Volcengine Ark Agent Plan`,"errorBoundary.title":`Sayfa yüklenemedi`,"errorBoundary.message":`Bu bölümde bir işleme hatası oluştu. Yeniden denemek için sayfayı yenileyin.`,"errorBoundary.details":`Hata`,"errorBoundary.reload":`Yeniden Yükle`,"routing.title":`Yönlendirme Zekası (beta)`,"routing.subtitle":`Politika profilleri, simülasyon değerlendirmesi ve kaynak destekli yönlendirme analitiği.`,"routing.loadFailed":`Yönlendirme verileri yüklenemedi`,"routing.empty":"Yapılandırılmış yönlendirme profili yok. config.json dosyasına `routingProfiles` ekleyin.","routing.revision":`revizyon`,"routing.detail":`Profil`,"routing.createProfile":`Profil oluştur`,"routing.dryRunError":`Simülasyon başarısız oldu (HTTP {status})`,"routing.removeConfirm":`{id} profili kaldırılsın mı?`,"routing.unknownEvidence.allow":`izin ver`,"routing.unknownEvidence.penalize":`cezalandır`,"routing.unknownEvidence.exclude":`hariç tut`,"routing.removeCandidate":`{provider}/{model} adayı kaldırılsın mı`,"routing.candidates":`Adaylar`,"routing.require":`Katı gereksinimler`,"routing.optimize":`Optimizasyon ağırlıkları`,"routing.limits":`Limitler`,"routing.unknownEvidence":`Bilinmeyen kanıt politikası`,"routing.compatibility.title":`Uyumluluk politikası`,"routing.compatibility.enabled":`Compatibility Lab kanıtı gerekli`,"routing.compatibility.requiredSuites":`Gerekli test süitleri`,"routing.compatibility.loadingCatalog":`Lab kataloğu yükleniyor…`,"routing.compatibility.catalogUnavailable":`Lab kataloğu kullanılamıyor — test süiti kimliklerini config.json içinde elle girin.`,"routing.compatibility.layer.protocol_conformance":`Protokol uyumu`,"routing.compatibility.layer.live_route_compatibility":`Canlı rota uyumluluğu`,"routing.compatibility.minStatus":`Minimum uyumluluk durumu`,"routing.none":`yok`,"routing.unavailable":`–`,"routing.dryRun":`Simülasyon değerlendirmesi`,"routing.dryRunContext":`İstek bağlam penceresi (jetonlar)`,"routing.dryRunTools":`İstek araç gerektiriyor`,"routing.dryRunImage":`İstek görsel girdisi gerektiriyor`,"routing.dryRunStructured":`İstek yapılandırılmış çıktı gerektiriyor`,"routing.dryRunRun":`Adayları değerlendir`,"routing.candidate":`Aday`,"routing.eligible":`Uygun`,"routing.exclusions":`Hariç Tutulanlar`,"routing.costCap":`Maliyet tavanı`,"routing.capOutcome.satisfied":`limit içinde`,"routing.capOutcome.exceeded":`limit aşıldı`,"routing.capOutcome.unknown-allowed":`bilinmiyor (izinli)`,"routing.capOutcome.unknown-excluded":`bilinmiyor (hariç tutuldu)`,"routing.exclusion.capability-unsatisfied":`yetenek karşılanmadı`,"routing.exclusion.unknown-capability":`bilinmeyen yetenek`,"routing.exclusion.cost-limit":`maliyet tavanı aşıldı`,"routing.exclusion.cost-limit-unknown":`maliyet tavanı doğrulanamadı`,"routing.exclusion.cooldown":`soğuma süresi`,"routing.exclusion.unknown-health":`bilinmeyen sağlık`,"routing.exclusion.unknown-quota":`bilinmeyen kota`,"routing.exclusion.unknown-price":`bilinmeyen fiyat`,"routing.exclusion.other":`hariç tutma: {code}`,"routing.score":`Puan`,"routing.selected":`seçildi`,"routing.yes":`evet`,"routing.no":`hayır`,"routing.analytics":`Yönlendirme analitiği`,"routing.analyticsTotal":`İstekler`,"routing.analyticsSuccessRate":`Başarı`,"routing.analyticsFallbackRate":`Yedekleme`,"routing.analyticsP50":`p50`,"routing.analyticsP95":`p95`,"routing.analyticsP99":`p99`,"routing.analyticsCooldown":`Soğuma süresi hataları`,"routing.analyticsConfidence":`Güvenilirlik`,"routing.analyticsTruncated":`kısaltılmış geçmiş`,"routing.analyticsRequests":`İstekler`,"routing.analyticsEmpty":`Henüz analitik verisi yok — önce birkaç istek gönderin.`,"startup.title":`Başlatma güvenliği`,"startup.subtitle":`Yerel proxy yönlendirmesi bir yeniden bağlanma döngüsüne girmeden önce Codex'in yeniden başlatmanın ardından opencodex'e erişebildiğini doğrulayın.`,"startup.refresh":`Yenile`,"startup.backToDashboard":`Gösterge Paneline Dön`,"startup.loading":`Başlatma koruması kontrol ediliyor…`,"startup.error":`Başlatma koruması okunamadı.`,"startup.staleData":`Son başlatma kontrolü başarısız oldu. Aşağıdaki değerler güncel değildir ve koruma kanıtı olarak kabul edilmemelidir.`,"startup.status.native":`Yerel yönlendirme`,"startup.status.protected":`Yeniden başlatma korumalı`,"startup.status.atRisk":`Eylem gerekiyor`,"startup.summary.native":`Codex yerel proxy'ye bağımlı değildir`,"startup.summary.protected":`opencodex yeniden başlatmanın ardından kullanılabilir olacaktır`,"startup.summary.atRisk":`Codex yeniden başlatmanın ardından model erişimini kaybedebilir`,"startup.riskDetail":`Codex yerel proxy'ye sabitlenmiş, ancak kalıcı bir servis veya sağlıklı başlatıcı shim bunu tekrar başlatmayacak.`,"startup.riskDetailCustomLocal":`Codex özel bir yerel ağ geçidine işaret ediyor. opencodex bu ağ geçidinin yeniden başlatma yaşam döngüsünü yönetemez veya doğrulayamaz.`,"startup.riskDetailWindowsShim":`Başlatıcı shim desteklenen CLI betiklerini korur, ancak Codex Desktop ve doğrudan codex.exe başlatmaları Windows'ta bunu atlayabilir.`,"startup.safeDetail":"Mevcut yönlendirme ve başlatma mekanizması tutarlıdır. Yeniden başlatmanın ardından manuel `ocx start` komutuna gerek yoktur.","startup.routing":`Codex yönlendirmesi`,"startup.routing.proxy":`Yerel proxy`,"startup.routing.native":`Yerel OpenAI`,"startup.routing.customLocal":`Özel yerel ağ geçidi`,"startup.routing.customRemote":`Özel uzak ağ geçidi`,"startup.routing.unknown":`Bilinmeyen veya geçersiz yönlendirme`,"startup.restartProtection":`Yeniden başlatma koruması`,"startup.preference":`İsteğe bağlı başlatma`,"startup.enabled":`Etkin`,"startup.disabled":`Devre dışı`,"startup.protection.service":`Arka plan servisi`,"startup.protection.shim":`Başlatıcı shim`,"startup.protection.none":`Yüklü değil`,"startup.details":`Koruma detayları`,"startup.service":`Arka plan servisi`,"startup.serviceHint":`Oturum açmada başlar ve çökmenin ardından proxy'yi yeniden başlatır.`,"startup.installed":`Yüklü`,"startup.notInstalled":`Yüklü değil`,"startup.unsupported":`Desteklenmiyor`,"startup.shim":`Codex başlatıcı shim`,"startup.shimHint":"Desteklenen bir Codex betik başlatıcısı başladığında `ocx ensure` çalıştırır.","startup.healthy":`Sağlıklı`,"startup.cliOnly":`Yalnızca CLI`,"startup.stale":`Eski`,"startup.viable":`Hazır`,"startup.unhealthy":`Yüklü ama sağlıksız`,"startup.conflict":`Servis çakışması`,"startup.installedDisabled":`Yüklü ama devre dışı`,"startup.install":`Yükle`,"startup.installing":`Yükleniyor…`,"startup.repair":`Onar`,"startup.repairing":`Onarılıyor…`,"startup.serviceInstalled":`Arka plan servisi başarıyla yüklendi.`,"startup.serviceRepaired":`Arka plan servisi başarıyla onarıldı.`,"startup.shimInstalled":`Codex başlatıcı shim başarıyla yüklendi.`,"startup.shimRepaired":`Codex başlatıcı shim başarıyla onarıldı.`,"startup.installFailed":`Yükleme başarısız oldu:`,"startup.tray.title":`Windows sistem tepsisi`,"startup.tray.hint":`Tek tıkla proxy başlatma, durdurma, yeniden başlatma, panel ve durum kontrolleri için oturum tepsisi simgesi yükleyin.`,"startup.tray.login":`Windows oturum açılışında tepsiyi başlat`,"startup.tray.notProtection":`Tepsi bir denetleyicidir, yeniden başlatma koruması değildir. İnsansız proxy kurtarma için hâlâ geçerli bir arka plan servisi gereklidir.`,"startup.tray.running":`Çalışıyor`,"startup.tray.stopped":`Yüklü, gizli`,"startup.tray.stale":`Onarım gerekiyor`,"startup.tray.notInstalled":`Yüklü değil`,"startup.tray.loading":`Kontrol ediliyor…`,"startup.tray.unavailable":`Durum kullanılamıyor`,"startup.tray.install":`Yükle ve tepsiyi göster`,"startup.tray.start":`Tepsi simgesini göster`,"startup.tray.stop":`Tepsi simgesinden çık`,"startup.tray.uninstall":`Oturum tepsisini kaldır`,"startup.tray.error":"Windows tepsi eylemi başarısız oldu. Detaylar için `ocx tray status` kontrol edin.","startup.recovery":`Onarım seçenekleri`,"startup.recoveryHint":`Yukarıdaki tek tıkla yükleyicileri kullanın veya manuel onarım için komutu kopyalayın. Codex Desktop ve Windows yürütülebilir dosyaları için arka plan servisi önerilir.`,"startup.command.service":`Önerilen: kalıcı arka plan servisi`,"startup.command.shim":`Alternatif: CLI başlatıcı shim`,"startup.command.native":`Güvenli mod: yerel Codex yönlendirmesini geri yükle`,"startup.copy":`Kopyala`,"startup.copied":`Kopyalandı`,"startup.recommended":`Önerilen onarım: {cmd}`,"startup.navRisk":`Başlatma koruması dikkat gerektiriyor`,"startup.codexRuntime.clampHidden":`OpenCodex, Codex {version} kullandığı için bazı akıl yürütme çabası seçenekleri gizlendi.`,"startup.codexRuntime.clampHiddenWithEfforts":`OpenCodex, Codex {version} kullandığı için bazı akıl yürütme çabası seçenekleri gizlendi (kaldırılanlar: {efforts}).`,"startup.codexRuntime.olderBinary":`OpenCodex eski bir Codex ikili dosyası ({version}) kullanıyor. Daha yeni bir kurulum mevcut.`,"dash.subtitle":`Yerel opencodex proxy'sinin, sağlayıcılarının ve Codex'e yönlendirilen modellerin canlı durumu.`,"dash.workspace.overview":`Genel Bakış`,"dash.workspace.sections":`Bölümler`,"dash.status":`Durum`,"dash.online":`Çevrimiçi`,"dash.offline":`Çevrimdışı`,"dash.version":`Sürüm`,"dash.uptime":`Çalışma Süresi`,"dash.providers":`Sağlayıcılar`,"dash.tokens30d":`Jetonlar (30 gün)`,"dash.coverage":`%{pct} kapsam`,"dash.mem.title":`Bellek izlenebilirliği`,"dash.mem.hint":`Salt okunur çalışma zamanı tanılamaları. Gözlemlenen bellek max(RSS, harici, ArrayBuffers) değeridir.`,"dash.mem.rss":`Yerleşik küme (RSS)`,"dash.mem.jsHeap":`Kullanımdaki JS yığını`,"dash.mem.jsHeapArena":`arena {total}`,"dash.mem.pressure":`Uyarı eşiğine göre`,"dash.mem.pressureOf":`Eşiğin %{pct}'si`,"dash.mem.pressureUnknown":`Bildirilen eşik yok`,"dash.mem.jscHeap":`JSC yığını`,"dash.mem.external":`Harici`,"dash.mem.arrayBuffers":`ArrayBuffers`,"dash.mem.observed":`Gözlemlenen`,"dash.mem.runtime":`Çalışma zamanı sayaçları`,"dash.mem.growth":`Saatlik gözlemlenen kayma`,"dash.mem.perHour":`/saat`,"dash.mem.store":`Devamlılık deposu`,"dash.mem.storeHint":`Proxy previous_response_id önbelleği.`,"dash.mem.storeEntries":`Girdiler`,"dash.mem.storeTotal":`Toplam`,"dash.mem.storeLargest":`En büyük`,"dash.mem.storeOldest":`En eski`,"dash.mem.threshold":`Uyarı eşiği`,"dash.mem.lastWarn":`Son uyarı`,"dash.mem.never":`Hiçbir zaman`,"dash.mem.details":`Detaylar`,"dash.mem.unavailable":`Bellek tanılaması kullanılamıyor (eski proxy).`,"dash.mem.inFlight":`İşlemdeki istekler`,"dash.mem.restart":`Boşalt & yeniden başlat`,"dash.mem.restartConfirm":`{count} işlemdeki isteğin tamamlanmasını bekleyin, ardından yeniden başlatın ({seconds} saniyeye kadar).`,"dash.mem.draining":`{count} istek boşaltılıyor… tamamlandığında yeniden başlatılacak`,"dash.mem.reconnecting":`Proxy yeniden başlatılıyor… yeniden bağlanması bekleniyor`,"dash.mem.restartFailed":`Boşaltma ve yeniden başlatma başarısız oldu. Proxy'nin çalıştığını kontrol edin.`,"dash.mem.restartNoSupervisor":`Yeniden başlatma koruması algılanmadı.`,"dash.activeProviders":`Aktif sağlayıcılar`,"dash.noProviders":`Yapılandırılmış sağlayıcı yok. {cmd} komutunu çalıştırın.`,"dash.col.name":`İsim`,"dash.col.adapter":`Adaptör`,"dash.col.baseUrl":`Taban URL`,"dash.col.model":`Model`,"dash.modelsNoResults":`Aramanızla eşleşen model bulunamadı.`,"dash.availableModels":`Kullanılabilir modeller`,"dash.noModels":`Model bulunamadı. Sağlayıcı API anahtarlarını kontrol edin.`,"dash.cannotConnect":`Proxy'ye bağlanılamıyor. Çalışıyor mu?`,"dash.runStart":`Proxy'yi başlatmak için {cmd} çalıştırın.`,"dash.stop":`Proxy'yi Durdur`,"dash.stopConfirm":`Proxy durdurulsun ve yerel Codex geri yüklensin mi?`,"dash.stopFailed":`Proxy durdurulamadı (HTTP {status}).`,"dash.maSwitchFailed":`Mod değiştirme başarısız oldu (HTTP {status}).`,"dash.maNetworkError":`Ağ hatası — proxy çalışıyor mu?`,"dash.stopping":`Durduruluyor…`,"dash.actions":`Proxy`,"dash.codexRestart":`Codex model listesini yenile`,"dash.codexRestarting":`Durduruluyor…`,"dash.codexRestartConfirm":`Model listesini yeniden okumaları için Codex app-server'ları durdurulsun mu? Süren bir Codex işlemi kesilir ve Codex kendiliğinden yeniden başlamaz — sonrasında yeniden açın.`,"dash.codexRestartDone":`{count} Codex app-server durduruldu. Güncel model listesi için Codex'i yeniden açın.`,"dash.codexRestartNothing":`Çalışan Codex app-server yok. Sonraki açılışta güncel model listesi okunur.`,"dash.codexRestartUnknown":`Süreçler listelenemedi, bu yüzden hiçbir şey durdurulmadı.`,"dash.codexRestartPartial":`{count} app-server kapanmadı. Model listesi eski kalırsa bunları elle durdurun.`,"dash.codexRestartFailed":`Codex model listesi yenilenemedi (HTTP {status}).`,"dash.codexRestartUnreachable":`Proxy'ye ulaşılamadı.`,"dash.codexRestartMalformed":`Proxy beklenmeyen bir yanıt döndürdü.`,"dash.codexRestartTimeout":`Proxy zamanında yanıt vermedi. App-server'ları durdurmaya devam ediyor olabilir.`,"models.staleBanner":`Codex, bu katalogdan daha eski bir model listesi gösteriyor. Yeniden okumak için Codex'i yeniden başlatın.`,"dash.codexAutoStart":`opencodex'i Codex ile başlat`,"dash.codexAutoStartHint":`Yüklü bir shim'in ocx ensure çalıştırmasına izin verir. Arka plan servisi veya yeniden başlatma koruması kurmaz; sistem durumu için Başlatma Güvenliği'ne bakın.`,"dash.searchModel":`Arama yan araç modeli`,"dash.searchModelHint":`OpenAI dışı yönlendirilen modellerde web_search için kullanılan model. ChatGPT girişi gerektirir.`,"dash.searchReasoning":`Arama akıl yürütme çabası`,"dash.visionModel":`Görsel yan araç modeli`,"dash.visionModelHint":`Salt metin yönlendirilen modeller için görselleri tanımlamakta kullanılan model. ChatGPT girişi gerektirir.`,"dash.webSearchSidecar":`Web arama yan aracı (sidecar)`,"dash.webSearchSidecarHint":`Yönlendirilen modellerde web araması için kullanılan arka ucu ve modeli seçin.`,"dash.webSearchStream":`Yanıtları canlı akıt`,"dash.webSearchStreamHint":`Model bir araç çağrısına karar verene kadar baştaki metni ve akıl yürütmeyi canlı akıtır; kalanı arama yakalama için arabelleğe alınır. Aramadan önce yazılan metin kısmen tekrarlanabilir.`,"dash.visionSidecar":`Görsel yan aracı (sidecar)`,"dash.visionSidecarHint":`Salt metin modeller için görselleri tanımlamakta kullanılan arka ucu ve modeli seçin.`,"dash.visionOff":`Kapalı`,"dash.shadowCallIntercept":`Gölge Çağrı Yakalama`,"dash.shadowCallInterceptHint":`Codex App'in arka plan yardımcı çağrılarını ({models}) başlık oluşturma ve commit mesajları için yakalar ve seçtiğiniz modele yönlendirir.`,"dash.shadowCallWarning":`⚠ Etkinleştirildiğinde, {models} için olan TÜM istekler seçilen modelle değiştirilecektir.`,"dash.shadowCallOriginal":`Orijinal`,"dash.shadowCallModel":`Yedek model`,"dash.shadowCallTooltip":`Codex App arka planda başlık ve commit mesajı oluşturmak için yardımcı çağrılar yapar (orijinal {models}). Etkinleştirerek bunları seçtiğiniz modele yönlendirebilirsiniz.`,"models.shadowCallIntercept":`Gölge Çağrı Yakalama`,"models.shadowCallInterceptHint":`Codex App'in başlıklar ve commit mesajları için yaptığı arka plan çağrılarını ({models}) yakalar ve seçtiğiniz modele yönlendirir.`,"dash.sidecarBackend":`Arka uç`,"dash.sidecarModel":`Model`,"dash.backendAuto":`Otomatik`,"dash.backendOpenAI":`OpenAI`,"dash.backendAnthropic":`Anthropic`,"dash.sidecarSaved":`Yan araç ayarları kaydedildi. Sonraki istekte uygulanacak.`,"dash.sidecarSaveFailed":`Yan araç ayarları kaydedilemedi.`,"dash.injectionLabel":`Alt ajan devri`,"dash.injectionHint":`Codex'in alt ajan işlerini devredeceği modeli seçin.`,"dash.injectionManage":`Ayarları aç`,"dash.syncCodexSubagentDefaults":`Ayrıca Codex varsayılanı olarak kaydet`,"dash.syncCodexSubagentDefaultsHint":`Açık olduğunda, yukarıdaki seçim Codex'in kendi yapılandırmasına yazılır.`,"dash.multiAgentGuidance":`Codex'e işi nasıl böleceğini söyle`,"dash.multiAgentGuidanceHint":`Codex'e işleri alt ajanlara nasıl devredeceğini söyleyen kısa bir not gönderir.`,"dash.injectionNone":`Yok`,"dash.injectionEffortLabel":`Akıl yürütme çabası`,"dash.injectionEffortNone":`Model varsayılanı`,"dash.effortCapLabel":`V2 ultra çaba limiti`,"dash.subagentEffortCapLabel":`V2 alt ajan çaba limiti`,"dash.effortCapHelp":`V2 ultra modu turları için akıl yürütme çabasını sınırlar. Ayarlandığında, gelen maksimum çaba istekleri (ultra modundan) seçilen seviye ile sınırlandırılır. Alt ajan limiti yalnızca türetilen çocuk ajanları etkiler. Limitler çabayı yalnızca düşürür, asla yükseltmez. Bir model sınırlandırılan seviyeyi desteklemiyorsa, desteklenen en yakın alt seviyeye iner.`,"dash.effortCapNone":`Limit yok`,"dash.maintenance":`Bakım`,"dash.maintenanceHint":`Codex'in model kataloğunu yenileyin veya daha yeni bir opencodex sürümü yükleyin.`,"dash.syncModels":`Modelleri senkronize et`,"dash.syncModelsHint":`Bağladığınız sağlayıcılardan Codex'in model kataloğunu yeniden yazın.`,"dash.syncRun":`Şimdi senkronize et`,"dash.syncing":`Senkronize ediliyor…`,"dash.syncOk":`Senkronizasyon tamamlandı. {count} model eklendi.`,"dash.syncStaleHint":`Codex hâlâ eski bir liste gösteriyorsa uygulama sunucusunu yeniden başlatın ({cmd}).`,"dash.syncFailed":`Senkronizasyon başarısız oldu: {error}`,"dash.projectConfigTitle":`Proje Codex konfigürasyonu OpenCodex'i atlıyor`,"dash.projectConfigHint":`Bu depoya özel ayarlar OpenCodex proxy'sini geçersiz kılar.`,"dash.checkUpdate":`Güncellemeyi kontrol et`,"dash.updateTitle":`opencodex'i güncelle`,"dash.updateDesc":`Seçilen kanal için npm'i kontrol edin.`,"dash.updateChannel":`Kanal`,"dash.updateChecking":`Güncellemeler kontrol ediliyor…`,"dash.updateInstalled":`Yüklü`,"dash.updateLatest":`En son`,"dash.updateAvailable":`Güncelleme mevcut`,"dash.updateCurrent":`Güncel`,"dash.updateCommand":`Komut`,"dash.updateSource":`Bu bir kaynak kod kopyasıdır. Terminalden güncelleyin.`,"dash.updateUnavailable":`npm'den en son sürüm okunamadı.`,"dash.updateRetry":`Tekrar dene`,"dash.updateRecheck":`Yeniden kontrol et`,"dash.updateCannotAuto":`Tek tıkla güncelleme kullanılamıyor ({reason}).`,"dash.updateReason.source_checkout":`kaynak kod kopyası`,"dash.updateReason.latest_unavailable":`npm sunucusuna ulaşılamıyor`,"dash.updateReason.already_latest":`zaten en son sürümde`,"dash.updateReason.unknown":`güncelleme kullanılamıyor`,"dash.updateRestart":`Güncellemeden sonra yeniden başlat`,"dash.updateRestartHint":`Önerilir. Proxy yeniden başlayana kadar mevcut GUI eski kodu çalıştırmaya devam eder.`,"dash.runUpdate":`Güncelle`,"dash.updateReconnecting":`Yeniden başlatılan proxy bekleniyor…`,"dash.updateStatus.running":`opencodex güncelleniyor.`,"dash.updateStatus.restarting":`Güncelleme yüklendi. Proxy yeniden başlatılıyor.`,"dash.updateStatus.succeeded":`Güncelleme tamamlandı.`,"dash.updateVersionTransition":`{currentVersion} -> {latestVersion}.`,"dash.updateStatus.failed":`Güncelleme başarısız oldu.`,"prov.subtitle":`opencodex'in Codex'e yönlendirdiği sağlayıcıları yapılandırın.`,"prov.add":`Sağlayıcı Ekle`,"prov.editJson":`JSON Düzenle`,"prov.accountLogin":`Hesap girişi`,"prov.noOauth":`Kullanılabilir OAuth sağlayıcısı yok.`,"prov.loggedIn":`giriş yapıldı`,"prov.notLoggedIn":`giriş yapılmadı`,"prov.logout":`Çıkış Yap`,"prov.login":`Giriş Yap`,"prov.loginWith":`{provider} ile Giriş Yap`,"prov.waitingBrowser":`Tarayıcı bekleniyor…`,"prov.didntOpen":`Açılmadı mı? Buraya tıklayın`,"prov.copyLink":`Bağlantıyı kopyala`,"prov.linkCopied":`Kopyalandı`,"prov.linkCopyUnavailable":`Pano kullanılamıyor`,"prov.deviceCode":`Cihaz kodu`,"prov.copyCode":`Kodu kopyala`,"prov.codeCopied":`Kod kopyalandı`,"prov.editAlias":`Takma adı düzenle`,"prov.aliasPrompt":`Görüntülenen ad (temizlemek için boş bırakın)`,"prov.aliasSaved":`Takma ad kaydedildi`,"prov.aliasSaveFailed":`Takma ad kaydedilemedi`,"prov.accountId":`ID`,"prov.pasteRedirect":`Yönlendirme URL'sini veya kodu yapıştırın`,"prov.pasteRedirectHint":`Tarayıcı localhost hatası gösterirse adres çubuğundaki URL'yi kopyalayıp buraya yapıştırın.`,"prov.pasteSubmit":`Gönder`,"prov.pasteSubmitting":`Gönderiliyor…`,"prov.pasteOk":`Kod gönderildi — giriş tamamlanıyor…`,"prov.pasteFail":`Kod gönderilemedi: {error}`,"prov.port":`Port`,"prov.default":`Varsayılan`,"prov.loadingConfig":`Yükleniyor…`,"prov.saved":`Kaydedildi! Uygulamak için proxy'yi yeniden başlatın.`,"prov.loadConfigFail":`Konfigürasyon yüklenemedi`,"prov.invalidJson":`Geçersiz JSON`,"prov.saveFailed":`Kaydetme başarısız`,"prov.loginFailStart":`{provider} girişi başlatılamadı`,"prov.loginError":`{provider} giriş hatası: {error}`,"prov.loginRequestFail":`{provider} giriş isteği başarısız oldu`,"prov.loginCancelled":`{provider} girişi iptal edildi`,"prov.loginTimeout":`{provider} girişi zaman aşımına uğradı.`,"prov.loginSameAccount":`Hâlâ aynı {provider} hesabı — tarayıcıda hesap değiştirin, ardından tekrar Hesap Ekle'yi deneyin.`,"prov.loginOk":`{provider} hesabına giriş yapıldı. Modellerini listelemek için {cmd} çalıştırın (veya canlı olarak uygulanır).`,"prov.added":`"{name}" eklendi. Modellerini listelemek için {cmd} çalıştırın (veya canlı olarak uygulanır).`,"oauthTos.highTitle":`{provider}: abonelik OAuth riski`,"oauthTos.elevatedTitle":`{provider}: gayri resmi OAuth köprüsü`,"oauthTos.anthropicBody":`Claude abonelik OAuth jetonlarının OpenCodex gibi üçüncü taraf bir proxy üzerinden doğrudan yeniden kullanılması desteklenen bir Anthropic entegrasyonu değildir ve erişim kısıtlamalarına yol açabilir. Claude aboneliklerini kullanan desteklenen Agent SDK entegrasyonları ayrıdır.`,"oauthTos.highBody":`OpenCodex, {provider} bağlantısını üçüncü taraf bir OAuth yolu üzerinden kurar. Desteklenmeyen kullanım, erişim kısıtlamalarına veya hesabın askıya alınmasına yol açabilir.`,"oauthTos.elevatedBody":`OpenCodex, {provider} bağlantısını resmi olmayan bir OAuth yolu üzerinden kurar. Mümkün olduğunda resmi istemciyi kullanın; sıra dışı veya otomatik trafik kötüye kullanım olarak değerlendirilebilir ve erişim kısıtlanabilir veya askıya alınabilir.`,"oauthTos.saferPath":`Daha güvenli seçenek: OpenCodex'te bir API anahtarı yapılandırın.`,"oauthTos.acknowledge":`Riski anlıyorum ve OAuth ile devam etmek istiyorum.`,"oauthTos.continue":`OAuth ile devam et`,"prov.logoutOk":`{provider} çıkışı yapıldı.`,"prov.logoutFail":`{provider} çıkışı yapılamadı.`,"prov.removed":`"{name}" kaldırıldı.`,"prov.removedDefault":`"{name}" kaldırıldı. Varsayılan sağlayıcı artık "{defaultProvider}".`,"prov.removeFail":`"{name}" kaldırılamadı.`,"prov.removeLastProvider":`Başka etkin sağlayıcı yokken bu sağlayıcıyı kaldıramazsınız.`,"prov.removeHasDependentCombos":`Önce bağımlı komboları kaldırın veya güncelleyin: {combos}.`,"prov.setDefault":`Varsayılan olarak ayarla`,"prov.setDefaultSuccess":`"{name}" artık varsayılan sağlayıcı.`,"prov.setDefaultFail":`"{name}" varsayılan yapılamadı.`,"prov.defaultDisabled":`Varsayılan yapmadan önce bu sağlayıcıyı etkinleştirin.`,"prov.updateFail":`Sağlayıcı güncellenemedi.`,"prov.networkError":`Ağ hatası. Proxy'nin çalıştığını kontrol edin.`,"prov.removeConfirm":`"{name}" sağlayıcısı kaldırılsın mı?`,"prov.hasApiKey":`API anahtarı yapılandırıldı`,"prov.hasHeaders":`özel başlıklar yapılandırıldı`,"prov.accounts":`Hesaplar ({n})`,"prov.accountsAria":`{name} hesaplarını aç/kapat`,"prov.accountActive":`Aktif`,"prov.accountReauth":`Tekrar giriş yap`,"prov.reauthenticate":`Yeniden doğrula`,"prov.reauthAccountMissing":`Seçilen hesap bulunamadı`,"prov.reauthIdentityMismatch":`Giriş yapılan hesap seçilen hesapla eşleşmedi`,"prov.accountAdd":`Hesap ekle`,"prov.accountNoLabel":`hesap {id}`,"prov.accountSwitchTitle":`Bu hesabı kullan`,"prov.accountSwitched":`{email} hesabına geçildi.`,"prov.accountSwitchFail":`Hesap değiştirilemedi`,"prov.accountRemoved":`{email} kaldırıldı.`,"prov.accountRemoveFail":`{email} kaldırılamadı.`,"prov.accountRemoveAria":`{email} hesabını kaldır`,"prov.accountRemoveConfirm":`{email} hesabı kaldırılsın mı?`,"prov.keyAdd":`API anahtarı ekle`,"prov.keyAdded":`{name} için API anahtarı eklendi.`,"prov.keyAddFail":`API anahtarı eklenemedi`,"prov.keyPlaceholder":`API anahtarını yapıştırın`,"prov.keySwitchTitle":`Bu anahtarı kullan`,"prov.keySwitched":`{key} anahtarına geçildi.`,"prov.keySwitchFail":`Anahtar değiştirilemedi`,"prov.keyRemoved":`{key} anahtarı kaldırıldı.`,"prov.keyRemoveAria":`{key} anahtarını kaldır`,"prov.keyRemoveConfirm":`{key} API anahtarı silinsin mi?`,"prov.activeBadge":`Aktif`,"prov.disabledBadge":`Devre Dışı`,"prov.defaultBadge":`Varsayılan`,"prov.enable":`Etkinleştir`,"prov.disable":`Devre Dışı Bırak`,"prov.enabled":`"{name}" etkinleştirildi.`,"prov.disabled":`"{name}" devre dışı bırakıldı.`,"prov.enableFail":`"{name}" etkinleştirilemedi.`,"prov.disableFail":`"{name}" devre dışı bırakılamadı.`,"prov.enableAria":`{name} sağlayıcısını etkinleştir`,"prov.disableAria":`{name} sağlayıcısını devre dışı bırak`,"prov.defaultCannotDisable":`Varsayılan sağlayıcı devre dışı bırakılamaz`,"prov.openaiAccountMode":`Codex hesap modu`,"prov.openaiModePool":`Havuz (Pool)`,"prov.openaiModeDirect":`Doğrudan (Direct)`,"prov.openaiPoolDesc":`Varsayılan. Ana girişi ve eklenen hesapları havuzda döndürür.`,"prov.openaiDirectDesc":`Yalnızca ana Codex girişini kullanır.`,"prov.openaiModeSaved":`OpenAI hesap modu {mode} olarak değiştirildi.`,"prov.openaiModeSaveFailed":`OpenAI hesap modu değiştirilemedi.`,"prov.openaiApiDesc":`OpenAI API anahtarı kullanır.`,"prov.manageCodexAccounts":`Codex hesaplarını yönet`,"prov.openaiApiMissing":`API anahtarı gerekli`,"prov.openaiApiSetup":`API anahtarı ayarla`,"models.tab.catalog":`Modeller`,"models.tab.combos":`Kombolar`,"models.tab.compatibility":`Uyumluluk`,"models.tab.routing":`Yönlendirme (beta)`,"models.tabsLabel":`Model yüzeyleri`,"models.subtitle.combos":`Tek bir kimlik olarak yanıt veren sıralı model grupları.`,"models.subtitle.compatibility":`Lab projeksiyon kanıtından salt okunur uyumluluk matrisi.`,"models.subtitle.routing":`Politika profilleri ve simülasyon değerlendirmesi.`,"models.subtitle":`Codex'in göreceği modelleri açıp kapatın.`,"models.nativeGroupLabel":`Yerel OpenAI`,"models.nativeHint":`Doğrudan geçiş modelleri Sağlayıcılar bölümünde seçilen Havuz veya Doğrudan seçeneğini kullanır.`,"models.active":`{active}/{total} görünür`,"models.workspace.providers":`Sağlayıcılar`,"models.workspace.allProviders":`Tüm sağlayıcılar`,"models.workspace.mainAria":`Model detayları`,"models.allOn":`Tümünü aç`,"models.allOff":`Tümünü kapat`,"models.cap350k":`350k Sınırı`,"models.capApplied":`Bağlam sınırı uygulandı.`,"models.capSaveFailed":`Bağlam sınırı kaydedilemedi`,"models.contextCapped":`350k sınırı`,"models.contextCapLabel":`Bağlam sınırı`,"models.v2Label":`Alt Ajan`,"models.shadowCallOriginal":`⚠ {models} →`,"models.v2DocsLink":`v1 / v2 nedir?`,"models.v2Mode_v1":`v1`,"models.v2Mode_default":`taban`,"models.v2Mode_v2":`v2`,"models.v2ModeDesc_v1":`Tüm modeller → v1 yüzeyi`,"models.v2ModeDesc_default":`Yukarı akış varsayılanları`,"models.v2ModeDesc_v2":`Tüm modeller → v2 yüzeyi`,"models.v2Help":`v1 alt ajanları birincil modelle sınırlandırır; base standart ajan sınırlarını devralır; v2 tam çoklu ajan orkestrasyonunu etkinleştirir.`,"dash.multiAgent":`Alt Ajan`,"models.v2Conflict":`[agents] max_threads ayarlanmış — config.toml dosyasından kaldırın`,"models.v2Applied":`Çoklu ajan modu güncellendi. Yeni oturumlar bu modu kullanacaktır; model seçiciyi yenilemek için Codex uygulamasını yeniden başlatın.`,"models.v2ThreadsLabel":`Maksimum iş parçacığı`,"models.v2ThreadsDefault":`varsayılan (4)`,"models.v2ThreadsApplied":`İş parçacığı limiti güncellendi`,"models.v2ThreadsInvalid":`İş parçacığı limiti >= 1 tamsayı olmalıdır`,"models.v2ThreadsApply":`Uygula`,"models.capValue":`Sınır {value}`,"models.contextSettings":`Bağlam pencereleri`,"models.contextSettingsTitle":`Bağlam pencereleri — {provider}`,"models.contextDefault":`Sağlayıcı varsayılanı`,"models.contextModel":`Model`,"models.contextModelOverride":`Model geçersiz kılma`,"models.contextHint":`Yukarı akış meta verileri eksik olduğunda kullanılır.`,"models.contextAutomatic":`Otomatik keşif`,"models.contextSaved":`Bağlam pencereleri güncellendi.`,"models.contextUnchanged":`Kaydedilecek bağlam penceresi değişikliği yok.`,"models.contextSaveFailed":`Bağlam pencereleri kaydedilemedi`,"models.contextInvalid":`Bağlam pencereleri pozitif tam sayılar olmalıdır`,"models.contextCappedValue":`{value} sınırı`,"models.setAll":`Tümünü ayarla`,"models.setAllHint":`{value} bağlam sınırını her yönlendirilen sağlayıcıya uygulayın.`,"models.collapseAll":`Tümünü daralt`,"models.expandAll":`Tümünü genişlet`,"models.orderHint":`Seçici sırası: Alt ajan seçimleri → kalan modeller.`,"models.custom":`Özel…`,"models.customApply":`Uygula`,"models.customPlaceholder":`Jetonlar (örn. 420000)`,"models.customAdd":`Özel model ekle`,"models.customAddTitle":`Özel model ekle — {provider}`,"models.customEditTitle":`Özel modeli düzenle — {provider}`,"models.customAdded":`Özel model eklendi`,"models.customUpdated":`Özel model güncellendi`,"models.customDeleted":`Özel model silindi`,"models.customSaveFailed":`Özel model kaydedilemedi`,"models.customSaving":`Kaydediliyor…`,"models.customAddBtn":`Ekle`,"models.customEditBtn":`Güncelle`,"models.customEdit":`Düzenle`,"models.customDelete":`Sil`,"models.customDeleteConfirm":`{name} modeli silinsin mi?`,"models.customBadge":`Özel`,"models.customSummary":`{count} özel`,"models.customFieldModelId":`Model ID`,"models.customFieldModelIdPlaceholder":`örn. qwen4-max-preview`,"models.customFieldDisplayName":`Görüntülenen ad (isteğe bağlı)`,"models.customFieldDisplayNamePlaceholder":`örn. Qwen 4 Max Preview`,"models.customFieldContext":`Bağlam penceresi`,"models.customFieldModalities":`Girdi türleri`,"models.customFieldReasoning":`Akıl yürütme çabası`,"models.customFieldReasoningOverride":`Akıl yürütme çabasını geçersiz kıl`,"models.reasoningEffort.none":`Yok`,"models.reasoningEffort.minimal":`Minimal`,"models.reasoningEffort.low":`Düşük`,"models.reasoningEffort.medium":`Orta`,"models.reasoningEffort.high":`Yüksek`,"models.reasoningEffort.xhigh":`Çok yüksek`,"models.reasoningEffort.max":`Maksimum`,"models.tipProvider":`Sağlayıcı`,"models.tipContext":`Bağlam`,"models.tipModalities":`Girdi Türleri`,"models.tipStatus":`Durum`,"models.tipActive":`Aktif`,"models.tipDisabled":`Devre Dışı`,"models.applied":`Uygulandı.`,"models.saveFailed":`Kaydetme başarısız`,"models.networkError":`Ağ hatası — proxy çalışıyor mu?`,"models.loadFail":`Modeller yüklenemedi — proxy çalışıyor mu?`,"models.noRouted":`Yönlendirilen model yok`,"models.noRoutedHint":`Önce bir sağlayıcıya giriş yapın veya ekleyin.`,"models.emptyDiscovery":`Keşfedilen model yok.`,"models.emptyDiscoveryDisabled":`Canlı model keşfi kapalı.`,"models.discoveryFailedBadge":`Keşif başarısız`,"models.discoveryFailedHttp":`Model keşfi başarısız oldu (HTTP {status}).`,"models.discoveryFailedBlocked":`Model keşfi engellendi.`,"models.discoveryFailedInvalidResponse":`Model keşfi geçersiz bir yanıt döndürdü.`,"models.discoveryFailedNetwork":`Model keşfi ağ hatası nedeniyle başarısız oldu.`,"models.discoveryFailedProvider":`Sağlayıcı bir model keşfi hatası bildirdi.`,"models.discoveryFailedGeneric":`Model keşfi başarısız oldu.`,"models.openProviderSettings":`Sağlayıcı ayarlarını aç`,"models.loading":`Yükleniyor…`,"models.search":`Modellerde ara…`,"models.showMore":`{n} tane daha göster`,"models.allowlistLabel":`Sadece seçilenler`,"models.allowlistHint":`Sadece işaretli modeller kataloğa gönderilir.`,"models.selectedCount":`{n} seçildi`,"sub.subtitle":`Codex'in {cmd} komutu, geçersiz kılma olarak yalnızca ilk 5 modeli (önceliğe göre) sunar. Buradan 5 taneye kadar seçin (yerel gpt veya yönlendirilen) ve opencodex bunların katalog önceliğini tam olarak bunların liderlik edeceği şekilde ayarlar. Diğer herhangi bir model tam adıyla çağrılabilir kalır; bu yalnızca neyin gösterileceğini kontrol eder.`,"sub.featured":`Öne Çıkarılanlar`,"sub.orderHint":`Burada gösterilen sıralama, Codex model seçicisinin üst kısmındaki 1-5 pozisyonlarını ve {cmd} için varsayılan model adaylarını belirler.`,"sub.noneSelected":`Hiçbiri seçilmedi — aşağıdaki listeden seçin.`,"sub.models":`Modeller`,"sub.search":`Modellerde ara…`,"sub.settings":`Ayarlar`,"sub.sections":`Alt ajan bölümleri`,"sub.delegation.model":`İlk çağrılacak model`,"sub.delegation.modelHint":`Codex'in iş devrederken ilk ulaştığı model.`,"sub.noModels":`Model yok — önce bir sağlayıcı ekleyin.`,"sub.saved":`{n} model kaydedildi. Bunları spawn_agent geçersiz kılmaları olarak görmek için yeni bir Codex oturumu başlatın (veya {cmd} çalıştırın).`,"sub.saveFailed":`Kaydetme başarısız`,"sub.networkError":`Ağ hatası — proxy çalışıyor mu?`,"sub.loadFail":`Modeller yüklenemedi`,"sub.loading":`Yükleniyor…`,"sub.moveUp":`{m} modelini yukarı taşı`,"sub.moveDown":`{m} modelini aşağı taşı`,"sub.removeAria":`{m} modelini kaldır`,"sub.workspace.addToFeatured":`{m} modelini öne çıkarılanlara ekle`,"sub.workspace.allModels":`Tüm modeller`,"sub.workspace.featuredFull":`Öne çıkarılanlar listesi dolu (maksimum 5)`,"sub.workspace.mainAria":`Alt ajan model detayları`,"sub.workspace.notFeatured":`Öne çıkarılmadı`,"sub.workspace.priority":`Öncelik`,"sub.workspace.removeFromFeatured":`{m} modelini öne çıkarılanlardan kaldır`,"sub.workspace.selectModel":`Bir model seçin`,"sub.workspace.selectModelDesc":`Detayları görmek için listeden bir model seçin.`,"sub.workspace.selector":`Genel seçici`,"sub.ultraMode":`Ultra modu`,"sub.ultraModeHint":`Tüm modeller ve reasoning effort için Proactive çoklu ajan delegasyon politikasını etkinleştirir (reasoning effort değerini değiştirmez). config.toml dosyasına features.multi_agent_v2.multi_agent_mode_hint_text yazar.`,"sub.ultraModeV2Required":`v2 çoklu ajan yüzeyi gerekir — önce multi_agent_v2'yi etkinleştirin ve alt ajan modu denetiminde v2'yi seçin.`,"sub.ultraModeText":`Ultra modu delegasyon metni`,"sub.ultraModePreset":`Ön ayarı geri yükle`,"sub.ultraModeLoadFail":`Ultra modu ayarları yüklenemedi — proxy çalışıyor mu?`,"sub.ultraModeSaveFail":`Ultra modu ayarları kaydedilemedi`,"sub.ultraModeSaved":`Ultra modu kaydedildi. Yeni Codex oturumlarına uygulanır.`,"logs.title":`İstek Günlükleri`,"logs.tabLogs":`Günlükler`,"logs.tabDebug":`Hata Ayıklama`,"logs.subtitle":`Proxy üzerinden yönlendirilen son istekler.`,"logs.autoRefresh":`Otomatik yenile`,"logs.noRequests":`Henüz istek yok.`,"logs.loadError":`İstek günlükleri yüklenemedi.`,"logs.filter.surface.label":`Yüzey`,"logs.filter.surface.all":`Tümü`,"logs.filter.surface.claude":`Claude`,"logs.filter.surface.codex":`Codex`,"logs.filter.surface.grok":`Grok`,"logs.filter.conversation.label":`Sohbet`,"logs.filter.conversation.placeholder":`Sohbet ID'sini yapıştırın`,"logs.filter.conversation.clear":`Temizle`,"logs.filter.conversation.apply":`Günlükleri filtrele`,"logs.conversation.totals":`{requests} istek · {tokens} jeton · {cost}`,"logs.conversation.scope":`Toplamlar yalnızca yüklü günlükleri kapsar.`,"logs.conversation.excluded":`({unpriced} fiyatlandırılmamış, {unmetered} ölçülmemiş hariç)`,"logs.detail.conversation":`Sohbet`,"logs.badge.claude":`Claude`,"logs.badge.grok":`Grok`,"logs.col.time":`Zaman`,"logs.col.request":`İstek`,"logs.col.model":`Model`,"logs.col.effort":`Çaba`,"logs.col.provider":`Sağlayıcı`,"logs.col.status":`Durum`,"logs.col.tokens":`Jetonlar`,"logs.col.tokPerSec":`jeton/sn`,"logs.col.estimatedCost":`~$`,"logs.metric.tokPerSecTitle":`Çıktı jetonu / saniye`,"logs.metric.estimatedCostTitle":`Tahmini API liste fiyatı`,"usage.cost.total":`API liste fiyatı eşdeğeri`,"usage.cost.disclaimer":`Fatura makbuzu değildir.`,"usage.cost.unpricedNote":`{count} istek hariç tutuldu`,"logs.detail.section.basic":`Temel bilgiler`,"logs.detail.route.section":`Yönlendirme kararı`,"logs.detail.route.kind":`Yönlendirme türü`,"logs.detail.route.profile":`Profil`,"logs.detail.route.selected":`Seçilen`,"logs.detail.route.candidates":`Adaylar`,"logs.detail.route.unknown":`Kayıtlı yönlendirme izi yok.`,"logs.detail.section.performance":`Performans`,"logs.detail.section.cost":`Tahmini maliyet`,"logs.detail.section.attempts":`Kombo denemeleri`,"logs.detail.section.usage":`Ham kullanım`,"logs.detail.ttft":`TTFT`,"logs.detail.costTotal":`Liste fiyatı eşdeğeri`,"logs.detail.totalTokens":`Toplam jeton`,"logs.detail.matchedKey":`Eşleşen anahtar`,"logs.detail.priceSource":`Fiyat kaynağı`,"logs.detail.unavailableReason":`Kullanılamama nedeni`,"logs.detail.copyRequestId":`İstek ID kopyala`,"logs.detail.copied":`Kopyalandı`,"logs.detail.source.jawcode":`katalog`,"logs.detail.source.expected":`Beklenen fiyat`,"logs.detail.source.user":`Kullanıcı tarafından yapılandırılan sağlayıcı fiyat katmanı`,"logs.detail.verification.verified":`Doğrulandı`,"logs.detail.verification.derived":`Taban modelden türetildi`,"logs.detail.attempt.target":`Sağlayıcı / model`,"logs.detail.attempt.reason":`Sonuç / neden`,"logs.detail.attempt.completed":`Tamamlandı`,"logs.detail.attempt.e2eNote":`Süreç bilgisi`,"logs.detail.attempt.recovery.transient5xx":`Geçici 5xx`,"logs.detail.attempt.recovery.connectionReset":`Bağlantı sıfırlandı`,"logs.detail.attempt.recovery.oauth401":`OAuth yeniden doğrulaması`,"logs.detail.attempt.recovery.key429":`Anahtar oranı kısıtlandı (429)`,"logs.detail.attempt.recovery.rateLimit429":`Oran kısıtlandı (429)`,"logs.detail.attempt.recovery.anthropicOauth429":`Anthropic OAuth kısıtlandı (429)`,"logs.detail.attempt.recovery.image413":`Görsel boyutu çok büyük (413)`,"logs.detail.attempt.recovery.emptyCompletion":`Boş tamamlama yeniden denemesi`,"logs.detail.attempt.recovery.unknown":`Bilinmeyen kurtarma nedeni`,"logs.detail.reason.usage_missing":`Kullanım bildirilmedi.`,"logs.detail.reason.usage_unsupported":`Bu sağlayıcı kullanım bildirmeyebilir.`,"logs.detail.reason.output_missing":`Çıktı jeton sayısı bildirilmedi.`,"logs.detail.reason.invalid_duration":`İstek süresi geçersiz.`,"logs.detail.reason.price_unmatched":`Eşleşen fiyat bulunamadı.`,"logs.detail.reason.invalid_cache_breakdown":`Önbellek detayları çakışıyor.`,"logs.detail.reason.invalid_usage":`Kullanım geçersiz bir jeton değeri içeriyor.`,"logs.detail.reason.combo_attempt_unavailable":`Kombo denemesi fiyatlandırılamadı.`,"logs.detail.estimate.usage_estimated":`Sağlayıcı kullanımı tahminidir.`,"logs.detail.estimate.cache_detail_missing":`Önbellek detayları eksik.`,"logs.detail.estimate.expected_price_overlay":`Doğrulanmış liste fiyatı kullanıldı.`,"logs.detail.estimate.provider_cost_overlay":`Kullanıcı tarafından yapılandırılan bir sağlayıcı fiyat katmanı kullanıldı.`,"logs.col.error":`Hata`,"logs.col.upstreamReason":`Yukarı akış nedeni`,"logs.col.duration":`Süre`,"logs.tokens.reported":`bildirilen`,"logs.tokens.unreported":`bildirilmeyen`,"logs.tokens.unsupported":`desteklenmeyen`,"logs.tokens.estimated":`tahmini`,"logs.tokens.input":`girdi`,"logs.tokens.output":`çıktı`,"logs.tokens.cacheRead":`önbellek okuma`,"logs.tokens.cacheWrite":`önbellek yazma`,"logs.tokens.reasoning":`akıl yürütme`,"logs.tokens.noCache":`önbellek verisi yok`,"logs.tokens.contextTotal":`aktif bağlam`,"logs.tokens.noCacheNote":`bu sağlayıcı önbellek jetonlarını bildirmiyor`,"logs.tokens.noCacheCursor":`Cursor önbellek detayı bildirilmedi`,"logs.tokens.noCacheCursorNote":`Cursor önbellek jeton sayılarını sunmaz`,"logs.tokens.estimatedNote":`tahmini kullanım`,"logs.details":`Detaylar`,"logs.detailTitle":`İstek detayları`,"logs.detailRaw":`Ham günlük kaydı`,"debug.title":`Hata Ayıklama`,"debug.subtitle":`Sağlayıcı taşıma ve kullanım çıkarma tanılamaları.`,"debug.debug":`Sağlayıcı hata ayıklama`,"debug.usage":`Kullanım çıkarma`,"debug.injection":`Enjeksiyon günlüğü`,"debug.claude":`Claude gelen istekler`,"debug.claudeInbound.title":`Claude gelen istekleri`,"debug.claudeInbound.sub":`Claude Code/Desktop tarafından gönderilen istekler.`,"debug.claudeInbound.empty":`Henüz istek yakalanmadı.`,"debug.claudeInbound.time":`Zaman`,"debug.claudeInbound.endpoint":`Uç nokta`,"debug.claudeInbound.model":`Model`,"debug.claudeInbound.none":`yok`,"debug.reset":`Sıfırla`,"debug.refresh":`Yenile`,"debug.follow":`Takip Et`,"debug.streamProvider":`Sağlayıcı`,"debug.streamUsage":`Kullanım`,"debug.streamInjection":`Enjeksiyon`,"debug.loading":`Ayarlar yükleniyor…`,"debug.loadFailed":`Ayarlar yüklenemedi.`,"debug.emptyTitle":`Hata ayıklama günlüğü kapalı`,"debug.empty":`Hata ayıklama seçeneğini açın.`,"debug.noLinesTitle":`Satırlar bekleniyor`,"debug.noLines.provider":`Sağlayıcı hata ayıklama açık.`,"debug.noLines.usage":`Kullanım çıkarma açık.`,"debug.noLines.injection":`Enjeksiyon günlüğü açık.`,"usage.title":`Kullanım`,"usage.subtitle":`Proxy'nizden yerel jeton muhasebesi.`,"usage.loading":`Kullanım verileri yükleniyor…`,"usage.empty":`Henüz kullanım kaydedilmedi.`,"usage.loadError":`Kullanım verileri yüklenemedi.`,"usage.range.all":`Tümü`,"usage.range.available":`Mevcut geçmiş`,"usage.historyTruncated":`Toplamlar yalnızca mevcut geçmişi kapsar.`,"usage.historyTruncatedWindow":`Yüklenen satırların istek başlangıç zamanları {start} ile {end} arasındadır. Dosyanın önceki kayıtları okuma sınırı nedeniyle atlandı, bu yüzden seçilen aralık eksik olabilir.`,"usage.range.30d":`30 gün`,"usage.range.7d":`7 gün`,"usage.card.requests":`İstekler`,"usage.card.measured":`Ölçülen`,"usage.card.reported":`Bildirilen`,"usage.card.totalTokens":`Toplam jeton`,"usage.card.cachedTokens":`Önbellek okuma`,"usage.card.cachedTokensHint":`Sağlayıcı önbelleğinden sunulan jetonlar.`,"usage.card.cacheWriteTokens":`önbellek yazma`,"usage.card.coverage":`Kapsam`,"usage.card.activeDays":`Aktif günler`,"usage.section.heatmap":`Günlük aktivite`,"usage.section.overview":`Genel bakış`,"usage.section.models":`Modeller`,"usage.section.providers":`Sağlayıcılar`,"usage.section.coverage":`Kapsam dağılımı`,"usage.workspace.report":`Kullanım raporu`,"usage.workspace.sections":`Kullanım bölümleri`,"usage.coverage.measured":`Ölçülen`,"usage.coverage.reported":`Bildirilen`,"usage.coverage.estimated":`Tahmin edilen`,"usage.coverage.note":`Ölçülen girdiler bildirilen ve tahmin edilen jeton sayılarını içerir.`,"usage.search.models":`Modellerde ara…`,"usage.col.requests":`İstekler`,"usage.col.measured":`Ölçülen`,"usage.col.reported":`Bildirilen`,"usage.col.tokens":`Jetonlar`,"usage.col.share":`Pay`,"usage.heatmap.less":`Daha az`,"usage.heatmap.more":`Daha fazla`,"usage.dayMon":`Pzt`,"usage.dayWed":`Çar`,"usage.dayFri":`Cum`,"usage.heatmap.tooltipTokens":`{tokens} jeton`,"usage.heatmap.tooltipRequests":`{requests} istek`,"nav.storage":`Depolama`,"storage.title":`Depolama`,"storage.subtitle":`CODEX_HOME dizinini nelerin kullandığını görün.`,"storage.loading":`Depolama taranıyor…`,"storage.empty":`CODEX_HOME boş veya eksik.`,"storage.error":`Depolama taraması başarısız oldu.`,"storage.refresh":`Yeniden tara`,"storage.rescanned":`Tarama tamamlandı.`,"storage.card.total":`Toplam boyut`,"storage.card.files":`Dosyalar`,"storage.card.home":`CODEX_HOME`,"storage.snapshot.lastScan":`Son tarama`,"storage.snapshot.scanning":`Taranıyor…`,"storage.snapshot.unavailable":`Henüz tarama yok.`,"storage.cleanupCard.title":`Alan açın`,"storage.cleanupCard.tabs":`Temizleme seçenekleri`,"storage.cleanupCard.tab.policy":`Politika`,"storage.cleanupCard.tab.quarantine":`Karantina`,"storage.cleanup.noArchives":`Temizlenecek arşivlenmiş oturum yok.`,"storage.section.buckets":`Kovalar`,"storage.section.largest":`En büyük dosyalar`,"storage.workspace.overview":`Genel Bakış`,"storage.workspace.selectBucket":`Ayrıntıları görmek için listeden bir kova seçin.`,"storage.col.bucket":`Kova`,"storage.col.size":`Boyut`,"storage.col.files":`Dosyalar`,"storage.col.oldest":`En eski`,"storage.col.newest":`En yeni`,"storage.col.rows":`DB satırları`,"storage.rows.unknown":`bilinmiyor (kilitli)`,"storage.bucket.sessions":`Aktif oturumlar`,"storage.bucket.archived_sessions":`Arşivlenmiş oturumlar`,"storage.bucket.logs_db":`Günlük veritabanı`,"storage.bucket.state_db":`Durum veritabanı`,"storage.bucket.attachments":`Eklentiler`,"storage.bucket.deletion_manifests":`Silme bildirimleri`,"storage.bucket.other":`Diğer`,"storage.cleanup.title":`Arşiv temizleme`,"storage.cleanup.help":`En eski arşivlenmiş oturumları yüzdeye göre kaldırın.`,"storage.cleanup.slider":`En eski arşivlenen yüzde`,"storage.cleanup.percent":`%{percent}`,"storage.cleanup.preset":`{percent}`,"storage.cleanup.preview":`Önizleme`,"storage.cleanup.confirmTitle":`Arşiv temizliğini onayla`,"storage.cleanup.confirmBody":`Toplam ~{size} tutan {count} arşivlenmiş oturum dosyası silinsin mi (%{percent} eşiği)?`,"storage.cleanup.moreFiles":`…ve {n} tane daha`,"storage.cleanup.permanent":`Kalıcı olarak sil (karantinayı atla)`,"storage.cleanup.permanentWarn":`Kalıcı silme geri alınamaz.`,"storage.cleanup.quarantineNote":`Dosyalar CODEX_HOME/.trash altına taşınır.`,"storage.cleanup.cancel":`İptal`,"storage.cleanup.confirmQuarantine":`Karantinaya Al`,"storage.cleanup.confirmPermanent":`Kalıcı Olarak Sil`,"storage.cleanup.doneQuarantine":`{count} dosya karantinaya alındı ({size}).`,"storage.cleanup.donePermanent":`{count} dosya kalıcı olarak silindi ({size}).`,"storage.cleanup.previewFailed":`Önizleme başarısız oldu.`,"storage.cleanup.cleanupFailed":`Temizleme başarısız oldu.`,"storage.cleanup.err.codex_busy":`Codex state.sqlite dosyasını kullanıyor.`,"storage.cleanup.err.stale_preview":`Önizlemeden sonra arşivlenmiş dosyalar değişti.`,"storage.cleanup.err.restore_pending_overlap":`Seçilen arşivler tamamlanmamış bir geri yükleme ile çakışıyor.`,"storage.cleanup.err.referenced_history":`Seçilen arşivler hâlâ geçmiş tarafından referans gösteriliyor.`,"storage.cleanup.err.invalid_digest":`Önizleme özeti eksik veya geçersiz.`,"storage.cleanup.err.invalid_mode":`Temizleme modu karantina veya kalıcı olmalıdır.`,"storage.cleanup.err.fs_failed":`Dosya sistemi temizliği başarısız oldu. Bazı dosyalar başarısızlıktan önce taşınmış olabilir; CODEX_HOME/.trash veya hedef dizini inceleyin.`,"storage.cleanup.err.fs_failed_trash":`{trashDir} için çöp kutusu işlemi başarısız oldu.`,"storage.cleanup.err.db_reconcile_failed":`Codex durum veritabanı güncellenemedi.`,"storage.cleanup.err.cleanup_failed":`Temizleme başarısız oldu.`,"storage.trash.title":`Karantina`,"storage.trash.help":`CODEX_HOME/.trash altına taşınan arşivlenmiş oturumlar.`,"storage.trash.empty":`Karantinaya alınmış öğe yok.`,"storage.trash.loading":`Karantina yükleniyor…`,"storage.trash.col.when":`Karantinaya Alındı`,"storage.trash.col.files":`Dosyalar`,"storage.trash.col.size":`Boyut`,"storage.trash.col.mode":`Mod`,"storage.trash.col.id":`Girdi`,"storage.trash.restore":`Geri Yükle`,"storage.trash.confirmTitle":`Karantina girdisi geri yüklensin mi?`,"storage.trash.confirmBody":`{id} kimliğinden {count} dosya (~{size}) geri yüklensin mi?`,"storage.trash.cancel":`İptal`,"storage.trash.confirmRestore":`Geri Yükle`,"storage.trash.done":`{count} dosya geri yüklendi ({size}).`,"storage.trash.restoreFailed":`Geri yükleme başarısız oldu.`,"storage.trash.listFailed":`Karantina girdileri listelenemedi.`,"storage.trash.mode.quarantine":`karantina`,"storage.trash.mode.permanent":`kalıcı (tamamlanmamış)`,"storage.trash.err.codex_busy":`Codex state.sqlite dosyasını kullanıyor.`,"storage.trash.err.invalid_trash":`Çöp girdisi ID'si eksik veya geçersiz.`,"storage.trash.err.missing_trash":`Çöp girdisi bulunamadı.`,"storage.trash.err.dest_exists":`Geri yükleme hedefi zaten mevcut.`,"storage.trash.err.fs_failed":`Dosya sistemi geri yüklemesi başarısız oldu.`,"storage.trash.err.db_reconcile_failed":`Veritabanı satırları geri yüklenemedi.`,"storage.trash.err.storage_mutation_busy":`Başka bir depolama eylemi devam ediyor.`,"storage.trash.err.restore_failed":`Geri yükleme başarısız oldu.`,"storage.trash.err.restore_worker_timeout":`Geri yükleme çok uzun sürdü.`,"storage.trash.err.restore_worker_aborted":`Geri yükleme iptal edildi.`,"storage.trash.err.restore_worker_failed":`Geri yükleme işleyicisi çöktü.`,"storage.policy.title":`Otomatik temizleme politikası`,"storage.policy.help":`İsteğe bağlı toplu temizleme politikası.`,"storage.policy.loading":`Politika yükleniyor…`,"storage.policy.loadFailed":`Temizleme politikası yüklenemedi.`,"storage.policy.saveFailed":`Temizleme politikası kaydedilemedi.`,"storage.policy.runFailed":`Politika çalıştırması başarısız oldu.`,"storage.policy.alreadyRunning":`Bir politika çalıştırması zaten devam ediyor.`,"storage.policy.invalid":`Geçersiz politika değerleri.`,"storage.policy.enabled":`Otomatik temizlemeyi etkinleştir`,"storage.policy.enabledHint":`Varsayılan olarak kapalıdır.`,"storage.policy.threshold":`Arşivlenen boyut aşıldığında (GiB)`,"storage.policy.trigger":`Tetikleyici`,"storage.policy.target":`Temizleme hedefi`,"storage.policy.targetPercent":`En eski arşivlenenleri kaldır (%)`,"storage.policy.targetReduce":`Arşiv boyutunu düşür (GiB)`,"storage.policy.thresholdInc":`Eşiği artır`,"storage.policy.thresholdDec":`Eşiği azalt`,"storage.policy.percentInc":`Yüzdeyi artır`,"storage.policy.percentDec":`Yüzdeyi azalt`,"storage.policy.reduceInc":`Hedef boyutu artır`,"storage.policy.reduceDec":`Hedef boyutu azalt`,"storage.policy.schedule":`Zamanlama`,"storage.policy.schedule.manual":`Yalnızca manuel`,"storage.policy.schedule.startup":`Proxy başlangıcında`,"storage.policy.schedule.daily":`Günlük`,"storage.policy.schedule.weekly":`Haftalık`,"storage.policy.mode":`Silme modu`,"storage.policy.mode.quarantine":`Karantina (varsayılan)`,"storage.policy.mode.permanent":`Kalıcı silme`,"storage.policy.permanentWarn":`Kalıcı mod geri alınamaz.`,"storage.policy.lastRun":`Son çalıştırma`,"storage.policy.lastRunDetail":`{count} kaldırıldı · {size} alan açıldı`,"storage.policy.nextRun":`Sonraki çalıştırma`,"storage.policy.never":`Hiçbir zaman`,"storage.policy.save":`Kaydet`,"storage.policy.runNow":`Şimdi çalıştır`,"storage.policy.running":`Çalıştırılıyor…`,"storage.policy.saved":`Politika kaydedildi.`,"storage.policy.skippedDisabled":`Politika devre dışı.`,"storage.policy.skippedUnder":`Arşiv boyutu eşiğin altında.`,"storage.policy.skippedEmpty":`Hedefle eşleşen aday yok.`,"storage.policy.doneQuarantine":`Politika {count} dosyayı karantinaya aldı ({size}).`,"storage.policy.donePermanent":`Politika {count} dosyayı kalıcı olarak sildi ({size}).`,"modal.addNamed":`Ekle: {label}`,"modal.add":`Sağlayıcı ekle`,"modal.search":`Sağlayıcılarda ara…`,"modal.logInWith":`{label} ile giriş yap`,"modal.waitingBrowser":`Tarayıcı bekleniyor…`,"modal.providerName":`Sağlayıcı adı`,"modal.adapter":`Adaptör`,"modal.baseUrl":`Taban URL`,"modal.endpoint":`Uç nokta`,"modal.endpoint.tokenPlan":`Jeton planı`,"modal.endpoint.payAsYouGo":`Kullandıkça öde`,"modal.endpoint.custom":`Özel`,"modal.defaultModel":`Varsayılan model (isteğe bağlı)`,"modal.allowPrivateNetwork":`Yerel/özel ağa izin ver`,"modal.allowPrivateNetworkHint":`Yalnızca yerel barındırılan sağlayıcılar için etkinleştirin.`,"modal.nameRequired":`Sağlayıcı adı gereklidir`,"modal.baseUrlRequired":`Taban URL gereklidir`,"modal.networkError":`Ağ hatası — proxy çalışıyor mu?`,"modal.loginFailStart":`Giriş başlatılamadı`,"modal.waitingLogin":`Tarayıcı girişi bekleniyor…`,"modal.loggingIn":`Giriş yapılıyor…`,"modal.loginTimeout":`Giriş zaman aşılanına uğradı.`,"modal.back":`Geri`,"modal.badge.oauth":`OAuth`,"modal.customProvider":`Özel sağlayıcı`,"modal.failedStatus":`Başarısız ({status})`,"modal.loginError":`Giriş hatası: {error}`,"modal.badge.codexLogin":`Codex girişi`,"modal.badge.local":`Yerel`,"modal.badge.apiKey":`API anahtarı`,"modal.badge.direct":`Doğrudan`,"modal.badge.pool":`Havuz`,"modal.badge.free":`Ücretsiz`,"modal.invalidPreset":`Bu yerleşik sağlayıcı ayarı eksik.`,"modal.freeTierTitle":`Ücretsiz katman`,"modal.freeTierDefault":`API anahtarı gerekmez. Doğrudan çalışır.`,"modal.tab.accounts":`Hesaplar`,"modal.tab.free":`Ücretsiz`,"modal.tab.paid":`Ücretli`,"modal.accountsHint":`ChatGPT/Codex ve OAuth hesaplarına buradan giriş yapın.`,"modal.accountsCodexAuthLink":`Codex Kimlik Doğrulaması`,"modal.notListed":`Sağlayıcı listede yok mu? Özel sağlayıcı ekleyin`,"modal.catalogLoading":`Katalog yükleniyor…`,"modal.accountLogin":`Giriş yap`,"modal.accountLogout":`Çıkış yap`,"modal.accountAdd":`Hesap ekle`,"modal.accountManage":`Yönet`,"modal.accountCodexPool":`ChatGPT hesap havuzu`,"modal.accountLoggedIn":`Giriş yapıldı`,"modal.accountLoggedOut":`Giriş yapılmadı`,"quota.fiveHourLimit":`5 saatlik limit`,"quota.weeklyLimit":`Haftalık limit`,"quota.monthlyLimit":`30 günlük limit`,"quota.cursorFirstParty":`Birinci taraf modeller`,"quota.cursorApiUsage":`API kullanımı`,"quota.totalSubscriptionCredits":`Toplam abonelik kredileri`,"quota.usedPercent":`%{pct} kullanıldı`,"quota.limitReached":`Limite ulaşıldı`,"quota.resetsToday":`Bugün {time} saatinde sıfırlanır`,"quota.resetsTomorrow":`Yarın {time} saatinde sıfırlanır`,"quota.resetsAt":`{when} sıfırlanır`,"quota.resetsRelativeMinutes":`{n} dakika içinde sıfırlanır`,"quota.resetsRelativeHours":`{n} saat içinde sıfırlanır`,"pws.status.ready":`Hazır`,"pws.status.needsSetup":`Kurulum gerekiyor`,"pws.status.needsAttention":`Dikkat gerekiyor`,"pws.auth.chatgptPassthrough":`ChatGPT doğrudan geçiş`,"pws.auth.noKey":`Anahtar gerekmiyor`,"pws.freeTitle":`Ücretsiz fiyatlandırma`,"pws.localTitle":`Yerel çalışma zamanı`,"pws.modelCountOne":`1 model`,"pws.modelCount":`{count} model`,"pws.rail.suffixDefault":` · varsayılan`,"pws.rail.suffixLocal":` · yerel`,"pws.rail.suffixFree":` · ücretsiz`,"pws.rail.selectAria":`{name} seç — {status}{suffix}`,"pws.searchPlaceholder":`Sağlayıcılarda ara…`,"pws.filterAria":`Sağlayıcıları filtrele`,"pws.providerFiltersAria":`Sağlayıcı filtreleri`,"pws.filters":`Filtreler`,"pws.filterStatus":`Durum`,"pws.pricing":`Fiyatlandırma`,"pws.paid":`Ücretli`,"pws.filterType":`Tür`,"pws.type.cloud":`Bulut`,"pws.type.local":`Yerel`,"pws.type.selfHosted":`Kendi barındırdığı`,"pws.type.login":`Giriş yap`,"pws.sort":`Sırala`,"pws.sortProvidersAria":`Sağlayıcıları sırala`,"pws.sort.az":`A–Z`,"pws.sort.za":`Z–A`,"pws.sort.freePaid":`Önce ücretsizler`,"pws.sort.paidFree":`Önce ücretliler`,"pws.sort.accountsFirst":`Önce hesaplar`,"pws.resetAll":`Tümünü sıfırla`,"pws.providerList":`Sağlayıcı listesi`,"pws.providersAria":`Sağlayıcılar`,"pws.groupReady":`Hazır ({count})`,"pws.groupNeedsSetup":`Kurulum gerekiyor ({count})`,"pws.groupDisabled":`Devre dışı ({count})`,"pws.noSearchResults":`Aramanızla eşleşen sağlayıcı yok.`,"pws.noMatchFilters":`Filtrelerle eşleşen sağlayıcı yok.`,"pws.noProvidersConfigured":`Yapılandırılmış sağlayıcı yok.`,"pws.workspaceMainAria":`Sağlayıcı detayları`,"pws.detailComingSoon":`Detay görünümü yakında geliyor.`,"pws.selectPrompt":`Listeden bir sağlayıcı seçin.`,"pws.connectFirst":`İlk sağlayıcınızı bağlayın`,"pws.empty.browseFree":`Ücretsiz sağlayıcılara göz atın`,"pws.empty.browseFreeDesc":`Abonelik olmadan başlayın`,"pws.empty.connectAccount":`Bir hesap bağlayın`,"pws.empty.connectAccountDesc":`ChatGPT veya sağlayıcı girişinizi kullanın`,"pws.empty.addEndpoint":`Bir uç nokta ekleyin`,"pws.empty.addEndpointDesc":`Özel taban URL ve API anahtarı`,"pws.tab.overview":`Genel Bakış`,"pws.tab.models":`Modeller`,"pws.tab.usage":`Kullanım`,"pws.tab.accounts":`Hesaplar`,"pws.tab.settings":`Ayarlar`,"pws.connection":`Bağlantı`,"pws.status.connected":`Bağlandı`,"pws.attentionTitle":`Dikkat gerekiyor`,"pws.attention.reauth":`Aktif hesap yeniden doğrulama gerektiriyor`,"pws.attention.reauthForward":`Aktif Codex hesabı yeniden doğrulama gerektiriyor`,"pws.attention.missingCredentials":`Kimlik bilgileri eksik`,"pws.cell.auth":`Kimlik Doğrulama`,"pws.cell.note":`Not`,"pws.cell.defaultModel":`Varsayılan model`,"pws.statsAria":`Sağlayıcı istatistikleri`,"pws.statsTitle":`İstatistikler`,"pws.stats.totalRequests":`İstekler (30 gün)`,"pws.stats.totalTokens":`Jetonlar (30 gün)`,"pws.stats.quotaUpdated":`Kota güncellendi`,"pws.stats.quotaTracked":`Oran limitleri Kullanım sekmesinde takip edilir.`,"pws.stats.source":`Kaynak`,"pws.usageLast30d":`Kullanım (son 30 gün)`,"pws.estimatedCost":`Tahmini maliyet`,"pws.costDisclaimer":`API liste fiyatı tahminidir.`,"pws.modelBreakdown":`Model dağılımı`,"pws.col.model":`Model`,"pws.col.cost":`Tahm. maliyet`,"pws.col.tokens":`Jetonlar`,"pws.col.requests":`İst.`,"pws.col.share":`Pay`,"pws.tokenInput":`Girdi`,"pws.tokenOutput":`Çıktı`,"pws.metricRequests":`istek`,"pws.metricTokens":`jeton`,"pws.usageUnavailable":`Henüz kullanım kaydedilmedi.`,"pws.rateLimits":`Oran limitleri`,"pws.quotaUnavailable":`Bu sağlayıcı için kota verisi yok.`,"pws.accountQuotaUnavailable":`Oran limiti verisi geçici olarak kullanılamıyor.`,"pws.selected":`Seçilen`,"pws.copyModelId":`ID Kopyala`,"pws.modelCopied":`Kopyalandı!`,"pws.modelsAvailable":`{count} kullanılabilir`,"pws.modelSearchPlaceholder":`Modelleri filtrele…`,"pws.modelsLoading":`Modeller yükleniyor…`,"pws.modelsLoadFailed":`Modeller yüklenemedi.`,"pws.modelsNeedsReauth":`Hesabın yeniden giriş yapması gerekiyor.`,"pws.modelsConfiguredFallback":`Yapılandırılmış modeller gösteriliyor.`,"pws.modelsTruncated":`{total} modelden ilk {shown} tanesi gösteriliyor.`,"pws.retry":`Tekrar Dene`,"pws.noModels":`Bu sağlayıcı için keşfedilen model yok.`,"pws.noModelMatch":`Filtreyle eşleşen model yok.`,"pws.adapterBaseRequired":`Adaptör ve taban URL gereklidir.`,"pws.addAccount":`Hesap ekle`,"pws.addKey":`API anahtarı ekle`,"pws.apiKeys":`API Anahtarları`,"pws.authMode":`Kimlik doğrulama modu`,"pws.availableAccounts":`Mevcut hesaplar`,"pws.accountOrdinal":`Hesap {count}`,"pws.accountsLoading":`Hesaplar yükleniyor…`,"pws.accountsLoadFailed":`Hesaplar yüklenemedi.`,"pws.retryAccounts":`Tekrar Dene`,"pws.noAccounts":`Henüz bağlı hesap yok.`,"pws.cockpitImportDescription":`Bu cihazdan bir Cockpit Tools Antigravity JSON dışa aktarımını içe aktarın. Dosya içeriği gösterilmez.`,"pws.cockpitImportFileLabel":`Cockpit Tools Antigravity JSON dışa aktarımı`,"pws.cockpitImportChooseFile":`JSON dosyası seç`,"pws.cockpitImporting":`İçe aktarılıyor…`,"pws.cockpitImportInvalid":`Seçilen dosya geçerli bir JSON dışa aktarımı değil veya çok büyük.`,"pws.cockpitImportFailed":`Hesap içe aktarımı tamamlanamadı.`,"pws.cockpitImportComplete":`İçe aktarma tamamlandı: {imported} içe aktarıldı, {updated} güncellendi, {failed} başarısız, {unsupported} desteklenmiyor.`,"pws.accountSwitching":`Değiştiriliyor…`,"pws.accountCurrent":`Mevcut hesap`,"pws.defaultModelNone":`Yok (sağlayıcı varsayılanını kullan)`,"pws.discardSettings":`Vazgeç`,"pws.jsonEditorDesc":`Ham sağlayıcı JSON konfigürasyonunu düzenleyin.`,"pws.jsonEditorTitle":`JSON düzenleyici — {name}`,"pws.jsonRestore":`Geri Yükle`,"pws.jsonSave":`Kaydet`,"pws.loggedInTitle":`Giriş yapıldı`,"pws.notLoggedInTitle":`Giriş yapılmadı`,"pws.note":`Not`,"pws.allowPrivateNetwork":`Yerel/özel ağa izin ver`,"pws.liveModels":`Sağlayıcıdan canlı model keşfet`,"pws.liveModelsDesc":`Sağlayıcının canlı model kataloğunu çekin.`,"pws.optionalPlaceholder":`İsteğe bağlı`,"pws.providerId":`Sağlayıcı ID`,"pws.reauth":`Yeniden doğrulama gerekiyor`,"pws.reauthenticate":`Yeniden doğrula`,"pws.copyDoctor":`ocx doctor kopyala`,"pws.doctorCopied":`Kopyalandı`,"pws.doctorCopyUnavailable":`Pano kullanılamıyor`,"pws.healthCooldownHint":`Soğuma süresi bitene kadar bekleyin.`,"pws.healthLabel.rateLimited":`Oran kısıtlandı`,"pws.healthLabel.quotaLimited":`Kota kısıtlandı`,"pws.healthLabel.reauthRequired":`Yeniden doğrulama gerekli`,"pws.healthLabel.refreshFailed":`Yenileme başarısız oldu`,"pws.healthLabel.metadataMismatch":`Meta veri uyuşmazlığı`,"pws.healthLabel.credentialConflict":`Kimlik bilgisi çakışması`,"pws.healthSummary.rateLimited":`{provider} {account}: {until} tarihine kadar oran kısıtlandı.`,"pws.healthSummary.quotaLimited":`{provider} {account}: {until} tarihine kadar kota kısıtlandı.`,"pws.healthSummary.reauthRequired":`{provider} {account}: yeniden doğrulama gerekli.`,"pws.healthSummary.credentialConflict":`{provider} {account}: kimlik bilgisi çakışması.`,"pws.healthSummary.metadataMismatch":`{provider} {account}: meta veri uyuşmazlığı.`,"pws.healthSummary.staleCredentials":`{provider} {account}: eksik kimlik bilgileri.`,"pws.removeConfirm":`Kaldır`,"pws.removeConfirmBody":`"{name}" sağlayıcısı kaldırılsın mı?`,"pws.removeDefaultConfirmBody":`Varsayılan sağlayıcı "{name}" kaldırılsın mı? "{defaultProvider}" varsayılan sağlayıcı olacaktır. Bu işlem geri alınamaz.`,"pws.removeConfirmTitle":`Sağlayıcıyı kaldır`,"pws.saveSettings":`Kaydet`,"pws.pacingTitle":`İstek aralığı`,"pws.pacingDesc":`Bu sağlayıcıya giden istek başlangıçlarını eşit aralıklarla geciktirir. Akış yanıtları çakışabilir.`,"pws.pacingEnabled":`Etkin`,"pws.pacingRpm":`Dakikadaki istek`,"pws.pacingRpmUnit":`RPM`,"pws.pacingDelay":`En kısa aralık (ms)`,"pws.pacingSlowerWins":`Daha yavaş sağlayıcı sınırı geçerlidir. Model kuralları yalnızca ek gecikme getirir.`,"pws.pacingQueued":`kuyrukta`,"pws.pacingNextSlot":`sonraki aralığa`,"pws.pacingLastModel":`son model`,"pws.pacingNone":`Yok`,"pws.pacingModelOverrides":`Model kuralları`,"pws.pacingModel":`Model`,"pws.pacingAdd":`Kural ekle`,"pws.pacingRemove":`Kaldır`,"pws.pacingRemoveModel":`{model} için istek aralığı kuralını kaldır`,"pws.pacingRuleRequired":`Önce bir sağlayıcı sınırı veya model kuralı belirleyin.`,"pws.saving":`Kaydediliyor…`,"pws.settingsSaved":`Ayarlar kaydedildi.`,"pws.accountModeSaved":`Hesap modu kaydedildi.`,"pws.accountModeFailed":`Hesap modu değiştirilemedi.`,"pws.accountModeConfirm":`OpenAI hesap modu değiştirilsin mi? Aktif oturumlar hedef hesap havuzuna yönlendirilecek ve kota yeni mod altında birikecektir.`,"pws.settingsUnsavedBar":`Kaydedilmemiş değişiklikleriniz var.`,"pws.unsavedLeaveBody":`Kaydedilmemiş değişiklikleriniz var. Ayrılmadan önce kaydetmek ister misiniz?`,"pws.unsavedLeaveTitle":`Kaydedilmemiş değişiklikler`,"pws.attentionRequired":`Dikkat gerekiyor`,"pws.attentionAria":`{name}: {reason}`,"pws.missingCredentials":`Kimlik bilgileri eksik`,"pws.editJsonDesc":`Proxy konfigürasyonunu JSON olarak düzenleyin`,"pws.updatesUnavailable":`Sağlayıcı güncellemeleri mevcut değil.`,"pws.dashboard.title":`Sağlayıcılara genel bakış`,"pws.dashboard.subtitle":`Tüm model sağlayıcılarınızı tek bir yerden yönetin.`,"pws.dashboard.rateLimits":`ORAN LİMİTLERİ`,"pws.capacity.estimate":`Havuz kapasite tahmini`,"pws.capacity.currentAccount":`Mevcut geçerli hesap`,"pws.capacity.nextRecovery":`Sonraki kapasite yenilenmesi`,"pws.capacity.recoveryShare":`+%{percent} havuz kapasitesi`,"pws.capacity.incomplete":`Kısmi pencere kapsamı ({unknown} bilinmeyen, {excluded} hariç tutuldu)`,"pws.capacity.partial":`Kısmi ({count} hesap kota metriği bildiriyor)`,"pws.capacity.windowPartial":`Kısmi`,"pws.capacity.windowPartialA11y":`{window}: eksik hesap kapsamı`,"pws.dashboard.recentlyUsed":`SON KULLANILANLAR`,"pws.dashboard.requests":`{count} istek`,"pws.dashboard.checkedAgo":`{time} önce kontrol edildi`,"pws.dashboard.noQuota":`Kota verisi yok`,"pws.dashboard.noUsage":`Henüz kullanım verisi yok`,"pws.dashboard.noRateLimits":`Henüz oran limiti verisi yok`,"pws.allProviders":`Sağlayıcı Genel Bakışı`,"pws.enabledLabel":`Etkin`,"pws.testConnection":`Bağlantıyı test et`,"pws.testing":`Test ediliyor…`,"pws.connectionOk":`Bağlantı Başarılı`,"pws.connectionFailed":`Bağlantı Başarısız`,"pws.connectionNotApplicable":`Uygulanamaz — bu sağlayıcı statik katalog kullanıyor.`,"pws.editSettings":`Ayarları düzenle`,"pws.viewUsage":`Detaylı kullanımı gör`,"pws.allSystemsOk":`Tüm sistemler çalışır durumda`,"pws.apiKeyConfigured":`API anahtarı yapılandırıldı`,"pws.addApiKey":`API anahtarı ekle`,"pws.loggedInAs":`{email} olarak giriş yapıldı`,"pws.notLoggedIn":`Giriş yapılmadı`,"pws.passthrough":`Codex doğrudan geçiş`,"pws.notes":`NOTLAR`,"pws.notePlaceholder":`Bu sağlayıcı hakkında bir not ekleyin...`,"pws.noteSaved":`Not kaydedildi`,"pws.authSummary":`KİMLİK DOĞRULAMA`,"time.justNow":`Az önce`,"time.notChecked":`Kontrol edilmedi`,"time.minutesAgo":`{n}dk önce`,"time.hoursAgo":`{n}sa önce`,"time.daysAgo":`{n}gün önce`,"modal.noMatch":`Eşleşme yok.`,"modal.oauthDefaultNote":`Hesabınızla giriş yapın — API anahtarı gerekmez.`,"modal.oauthComingSoon":`{label} için OAuth girişi gelecektir. Şimdilik API anahtarı kullanın.`,"modal.oauthComingSoonShort":`Bu sağlayıcı için OAuth girişi gelecektir — şimdilik API anahtarı kullanın.`,"modal.useApiKeyInstead":`Bunun yerine API anahtarı kullanın`,"modal.setupGuide":`Kurulum rehberi`,"modal.setupStep1Prefix":`Adresine gidin:`,"modal.setupDashboardLink":`{label} paneli`,"modal.setupStep1Suffix":`ve API anahtarınızı kopyalayın`,"modal.setupStep2":`Aşağıdaki API anahtarı alanına yapıştırın`,"modal.setupStep3":`Sağlayıcı ekle'ye tıklayın — modeller otomatik keşfedilir`,"modal.namePlaceholder":`örn. openrouter`,"modal.duplicateWarn":`"{name}" sağlayıcısı mevcut ve üzerine yazılacak.`,"modal.forwardHintPrefix":`Anahtar gerekmez — proxy kimlik bilgilerinizi iletir`,"modal.forwardCredentials":`codex girişi`,"modal.forwardHintSuffix":`kimlik bilgilerini bu sağlayıcıya iletir.`,"modal.localHint":`Yerel mod, Cursor'ın statik kamuya açık kataloğunu kaydeder. Canlı taşıma, dosya ve kabuk (shell) araçları denetlenene kadar kapalı kalır.`,"modal.getApiKey":`{label} API anahtarınızı alın`,"modal.apiKey":`API anahtarı`,"modal.apiKeyTransport":`API anahtar başlığı`,"modal.apiKeyTransportNative":`x-api-key (Anthropic yerel)`,"modal.apiKeyTransportBearer":`Authorization: Bearer`,"modal.apiKeyPlaceholder":`sk-… (veya $ENV_VAR)`,"modal.defaultModelPlaceholder":`örn. gpt-5.5`,"modal.baseUrlPlaceholder":`https://...`,"modal.baseUrlPlaceholderError":`Taban URL çözümlenmemiş bir {placeholder} içeriyor.`,"modal.baseUrlPlaceholderHint":`Eklemeden önce {placeholder} değerini gerçek Hesap ID'nizle değiştirin.`,"modal.adding":`Ekleniyor…`,"modal.useOauthLogin":`← OAuth girişini kullan`,"nav.codexAuth":`Codex Kimlik Doğrulama`,"nav.api":`API`,"nav.integrations":`Entegrasyonlar`,"nav.openMenu":`Menüyü aç`,"nav.closeMenu":`Menüyü kapat`,"integrations.subtitle":`İstemcileri opencodex'e bağlayın, kimlik bilgilerini yönetin.`,"integrations.tabsLabel":`Entegrasyon yüzeyleri`,"integrations.tab.overview":`Genel Bakış`,"integrations.tab.keys":`API Anahtarları`,"integrations.tab.codex":`Codex CLI`,"integrations.tab.claude":`Claude`,"integrations.tab.grok":`Grok Build`,"integrations.tab.opencode":`OpenCode`,"integrations.tab.pi":`Pi`,"integrations.tab.omp":`OMP`,"integrations.tab.hermes":`Hermes`,"integrations.tab.openclaw":`OpenClaw`,"integrations.tab.kimi":`Kimi Code`,"integrations.tab.gajae":`Gajae Code`,"integrations.tab.dsh":`DeepSeek Harness (DSH)`,"integrations.tab.mcode":`MiniMax Code`,"integrations.codex.title":`Codex CLI`,"integrations.codex.body":`Codex bağlantısı proxy servisine aittir.`,"integrations.codex.openService":`Servis kontrollerini aç`,"integrations.state.notInstalled":`Yüklü değil`,"integrations.state.unknown":`Kontrol ediliyor…`,"integrations.detail.codexRouted":`Codex istekleri bu proxy üzerinden geçer`,"integrations.detail.codexAbsent":`Codex henüz bu proxy üzerinden yönlendirilmedi`,"integrations.detail.keyCount":`{count} anahtar oluşturuldu`,"integrations.detail.keyNone":`Oluşturulmuş anahtar yok`,"integrations.detail.keyChecking":`Kontrol ediliyor…`,"integrations.detail.keyUnavailable":`Anahtar durumu kullanılamıyor`,"integrations.detail.claudeOff":`Bağlantı kapalı`,"integrations.detail.desktopCurrent":`Desktop bu profili çalıştırıyor`,"integrations.detail.desktopStale":`Profil dosyası değiştirildi`,"integrations.detail.desktopNotServed":`Profil mevcut ancak Desktop başkasını kullanıyor`,"integrations.detail.desktopAbsent":`Uygulanan profil yok`,"integrations.detail.desktopDesiredOff":`Claude Desktop entegrasyonu kapalı`,"integrations.detail.desktopDesiredOnNotApplied":`Entegrasyon açık ancak Desktop kullanmıyor`,"integrations.detail.desktopSelectedElsewhere":`Desktop başka bir profil kullanıyor`,"integrations.detail.desktopProfileDrift":`Seçilen Desktop profili değişti`,"integrations.detail.desktopObservedUnsafe":`Desktop profili güvenle değiştirilemiyor`,"integrations.detail.desktopNotInstalled":`Claude Desktop kütüphanesi yüklü değil`,"integrations.detail.grokModels":`{count} model bağlandı`,"integrations.detail.grokAbsent":`Konfigürasyonda opencodex bloğu yok`,"integrations.dialog.grok.title":`Grok Build entegrasyonu devre dışı bırakılsın mı?`,"integrations.dialog.grok.changes":`Yalnızca {path} dosyasında opencodex tarafından işaretlenen blok kaldırılacaktır. Blok dışında yazılan içerik değişmeden kalır.`,"integrations.dialog.grok.breakage":`Devre dışı bırakmak, opencodex model takma adlarını Grok Build'den kaldırır. xAI hesabınızla kullanılan modeller kullanılabilir kalır.`,"integrations.dialog.grok.undo":`opencodex bir geri döngü (loopback) adresinde çalışıyorsa, bunu tekrar açmak şu anda mevcut olan modellerden yeni bir blok yazar.`,"integrations.dialog.grok.confirm":`Devre Dışı Bırak`,"integrations.dialog.desktop.title":`Claude Desktop entegrasyonu devre dışı bırakılsın mı?`,"integrations.dialog.desktop.changes":`Eğer {path} opencodex tarafından yönetilen bir ağ geçidi profili içeriyorsa, Desktop önce kimlik bilgisiz yeni bir standart profil seçer, ardından eski profili ve yedeği kaldırır.`,"integrations.dialog.desktop.breakage":`Claude Desktop, opencodex üzerinden yönlendirilen modeller yerine standart Claude'a geri dönecektir.`,"integrations.dialog.desktop.undo":`Bunu tekrar açmak, kaydedilmiş model atamalarınızdan opencodex profilini yeniden oluşturur.`,"integrations.dialog.desktop.restart":`Claude Desktop bu yapılandırmayı yalnızca açılışta okur. Değişikliğin yürürlüğe girmesi için uygulamayı tamamen kapatıp yeniden açın.`,"integrations.dialog.desktop.confirm":`Devre Dışı Bırak`,"integrations.native.msg.nonLoopbackRemoved":`Grok Build yalnızca opencodex bir geri döngü (loopback) adresinde çalışırken otomatik olarak kaydolabilir. Loopback'i işaret eden önceki blok kaldırıldı.`,"integrations.native.msg.nonLoopbackRemovedNoop":`Grok Build yalnızca opencodex bir geri döngü (loopback) adresinde çalışırken otomatik olarak kaydolabilir. Kaldırılacak önceki bir blok yoktu.`,"integrations.native.msg.nonLoopbackSuperseded":`Grok Build yalnızca opencodex bir geri döngü adresi üzerinde çalışırken otomatik kaydedilebilir. Bu sırada başka bir işlem yeni bir blok yazdı, bu nedenle şu an dosyadaki blok bu istek tarafından oluşturulmadı.`,"integrations.native.error.orphanedMarker":`{path} bir opencodex başlangıç işaretine sahip ancak bitiş işareti yok. opencodex bloğunun nerede bittiğini belirleyemediği için dosya değiştirilmeden bırakıldı.`,"integrations.native.error.homeMismatch":`Yüklü servis dizini mevcut ev dizini ile uyuşmuyor, bu nedenle dosya değiştirilmeden bırakıldı.`,"integrations.native.error.notInstalled":`Grok Build yüklü değil, bu nedenle değiştirilecek bir şey yok.`,"integrations.native.error.configBusy":`Yapılandırma başka bir yerde kaydediliyor ve değiştirilemedi. Kısa süre sonra tekrar deneyin.`,"integrations.native.error.desktopUnsafeMetadata":`{path} konumundaki Claude Desktop meta verileri güvenle okunamadı, bu nedenle kütüphanesi değiştirilmedi.`,"integrations.native.error.desktopCleanupIncomplete":`Claude Desktop standart moda yönlendirildi, ancak eski opencodex kimlik bilgisi dosyaları şu konumda kalmaya devam ediyor: {paths}.`,"integrations.native.msg.desktopDisabled":`Claude Desktop entegrasyonu devre dışı bırakıldı.`,"integrations.native.msg.desktopEnabled":`Claude Desktop entegrasyonu etkinleştirildi.`,"integrations.state.absent":`Uygulanmadı`,"integrations.state.current":`Uygulandı`,"integrations.state.stale":`Güncelleme gerekiyor`,"integrations.state.conflict":`Çakışma`,"integrations.state.unsafe":`Doğrulanamadı`,"integrations.summary.detected":`Algılanan istemciler`,"integrations.summary.applied":`Yapılandırılan istemciler`,"integrations.summary.stale":`Güncelleme gerekiyor`,"integrations.summary.lastChange":`Son değişiklik`,"integrations.summary.disableAll":`Tümünü devre dışı bırak…`,"integrations.onboarding":`Uygulama işlemi bir yedek aldıktan sonra yazar.`,"integrations.empty.title":`Yüklü istemci algılanmadı`,"integrations.empty.body":`Desteklenen bir istemci yükleyin.`,"integrations.action.apply":`Uygula`,"integrations.action.disable":`Devre Dışı Bırak`,"integrations.action.refresh":`Güncelle`,"integrations.action.settings":`Ayarlar`,"integrations.action.manageKeys":`Anahtarları yönet`,"integrations.action.restore":`Geri Yükle…`,"integrations.action.undo":`Geri Al`,"integrations.action.restorePoint":`Bu noktayı geri yükle…`,"integrations.action.snapshotExpired":`Yedek süresi doldu`,"integrations.rollback.title":`Geri alma merkezi`,"integrations.rollback.empty":`Henüz uygulama geçmişi yok`,"integrations.rollback.emptyBody":`Her başarılı yazma bir anlık görüntü saklar.`,"integrations.restore.title":`Bu anlık görüntü geri yüklensin mi?`,"integrations.restore.body":`Mevcut dosya önce yedeklenir.`,"integrations.restore.driftTitle":`Daha yeni düzenlemeler algılandı`,"integrations.restore.driftBody":`Bu anlık görüntüden sonra yapılan değişiklikler yedeklenecektir.`,"integrations.restore.confirm":`Geri Yükle`,"integrations.restore.confirmDrift":`Yedekle ve geri yükle`,"integrations.restore.pending":`Geri yükleniyor…`,"integrations.restore.manual":`{reason}: {path} dosyasını el ile geri yükleyin`,"integrations.error.load":`Entegrasyon durumu yüklenemedi.`,"integrations.error.stale":`Son yenileme başarısız oldu.`,"integrations.error.busy":`İşlem devam ediyor.`,"integrations.error.conflict":`Konfigürasyon yazıldıktan sonra değişti.`,"integrations.error.unsafe":`Konfigürasyon güvenle değiştirilemiyor.`,"integrations.error.generic":`Entegrasyon değişikliği başarısız oldu.`,"integrations.error.nonLoopback":`{client} istemcisi geri döngü (loopback) dışında bir adreste. Yerel entegrasyonlar yalnızca loopback (127.0.0.1 veya ::1) üzerinden düzenlenebilir. Bir API anahtarı ayarlayın veya yerel erişim kullanın.`,"integrations.status.installed":`Yüklü`,"integrations.status.notInstalled":`Yüklü değil`,"integrations.status.appliedAt":`Uygulandı`,"integrations.status.backup":`Yedek`,"integrations.status.lastRestore":`Son geri yükleme`,"integrations.status.unknown":`Bilinmiyor`,"integrations.bulk.title":`Uygulanan istemci entegrasyonları devre dışı bırakılsın mı?`,"integrations.bulk.body":`Yalnızca opencodex bloğu kaldırılır.`,"integrations.bulk.partial":`Bazı istemciler devre dışı bırakılamadı: {clients}`,"integrations.bulk.success":`Uygulanan istemci entegrasyonları devre dışı bırakıldı.`,"integrations.retention.degraded":`Yedek temizliği geride kaldı.`,"integrations.error.residual":`{path} konumunda {message}`,"integrations.error.recover":`{path} kurtarılırken {message}`,"integrations.kind.apply":`Uygulandı`,"integrations.kind.disable":`Devre Dışı Bırakıldı`,"integrations.kind.refresh":`Güncellendi`,"integrations.kind.restore":`Geri Yüklendi`,"integrations.semantics.opencode":`Doğrudan disk başlatmaları.`,"integrations.semantics.pi":`Yeni oturumlara uygulanır.`,"integrations.semantics.hermes":`Yeni oturumlara uygulanır.`,"integrations.semantics.openclaw":`Anında uygulanır.`,"integrations.semantics.kimi":`Uygulamak için yeniden başlatın.`,"integrations.semantics.gajae":`Yeni oturuma uygulanır.`,"integrations.semantics.dsh":`OpenCodex yalnızca $DSH_HOME/settings.yaml içindeki llm-pi-ai.providers.opencodex bölümünü yönetir. DSH bu sağlayıcıyı çalışırken yeniden yükler; varsayılan modeliniz ve deepseek-official değişmez. Şimdilik yalnızca geri döngü desteklenir; gerçek kimlik bilgisi yazılmaz.`,"integrations.semantics.mcode":`Yalnızca custom_provider.opencodex bölümünü yönetir. Varsayılan model ve MiniMax oturumu değişmez.`,"integrations.semantics.omp":`Kataloğu yüklemek için OMP'yi yeniden başlatın.`,"codexAuth.mainAccount":`Ana Hesap`,"codexAuth.logLabel":`Günlük etiketi`,"codexAuth.codexApp":`Codex Uygulaması`,"codexAuth.appLogin":`Uygulama girişi`,"codexAuth.accountPool":`Hesap Havuzu`,"codexAuth.accountModeTitle":`OpenAI hesap modu`,"codexAuth.accountModePool":`Havuz modu`,"codexAuth.accountModePoolDesc":`Ana giriş ve eklenen hesaplar burada döner.`,"codexAuth.accountModeDirect":`Doğrudan mod`,"codexAuth.accountModeDirectDesc":`İstekler yalnızca ana girişi kullanır.`,"codexAuth.accountPickerTitle":`Model seçiciden belirli bir Codex hesabını hedefleyin`,"codexAuth.accountPickerOffDesc":`Etkinleştirildiğinde, sıradan GPT seçici satırlarının yerini her hesap seçicisi için bir giriş alır, böylece çıkış yapmadan bir konuşma için tam hesabı seçebilirsiniz. Kapatılması hiçbir hesabı kaldırmaz.`,"codexAuth.accountPickerOnDesc":`Her seçici, kayıtlı bir hesap için genel bir etikettir. Bunu seçmek, konuşmayı eşlenen hesaba kilitler: asla dönmez veya yedek hesaba geçmez ve aktif Havuz hesabını değiştirmez.`,"codexAuth.accountPickerCompatibility":`Yerleşik Codex Uygulama girişinin kendi seçicisi vardır; oluşturulan haritalar normalde bunu main olarak adlandırır ve gerektiğinde main-2 gibi çakışmasız bir son ek kullanır. Eklenen hesaplar kararlı ve gizlilik açısından güvenli etiketler alırken, özel seçici etiketleri değişmeden kalır. Mevcut konuşmalar ve kaydedilmiş model seçimleri yönlendirilmeye devam eder. Bunu kapatmak oluşturulan girişleri gizler ancak seçicileri ve tam rotaları korur. Yalın GPT model kimlikleri Havuz veya Doğrudan davranışlarını sürdürür.`,"codexAuth.accountPickerUpdated":`Hesap hedefleme güncellendi.`,"codexAuth.accountPickerUpdateFailed":`Hesap hedefleme güncellenemedi. Son doğrulanan ayar gösteriliyor.`,"codexAuth.accountPickerLoadFailed":`Hesap hedefleme ayarı yüklenemedi.`,"codexAuth.accountPickerRefreshFailed":`Bu ayar yenilenemedi. Son doğrulanan değer hâlâ gösteriliyor.`,"codexAuth.advancedSettings":`Gelişmiş ayarlar`,"codexAuth.advancedSettingsAria":`Gelişmiş Codex Auth ayarlarını göster veya gizle`,"codexAuth.catalogRefreshPending":`Değişiklik kaydedildi ancak Codex model kataloğunun yenilenmesi bekleniyor. Yeniden denemek için ocx sync çalıştırın.`,"codexAuth.openaiMissing":`Yerleşik OpenAI sağlayıcısı yapılandırılmamış.`,"codexAuth.openaiDisabled":`Yerleşik OpenAI sağlayıcısı devre dışı.`,"codexAuth.openaiUnavailableDesc":`OpenAI hesaplarınız kullanılabilir.`,"codexAuth.enableOpenai":`OpenAI'yi Etkinleştir`,"codexAuth.enablingOpenai":`Etkinleştiriliyor...`,"codexAuth.enableOpenaiFailed":`OpenAI sağlayıcısı etkinleştirilemedi.`,"codexAuth.openaiPresetLoadFailed":`Ayar yüklenemedi.`,"codexAuth.openaiPresetUnavailable":`Ayar kullanılamıyor.`,"codexAuth.openProviders":`Sağlayıcıları Aç`,"codexAuth.add":`Ekle`,"codexAuth.refreshQuota":`Kotaları yenile`,"codexAuth.refreshingQuota":`Yenileniyor...`,"codexAuth.quotaRefreshed":`Kotalar yenilendi`,"codexAuth.quotaRefreshFailed":`Kotalar yenilenemedi`,"codexAuth.pauseExhausted":`Tükenenleri duraklat`,"codexAuth.pausingExhausted":`Kotalar kontrol ediliyor...`,"codexAuth.pauseExhaustedSucceeded":`Limitteki hesaplar duraklatıldı: {count}`,"codexAuth.pauseExhaustedNone":`%100 kullanımı doğrulanmış hesap yok.`,"codexAuth.pauseExhaustedFailed":`Tükenen hesaplar kontrol edilemedi.`,"codexAuth.noPool":`Henüz havuz hesabı eklenmedi.`,"codexAuth.pause":`Duraklat`,"codexAuth.resume":`Devam Ettir`,"codexAuth.paused":`DURAKLATILDI`,"codexAuth.pauseSucceeded":`{email} duraklatıldı`,"codexAuth.resumeSucceeded":`{email} tekrar havuza alındı`,"codexAuth.pauseFailed":`{email} duraklatılamadı.`,"codexAuth.resumeFailed":`{email} devam ettirilemedi.`,"codexAuth.pausedHint":`Devam ettirilene kadar otomatik seçimden hariç tutulur.`,"codexAuth.pinned":`SABİTLENDİ`,"codexAuth.pinnedHint":`Bu hesabı elle seçtiniz.`,"codexAuth.fiveHour":`5saat`,"codexAuth.weekly":`Hafta`,"codexAuth.monthly":`30gün`,"codexAuth.resets":`sıfırlanma`,"codexAuth.today":`Bugün`,"codexAuth.current":`MEVCUT`,"codexAuth.nextSession":`SEÇİLEN`,"codexAuth.poolPrepared":`HAVUZ İÇİN HAZIRLANDI`,"codexAuth.preparePoolTitle":`Bu hesap Havuz modu için hazırlansın mı?`,"codexAuth.preparePoolDesc":`Doğrudan istekler ana girişi kullanmaya devam eder.`,"codexAuth.prepareForPool":`Havuz İçin Hazırla`,"codexAuth.poolPreparedToast":`{email} Havuz modu için hazırlandı`,"codexAuth.switchTitle":`Aktif hesap değiştirilsin mi?`,"codexAuth.switchDesc":`Anında yürürlüğe girer. Mevcut hesaba bağlı iş parçacıkları ve işlenmekte olan istekler yakalanan hesaplarını korur; yeni veya bağımsız istekler seçilen hesabın sıra kademesini kullanır ve aynı seçim sırasındaki hesaplar sırayla görev almaya devam eder.`,"codexAuth.cacheWarning":`Hesap değiştirildiğinde önbellek sıfırlanır.`,"codexAuth.setAsNext":`Sonraki istekte bu hesabı kullan`,"codexAuth.cancel":`İptal`,"codexAuth.switchBack":`Ana hesaba geri dönülsün mü?`,"codexAuth.switchBackDesc":`Anında yürürlüğe girer. Mevcut hesaba bağlı iş parçacıkları ve işlenmekte olan istekler yakalanan hesaplarını korur; yeni veya bağımsız istekler Uygulama giriş hesabınızın sıra kademesini kullanır ve aynı seçim sırasındaki hesaplar sırayla görev almaya devam eder.`,"codexAuth.autoSwitch":`Kullanıma dayalı proaktif geçiş`,"codexAuth.autoSwitchQuotaDesc":`Kota: %{threshold} veya üzeri kullanımda sonraki istek daha az kullanılan bir hesaba geçebilir.`,"codexAuth.autoSwitchQuotaOffDesc":`Kullanıma dayalı proaktif geçiş kapalı.`,"codexAuth.autoSwitchRoundRobinDesc":`Round-robin bu eşiği kullanmaz.`,"codexAuth.autoSwitchFillFirstDesc":`Kullanım %{threshold} eşiğini aşana kadar hesabı doldurun, ardından sonraki kullanılabilir hesaba geçin.`,"codexAuth.autoSwitchFillFirstOffDesc":`İlk doldurma modunda kullanım boşaltma noktası yok.`,"codexAuth.failureRecoveryNote":`Hata kurtarma ayrıdır.`,"codexAuth.autoSwitchThreshold":`Kullanım eşiği`,"codexAuth.autoSwitchThresholdAria":`Kullanım eşiği, yüzde`,"codexAuth.autoSwitchThresholdInc":`Kullanım eşiğini artır`,"codexAuth.autoSwitchThresholdDec":`Kullanım eşiğini azalt`,"codexAuth.autoSwitchLoadFailed":`Ayarlar yüklenemedi.`,"codexAuth.autoSwitchThresholdInvalid":`1 ile 100 arasında bir tam sayı girin`,"codexAuth.autoSwitchUpdated":`Proaktif geçiş güncellendi`,"codexAuth.autoSwitchUpdateFailed":`Geçiş güncellemesi doğrulanamadı.`,"codexAuth.requestUserInput":`Varsayılan modda kullanıcı girdisi iste`,"codexAuth.requestUserInputDesc":`Codex'in soru sormasına izin verir.`,"codexAuth.requestUserInputUpdated":`Özellik güncellendi.`,"codexAuth.requestUserInputUpdatedRestart":`Özellik güncellendi. Codex uygulamasını yeniden başlatın.`,"codexAuth.requestUserInputUpdateFailed":`Özellik güncellenemedi.`,"codexAuth.requestUserInputLoadFailed":`Özellik okunamadı.`,"anthropicPool.title":`Claude hesap havuzu (deneysel)`,"anthropicPool.enabledDesc":`Kullanım %{threshold} seviyesine ulaştığında sonraki anahtara geçin.`,"anthropicPool.disabledDesc":`Yalnızca aktif Claude hesabını kullanır.`,"anthropicPool.experimentalWarning":`Deneysel: Claude OAuth hesaplarını döndürmek desteklenmeyen bir kullanım yoludur ve Anthropic hesap kısıtlamalarına veya hesabın askıya alınmasına yol açabilir. Aynı kuruluşu paylaşan hesaplar oran limitlerini paylaşır ve döndürmeden ek kapasite kazanmaz. Riskleri anlamıyorsanız kapalı tutun.`,"anthropicPool.needTwoAccounts":`Havuzu etkinleştirmeden önce en az iki Claude OAuth hesabı ekleyin.`,"anthropicPool.threshold":`Yeni oturum kullanım eşiği`,"anthropicPool.thresholdAria":`Yeni oturum kullanım eşiği, yüzde`,"anthropicPool.thresholdHelp":`0 kota bazlı seçimi devre dışı bırakır. Varsayılan 80.`,"anthropicPool.thresholdInvalid":`0 ile 100 arasında bir tam sayı girin`,"anthropicPool.loadFailed":`Claude havuz ayarları yüklenemedi.`,"anthropicPool.saveFailed":`Claude havuz ayarları kaydedilemedi.`,"anthropicPool.on":`Açık`,"anthropicPool.off":`Kapalı`,"accountPool.strategy":`Rotasyon stratejisi`,"accountPool.strategyDesc":`OpenCodex'in yeni bir göreve nasıl hesap atayacağı.`,"accountPool.strategyQuota":`Kota`,"accountPool.strategyRoundRobin":`Round-robin`,"accountPool.strategyFillFirst":`İlk doldurma`,"accountPool.strategyHintQuota":`Kota kullanımı eşik aşıldığında hesabı değiştirebilir.`,"accountPool.strategyHintRoundRobin":`Round-robin yalnızca canlı bir hesap bağı olmayan yeni/bağımsız görevleri döndürür; mevcut görevler bağlı kalabilir ve kullanım eşiği normal rotasyonu değiştirmez.`,"accountPool.strategyHintFillFirst":`İlk doldurma eşiği boşaltma noktası olarak kullanır.`,"accountPool.unboundDefinition":`Bağlı olmayan yeni görev.`,"accountPool.stickyLimit":`Döndürmeden önceki sabit atamalar`,"accountPool.stickyLimitAria":`Döndürmeden önceki sabit atamalar`,"accountPool.stickyLimitInc":`Sabit limiti artır`,"accountPool.stickyLimitDec":`Sabit limiti azalt`,"accountPool.stickyLimitHelp":`Seçilen hesabı bu kadar yeni atama boyunca tutun.`,"accountPool.stickyLimitInvalid":`1 ile 100 arasında bir tam sayı girin`,"accountPool.strategyLoadFailed":`Strateji yüklenemedi.`,"accountPool.strategyUpdateFailed":`Strateji kaydedilemedi.`,"accountPool.priority":`Seçim sırası`,"accountPool.priorityAria":`Bu hesap için seçim sırası`,"accountPool.priorityHint":`Yüksek sayılar önce kullanılır.`,"accountPool.priorityFirst":`İlk`,"accountPool.priorityEarlier":`Daha önce`,"accountPool.priorityNormal":`Normal`,"accountPool.priorityLater":`Daha sonra`,"accountPool.priorityLast":`Son`,"accountPool.priorityOption":`{name} ({value})`,"accountPool.priorityCustom":`Özel`,"accountPool.priorityUpdated":`{email} için seçim sırası güncellendi`,"accountPool.priorityUpdateFailed":`{email} için öncelik güncellenemedi`,"codexAuth.switched":`Sonraki istek için {email} seçildi`,"codexAuth.loadFailed":`Codex hesap ayarları yüklenemedi.`,"codexAuth.switchFailed":`Hesap değiştirilemedi.`,"codexAuth.removeConfirm":`{id} kaldırılsın mı?`,"codexAuth.removeFailed":`Hesap kaldırılamadı.`,"codexAuth.addTitle":`Codex Hesabı Ekle`,"codexAuth.addIdLabel":`Hesap ID`,"codexAuth.addIdPlaceholder":`codex-is, codex-yedek...`,"codexAuth.resetCreditsAria":`{count} sıfırlama kredisi`,"codexAuth.addJsonLabel":`auth.json içeriği`,"codexAuth.addHelp":`Başka bir makineden kopyalayın.`,"codexAuth.importBtn":`İçe Aktar`,"codexAuth.importInvalidJson":`Geçersiz JSON`,"codexAuth.importMissingTokens":`Eksik jetonlar`,"codexAuth.importMissingId":`Hesap ID gereklidir`,"codexAuth.accountAdded":`Hesap havuza eklendi`,"codexAuth.addPickDesc":`Havuza eklemek için başka bir ChatGPT hesabı ile giriş yapın.`,"codexAuth.oauthLogin":`OAuth Girişi`,"codexAuth.oauthDesc":`Tarayıcıda ChatGPT girişini açar`,"codexAuth.importAuthJson":`auth.json İçe Aktar`,"codexAuth.importAuthJsonDesc":`Başka bir kurulumdan veya dışa aktarımdan`,"codexAuth.back":`Geri`,"codexAuth.oauthAlreadyInProgress":`Giriş zaten devam ediyor.`,"codexAuth.oauthWaiting":`Tarayıcıda girişin tamamlanması bekleniyor...`,"codexAuth.oauthSubmittingCode":`Kod gönderiliyor…`,"codexAuth.oauthCodeSubmitted":`Kod gönderildi — giriş bitmesi bekleniyor…`,"codexAuth.oauthStatusRetrying":`Durum kontrol edilirken hata — tekrar deneniyor…`,"codexAuth.oauthCancelled":`Giriş iptal edildi.`,"codexAuth.loginFailed":`Giriş başarısız oldu`,"codexAuth.needsReauth":`Tekrar Giriş Yap`,"codexAuth.reauthenticate":`Yeniden Doğrula`,"codexAuth.tokenExpired":`Jeton süresi doldu — hesabı yeniden doğrulayın`,"codexAuth.mainTokenExpired":`Jeton süresi doldu — tekrar giriş yapın`,"codexAuth.emailCollision":`Bu hesap ana girişinizle eşleşiyor.`,"codexAuth.resetCreditsTitle":`Kredileri Sıfırla`,"codexAuth.resetCreditsAvailable":`{count} sıfırlama krediniz var.`,"codexAuth.resetCreditsDesc":`Her kredi oran limitlerinizi anında sıfırlar.`,"codexAuth.noResetCredits":`Sıfırlama krediniz yok.`,"codexAuth.earnCreditsHint":`Krediler aylık ve tavsiye programı ile kazanılır.`,"codexAuth.creditsExpireNote":`Kredilerin süresi 30 gün içinde dolmaktadır.`,"codexAuth.useOneCredit":`1 Kredi Kullan`,"codexAuth.confirmResetTitle":`Sıfırlama Kredisi Kullanılsın mı?`,"codexAuth.confirmResetDesc":`Bu işlem oran limitlerinizi anında sıfırlayacaktır. {count} krediniz kaldı.`,"codexAuth.irreversible":`Bu işlem geri alınamaz.`,"codexAuth.useCredit":`Kredi Kullan`,"codexAuth.redeeming":`Sıfırlanıyor...`,"codexAuth.resetSuccess":`Oran limitleri sıfırlandı! Kalan kredi: {remaining}.`,"codexAuth.resetSuccessGeneric":`Oran limitleri sıfırlandı!`,"codexAuth.resetAlreadyRedeemed":`Bu kredi zaten kullanıldı.`,"codexAuth.resetNothingToReset":`Şu anda sıfırlanması gereken oran limiti yok.`,"codexAuth.resetNoCredit":`Kullanılabilir sıfırlama kredisi yok.`,"codexAuth.resetError":`Sıfırlama kredisi kullanılamadı.`,"codexAuth.fifoNote":`En eski kredi ilk önce kullanılır.`,"codexAuth.confirmWhichCredit":`{date} tarihli kredi kullanılacak.`,"codexAuth.creditNext":`Sonraki kullanılacak`,"codexAuth.creditLabel":`Kredi #{n}`,"codexAuth.creditNextBadge":`SONRAKİ`,"codexAuth.creditGranted":`Verildiği tarih {date}`,"codexAuth.creditExpires":`Son kullanma {date} ({days}gün kaldı)`,"api.title":`API Erişimi`,"api.subtitle":`Harici uygulamalardan opencodex proxy'sine erişmek için üretilen API anahtarlarını kullanın. Anahtarlar {authHeader} başlığı üzerinden kimlik doğrulaması yapar; her bir uç noktanın neleri kabul ettiğini görmek için aşağıdaki tabloya bakın.`,"api.baseUrl":`Taban URL`,"api.responsesEndpoint":`Responses API`,"api.chatCompletionsEndpoint":`Chat Completions API`,"api.messagesEndpoint":`Messages API`,"api.modelsEndpoint":`Models API`,"api.endpointNote":`OpenAI uyumlu istemcilerle taban URL'yi kullanın.`,"api.endpointsTitle":`Uç noktalar`,"api.authTitle":`Kimlik Doğrulama`,"api.authLoopback":`Geri döngü (loopback) bağlantıları (127.0.0.1 / ::1) kimlik doğrulamasını atlar. Harici/ağ istemcileri x-opencodex-api-key veya Authorization başlığında bir ocx_ API anahtarı ya da OPENCODEX_API_AUTH_TOKEN göndermelidir.`,"api.authBaseUrlNote":`İstemcileri taban URL ile yapılandırın.`,"api.newKeyTitle":`Yeni anahtar oluşturuldu`,"api.newKeyNote":`Bu anahtarı şimdi kopyalayın — tekrar gösterilmeyecektir.`,"api.copy":`Kopyala`,"api.copied":`Kopyalandı`,"api.dismiss":`Kapat`,"api.generateTitle":`Anahtar oluştur`,"api.keyNamePlaceholder":`Anahtar adı (isteğe bağlı)`,"api.generate":`Oluştur`,"api.generating":`Oluşturuluyor…`,"api.activeKeys":`Aktif anahtarlar ({count})`,"api.activeKeysLoading":`Aktif anahtarlar`,"api.noKeys":`Henüz API anahtarı yok. Yukarıdan bir tane oluşturun.`,"api.workspace.sections":`API bölümleri`,"api.section.keys":`Anahtarlar`,"api.section.connect":`Bağlan`,"api.section.endpoints":`Uç noktalar`,"api.section.models":`Modeller`,"api.section.examples":`Örnekler`,"api.workspace.details":`API anahtar detayları`,"api.workspace.keyDetails":`Anahtar detayları`,"api.workspace.keyPrefix":`Anahtar ön eki`,"api.workspace.deleteKey":`Anahtarı sil`,"api.workspace.deleteConfirm":`Bu API anahtarı silinsin mi? Bunu kullanan istemciler erişimi anında kaybedecektir. Bu işlem geri alınamaz.`,"api.workspace.usageExamples":`Kullanım örnekleri`,"api.copyUrlHint":`URL kopyalamak için tıklayın`,"api.urlCopied":`URL kopyalandı`,"api.copyExampleHint":`Örnek kopyalamak için tıklayın`,"api.exampleCopied":`Örnek kopyalandı`,"api.colName":`İsim`,"api.colKey":`Anahtar`,"api.colCreated":`Oluşturuldu`,"api.confirm":`Onayla`,"api.deleteAria":`API anahtarını sil`,"api.modelsTitle":`Harici model kataloğu`,"api.modelsCount":`{count} çağrılabilir`,"api.modelsLoading":`Modeller yükleniyor…`,"api.modelsSearch":`Modellerde ara`,"api.modelsSubtitle":`Uç noktalarınızla bu tam model ID'lerini kullanın.`,"api.modelsEmpty":`Henüz harici olarak çağrılabilir model yok.`,"api.modelsNoMatch":`“{query}” ile eşleşen model yok.`,"api.modelsLoadFailed":`Harici model kataloğu yüklenemedi.`,"api.colModel":`Model`,"api.colSource":`Kaynak`,"api.colProtocols":`Protokoller`,"api.sourceNative":`ChatGPT havuzu`,"api.sourceCombo":`Kombo rotası`,"api.sourceCustom":`Özel`,"api.protocolResponses":`Responses`,"api.protocolChatCompletions":`Chat Completions`,"api.protocolMessages":`Messages`,"api.copyModelId":`ID Kopyala`,"api.modelCopied":`Kopyalandı`,"api.testModel":`Test Et`,"api.testingModel":`Test ediliyor…`,"api.testSucceeded":`Tamam`,"api.testFailed":`Başarısız`,"api.usageChatTitle":`Chat Completions örneği`,"api.usageResponsesTitle":`Responses örneği`,"api.usageMessagesTitle":`Messages örneği`,"api.usageSampleInput":`Merhaba dünya!`,"api.clientConfig.title":`İstemci konfigürasyonu`,"api.clientConfig.rowsLabel":`Bir istemci bağlayın`,"api.clientConfig.details":`Detaylar`,"api.clientConfig.detailsAria":`{client} konfigürasyon detayları`,"api.clientConfig.copyAria":`{client} konfigürasyon JSON kopyala`,"api.clientConfig.downloadAria":`{client} konfigürasyonu indir`,"api.clientConfig.rowMeta":`{destination} · {count} model`,"api.clientConfig.rowError":`{client} konfigürasyonu oluşturulamadı.`,"api.clientConfig.copiedAnnounceClient":`{client} konfigürasyon JSON panoya kopyalandı.`,"api.clientConfig.clientOpencode":`OpenCode`,"api.clientConfig.clientPi":`Pi`,"api.clientConfig.clientHermes":`Hermes`,"api.clientConfig.clientOpenclaw":`OpenClaw`,"api.clientConfig.clientKimi":`Kimi Code`,"api.clientConfig.clientGajae":`Gajae Code`,"api.clientConfig.clientDsh":`DeepSeek Harness (DSH)`,"api.clientConfig.clientMcode":`MiniMax Code`,"api.clientConfig.copy":`JSON Kopyala`,"api.clientConfig.download":`İndir`,"api.clientConfig.loading":`İstemci konfigürasyonu oluşturuluyor…`,"api.clientConfig.jsonLabel":`{client} konfigürasyon JSON`,"api.clientConfig.destination":`Hedef dosya`,"api.clientConfig.envHint":`Başlatmadan önce anahtarı ayarlayın`,"api.clientConfig.mergeWarning":`Bunu hedef dosyaya birleştirin. Dosyanın üzerine yazıp değiştirmek, diğer sağlayıcılarınızı ve MCP ayarlarınızı silecektir.`,"api.clientConfig.modelCount":`{count} model dışa aktarıldı`,"api.clientConfig.missingLimits":`{total} modelden {count} tanesi bağlam sınırı olmadan gönderildi.`,"api.clientConfig.noKeyYet":`{env} arkasında henüz anahtar yok.`,"api.clientConfig.loadFailed":`Model listesi okunamadı.`,"api.clientConfig.copiedAnnounce":`İstemci konfigürasyonu JSON panoya kopyalandı.`,"api.clientConfig.copyFailed":`Kopyalanamadı.`,"api.clientConfig.downloadedAnnounce":`{filename} indirildi. Henüz hiçbir şey değişmedi — kendiniz {destination} konumuna birleştirin.`,"api.clientConfig.whereDisclosure":`Bu dosya nereye gidiyor`,"api.clientConfig.whereBody":`Yukarıdaki hedef genel (global) yoldur. Çalışma dizinindeki projeye özel bir konfigürasyon dosyası buna öncelik eder ve istemci anahtarı bu dosyadan değil, konfigürasyonda belirtilen çevre değişkeninden okur.`,"api.clientConfig.clientOmp":`OMP`,"api.keysLoadFailed":`API anahtarları yüklenemedi.`,"api.createFailed":`API anahtarı oluşturulamadı.`,"api.deleteFailed":`API anahtarı silinemedi.`,"api.auth.endpoint":`Uç nokta`,"api.auth.required":`Gerekli`,"api.auth.accepted":`Kabul edildi`,"api.auth.rejected":`Kabul edilmedi`,"api.auth.testProtocol":`{protocol} Test Et`,"api.auth.testNeedsFreshKey":`Test için bir anahtar oluşturun.`,"api.key.name":`Anahtar adı`,"api.key.rename":`Yeniden adlandır`,"api.key.saveName":`İsmi kaydet`,"api.key.renaming":`Kaydediliyor…`,"api.key.renameFailed":`Yeniden adlandırılamadı.`,"api.key.deleting":`Siliniyor…`,"api.key.copyFailed":`Otomatik kopyalanamadı. Kapatmadan önce anahtarı manuel olarak seçip kopyalayın — tekrar gösterilmeyecektir.`,"api.attribution.title":`Atfedilen kullanım`,"api.attribution.requests7d":`Son 7 gün istekleri`,"api.attribution.totalRequests":`Toplam atfedilen istekler`,"api.attribution.totalRequestsAvailable":`Mevcut geçmişteki istekler`,"api.attribution.sinceAvailable":`Mevcut atıf başlangıcı`,"api.attribution.lastUsed":`Son kullanım`,"api.attribution.since":`Atıf başlangıcı`,"api.attribution.neverUsed":`Henüz kullanılmadı`,"api.attribution.unavailable":`Kullanım mevcut değil`,"api.attribution.unavailableDetail":`Henüz kullanım atfedilmedi.`,"api.attribution.ambiguous":`İki anahtar aynı ID'yi paylaşıyor.`,"api.attribution.railAmbiguous":`mükerrer ID`,"claude.subtitle":`Claude Code içinde GPT, Gemini ve diğer modelleri kullanın.`,"claude.pageTitle":`Claude Code`,"claude.workspace.settings":`Ayarlar`,"claude.enabledLabel":`Claude bağlantısı`,"claude.enabledHint":`Kapalı olduğunda Claude Code bu proxy'yi kullanamaz.`,"claude.authMode":`Kimlik Doğrulama Modu`,"claude.authModeHint":`Abonelik Claude hesabı gerektirir, Proxy modunda gerekmez`,"claude.authModeSubscription":`Abonelik (Claude hesabı)`,"claude.authModeProxy":`Proxy (hesap gerekmez)`,"claude.authModeAuto":`Otomatik (Claude doğrulamasını algıla)`,"claude.effectiveMode.label":`Sonraki başlatmada geçerli`,"claude.effectiveMode.manual":`Manuel: {mode}`,"claude.effectiveMode.autoPresent":`Otomatik: abonelik — {source} üzerinden Claude kimliği bulundu`,"claude.effectiveMode.autoAbsent":`Otomatik: proxy modu — Claude kimliği bulunamadı`,"claude.effectiveMode.autoUnknown":`Otomatik: abonelik — doğrulanamadı`,"claude.effectiveMode.admissionKey":`Bu proxy'nin API anahtarı hâlâ gönderiliyor.`,"claude.authSource.claude-json-oauth":`Claude hesabı`,"claude.authSource.claude-credentials-file":`kimlik bilgileri dosyası`,"claude.authSource.macos-keychain":`macOS Keychain`,"claude.authSource.exported-env":`ortam değişkeni`,"claude.authSource.unknown":`algılanan bir kimlik bilgisi`,"claude.systemEnv":`Otomatik bağlan`,"claude.systemEnvDesc":`Açık olduğunda terminalde claude çalıştırmak proxy üzerinden geçer.`,"claude.systemEnvUnsupported":`Otomatik bağlanma yalnızca macOS üzerinde kullanılabilirdir. Bu sistemde Claude'u {cmd} ile başlatın.`,"claude.systemEnvWarn":`⚠ Terminal uygulamasını tamamen kapatıp yeniden açmalısınız.`,"claude.fastMode":`Hızlı Mod (OpenAI)`,"claude.fastModeDesc":`OpenAI modelleri için service_tier ayarını kontrol eder.`,"claude.fastAuto":`Otomatik`,"claude.fastOn":`AÇIK`,"claude.fastOff":`KAPALI`,"claude.autoContext":`Otomatik büyük bağlam kullan`,"claude.autoContextDesc":`1M işaretinin ne kadar ileri gideceğini kontrol eder. AÇIK: 200k jeton üzerindeki her model (GPT modelleri vb.) 1M aralığı kazanır. KAPALI: yalnızca gerçek 1M modelleri alır.`,"claude.autoContextInert":`Pasif durumdadır çünkü konfigürasyon dosyasında eski bir bağlam boyutu değeri (maxContextTokens) var. Yeniden etkinleştirmek için oradan kaldırın.`,"claude.autoCompactWindow":`Otomatik özetleme noktası`,"claude.autoCompactDefault":`350k (varsayılan)`,"claude.autoCompactWindowDesc":`Sohbet bu noktaya ulaştığında eski mesajlar özetlenir. Her modelin kendi sınırını asla aşmaz, bu nedenle 200k modeller etkilenmez.`,"claude.autoCompactWindowWarn":`Bunu değiştirmek GPT modellerini bozabilir — bir modelin gerçek sınırından daha yüksek ayarlanırsa, sohbetler özet devreye girmeden önce hata verecektir.`,"claude.injectAgents":`Alt ajanları otomatik kaydet`,"claude.injectAgentsDesc":`Alt Ajanlar sekmesinde seçilen modelleri (ve mevcut varsayılan modeli) çağrılabilir Claude Code ajanları (ocx-*) olarak kaydeder. Sonraki oturumdan itibaren uygulanır.`,"claude.webSearchSidecar":`Web arama yan araç geçersiz kılması`,"claude.webSearchSidecarHint":`Claude Code istekleri için ana web arama sidecar'ını geçersiz kılın.`,"claude.visionSidecar":`Görsel yan araç geçersiz kılması`,"claude.visionSidecarHint":`Claude Code istekleri için ana görsel sidecar'ını geçersiz kılın.`,"claude.useMainSetting":`Ana ayarı kullan`,"claude.sidecarModelPlaceholder":`Ana ayar modeli`,"claude.quickstart":`Başlarken`,"claude.quickstartHint":`{cmd} Claude Code'u proxy üzerinden açar. claude.ai girişiniz aktif kalır.`,"claude.manualEnv":`Manuel kurulum (gelişmiş)`,"claude.smallFastModel":`Arka plan yardımcı modeli`,"claude.smallFastModelHint":`Claude Code'un sohbet özetleri ve konu tespiti gibi arka plan işleri için kullandığı model. haiku alt ajan takma adı da bunu kullanır. Boş = Claude varsayılanı (Haiku).`,"claude.smallFastModelAccurateHint":`Claude Code'un sohbet özetleri ve konu tespiti gibi arka plan işleri için kullandığı model. haiku alt ajan takma adı da bunu kullanır.`,"claude.smallFastModelUnsetOption":`Bırakın Claude Code seçsin (yerel model)`,"claude.smallFastModelNativeWarning":`Ayarlanmadığında, OpenCodex yardımcı model geçersiz kılmalarını boş bırakır. Claude Code kendi yerel Sonnet modelini kullanabilir ve bu durum yerel sağlayıcınızdan ücret alınmasına yol açabilir.`,"claude.slotUnset":`Claude varsayılanını kullan`,"claude.modelMap":`Model yakalama`,"claude.modelMapHint":`Belirli bir model isteklerini yakalar ve seçtiğiniz modele yönlendirir.`,"claude.mapFrom":`Orijinal model (örn. claude-sonnet-4-5)`,"claude.mapTo":`Değiştirilecek model (örn. gemini/gemini-3-pro)`,"claude.addMapping":`Kural ekle`,"claude.removeMapping":`Kuralı kaldır`,"claude.aliases":`Kullanılabilir modeller`,"claude.aliasesHint":`Claude Code'un /model menüsünde görünen modeller.`,"claude.aliasProviderOther":`Diğer`,"claude.loading":`Yükleniyor…`,"claude.loadFail":`Claude ayarları yüklenemedi`,"claude.saved":`Kaydedildi.`,"claude.saveFailed":`Kaydetme başarısız`,"claude.networkError":`Ağ hatası — proxy çalışıyor mu?`,"claude.toggleAria":`Claude bağlantısını değiştir`,"claude.none":`Yok`,"cws.loading":`Kombolar yükleniyor…`,"cws.loadFailed":`Kombolar yüklenemedi.`,"cws.saveFailed":`Kombo kaydedilemedi.`,"cws.removeFailed":`Kombo kaldırılamadı.`,"cws.saved":`Kombo kaydedildi.`,"cws.created":`{model} oluşturuldu.`,"cws.removed":`combo/{id} kaldırıldı.`,"cws.renamed":`{from}, {to} olarak yeniden adlandırıldı.`,"cws.add":`Kombo ekle`,"cws.addTitle":`Kombo ekle`,"cws.addSubtitle":`Sağlayıcılar arasında sanal bir model oluşturun.`,"cws.create":`Kombo oluştur`,"cws.railAria":`Kombo listesi`,"cws.searchPlaceholder":`Kombolarda veya hedeflerde ara…`,"cws.noSearchResults":`Aramanızla eşleşen kombo yok.`,"cws.group.failover":`Yedekli (Failover)`,"cws.group.roundRobin":`Round-robin`,"cws.targetCount":`{count} hedef`,"cws.targetCountOne":`1 hedef`,"cws.overviewTitle":`Kombolar`,"cws.overviewBlurb":`Sağlayıcı/model hedefleri arasında devreden sanal modeller.`,"cws.count.total":`Toplam`,"cws.count.failover":`Failover`,"cws.count.roundRobin":`Round-robin`,"cws.howTitle":`Nasıl çalışır`,"cws.howBody":`Codex'ten kombonun kamuya açık model adını isteyin. Bir ad olmadan varsayılan combo/<id> şeklindedir. OpenCodex bir hedef seçer ve yalnızca yeniden denenebilir yukarı akış hatalarında atlar. Hiçbir hedef kullanılabilir kalmazsa, istek küresel varsayılan sağlayıcıyı kullanmak yerine kapalı olarak başarısız olur (fail closed).`,"cws.attentionTitle":`Dikkat gerekiyor`,"cws.attention.empty":`Yapılandırılmış hedef yok`,"cws.attention.few":`Yalnızca bir hedef — geçiş yapılacak yer yok`,"cws.attention.catalogOmitted":`Model kataloğunda eksik — üye yetenekleri eksik veya uyumsuz (eksik bağlam penceresi / meta veri veya boş modalite kesişimi). Takma ada göre yönlendirme hâlâ çalışır`,"cws.emptyTitle":`İlk kombonuzu oluşturun`,"cws.empty.createDesc":`Sanal bir model adlandırın ve iki veya daha fazla arka ucu bağlayın.`,"cws.backToAll":`Tüm kombolara dön`,"cws.allCombos":`Tüm kombolar`,"cws.copyModel":`ID kopyala`,"cws.copied":`Kopyalandı`,"cws.tabsLabel":`Kombo detay bölümleri`,"cws.tab.config":`Konfigürasyon`,"cws.tab.about":`Hakkında`,"cws.strategy":`Strateji`,"cws.strategy.failover":`Yedekli (Failover)`,"cws.strategy.roundRobin":`Round-robin`,"cws.strategy.failoverHint":`Hedefleri sırayla deneyin. İlk hedef yeniden denenebilir bir hatayla (oran sınırı, kesinti, abonelik engeli) başarısız olursa sonraki hedefe atlayın.`,"cws.strategy.roundRobinHint":`Trafiği ağırlığa göre kararlı bir şekilde dengeleyin. Seçilen her hedefi bir dizi başarılı istek boyunca tutun, ardından ilerleyin.`,"cws.field.id":`Kombo ID`,"cws.field.idHint":`İstemciler {model} isteyecek`,"cws.field.idInternalHint":`Dahili kombo ID. Oluşturduktan sonra değiştirebilirsiniz.`,"cws.field.idHintEdit":`Yeniden adlandırmak komboyu yeni bir ID'ye taşır. İstemciler {model} ister.`,"cws.field.alias":`Genel model adı`,"cws.field.aliasPlaceholder":`deepseek-v4-flash veya üretici/model`,"cws.field.aliasHint":`İsteğe bağlı. Ön eki olmayan yalın bir ad, üretici/model gibi özel bir ön ek kullanın veya combo/<id> kullanmak için boş bırakın.`,"cws.field.nativeAlias":`Yerel OpenAI takma adı`,"cws.field.nativeAliasHint":`Bu kombonun desteklenen nitelemesiz yerel bir OpenAI model kimliğine sahip olmasına izin verin. Hesap ve sağlayıcı nitelikli OpenAI rotaları ayrı kalır.`,"cws.field.displayName":`Görünen ad`,"cws.field.displayNameHint":`Bu kombo için seçici etiketi. Yerel OpenAI takma adı etkinleştirildiğinde gereklidir.`,"cws.field.stickyLimit":`Döndürmeden önceki sabit başarılar`,"cws.field.stickyLimitHint":`Ağırlıklı seçici ilerlemeden önce seçilen hedefi bu kadar başarılı istek boyunca tutun.`,"cws.field.defaultEffort":`Varsayılan akıl yürütme`,"cws.field.defaultEffortNone":`Yok (hedef varsayılanı)`,"cws.field.defaultEffortHint":`Yalnızca istemci akıl yürütme çabasını belirtmediğinde (atladığında) kullanılır. Seçenekler, seçilen hedeflerin duyurulan çabalarının kesişimidir; katalog çaba meta verisi olmayan hedefler hiçbir seçenek sunmaz.`,"cws.capability.imageInputUnavailable":`Seçilen tüm hedefler görsel girişini destekleyene kadar kullanılamaz.`,"cws.capability.imageInputHint":`Tüm hedefler görselleri desteklediğinde varsayılan olarak açıktır. Yalnızca metin kabul etmek için kapatın.`,"cws.capability.imageInput":`Görsel / çok modlu`,"cws.capabilities":`Yetenekler`,"cws.field.defaultEffortUnsupported":`Bu çaba hedeflerin ortak merdiveninde yok — istek anında yok sayılacak veya uydurulacaktır.`,"cws.field.defaultEffortUnsupportedOption":`kesişimde değil`,"cws.targets":`Hedefler`,"cws.targets.failoverHint":`Sıralama önemlidir — birincil olan ilktir.`,"cws.targets.roundRobinHint":`Ağırlıklar kararlı bağıntılı seçimi kontrol eder; sıralama rotasyon halkasındaki eşitlikleri bozar.`,"cws.target.provider":`Sağlayıcı`,"cws.target.model":`Model`,"cws.target.weight":`Ağırlık`,"cws.target.pickProvider":`Sağlayıcı seçin…`,"cws.target.pickProviderFirst":`Önce bir sağlayıcı seçin…`,"cws.target.pickModel":`Model seçin…`,"cws.target.noModels":`Bu sağlayıcı için model yok`,"cws.target.modelPlaceholder":`model ID`,"cws.target.add":`Hedef ekle`,"cws.target.drag":`Yeniden sıralamak için sürükleyin`,"cws.target.moveUp":`Yukarı taşı`,"cws.target.moveDown":`Aşağı taşı`,"cws.aboutTitle":`Çalışma zamanı`,"cws.aboutBody":`Başarısız hedefler Retry-After süresine uyarak kısa süreliğine soğumaya alınır. Geçersiz istek veya bağlam (context) hataları diğer hedefe atlamaz. Her hedef çabayı kendi yeteneklerine uyarlar; tükenen kombolar kapalı olarak başarısız olur (fail closed). Günlükler ve Kullanım bölümü sıralı fiziksel denemeleri ve deneme başına kullanımı saklar.`,"cws.removeConfirmTitle":`{model} kaldırılsın mı?`,"cws.removeConfirmDesc":`Bu işlem sanal modeli konfigürasyondan ve Codex kataloğundan kaldırır. Hiçbir sağlayıcıyı silmez.`,"cws.unsavedTitle":`Kaydedilmemiş değişiklikler`,"cws.unsavedDesc":`Düzenlemelerden vazgeçip devam edilsin mi?`,"cws.keepEditing":`Düzenlemeye devam et`,"cws.err.missingId":`Kombo ID gereklidir.`,"cws.err.invalidId":`ID harf veya sayı ile başlamalıdır.`,"cws.err.duplicateId":`Bu ID ile bir kombo zaten var.`,"cws.err.invalidAlias":`Takma ad geçerli karakterler içermelidir.`,"cws.err.aliasReservedNamespace":`Takma ad ayrılmış namespace kullanamaz.`,"cws.err.aliasNativeFamily":`Yerel OpenAI isimlerine izin verilmez.`,"cws.err.unsupportedNativeAlias":`Yerel takma ad, şu anda desteklenen yalın bir OpenAI model kimliği olmalıdır.`,"cws.err.missingNativeAliasDisplayName":`Yerel takma adlar için bir görünen ad gereklidir.`,"cws.err.invalidDisplayName":`Görünen ad en fazla 128 karakter olmalı ve kontrol karakteri içermemelidir.`,"cws.err.duplicateAlias":`Başka bir kombo bu takma adı zaten kullanıyor.`,"cws.err.noTargets":`En az bir hedef ekleyin.`,"cws.err.incompleteTarget":`Her hedefin bir sağlayıcısı ve modeli olmalıdır.`,"cws.target.disabled":`{name} (devre dışı)`,"cws.err.reservedNamespace":`Önce fiziksel sağlayıcı yeniden adlandırılmalıdır.`,"cws.err.providerCollision":`Kombo ID'si bir sağlayıcı adı ile çakışıyor.`,"cws.err.unknownProvider":`Her hedef yapılandırılmış bir sağlayıcı kullanmalıdır.`,"cws.err.duplicateTarget":`Aynı hedef yalnızca bir kez görünebilir.`,"cws.err.invalidStickyLimit":`Limit 1 ile 100 arasında bir tam sayı olmalıdır.`,"cws.err.invalidWeight":`Ağırlık 1 ile 10000 arasında olmalıdır.`,"cws.err.noEnabledTarget":`En az bir hedef etkin bir sağlayıcı kullanmalıdır.`,"claude.tabsLabel":`Claude istemcisi`,"claude.tabCode":`Code`,"claude.tabDesktop":`Desktop`,"claudeDesktop.title":`Claude Desktop`,"claudeDesktop.subtitle":`Claude model ailelerini {port} portundaki bir modele yönlendirin.`,"claudeDesktop.importJson":`JSON İçe Aktar`,"claudeDesktop.exportJson":`JSON Dışa Aktar`,"claudeDesktop.loading":`Claude Desktop profili yükleniyor…`,"claudeDesktop.loadFail":`Claude Desktop profili yüklenemedi.`,"claudeDesktop.retry":`Tekrar Dene`,"claudeDesktop.saveFailed":`Claude Desktop profili kaydedilemedi.`,"claudeDesktop.applyFailed":`Profil kaydedildi ancak uygulanamadı.`,"claudeDesktop.updateFailed":`Güncelleme başarısız oldu.`,"claudeDesktop.savedApplied":`Profil kaydedildi ve uygulandı.`,"claudeDesktop.appliedMarkerUnsaved":`Profil uygulandı ancak işaretçi kaydedilmedi.`,"claudeDesktop.savedAppliedAnnounce":`Profil kaydedildi ve uygulandı.`,"claudeDesktop.saved":`Profil kaydedildi.`,"claudeDesktop.savedAnnounce":`Profil kaydedildi.`,"claudeDesktop.exported":`Profil JSON olarak dışa aktarıldı.`,"claudeDesktop.importExpected":`Sürüm 1 profili bekleniyordu.`,"claudeDesktop.importReady":`JSON içe aktarıldı.`,"claudeDesktop.importedAnnounce":`Profil JSON içe aktarıldı.`,"claudeDesktop.importInvalid":`Seçilen dosya geçerli bir profil değil.`,"claudeDesktop.importFailed":`İçe aktarma başarısız oldu. {error}`,"claudeDesktop.moved":`{route}, {family} ailesine taşındı.`,"claudeDesktop.unsaved":`Kaydedilmemiş değişiklikler`,"claudeDesktop.upToDate":`Profil güncel`,"claudeDesktop.saving":`Kaydediliyor…`,"claudeDesktop.applying":`Uygulanıyor…`,"claudeDesktop.saveApply":`Kaydet & uygula`,"claudeDesktop.emptyTitle":`Kullanılabilir model yok`,"claudeDesktop.emptyHint":`Bir sağlayıcı ekleyin veya etkinleştirin.`,"claudeDesktop.assignmentsLabel":`Claude model ailesi atamaları`,"claudeDesktop.family.opus":`Opus`,"claudeDesktop.family.fable":`Fable`,"claudeDesktop.family.sonnet":`Sonnet`,"claudeDesktop.family.haiku":`Haiku`,"claudeDesktop.modelCountOne":`{count} model`,"claudeDesktop.modelCountMany":`{count} model`,"claudeDesktop.chooseDefault":`Bir varsayılan seçin`,"claudeDesktop.temporaryDefault":`Geçici varsayılan`,"claudeDesktop.laneEmpty":`Buraya bir model sürükleyin.`,"claudeDesktop.laneNoMatch":`Bu ailede aramanızla eşleşen model yok.`,"nav.grok":`Grok`,"grok.title":`Grok Build`,"grok.subtitle":`opencodex'in Grok konfigürasyonunuza kaydettiği modeller.`,"grok.loading":`Grok durumu yükleniyor…`,"grok.loadFail":`Grok konfigürasyonu okunamadı.`,"grok.notConfiguredTitle":`Grok Build henüz bağlanmadı`,"grok.notConfiguredHint":`Proxy'yi Grok yüklüyken başlatın.`,"grok.endpoint":`Uç nokta`,"grok.colModel":`Model`,"grok.colAlias":`Grok takma adı`,"grok.colContext":`Bağlam`,"grok.groupNative":`Yerel modeller`,"grok.groupRouted":`Yönlendirilen modeller`,"grok.enabledCount":`{total} modelden {on} tanesi kayıtlı`,"grok.saved":`Seçim kaydedildi.`,"grok.savedApplied":`Seçim kaydedildi ve Grok konfigürasyonuna yazıldı.`,"grok.saveFailed":`Grok seçimi kaydedilemedi.`,"grok.applyFailed":`Seçim kaydedildi ancak Grok güncellenemedi.`,"grok.applySkipped":`Seçim kaydedildi.`,"grok.saveApply":`Kaydet & uygula`,"grok.saving":`Kaydediliyor…`,"grok.applying":`Uygulanıyor…`,"grok.unsaved":`Kaydedilmemiş değişiklikler`,"grok.upToDate":`Seçim güncel`,"grok.toggleModel":`{id} modelini Grok ile kaydet`,"claudeDesktop.available":`Kullanılabilir`,"claudeDesktop.defaultBadge":`Varsayılan`,"claudeDesktop.supports1m":`1M`,"claudeDesktop.unavailable":`Kullanılamıyor`,"claudeDesktop.contextM":`{n}M bağlam`,"claudeDesktop.contextK":`{n}k bağlam`,"claudeDesktop.contextUnknown":`bağlam bilinmiyor`,"claudeDesktop.alias":`Takma Ad`,"claudeDesktop.useAsDefault":`{family} varsayılanı olarak kullan`,"claudeDesktop.moveTo":`Şuraya taşı`,"claudeDesktop.move":`Taşı`,"claudeDesktop.status.applied":`Desktop'a Uygulandı`,"claudeDesktop.status.stale":`Konfigürasyon eski — tekrar uygulayın`,"claudeDesktop.status.notApplied":`Uygulanmadı`,"claudeDesktop.status.notActiveProfile":`Desktop başka bir profil kullanıyor`,"claudeDesktop.status.disabled":`Claude Desktop entegrasyonu kapalı.`,"claudeDesktop.enableApply":`Etkinleştir ve uygula`,"claudeDesktop.health.lastRequest":`Son istek`,"claudeDesktop.health.stats":`{count} istek / {errors} hata`,"claudeDesktop.effort.supported":`çaba`,"claudeDesktop.effort.displayOnly":`çaba (yalnızca ekran)`,"lab.title":`Compatibility Lab`,"lab.subtitle":`Read-only compatibility verdict matrix from lab projection evidence.`,"lab.loadFailed":`Could not load compatibility lab data`,"lab.projectionUnavailable":`Lab projection is not available. Run conformance or live probes first.`,"lab.projectionIncompatible":`Lab projection schema is incompatible. Rebuild the projection.`,"lab.statusTitle":`Projection status`,"lab.matrixTitle":`Compatibility matrix`,"lab.verdictsTitle":`Verdict records`,"lab.filter.layer":`Evidence layer`,"lab.filter.verdict":`Verdict`,"lab.filter.subject":`Subject ID`,"lab.filter.all":`All`,"lab.col.subject":`Subject`,"lab.col.layer":`Layer`,"lab.col.suite":`Suite`,"lab.col.verdict":`Verdict`,"lab.col.asOf":`As of`,"lab.col.protocol":`Protocol conformance`,"lab.col.live":`Live route compatibility`,"lab.col.task":`Task effectiveness`,"lab.empty":`No compatibility verdicts in the projection yet.`,"lab.subjectKind":`Kind`,"lab.observationCount":`Observations`,"lab.eventCount":`Events`,"lab.verdictCount":`Verdicts`,"lab.subjectCount":`Subjects`,"lab.builtAt":`Built`,"lab.loading":`Loading compatibility evidence…`,"lab.loadMore":`Load more`,"lab.detailTitle":`Verdict detail`,"lab.detailClose":`Close`,"lab.detailSubject":`Subject`,"lab.detailObservations":`Observations`,"lab.detailEvents":`Contributing events`,"lab.detailArtifacts":`Artifact metadata`,"lab.production.title":`Gözlemlenen üretim trafiği`,"lab.production.notVerification":`Lab doğrulaması değildir`,"lab.production.attempts":`Denemeler`,"lab.production.successes":`Başarılı denemeler`,"lab.production.routeErrors":`Rota hataları`,"lab.production.lastObserved":`Son gözlem`,"lab.detailLoadFailed":`Could not load verdict detail`,"lab.refresh":`Refresh`,"lab.verdict.UNKNOWN":`Unknown`,"lab.verdict.CLAIMED":`Claimed`,"lab.verdict.PROBED":`Probed`,"lab.verdict.VERIFIED":`Verified`,"lab.verdict.DEGRADED":`Degraded`,"lab.verdict.BLOCKED":`Blocked`,"lab.verdict.UNSUPPORTED":`Unsupported`,"lab.layer.protocol_conformance":`Protocol conformance`,"lab.layer.live_route_compatibility":`Live route compatibility`,"lab.layer.task_effectiveness":`Task effectiveness`,"dash.visionAdvanced":`Gelişmiş ayarlar`,"dash.visionMaxDescriptions":`Tur başına en fazla açıklama`,"dash.visionMaxDescriptionsInvalid":`Pozitif bir tam sayı girin.`,"dash.visionTimeout":`Zaman aşımı`,"dash.visionTimeoutInvalid":`{min} ile {max} milisaniye arasında bir tam sayı girin.`,"dash.visionAdvancedPopover":`Gelişmiş görsel ayarları`},Ie={en:{"lab.title":`Compatibility Lab`,"lab.subtitle":`Read-only compatibility verdict matrix from lab projection evidence.`,"lab.loadFailed":`Could not load compatibility lab data`,"lab.projectionUnavailable":`Lab projection is not available. Run conformance or live probes first.`,"lab.projectionIncompatible":`Lab projection schema is incompatible. Rebuild the projection.`,"lab.statusTitle":`Projection status`,"lab.matrixTitle":`Compatibility matrix`,"lab.verdictsTitle":`Verdict records`,"lab.filter.layer":`Evidence layer`,"lab.filter.verdict":`Verdict`,"lab.filter.subject":`Subject ID`,"lab.filter.all":`All`,"lab.col.subject":`Subject`,"lab.col.layer":`Layer`,"lab.col.suite":`Suite`,"lab.col.verdict":`Verdict`,"lab.col.asOf":`As of`,"lab.col.protocol":`Protocol conformance`,"lab.col.live":`Live route compatibility`,"lab.col.task":`Task effectiveness`,"lab.empty":`No compatibility verdicts in the projection yet.`,"lab.subjectKind":`Kind`,"lab.observationCount":`Observations`,"lab.eventCount":`Events`,"lab.verdictCount":`Verdicts`,"lab.subjectCount":`Subjects`,"lab.builtAt":`Built`,"lab.loading":`Loading compatibility evidence…`,"lab.loadMore":`Load more`,"lab.detailTitle":`Verdict detail`,"lab.detailClose":`Close`,"lab.detailSubject":`Subject`,"lab.detailObservations":`Observations`,"lab.detailEvents":`Evidence events`,"lab.detailArtifacts":`Artifact metadata`,"lab.detailLoadFailed":`Could not load verdict detail`,"lab.refresh":`Refresh`,"lab.verdict.UNKNOWN":`Unknown`,"lab.verdict.CLAIMED":`Claimed`,"lab.verdict.PROBED":`Probed`,"lab.verdict.VERIFIED":`Verified`,"lab.verdict.DEGRADED":`Degraded`,"lab.verdict.BLOCKED":`Blocked`,"lab.verdict.UNSUPPORTED":`Unsupported`,"lab.layer.protocol_conformance":`Protocol conformance`,"lab.layer.live_route_compatibility":`Live route compatibility`,"lab.layer.task_effectiveness":`Task effectiveness`},de:{"lab.title":`Kompatibilitäts-Labor`,"lab.subtitle":`Schreibgeschützte Kompatibilitätsmatrix aus den Evidenzen der Lab-Projektion.`,"lab.loadFailed":`Kompatibilitätsdaten konnten nicht geladen werden`,"lab.projectionUnavailable":`Die Lab-Projektion ist nicht verfügbar. Führe zuerst Konformitäts- oder Live-Probes aus.`,"lab.projectionIncompatible":`Das Schema der Lab-Projektion ist inkompatibel. Baue die Projektion neu auf.`,"lab.statusTitle":`Projektionsstatus`,"lab.matrixTitle":`Kompatibilitätsmatrix`,"lab.verdictsTitle":`Urteilsdatensätze`,"lab.filter.layer":`Evidenzschicht`,"lab.filter.verdict":`Urteil`,"lab.filter.subject":`Subjekt-ID`,"lab.filter.all":`Alle`,"lab.col.subject":`Subjekt`,"lab.col.layer":`Schicht`,"lab.col.suite":`Suite`,"lab.col.verdict":`Urteil`,"lab.col.asOf":`Stand`,"lab.col.protocol":`Protokollkonformität`,"lab.col.live":`Live-Route-Kompatibilität`,"lab.col.task":`Aufgabenwirksamkeit`,"lab.empty":`In der Projektion gibt es noch keine Kompatibilitätsurteile.`,"lab.subjectKind":`Art`,"lab.observationCount":`Beobachtungen`,"lab.eventCount":`Ereignisse`,"lab.verdictCount":`Urteile`,"lab.subjectCount":`Subjekte`,"lab.builtAt":`Erstellt`,"lab.loading":`Kompatibilitätsevidenz wird geladen…`,"lab.loadMore":`Mehr laden`,"lab.detailTitle":`Urteilsdetails`,"lab.detailClose":`Schließen`,"lab.detailSubject":`Subjekt`,"lab.detailObservations":`Beobachtungen`,"lab.detailEvents":`Evidenzereignisse`,"lab.detailArtifacts":`Artefakt-Metadaten`,"lab.detailLoadFailed":`Urteilsdetails konnten nicht geladen werden`,"lab.refresh":`Aktualisieren`,"lab.verdict.UNKNOWN":`Unbekannt`,"lab.verdict.CLAIMED":`Behauptet`,"lab.verdict.PROBED":`Geprüft`,"lab.verdict.VERIFIED":`Verifiziert`,"lab.verdict.DEGRADED":`Eingeschränkt`,"lab.verdict.BLOCKED":`Blockiert`,"lab.verdict.UNSUPPORTED":`Nicht unterstützt`,"lab.layer.protocol_conformance":`Protokollkonformität`,"lab.layer.live_route_compatibility":`Live-Route-Kompatibilität`,"lab.layer.task_effectiveness":`Aufgabenwirksamkeit`},ko:{"lab.title":`호환성 랩`,"lab.subtitle":`랩 프로젝션 증거를 기반으로 한 읽기 전용 호환성 판정 매트릭스입니다.`,"lab.loadFailed":`호환성 랩 데이터를 불러오지 못했습니다`,"lab.projectionUnavailable":`랩 프로젝션을 사용할 수 없습니다. 먼저 적합성 또는 라이브 프로브를 실행하세요.`,"lab.projectionIncompatible":`랩 프로젝션 스키마가 호환되지 않습니다. 프로젝션을 다시 빌드하세요.`,"lab.statusTitle":`프로젝션 상태`,"lab.matrixTitle":`호환성 매트릭스`,"lab.verdictsTitle":`판정 레코드`,"lab.filter.layer":`증거 레이어`,"lab.filter.verdict":`판정`,"lab.filter.subject":`대상 ID`,"lab.filter.all":`전체`,"lab.col.subject":`대상`,"lab.col.layer":`레이어`,"lab.col.suite":`스위트`,"lab.col.verdict":`판정`,"lab.col.asOf":`기준 시각`,"lab.col.protocol":`프로토콜 적합성`,"lab.col.live":`라이브 경로 호환성`,"lab.col.task":`작업 효과성`,"lab.empty":`프로젝션에 아직 호환성 판정이 없습니다.`,"lab.subjectKind":`종류`,"lab.observationCount":`관측`,"lab.eventCount":`이벤트`,"lab.verdictCount":`판정`,"lab.subjectCount":`대상`,"lab.builtAt":`빌드 시각`,"lab.loading":`호환성 증거를 불러오는 중…`,"lab.loadMore":`더 불러오기`,"lab.detailTitle":`판정 상세`,"lab.detailClose":`닫기`,"lab.detailSubject":`대상`,"lab.detailObservations":`관측`,"lab.detailEvents":`증거 이벤트`,"lab.detailArtifacts":`아티팩트 메타데이터`,"lab.detailLoadFailed":`판정 상세를 불러오지 못했습니다`,"lab.refresh":`새로고침`,"lab.verdict.UNKNOWN":`알 수 없음`,"lab.verdict.CLAIMED":`주장됨`,"lab.verdict.PROBED":`프로브됨`,"lab.verdict.VERIFIED":`검증됨`,"lab.verdict.DEGRADED":`저하됨`,"lab.verdict.BLOCKED":`차단됨`,"lab.verdict.UNSUPPORTED":`지원되지 않음`,"lab.layer.protocol_conformance":`프로토콜 적합성`,"lab.layer.live_route_compatibility":`라이브 경로 호환성`,"lab.layer.task_effectiveness":`작업 효과성`},zh:{"lab.title":`兼容性实验室`,"lab.subtitle":`基于实验室投影证据的只读兼容性判定矩阵。`,"lab.loadFailed":`无法加载兼容性实验室数据`,"lab.projectionUnavailable":`实验室投影不可用。请先运行一致性探测或实时探测。`,"lab.projectionIncompatible":`实验室投影架构不兼容。请重新构建投影。`,"lab.statusTitle":`投影状态`,"lab.matrixTitle":`兼容性矩阵`,"lab.verdictsTitle":`判定记录`,"lab.filter.layer":`证据层`,"lab.filter.verdict":`判定`,"lab.filter.subject":`主体 ID`,"lab.filter.all":`全部`,"lab.col.subject":`主体`,"lab.col.layer":`层`,"lab.col.suite":`测试套件`,"lab.col.verdict":`判定`,"lab.col.asOf":`截至`,"lab.col.protocol":`协议一致性`,"lab.col.live":`实时路由兼容性`,"lab.col.task":`任务有效性`,"lab.empty":`投影中还没有兼容性判定。`,"lab.subjectKind":`类型`,"lab.observationCount":`观测`,"lab.eventCount":`事件`,"lab.verdictCount":`判定`,"lab.subjectCount":`主体`,"lab.builtAt":`构建时间`,"lab.loading":`正在加载兼容性证据…`,"lab.loadMore":`加载更多`,"lab.detailTitle":`判定详情`,"lab.detailClose":`关闭`,"lab.detailSubject":`主体`,"lab.detailObservations":`观测`,"lab.detailEvents":`证据事件`,"lab.detailArtifacts":`制品元数据`,"lab.detailLoadFailed":`无法加载判定详情`,"lab.refresh":`刷新`,"lab.verdict.UNKNOWN":`未知`,"lab.verdict.CLAIMED":`已声明`,"lab.verdict.PROBED":`已探测`,"lab.verdict.VERIFIED":`已验证`,"lab.verdict.DEGRADED":`降级`,"lab.verdict.BLOCKED":`已阻止`,"lab.verdict.UNSUPPORTED":`不支持`,"lab.layer.protocol_conformance":`协议一致性`,"lab.layer.live_route_compatibility":`实时路由兼容性`,"lab.layer.task_effectiveness":`任务有效性`},"zh-TW":{"lab.title":`相容性實驗室`,"lab.subtitle":`基於實驗室投影證據的唯讀相容性判定矩陣。`,"lab.loadFailed":`無法載入相容性實驗室資料`,"lab.projectionUnavailable":`實驗室投影不可用。請先執行一致性探測或即時探測。`,"lab.projectionIncompatible":`實驗室投影架構不相容。請重新建置投影。`,"lab.statusTitle":`投影狀態`,"lab.matrixTitle":`相容性矩陣`,"lab.verdictsTitle":`判定記錄`,"lab.filter.layer":`證據層`,"lab.filter.verdict":`判定`,"lab.filter.subject":`主體 ID`,"lab.filter.all":`全部`,"lab.col.subject":`主體`,"lab.col.layer":`層`,"lab.col.suite":`測試套件`,"lab.col.verdict":`判定`,"lab.col.asOf":`截至`,"lab.col.protocol":`協定一致性`,"lab.col.live":`即時路由相容性`,"lab.col.task":`任務有效性`,"lab.empty":`投影中還沒有相容性判定。`,"lab.subjectKind":`類型`,"lab.observationCount":`觀測`,"lab.eventCount":`事件`,"lab.verdictCount":`判定`,"lab.subjectCount":`主體`,"lab.builtAt":`建置時間`,"lab.loading":`正在載入相容性證據…`,"lab.loadMore":`載入更多`,"lab.detailTitle":`判定詳情`,"lab.detailClose":`關閉`,"lab.detailSubject":`主體`,"lab.detailObservations":`觀測`,"lab.detailEvents":`證據事件`,"lab.detailArtifacts":`產物中繼資料`,"lab.detailLoadFailed":`無法載入判定詳情`,"lab.refresh":`重新整理`,"lab.verdict.UNKNOWN":`未知`,"lab.verdict.CLAIMED":`已聲明`,"lab.verdict.PROBED":`已探測`,"lab.verdict.VERIFIED":`已驗證`,"lab.verdict.DEGRADED":`降級`,"lab.verdict.BLOCKED":`已封鎖`,"lab.verdict.UNSUPPORTED":`不支援`,"lab.layer.protocol_conformance":`協定一致性`,"lab.layer.live_route_compatibility":`即時路由相容性`,"lab.layer.task_effectiveness":`任務有效性`},ru:{"lab.title":`Лаборатория совместимости`,"lab.subtitle":`Матрица вердиктов совместимости только для чтения на основе данных проекции лаборатории.`,"lab.loadFailed":`Не удалось загрузить данные лаборатории совместимости`,"lab.projectionUnavailable":`Проекция лаборатории недоступна. Сначала выполните проверки соответствия или live-проверки.`,"lab.projectionIncompatible":`Схема проекции лаборатории несовместима. Перестройте проекцию.`,"lab.statusTitle":`Состояние проекции`,"lab.matrixTitle":`Матрица совместимости`,"lab.verdictsTitle":`Записи вердиктов`,"lab.filter.layer":`Слой доказательств`,"lab.filter.verdict":`Вердикт`,"lab.filter.subject":`ID субъекта`,"lab.filter.all":`Все`,"lab.col.subject":`Субъект`,"lab.col.layer":`Слой`,"lab.col.suite":`Набор`,"lab.col.verdict":`Вердикт`,"lab.col.asOf":`По состоянию на`,"lab.col.protocol":`Соответствие протоколу`,"lab.col.live":`Совместимость live-маршрута`,"lab.col.task":`Эффективность задач`,"lab.empty":`В проекции пока нет вердиктов совместимости.`,"lab.subjectKind":`Тип`,"lab.observationCount":`Наблюдения`,"lab.eventCount":`События`,"lab.verdictCount":`Вердикты`,"lab.subjectCount":`Субъекты`,"lab.builtAt":`Собрано`,"lab.loading":`Загрузка доказательств совместимости…`,"lab.loadMore":`Загрузить ещё`,"lab.detailTitle":`Детали вердикта`,"lab.detailClose":`Закрыть`,"lab.detailSubject":`Субъект`,"lab.detailObservations":`Наблюдения`,"lab.detailEvents":`События доказательств`,"lab.detailArtifacts":`Метаданные артефактов`,"lab.detailLoadFailed":`Не удалось загрузить детали вердикта`,"lab.refresh":`Обновить`,"lab.verdict.UNKNOWN":`Неизвестно`,"lab.verdict.CLAIMED":`Заявлено`,"lab.verdict.PROBED":`Проверено пробой`,"lab.verdict.VERIFIED":`Подтверждено`,"lab.verdict.DEGRADED":`Ограничено`,"lab.verdict.BLOCKED":`Заблокировано`,"lab.verdict.UNSUPPORTED":`Не поддерживается`,"lab.layer.protocol_conformance":`Соответствие протоколу`,"lab.layer.live_route_compatibility":`Совместимость live-маршрута`,"lab.layer.task_effectiveness":`Эффективность задач`},ja:{"lab.title":`互換性ラボ`,"lab.subtitle":`ラボ投影の証拠に基づく読み取り専用の互換性判定マトリクスです。`,"lab.loadFailed":`互換性ラボのデータを読み込めませんでした`,"lab.projectionUnavailable":`ラボ投影を利用できません。先に適合性プローブまたはライブプローブを実行してください。`,"lab.projectionIncompatible":`ラボ投影のスキーマに互換性がありません。投影を再構築してください。`,"lab.statusTitle":`投影ステータス`,"lab.matrixTitle":`互換性マトリクス`,"lab.verdictsTitle":`判定レコード`,"lab.filter.layer":`証拠レイヤー`,"lab.filter.verdict":`判定`,"lab.filter.subject":`サブジェクト ID`,"lab.filter.all":`すべて`,"lab.col.subject":`サブジェクト`,"lab.col.layer":`レイヤー`,"lab.col.suite":`スイート`,"lab.col.verdict":`判定`,"lab.col.asOf":`時点`,"lab.col.protocol":`プロトコル適合性`,"lab.col.live":`ライブ経路互換性`,"lab.col.task":`タスク有効性`,"lab.empty":`投影にはまだ互換性判定がありません。`,"lab.subjectKind":`種類`,"lab.observationCount":`観測`,"lab.eventCount":`イベント`,"lab.verdictCount":`判定`,"lab.subjectCount":`サブジェクト`,"lab.builtAt":`構築日時`,"lab.loading":`互換性の証拠を読み込み中…`,"lab.loadMore":`さらに読み込む`,"lab.detailTitle":`判定の詳細`,"lab.detailClose":`閉じる`,"lab.detailSubject":`サブジェクト`,"lab.detailObservations":`観測`,"lab.detailEvents":`証拠イベント`,"lab.detailArtifacts":`アーティファクトのメタデータ`,"lab.detailLoadFailed":`判定の詳細を読み込めませんでした`,"lab.refresh":`更新`,"lab.verdict.UNKNOWN":`不明`,"lab.verdict.CLAIMED":`申告済み`,"lab.verdict.PROBED":`プローブ済み`,"lab.verdict.VERIFIED":`検証済み`,"lab.verdict.DEGRADED":`低下`,"lab.verdict.BLOCKED":`ブロック`,"lab.verdict.UNSUPPORTED":`未対応`,"lab.layer.protocol_conformance":`プロトコル適合性`,"lab.layer.live_route_compatibility":`ライブ経路互換性`,"lab.layer.task_effectiveness":`タスク有効性`},tr:{"lab.title":`Uyumluluk Laboratuvarı`,"lab.subtitle":`Laboratuvar projeksiyonu kanıtlarından oluşturulan salt okunur uyumluluk karar matrisi.`,"lab.loadFailed":`Uyumluluk laboratuvarı verileri yüklenemedi`,"lab.projectionUnavailable":`Laboratuvar projeksiyonu kullanılamıyor. Önce uygunluk veya canlı probları çalıştırın.`,"lab.projectionIncompatible":`Laboratuvar projeksiyonu şeması uyumsuz. Projeksiyonu yeniden oluşturun.`,"lab.statusTitle":`Projeksiyon durumu`,"lab.matrixTitle":`Uyumluluk matrisi`,"lab.verdictsTitle":`Karar kayıtları`,"lab.filter.layer":`Kanıt katmanı`,"lab.filter.verdict":`Karar`,"lab.filter.subject":`Özne kimliği`,"lab.filter.all":`Tümü`,"lab.col.subject":`Özne`,"lab.col.layer":`Katman`,"lab.col.suite":`Paket`,"lab.col.verdict":`Karar`,"lab.col.asOf":`Tarih`,"lab.col.protocol":`Protokol uygunluğu`,"lab.col.live":`Canlı rota uyumluluğu`,"lab.col.task":`Görev etkinliği`,"lab.empty":`Projeksiyonda henüz uyumluluk kararı yok.`,"lab.subjectKind":`Tür`,"lab.observationCount":`Gözlemler`,"lab.eventCount":`Olaylar`,"lab.verdictCount":`Kararlar`,"lab.subjectCount":`Özneler`,"lab.builtAt":`Oluşturulma`,"lab.loading":`Uyumluluk kanıtları yükleniyor…`,"lab.loadMore":`Daha fazla yükle`,"lab.detailTitle":`Karar ayrıntısı`,"lab.detailClose":`Kapat`,"lab.detailSubject":`Özne`,"lab.detailObservations":`Gözlemler`,"lab.detailEvents":`Kanıt olayları`,"lab.detailArtifacts":`Artefakt meta verileri`,"lab.detailLoadFailed":`Karar ayrıntısı yüklenemedi`,"lab.refresh":`Yenile`,"lab.verdict.UNKNOWN":`Bilinmiyor`,"lab.verdict.CLAIMED":`İddia edildi`,"lab.verdict.PROBED":`Problandı`,"lab.verdict.VERIFIED":`Doğrulandı`,"lab.verdict.DEGRADED":`Kısıtlı`,"lab.verdict.BLOCKED":`Engellendi`,"lab.verdict.UNSUPPORTED":`Desteklenmiyor`,"lab.layer.protocol_conformance":`Protokol uygunluğu`,"lab.layer.live_route_compatibility":`Canlı rota uyumluluğu`,"lab.layer.task_effectiveness":`Görev etkinliği`}},Le={en:{subjectKindUnknown:`Unknown`,"artifact.present":`Present`,"artifact.corrupt":`Corrupt`,"artifact.purged_unavailable":`Purged / unavailable`,selectVerdict:`View verdict for {subject}`,"community.title":`Community evidence`,"community.notLocalVerdict":`Untrusted read-only context. Not included in this local verdict.`,"community.bundles":`Bundles`,"community.activeRecords":`Active records`,"community.revokedRecords":`Revoked records`},de:{subjectKindUnknown:`Unbekannt`,"artifact.present":`Vorhanden`,"artifact.corrupt":`Beschädigt`,"artifact.purged_unavailable":`Gelöscht / nicht verfügbar`,selectVerdict:`Urteil für {subject} anzeigen`,"community.title":`Community-Evidenz`,"community.notLocalVerdict":`Nicht vertrauenswürdiger Nur-Lese-Kontext. Nicht Teil dieses lokalen Urteils.`,"community.bundles":`Pakete`,"community.activeRecords":`Aktive Einträge`,"community.revokedRecords":`Widerrufene Einträge`},ko:{subjectKindUnknown:`알 수 없음`,"artifact.present":`있음`,"artifact.corrupt":`손상됨`,"artifact.purged_unavailable":`삭제됨 / 사용할 수 없음`,selectVerdict:`{subject}의 판정 보기`,"community.title":`커뮤니티 증거`,"community.notLocalVerdict":`신뢰되지 않는 읽기 전용 컨텍스트입니다. 이 로컬 판정에는 포함되지 않습니다.`,"community.bundles":`번들`,"community.activeRecords":`활성 레코드`,"community.revokedRecords":`폐기된 레코드`},zh:{subjectKindUnknown:`未知`,"artifact.present":`存在`,"artifact.corrupt":`已损坏`,"artifact.purged_unavailable":`已清除 / 不可用`,selectVerdict:`查看 {subject} 的判定`,"community.title":`社区证据`,"community.notLocalVerdict":`不受信任的只读上下文。不计入此本地判定。`,"community.bundles":`证据包`,"community.activeRecords":`有效记录`,"community.revokedRecords":`已撤销记录`},"zh-TW":{subjectKindUnknown:`未知`,"artifact.present":`存在`,"artifact.corrupt":`已損壞`,"artifact.purged_unavailable":`已清除 / 不可用`,selectVerdict:`查看 {subject} 的判定`,"community.title":`社群證據`,"community.notLocalVerdict":`不受信任的唯讀脈絡。不計入此本地判定。`,"community.bundles":`證據包`,"community.activeRecords":`有效記錄`,"community.revokedRecords":`已撤銷記錄`},ru:{subjectKindUnknown:`Неизвестно`,"artifact.present":`Доступен`,"artifact.corrupt":`Повреждён`,"artifact.purged_unavailable":`Удалён / недоступен`,selectVerdict:`Открыть вердикт для {subject}`,"community.title":`Данные сообщества`,"community.notLocalVerdict":`Недоверенный контекст только для чтения. Не входит в этот локальный вердикт.`,"community.bundles":`Пакеты`,"community.activeRecords":`Активные записи`,"community.revokedRecords":`Отозванные записи`},ja:{subjectKindUnknown:`不明`,"artifact.present":`存在`,"artifact.corrupt":`破損`,"artifact.purged_unavailable":`削除済み / 利用不可`,selectVerdict:`{subject} の判定を表示`,"community.title":`コミュニティ証拠`,"community.notLocalVerdict":`信頼されていない読み取り専用コンテキストです。このローカル判定には含まれません。`,"community.bundles":`バンドル`,"community.activeRecords":`有効なレコード`,"community.revokedRecords":`取り消されたレコード`},tr:{subjectKindUnknown:`Bilinmiyor`,"artifact.present":`Mevcut`,"artifact.corrupt":`Bozuk`,"artifact.purged_unavailable":`Temizlenmiş / kullanılamıyor`,selectVerdict:`{subject} için kararı görüntüle`,"community.title":`Topluluk kanıtı`,"community.notLocalVerdict":`Güvenilmeyen salt okunur bağlam. Bu yerel karara dahil değildir.`,"community.bundles":`Paketler`,"community.activeRecords":`Etkin kayıtlar`,"community.revokedRecords":`Geri çekilen kayıtlar`}};function Re(e,t,n){let r=Le[e][t];if(n)for(let[e,t]of Object.entries(n))r=r.split(`{${e}}`).join(String(t));return r}function ze(e,t){return{...t,...Ie[e]}}var Be={en:ze(`en`,Oe),de:ze(`de`,ke),ko:ze(`ko`,Ae),zh:ze(`zh`,je),"zh-TW":ze(`zh-TW`,Me),ru:ze(`ru`,Ne),ja:ze(`ja`,Pe),tr:ze(`tr`,Fe)};function Ve(e){return Be[e][`lang.nativeName`]}function He(e,t){return Be[e][t]}var Ue=[{code:`en`,htmlLang:`en`},{code:`de`,htmlLang:`de`},{code:`ko`,htmlLang:`ko`},{code:`zh`,htmlLang:`zh-CN`},{code:`zh-TW`,htmlLang:`zh-TW`},{code:`ru`,htmlLang:`ru`},{code:`ja`,htmlLang:`ja`},{code:`tr`,htmlLang:`tr`}],We=`ocx-lang`,Ge=null;function Ke(){try{let e=localStorage.getItem(We);if(e===`en`||e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`)return e}catch{}let e=typeof navigator<`u`&&navigator?.language?navigator.language.toLowerCase():`en`;return e.startsWith(`de`)?`de`:e.startsWith(`ko`)?`ko`:e.startsWith(`zh`)?e.includes(`tw`)||e.includes(`hk`)||e.includes(`mo`)||e.includes(`hant`)?`zh-TW`:`zh`:e.startsWith(`ru`)?`ru`:e.startsWith(`ja`)?`ja`:e.startsWith(`tr`)?`tr`:`en`}function qe(){return Ge??Ke()}function Je(e){Ge=e}var Ye=(0,_.createContext)(null);function Xe(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 Ze(){let e=(0,_.useContext)(Ye);if(!e)throw Error(`useI18n must be used within LanguageProvider`);return e}function Z(){return Ze().t}function Qe({children:e}){let[t,n]=(0,_.useState)(()=>{let e=Ke();return Je(e),e}),r=(0,_.useCallback)(e=>{Je(e),n(e)},[]);(0,_.useEffect)(()=>{let e=Ue.find(e=>e.code===t)??Ue[0];document.documentElement.lang=e.htmlLang;try{localStorage.setItem(`ocx-lang`,t)}catch{}},[t]);let i=(0,_.useCallback)((e,n)=>Xe(Be[t][e]??Oe[e]??e,n),[t]),a=(0,_.useMemo)(()=>({locale:t,setLocale:r,t:i}),[t,i]);return(0,z.jsx)(Ye.Provider,{value:a,children:e})}function $e({k:e,cmd:t,vars:n}){let{t:r}=Ze(),[i,a=``]=r(e,n).split(`{cmd}`);return(0,z.jsxs)(z.Fragment,{children:[i,(0,z.jsx)(`code`,{className:`chip`,children:t}),a]})}function et(e){return e.replace(/^#\/?/,``)}function tt(e,t=window){let n=et(e);if(et(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function nt(e,t=window){let n=et(e);et(t.location.hash)!==n&&(t.location.hash=n)}var rt=m(),it=4,at=8,Q=8,ot=280,st=120,ct=160,lt=12;function ut(){return typeof window<`u`?window.innerHeight:800}function dt(){return typeof window<`u`?window.innerWidth:1024}function ft(e,{align:t,placement:n=`below`,menuHeight:r=ot}={}){let i=Math.min(Math.max(r,st),ot),a=ut(),o=dt();if(n===`right`){let t=a-e.top-Q,n=e.top-Q,r=i+at>t&&n>t,s=Math.max(Q,Math.min(e.right+lt,o-ct-Q));return r?{position:`fixed`,left:s,bottom:a-e.top+at,minWidth:ct,maxHeight:Math.max(st,Math.min(ot,e.top-Q-it))}:{position:`fixed`,top:e.top,left:s,minWidth:ct,maxHeight:Math.max(st,Math.min(ot,a-e.top-Q))}}let s=t??(e.right>o/2?`right`:`left`),c=Math.max(e.width,0),l=a-e.bottom-Q,u=e.top-Q;if(i+it>l&&u>l){let t={position:`fixed`,bottom:a-e.top+at,minWidth:c,maxHeight:Math.max(0,Math.min(ot,u-it))};return s===`right`?t.right=Math.max(Q,o-e.right):t.left=Math.max(Q,Math.min(e.left,o-Q-c)),t}let d={position:`fixed`,top:e.bottom+it,minWidth:c,maxHeight:Math.max(0,Math.min(ot,l-it))};return s===`right`?d.right=Math.max(Q,o-e.right):d.left=Math.max(Q,Math.min(e.left,o-Q-c)),d}function pt({on:e,onClick:t,disabled:n,label:r}){return(0,z.jsx)(`button`,{type:`button`,className:`switch${e?` on`:``}`,onClick:t,disabled:n,"aria-pressed":e,"aria-label":r??(e?`enabled`:`disabled`),children:(0,z.jsx)(`span`,{className:`knob`})})}function $({tone:e,children:t}){return(0,z.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,z.jsx)(J,{}):(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{children:t})]})}function mt({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,rt.createPortal)((0,z.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,z.jsxs)(`div`,{className:`toast-notice notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[e===`ok`?(0,z.jsx)(J,{}):(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,z.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function ht({value:e,options:t,onChange:n,disabled:r,id:i,label:a,describedBy:o,title:s,style:c,align:l,placement:u,dropdownStyle:d,portal:f=!0}){let p=(0,_.useId)(),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useCallback)(e=>`${p}-${e}`,[p]),T=t.find(t=>t.value===e),E=t.length===0?0:Math.max(0,t.findIndex(t=>t.value===e)),D=!m||t.length===0?E:Math.min(g??E,t.length-1),O=(0,_.useCallback)((e=!1)=>{h(!1),v(null),e&&S.current?.focus()},[]),k=(0,_.useCallback)(e=>{if(r||t.length===0)return;let n=Math.max(0,Math.min(t.length-1,e));v(n),h(!0)},[r,t.length]),A=(0,_.useCallback)(e=>{if(!f)return;let t=S.current;t&&b(ft(t.getBoundingClientRect(),{align:l,placement:u,menuHeight:e}))},[l,u,f]);(0,_.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.target;x.current?.contains(t)||C.current?.contains(t)||O()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[O,m]),(0,_.useLayoutEffect)(()=>{if(!m||!f)return;A();let e=()=>A(C.current?.offsetHeight);return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[m,t.length,f,A]),(0,_.useLayoutEffect)(()=>{if(!m||!f||!C.current||!S.current)return;let e=C.current.offsetHeight;if(!e)return;let t=ft(S.current.getBoundingClientRect(),{align:l,placement:u,menuHeight:e});b(e=>e?.top===t.top&&e?.bottom===t.bottom&&e?.maxHeight===t.maxHeight?e:t)},[l,m,t.length,u,f]),(0,_.useLayoutEffect)(()=>{!m||!C.current||C.current.querySelector(`[id="${w(D)}"]`)?.scrollIntoView({block:`nearest`})},[D,m,w]);let j=e=>{if(r)return;let i=t[e];i&&(n(i.value),O(!0))},M=e=>{if(!r)switch(e.key){case`ArrowDown`:e.preventDefault(),k(m?Math.min(t.length-1,D+1):E);break;case`ArrowUp`:e.preventDefault(),k(m?Math.max(0,D-1):E);break;case`Home`:e.preventDefault(),k(0);break;case`End`:e.preventDefault(),k(t.length-1);break;case`Enter`:case` `:e.preventDefault(),m?j(D):k(E);break;case`Escape`:m&&(e.preventDefault(),O(!0));break;case`Tab`:if(m){let e=t[D];e&&n(e.value),h(!1)}}},N=m&&t[D]?w(D):void 0,P=m&&!r?(0,z.jsx)(`div`,{ref:C,id:p,className:`select-dropdown${f?` select-dropdown-portal`:``}${!f&&l===`right`?` select-dropdown-right`:``}${!f&&u===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":a,style:f?{...y,zIndex:60,...d}:d,children:t.map((t,n)=>(0,z.jsx)(`button`,{id:w(n),type:`button`,role:`option`,tabIndex:-1,disabled:r,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}${n===D?` select-option-active`:``}`,onMouseEnter:()=>v(n),onClick:()=>j(n),children:t.label},t.value))}):null;return(0,z.jsxs)(`div`,{ref:x,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...c},children:[(0,z.jsxs)(`button`,{ref:S,id:i,type:`button`,role:`combobox`,title:s,"aria-describedby":o,className:`select-trigger`,onClick:()=>{r||(m?O():k(E))},onKeyDown:M,disabled:r,"aria-haspopup":`listbox`,"aria-expanded":m,"aria-controls":m?p:void 0,"aria-activedescendant":N,"aria-label":a,children:[(0,z.jsx)(`span`,{children:T?.label??e}),(0,z.jsx)(fe,{style:{width:12,height:12,color:`var(--muted)`,transform:m?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),f?P&&(0,rt.createPortal)(P,document.body):P]})}function gt({icon:e,title:t,children:n,className:r,style:i}){return(0,z.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,z.jsx)(`div`,{className:`title`,children:t}),n&&(0,z.jsx)(`div`,{className:`text-control`,children:n})]})}function _t({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,z.jsxs)(`button`,{type:`button`,className:`ocx-tooltip`,onMouseEnter:c,onMouseLeave:l,onFocus:c,onBlur:l,onKeyDown:e=>{e.key===`Escape`&&l()},"aria-describedby":i?o:void 0,style:{display:`inline`,border:0,background:`transparent`,padding:0,margin:0,color:`inherit`,font:`inherit`,cursor:`inherit`},children:[t,i&&(0,z.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var vt=45e3,yt=2147483647;async function bt(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 xt(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function St(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=xt(await e.json(),t)}catch{}throw Error(n)}return bt(e)}async function Ct(e){if(!e.ok)return null;try{return await bt(e)}catch{return null}}var wt=`dashboard/update`;function Tt(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function Et(){return window.location.hash.replace(/^#\/?/,``)===wt}function Dt(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function Ot(e,t){let n=await St(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var kt=[`low`,`medium`,`high`,`xhigh`];function At(e){return e?.includes(`-preview.`)?`preview`:`latest`}function jt(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 Mt(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 Nt(e,t){let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),t?.reasoning!==void 0&&(n.reasoning=t.reasoning),t?.streamRoutedModelOutput!==void 0&&(n.streamRoutedModelOutput=t.streamRoutedModelOutput),t?.enabled!==void 0&&(n.enabled=t.enabled),t?.maxDescriptionsPerTurn!==void 0&&(n.maxDescriptionsPerTurn=t.maxDescriptionsPerTurn),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),n}function Pt(e){return{vision:{reasoning:e}}}function Ft(e){return{vision:{enabled:e}}}function It(e){return{vision:{maxDescriptionsPerTurn:e}}}function Lt(e){return{vision:{timeoutMs:e}}}var Rt=vt,zt=yt,Bt=1;function Vt(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Ht(e){let t=Vt(e);if(!(t===void 0||t<Bt||t>zt))return t}var Ut=[`low`,`medium`,`high`,`xhigh`,`max`];function Wt(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...Ut];let r=Ut.filter(e=>n.includes(e));return r.length>0?r:[...Ut]}function Gt(e,t){let n=Kt(e,t);return e.includes(n)?e:[n,...e]}function Kt(e,t){if(e.length===0||e.includes(t))return t;let n=Ut.indexOf(t),r=e[0],i=Ut.indexOf(r);for(let t of e){let e=Ut.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function qt(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 Jt(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):qt(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function Yt(e,t){let n=[{value:``,label:`—`},...e.map(e=>({value:e.namespaced,label:e.namespaced}))];return t&&!n.some(e=>e.value===t)&&n.push({value:t,label:t}),n}function Xt(e,t){return e.find(e=>e.id===t)?.provider===`anthropic`?`anthropic`:`openai`}function Zt(e,t,n){return t.find(e=>e.value===n)?.backend??Xt(e,n)}var Qt=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{Qt=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{Qt=!1},{capture:!0,passive:!0}));function $t(e){if(e){if(Qt){e.focus({preventScroll:!0});return}try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function en(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(),$t(t.current)}},[e,t]),(0,_.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),$t(t.current)},[t]),n}var tn=[`gpt-5.6-luna`];function nn(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length>0?t:tn}function rn(e){return nn(e).join(`, `)}function an(e){return nn(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function on(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,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`dialog`,{ref:i,id:`dashboard-update-dialog`,className:`modal-overlay`,style:{display:n?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`update-title`,onCancel:e=>{e.preventDefault(),r()},children:(0,z.jsxs)(`div`,{className:`modal-card`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,z.jsx)(Y,{})})]}),(0,z.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,z.jsxs)(`div`,{className:`update-row`,children:[(0,z.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,z.jsx)(ht,{value:a,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>o(e),disabled:s,label:t(`dash.updateChannel`),portal:!1})]}),s&&(0,z.jsx)(gt,{className:`update-empty`,icon:(0,z.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,z.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{children:c})]}),l&&!s&&(0,z.jsxs)(`div`,{className:`update-box`,children:[(0,z.jsxs)(`div`,{className:`spread`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,z.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,z.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,z.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),(0,z.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,z.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,z.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,z.jsx)(se,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,z.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,z.jsx)(se,{}),` `,t(`dash.updateUnavailable`),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,z.jsx)(re,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,z.jsxs)(`div`,{className:`update-recheck`,children:[(0,z.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:jt(l.reason,t)})}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,z.jsx)(re,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,z.jsxs)(`div`,{className:`spread update-restart`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,z.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,z.jsx)(`span`,{className:`knob`})})]})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,z.jsxs)(`dialog`,{ref:g,id:`multi-agent-help-dialog`,className:`modal-overlay`,style:{display:m?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`multi-agent-help-title`,onCancel:e=>{e.preventDefault(),h(!1)},children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,z.jsx)(Y,{})})]}),(0,z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,z.jsx)(`div`,{style:{marginTop:12},children:(0,z.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,z.jsx)(`div`,{className:`modal-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,z.jsxs)(`dialog`,{ref:y,id:`effort-cap-help-dialog`,className:`modal-overlay`,style:{display:_?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`effort-cap-help-title`,onCancel:e=>{e.preventDefault(),v(!1)},children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,z.jsx)(Y,{})})]}),(0,z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,z.jsx)(`div`,{className:`modal-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,z.jsxs)(`dialog`,{ref:S,id:`shadow-call-help-dialog`,className:`modal-overlay`,style:{display:b?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`shadow-call-help-title`,onCancel:e=>{e.preventDefault(),x(!1)},children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,z.jsx)(Y,{})})]}),(0,z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:rn(C?.sourceModels)})}),(0,z.jsx)(`div`,{className:`modal-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]})]})}var sn={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`,cline:`cline-color.svg`,"cline-pass":`cline-color.svg`,"command-code":`commandcode-color.svg`,commandcode:`commandcode-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.svg`,"mimo-free":`xiaomi-color.svg`,xiaomi:`xiaomi-color.svg`},cn={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`,cline:`Cline`,"cline-pass":`ClinePass`,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`},ln={"command-code":`provider.name.commandCodeAuth`,commandcode:`provider.name.commandCodeApi`,volcengine:`provider.name.volcengine`,"volcengine-coding-plan":`provider.name.volcengineCodingPlan`,"volcengine-agent-plan":`provider.name.volcengineAgentPlan`},un=new Set([...Object.keys(cn),...Object.keys(ln)]);function dn(e){let t=e.toLowerCase();return Object.hasOwn(sn,t)?sn[t]:void 0}function fn(e,t){let n=dn(e);return n?`/provider-icons/${n}`:void 0}function pn(e,t){let n=e.toLowerCase(),r=Object.hasOwn(ln,n)?ln[n]:void 0;return r?t(r):(Object.hasOwn(cn,n)?cn[n]:void 0)||(e===n&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)?e.split(`-`).map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(` `):e)}function mn(e){return un.has(e.toLowerCase())}function hn(e){return e===`command-code`?`commandcode-auth`:e===`commandcode`?`commandcode-api`:e}function gn(e,t){let n=e.indexOf(`/`);if(n<=0)return e;let r=e.slice(0,n),i=e.slice(n+1);if(r===`command-code`||r===`commandcode`){let e=i.match(/^([a-z0-9]+)-([a-z0-9]+(?:-[a-z0-9]+)+)$/i);return e&&i.startsWith(`${e[1]}-${e[1]}-`)&&(i=i.slice(e[1].length+1)),`${r===`command-code`?`commandcode-auth`:`commandcode-api`}/${i}`}return e}function _n({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,z.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,z.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,z.jsx)(gt,{title:e(`dash.noModels`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,z.jsx)(le,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,z.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:e(`models.search`),value:r,onChange:e=>i(e.target.value),"aria-label":e(`models.search`)})]}),a.length===0?(0,z.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,z.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,z.jsxs)(`div`,{className:`dash-model-group`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`dash-model-head`,onClick:()=>s(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),"aria-expanded":i,children:[(0,z.jsx)(fe,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:`font-semibold`,children:pn(t,e)}),(0,z.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,z.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,z.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}var vn={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:`万`}],"zh-TW":[{v:0x2386f26fc10000,s:`京`},{v:0xe8d4a51000,s:`兆`},{v:1e8,s:`億`},{v:1e4,s:`萬`}]};function yn(e){return e.replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function bn(e,t){let n=vn[t];if(n){for(let t of n)if(e>=t.v)return`${yn((e/t.v).toFixed(1))}${t.s}`;return String(e)}return e<1e4?String(e):e<1e6?`${yn((e/1e3).toFixed(1))}K`:e<1e9?`${yn((e/1e6).toFixed(1))}M`:e<0xe8d4a51000?`${yn((e/1e9).toFixed(1))}B`:`${yn((e/0xe8d4a51000).toFixed(1))}T`}function xn(e,t){let n=Math.max(0,Math.floor(e)),r=He(t,`uptime.day`),i=He(t,`uptime.hour`),a=He(t,`uptime.minute`),o=He(t,`uptime.second`);if(n<300)return`${n}${o}`;let s=Math.floor(n/60);if(s<60)return`${s}${a}`;let c=Math.floor(s/60);if(c<24){let e=s%60;return e>0?`${c}${i} ${e}${a}`:`${c}${i}`}let l=Math.floor(c/24),u=c%24;return u>0?`${l}${r} ${u}${i}`:`${l}${r}`}function Sn({locale:e,health:t,providers:n,usage30d:r,usageLoading:i,healthLoading:a,startupHealth:o,projectConfigWarnings:s,maMode:c,maBusy:l,maHelpTriggerRef:u,maHelpOpen:d,setMaHelpOpen:f,switchMaMode:p,maError:m}){let h=Z(),g=t?.status===`ok`;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,z.jsxs)(`div`,{className:`stat-row`,children:[(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[h(`dash.multiAgent`),(0,z.jsx)(`button`,{ref:u,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>f(!0),"aria-label":h(`dash.multiAgent`),"aria-haspopup":`dialog`,"aria-controls":`multi-agent-help-dialog`,"aria-expanded":d,children:(0,z.jsx)(ce,{width:14,height:14,"aria-hidden":`true`})})]}),(0,z.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,z.jsx)(`div`,{role:`radiogroup`,"aria-label":h(`dash.multiAgent`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,z.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:h(`models.v2Mode_${e}`)},e))})}),m&&(0,z.jsx)(`div`,{role:`alert`,className:`text-caption`,style:{color:`var(--red)`,marginTop:4,textAlign:`center`,maxWidth:280,wordBreak:`break-word`},children:m})]}),(0,z.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,z.jsx)(`div`,{className:`label`,children:h(`dash.status`)}),(0,z.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:g?`var(--green)`:`var(--red)`},children:[(0,z.jsx)(`span`,{className:`dot ${g?`dot-green`:`dot-red`}`}),h(g?`dash.online`:`dash.offline`)]})]}),(0,z.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,z.jsx)(`div`,{className:`label`,children:h(`dash.version`)}),(0,z.jsx)(`div`,{className:`value mono`,children:t?.version??`—`})]}),(0,z.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,z.jsx)(`div`,{className:`label`,children:h(`dash.uptime`)}),(0,z.jsx)(`div`,{className:`value mono`,children:t?xn(t.uptime,e):`—`})]}),(0,z.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,z.jsx)(`div`,{className:`label`,children:h(`dash.providers`)}),(0,z.jsx)(`div`,{className:`value`,children:n.length})]}),(0,z.jsxs)(`div`,{className:`stat`,"aria-busy":i||void 0,children:[(0,z.jsx)(`div`,{className:`label`,children:h(`dash.tokens30d`)}),(0,z.jsx)(`div`,{className:`value mono`,children:r&&r.summary.requests>0?bn(r.summary.totalTokens,e):`—`}),(0,z.jsx)(`div`,{className:`muted text-label dash-stat-coverage`,children:r&&r.summary.requests>0?h(`dash.coverage`).replace(`{pct}`,`${Math.round(r.summary.coverageRatio*100)}%`):`\xA0`})]})]}),(0,z.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,z.jsxs)(`button`,{type:`button`,className:`startup-health-bar`,onClick:()=>nt(`startup`),children:[(0,z.jsx)(`span`,{className:`dot ${o===`error`?`dot-red`:o===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:`startup-health-bar__summary`,children:h(o===`error`?`startup.error`:o===`at-risk`?`startup.summary.atRisk`:o===`protected`?`startup.summary.protected`:`startup.summary.native`)})]}):(0,z.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`dot dot-amber`}),(0,z.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),s.length>0&&(0,z.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,z.jsx)(se,{}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:h(`dash.projectConfigTitle`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:h(`dash.projectConfigHint`)}),(0,z.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,z.jsxs)(`li`,{style:{marginBottom:8},children:[(0,z.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,z.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}function Cn(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 wn=new Map;function Tn(e,t){let n=`${e}:${t}`,r=wn.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),wn.set(n,r)),r}var En=new Map;function Dn(e){let t=En.get(e);return t||(t=new Intl.NumberFormat(e),En.set(e,t)),t}function On(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`${Tn(t,r===0?0:1).format(i)} ${n[r]}`}function kn(e,t){return!Number.isFinite(e)||e<0?`—`:xn(e/1e3,t)}function An(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function jn(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 Mn(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:(An(n)-An(t))/r*36e5}function Nn({label:e,value:t,sub:n,tone:r}){return(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:e}),(0,z.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,z.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function Pn({observedBytes:e,thresholdBytes:t,metric:n,locale:r,t:i}){let a=e!==null&&t!==null&&t>0?e/t:null,o=a===null?`unknown`:a>=1?`over`:a>=.75?`warn`:`ok`,s=a===null?null:Math.round(a*100);return(0,z.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,z.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,z.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,z.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,z.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:On(e,r),t!==null&&(0,z.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,On(t,r)]})]})]}),(0,z.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,z.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,z.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var Fn=60,In=1500,Ln=12e4;function Rn({apiBase:e}){let{locale:t,t:n}=Ze(),[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=Cn(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=Cn(5e3);i=o,fetch(`${e}/healthz`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=Ln&&(c(`error`),u(n(`dash.mem.restartFailed`)));return}let r=h==null;if(h!=null)try{let t=await e.json();r=typeof t.pid==`number`&&t.pid!==h}catch{r=!0}if(!t){if(r){c(`idle`),g(null),u(null);return}Date.now()-a>=Ln&&(c(`error`),u(n(`dash.mem.restartFailed`)))}}).catch(()=>{t||Date.now()-a>=Ln&&(c(`error`),u(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let l=setInterval(o,In);return()=>{t=!0,i?.controller.abort(),i?.clear(),clearInterval(l)}},[e,s,h,n]);let v=()=>{let t=r?.activeTurnCount??0,i=[n(`dash.mem.restartConfirm`,{count:t,seconds:Fn})];d&&i.push(n(`dash.mem.restartNoSupervisor`)),window.confirm(i.join(`
|
|
52
52
|
|
|
53
|
-
`))&&(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,z.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,z.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,z.jsx)(K,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?Mn(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??An(r):null,x=r?jn(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,z.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,z.jsxs)(`div`,{className:`mem-head`,children:[(0,z.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,z.jsx)(K,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,z.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,z.jsxs)(`span`,{className:`mem-inflight`,children:[(0,z.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,z.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?Dn(t).format(w):`—`})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,z.jsx)(Pn,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,z.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,z.jsx)(Nn,{label:n(`dash.mem.rss`),value:r?On(r.rss,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.jsHeap`),value:r?On(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:On(r.heapTotal,t)}):void 0}),(0,z.jsx)(Nn,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?On(r.jscHeap.heapSize,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${On(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,z.jsxs)(`details`,{style:{marginTop:10},children:[(0,z.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,z.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,z.jsxs)(`div`,{className:`stat-row`,children:[(0,z.jsx)(Nn,{label:n(`dash.mem.observed`),value:b===null?`—`:`${On(b,t)} (${x})`}),(0,z.jsx)(Nn,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:On(r.external,t)}),(0,z.jsx)(Nn,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:On(r.arrayBuffers,t)})]}),(0,z.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,z.jsxs)(`div`,{className:`stat-row`,children:[(0,z.jsx)(Nn,{label:n(`dash.mem.storeEntries`),value:C?Dn(t).format(C.count):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.storeTotal`),value:C?On(C.totalBytes,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.storeLargest`),value:C?On(C.largestBytes,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:kn(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,z.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,z.jsx)(Nn,{label:n(`dash.mem.threshold`),value:On(r.watchdog.warnThresholdBytes,t)}),(0,z.jsx)(Nn,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,z.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,z.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,z.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,z.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,z.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function zn({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,z.jsx)(`div`,{className:`panel`,children:(0,z.jsxs)(`div`,{className:`injection-head`,children:[(0,z.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,z.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,z.jsx)(ce,{width:13,height:13,"aria-hidden":`true`})})]}),(0,z.jsx)(ht,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...kt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Ot(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({effortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.effortCapLabel`),align:`right`}),(0,z.jsx)(ht,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...kt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Ot(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subagentEffortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.subagentEffortCapLabel`),align:`right`})]})})}function Bn({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,z.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,z.jsx)(ht,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:gn(`${e.provider}/${e.model}`,t)}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`),align:`right`}),n&&i.length>0&&(0,z.jsx)(ht,{value:r,options:[{value:``,label:t(`dash.injectionEffortNone`)},...i.map(e=>({value:e,label:e}))],onChange:e=>{s({model:n||null,effort:e||null})},disabled:o,label:t(`dash.injectionEffortLabel`),align:`right`}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>nt(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function Vn({d:e}){let{t,runSync:n,syncing:r,updateTriggerRef:i,openUpdateDialog:a,updateLoading:o,updateOpen:s,syncResult:c,syncError:l,updateJob:u,reconnecting:d,clearSyncFeedback:f}=e,p=!!c&&(!!c.warning||!!c.nativeSubagentDefaultsWarning||!!c.staleAppServerHint),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(null);(0,_.useEffect)(()=>(g.current&&=(clearTimeout(g.current),null),(c||l)&&!p&&(g.current=setTimeout(()=>{g.current=null,h(!0),f()},l?8e3:6e3)),()=>{g.current&&clearTimeout(g.current)}),[c,l,p,f]);let v=()=>{h(!1),n()},y=()=>{h(!0),f()};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,z.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,z.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,z.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,z.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:r,children:[(0,z.jsx)(re,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,z.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})]})]}),u&&(0,z.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,z.jsx)(se,{}):(0,z.jsx)(re,{}),(0,z.jsxs)(`span`,{children:[Mt(u.status,t),u.latestVersion?` ${t(`dash.updateVersionTransition`,{currentVersion:u.currentVersion,latestVersion:u.latestVersion})}`:``,d?` ${t(`dash.updateReconnecting`)}`:``,u.error?` ${u.error}`:``]})]})]}),!m&&c&&(0,z.jsxs)(`div`,{className:`action-toast notice ${p?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[p?(0,z.jsx)(se,{}):(0,z.jsx)(J,{}),(0,z.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,z.jsxs)(z.Fragment,{children:[` `,(0,z.jsx)($e,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,z.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,z.jsx)(Y,{width:13,height:13,"aria-hidden":`true`})})]}),!m&&l&&(0,z.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})}),(0,z.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,z.jsx)(Y,{width:13,height:13,"aria-hidden":`true`})})]})]})}function Hn({t:e,open:t,triggerRef:n,onClose:r,maxValue:i,maxInvalid:a,timeoutValue:o,timeoutInvalid:s,disabled:c,setMaxDraft:l,setMaxInvalid:u,setTimeoutDraft:d,setTimeoutInvalid:f,commitMaxDescriptions:p,commitTimeout:m}){let h=(0,_.useRef)(null),g=(0,_.useRef)(null),[v,y]=(0,_.useState)(),b=(0,_.useCallback)(()=>{n.current&&y(ft(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,_.useLayoutEffect)(()=>{if(!t)return;b();let e=()=>b();return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[t,b,a,s]),(0,_.useEffect)(()=>{if(!t)return;let e=e=>{let t=e.target;if(h.current?.contains(t)||n.current?.contains(t))return;let i=document.activeElement;i&&h.current?.contains(i)&&i.blur(),r()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t,r,n]),(0,_.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),r(),n.current?.focus())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,r,n]),(0,_.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,z.jsxs)(`div`,{ref:h,id:`dash-vision-advanced-popover`,className:`dash-vision-advanced-popover`,role:`dialog`,"aria-modal":`false`,"aria-label":e(`dash.visionAdvancedPopover`),style:{...v,zIndex:60},children:[(0,z.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,z.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,z.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,z.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,z.jsx)(`input`,{ref:g,className:`input mono codex-auto-switch-input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:i,disabled:c,"aria-invalid":a||void 0,"aria-label":e(`dash.visionMaxDescriptions`),"aria-describedby":a?`dash-vision-max-error dash-vision-max-label`:`dash-vision-max-label`,onChange:e=>{u(!1),l(e.target.value)},onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),p(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),l(null),u(!1)))}})}),a&&(0,z.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,z.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,z.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,z.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:Bt,max:zt,step:1e3,inputMode:`numeric`,value:o,disabled:c,"aria-invalid":s||void 0,"aria-label":e(`dash.visionTimeout`),"aria-describedby":s?`dash-vision-timeout-error dash-vision-timeout-label`:`dash-vision-timeout-label`,onChange:e=>{f(!1),d(e.target.value)},onBlur:e=>m(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),m(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),d(null),f(!1)))}}),(0,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,z.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:Bt,max:zt})})]})]}):null}function Un({d:e}){let{t,settings:n,settingsSaving:r,toggleCodexAutoStart:i,sidecar:a,sidecarSaving:o,sidecarModels:s,visionModels:c,models:l,saveSidecar:u,shadowCall:d,shadowCallSaving:f,shadowCallHelpTriggerRef:p,shadowCallHelpOpen:m,setShadowCallHelpOpen:h,saveShadowCall:g}=e,v=a?.vision.enabled!==!1,y=v?a?.vision.model??`gpt-5.4-mini`:``,b=a?.vision.reasoning??`low`,x=Wt(l,y),S=Kt(x,b),C=String(a?.vision.maxDescriptionsPerTurn??8),w=String(a?.vision.timeoutMs??Rt),[T,E]=(0,_.useState)(null),[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),F=(0,_.useRef)(null),I=T??C,L=D??w,R=(e=I)=>{let t=Vt(e);if(t===void 0){E(e),A(!0);return}A(!1),E(null),t!==(a?.vision.maxDescriptionsPerTurn??8)&&u(It(t))},B=(e=L)=>{let t=Ht(e);if(t===void 0){O(e),M(!0);return}M(!1),O(null),t!==(a?.vision.timeoutMs??Rt)&&u(Lt(t))};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`panel`,children:(0,z.jsxs)(`div`,{className:`spread`,children:[(0,z.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,z.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,z.jsx)(`span`,{className:`knob`})})]})}),(0,z.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,z.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!a||void 0,children:[(0,z.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,z.jsx)(ht,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{u({webSearch:{model:e,backend:Xt(l,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`),align:`right`}),(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},title:t(`dash.webSearchStreamHint`),children:[(0,z.jsx)(`span`,{className:`muted setting-hint`,children:t(`dash.webSearchStream`)}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${a?.webSearch.streamRoutedModelOutput?`on`:``}`,onClick:()=>{u({webSearch:{streamRoutedModelOutput:!a?.webSearch.streamRoutedModelOutput}})},disabled:!a||o,"aria-label":t(`dash.webSearchStream`),"aria-pressed":a?.webSearch.streamRoutedModelOutput===!0,children:(0,z.jsx)(`span`,{className:`knob`})})]})]})]}),(0,z.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!a||void 0,children:[(0,z.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,z.jsxs)(`div`,{className:`dash-vision-select-row`,children:[(0,z.jsx)(ht,{value:y,options:[{value:``,label:t(`dash.visionOff`)},...c],onChange:e=>{if(e===``){u(Ft(!1));return}let t=Kt(Wt(l,e),S),n={vision:{model:e,backend:Zt(l,c,e),reasoning:t}};v||(n.vision={...n.vision,enabled:!0}),u(n)},disabled:!a||o,label:t(`dash.sidecarModel`)}),(0,z.jsx)(ht,{value:S,options:Gt(x,S).map(e=>({value:e,label:e})),onChange:e=>{u(Pt(e))},disabled:!v||!a||o,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),(0,z.jsx)(`div`,{className:`dash-vision-advanced-row`,children:(0,z.jsxs)(`button`,{type:`button`,ref:F,className:`dash-vision-advanced-trigger`,onClick:()=>P(e=>!e),disabled:!v||!a||o,"aria-expanded":N,"aria-haspopup":`dialog`,"aria-controls":`dash-vision-advanced-popover`,children:[(0,z.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,style:{transform:N?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,rt.createPortal)((0,z.jsx)(Hn,{t,open:N,triggerRef:F,onClose:()=>P(!1),maxValue:I,maxInvalid:k,timeoutValue:L,timeoutInvalid:j,disabled:!v||!a||o,setMaxDraft:E,setMaxInvalid:A,setTimeoutDraft:O,setTimeoutInvalid:M,commitMaxDescriptions:R,commitTimeout:B}),document.body)]})]}),(0,z.jsx)(`div`,{className:`panel`,"aria-busy":!d||void 0,children:(0,z.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,z.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,z.jsx)(`button`,{ref:p,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:()=>h(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":m,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,z.jsx)(ce,{width:13,height:13,"aria-hidden":`true`})}),(0,z.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${an(d?.sourceModels)}`})]}),(0,z.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,z.jsx)(`button`,{type:`button`,className:`switch ${d?.enabled?`on`:``}`,onClick:()=>g({enabled:!d?.enabled}),disabled:!d||f,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":d?.enabled??!1,children:(0,z.jsx)(`span`,{className:`knob`})}),(0,z.jsx)(ht,{value:d?.model??``,options:Yt(l,d?.model).map(e=>e.value===``?e:{...e,label:gn(e.value,t)}),onChange:e=>{g({model:e})},disabled:!d||f||!d?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function Wn(e){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(zn,{apiBase:e.apiBase,d:e}),(0,z.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,z.jsx)(Bn,{apiBase:e.apiBase,d:e}),(0,z.jsx)(Vn,{d:e})]}),(0,z.jsx)(Un,{d:e}),(0,z.jsx)(Rn,{apiBase:e.apiBase})]})}function Gn(e){return(0,z.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,z.jsx)(Sn,{...e}),(0,z.jsx)(Wn,{...e})]})}function Kn({t:e,providers:t}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,z.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,z.jsx)(gt,{title:(0,z.jsx)($e,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:e(`dash.col.name`)}),(0,z.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,z.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,z.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,z.jsx)(`tbody`,{children:t.map(t=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`font-semibold`,children:pn(t.name,e)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,z.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,z.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}function qn(e){try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Jn(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function Yn(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function Xn(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Zn(e,t){return{request:++e.current,mutation:t.current}}var Qn=2e3;function $n(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function er(e){return e?e.stale&&e.status!==`error`:!1}function tr(e,t){return!t||e!==null&&e!==`error`?e:t.status}var nr=3e4;function rr(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function ir(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function ar(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=$n(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(ir(e,t))throw e;return{status:`error`,stale:!1}}}async function or(e,t){try{return(await Ct(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function sr(e,t){return Ot(await fetch(`${e}/api/models`,{signal:t}))}async function cr(e,t){return Ot(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function lr(e,t,n){let{request:r,mutation:i}=Zn(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 Ot(a),c;try{if(o.ok){let e=await o.json();Xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else Xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{Xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}return{sidecar:s,shadowCall:c}}async function ur(e,t,n){let{request:r,mutation:i}=Zn(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Ot(await fetch(`${e}/api/settings`,{signal:t})),o,s;return Xn({request:r,mutation:i},{request:n.settingsRequestEpochRef.current,mutation:n.settingsMutationEpochRef.current,mutationInFlight:n.settingsMutationInFlightRef.current})&&(o=a,s=a.startupHealth),{settings:o,startupHealthSeed:s}}async function dr(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(ir(e,t))throw e;return{maMode:`default`}}}async function fr(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await Ot(n),providers:await Ot(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function pr(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={...rr(e),injectionEfforts:e.efforts??[],injectionAvailable:e.available??[]}}}catch{}let a;try{if(r?.ok){let e=await r.json();a={effortCap:e.effortCap??``,subagentEffortCap:e.subagentEffortCap??``}}}catch{}return{injection:i,effortCaps:a}}function mr(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}var hr=`ocx.dash.controls.v1:`,gr=`ocx.dash.overview.v1:`,_r=`ocx.dash.usage30d.v1:`,vr=`ocx.dash.startup.v1:`,yr=`ocx.dash.maMode.v1:`;function br(e){let t=new Map;for(let n of e){let e=t.get(n.provider);e?e.push(n):t.set(n.provider,[n])}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t))}function xr(e){return`${hr}${e}`}function Sr(e){let{locale:t,t:n}=Ze(),[r,i]=(0,_.useState)(Tt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>qn(xr(e)),[e]),u=(0,_.useMemo)(()=>qn(`${gr}${e}`),[e]),d=(0,_.useMemo)(()=>qn(`${_r}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=qn(`${vr}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>qn(`${yr}${e}`),[e]),[m,h]=(0,_.useState)(()=>u?.health??null),[g,v]=(0,_.useState)(()=>f),[y,b]=(0,_.useState)(()=>u?.providers??[]),[x,S]=(0,_.useState)([]),[C,w]=(0,_.useState)(()=>l?.settings??null),[T,E]=(0,_.useState)(()=>l?.sidecar??null),[D,O]=(0,_.useState)(()=>l?.shadowCall??null),[k,A]=(0,_.useState)(()=>d),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),[F,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(()=>p??`default`),[W,G]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(null),[K,q]=(0,_.useState)(!1),[J,Y]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)([]),[ue,X]=(0,_.useState)([]),[de,fe]=(0,_.useState)(!1),[pe,me]=(0,_.useState)(!0),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(``),[ye,be]=(0,_.useState)(``),[xe,Se]=(0,_.useState)(!1),[Ce,we]=(0,_.useState)(null),[Te,Ee]=(0,_.useState)(null),[De,Oe]=(0,_.useState)([]),[ke,Ae]=(0,_.useState)(!1),[je,Me]=(0,_.useState)(`latest`),[Ne,Pe]=(0,_.useState)(!0),[Fe,Ie]=(0,_.useState)(!1),Le=(0,_.useRef)(0),Re=(0,_.useRef)(null),ze=(0,_.useRef)(0),Be=(0,_.useRef)(0),Ve=(0,_.useRef)(0),He=(0,_.useRef)(!1),Ue=(0,_.useRef)(0),We=(0,_.useRef)(0),Ge=(0,_.useRef)(!1),[Ke,qe]=(0,_.useState)(null),[Je,Ye]=(0,_.useState)(null),[Xe,Z]=(0,_.useState)(null),[Qe,$e]=(0,_.useState)(!1),[et,nt]=(0,_.useState)(!1),rt=(0,_.useRef)(null),it=(0,_.useRef)(null),at=(0,_.useRef)(null),Q=(0,_.useRef)(null),ot=en(J,rt),st=en(ke,it),ct=en(K,at),lt=en(ne,Q);(0,_.useEffect)(()=>{let e=()=>i(Tt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{ze.current+=1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null)},[]);let ut=(0,_.useRef)(f),dt=(0,_.useRef)(0),ft=(0,_.useRef)({settingsRequestEpochRef:Be,settingsMutationEpochRef:Ve,settingsMutationInFlightRef:He,shadowCallRequestEpochRef:Ue,shadowCallMutationEpochRef:We,shadowCallMutationInFlightRef:Ge}).current,pt=I(`dashboard-startup-health:${e}`,[e],t=>ar(e,t),{pollMs:3e4}),$=er(pt.data),mt=pt.refresh;(0,_.useEffect)(()=>{if(!$)return;let e=window.setTimeout(()=>{mt()},Qn);return()=>window.clearTimeout(e)},[$,mt]);let ht=I(`dashboard-overview:${e}`,[e],t=>fr(e,t),{pollMs:5e3}),gt=m!==null||ht.data!==void 0,_t=I(`dashboard-ma-mode:${e}`,[e],t=>dr(e,t),{pollMs:5e3}),vt=I(`dashboard-sidecars:${e}`,[e],async t=>{let n=dt.current;return{...await lr(e,t,ft),startupHealthGeneration:n}},{pollMs:5e3}),yt=I(`dashboard-settings:${e}`,[e],async t=>{let n=dt.current;return{...await ur(e,t,ft),startupHealthGeneration:n}},{pollMs:5e3}),bt=I(`dashboard-multi-agent:${e}`,[e],t=>pr(e,t),{pollMs:5e3,enabled:gt}),xt=I(mr(e),[e],t=>cr(e,t),{enabled:gt}),St=I(`dashboard-diagnostics:${e}`,[e],t=>or(e,t),{pollMs:nr,enabled:gt}),Ct=I(`dashboard-models:${e}`,[e,et],t=>sr(e,t),{enabled:gt&&!et});(0,_.useEffect)(()=>{if(pt.data!==void 0){let t=pt.data;dt.current+=1,v(t.status),ut.current=t.status,t.status!==`error`&&!t.stale&&Jn(`${vr}${e}`,t.status)}},[pt.data,e]),(0,_.useEffect)(()=>{let t=ht.data;t&&(t.health&&(h(t.health),b(t.providers),Jn(`${gr}${e}`,{health:t.health,providers:t.providers})),nt(t.error))},[ht.data,e]),(0,_.useEffect)(()=>{_t.data!==void 0&&(U(_t.data.maMode),Jn(`${yr}${e}`,_t.data.maMode))},[_t.data,e]);let wt=_t.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=bt.data;e&&(e.injection&&(me(e.injection.multiAgentGuidanceEnabled),ge(e.injection.syncCodexSubagentDefaults),ae(e.injection.injectionModel),se(e.injection.injectionEffort),le(e.injection.injectionEfforts),X(e.injection.injectionAvailable)),e.effortCaps&&(ve(e.effortCaps.effortCap),be(e.effortCaps.subagentEffortCap)))},[bt.data]),(0,_.useEffect)(()=>{let t=vt.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=qn(xr(e))??{};Jn(xr(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[vt.data,e]),(0,_.useEffect)(()=>{let t=yt.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===dt.current){let n=tr(ut.current,t.startupHealthSeed);v(n),ut.current=n,n&&Jn(`${vr}${e}`,n)}if(t.settings!==void 0){let n=qn(xr(e))??{};Jn(xr(e),{...n,settings:t.settings})}}},[yt.data,e]),(0,_.useEffect)(()=>{xt.data!==void 0&&(A(xt.data),Jn(`${_r}${e}`,xt.data))},[xt.data,e]),(0,_.useEffect)(()=>{St.data&&Oe(St.data)},[St.data]),(0,_.useEffect)(()=>{Ct.data&&S(Ct.data),L(Ct.loading)},[Ct.data,Ct.loading]),(0,_.useEffect)(()=>()=>{Be.current+=1,Ue.current+=1},[]);let Dt=I(Xe?.id&&Xe.restart?`update-job:${e}:${Xe.id}`:`update-job:idle:${e}`,[e,Xe?.id,Xe?.restart,Xe?.latestVersion],async t=>{if(!Xe?.id||!Xe.restart)return{reconnecting:!1};let n=Xe.latestVersion;try{let r=await Ot(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Xe.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Ot(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:!!(Xe?.id&&Xe.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=Dt.data;e&&(`job`in e&&e.job&&Z(e.job),$e(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[Dt.data]);let kt=(0,_.useMemo)(()=>br(x),[x]),jt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return kt;let t=[];for(let[n,r]of kt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[kt,a]),Mt=(0,_.useMemo)(()=>{let e=qt(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]),Pt=(0,_.useMemo)(()=>Jt(T?.visionModels,x,T?.vision?.model,T?.vision?.backend),[T?.visionModels,x,T?.vision]),Ft=async t=>{if(!T||j)return;let n=T,r={webSearch:Nt(T.webSearch,t.webSearch),vision:Nt(T.vision,t.vision),...T.visionModels?{visionModels:T.visionModels}:{}};M(!0),E(r);try{let n=await Ot(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,...n.visionModels?{visionModels:n.visionModels}:{}});let r=qn(xr(e))??{};Jn(xr(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{}}})}catch{E(n)}finally{M(!1)}};async function It(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),Ge.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`);We.current+=1}catch{O(n)}finally{Ge.current=!1,P(!1)}}let Lt=async t=>{if(!(W||H===t)){G(!0),te(null);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})});if(r.ok)U(t),Jn(`${yr}${e}`,t);else{let e=n(`dash.maSwitchFailed`,{status:String(r.status)});try{let t=await r.json();e=typeof t.error==`string`&&t.error||typeof t.message==`string`&&t.message||e}catch{}te(e)}}catch(e){te(e instanceof Error?e.message:n(`dash.maNetworkError`))}finally{G(!1)}}},Rt=async t=>{if(!de){fe(!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 Ot(await fetch(`${e}/api/injection-model`)),r=rr(n);me(r.multiAgentGuidanceEnabled),ge(r.syncCodexSubagentDefaults),ae(r.injectionModel),se(r.injectionEffort),Array.isArray(n.efforts)&&le(n.efforts),Array.isArray(n.available)&&X(n.available)}catch{}finally{fe(!1)}}},zt=async()=>{if(!C||R)return;let t=!C.codexAutoStart;z(!0),He.current=!0,w({...C,codexAutoStart:t});try{let n=await Ot(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Ve.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),nt(!0)}finally{He.current=!1,z(!1)}},Bt=(0,_.useCallback)(()=>{we(null),Ee(null)},[]),Vt=async()=>{if(!B){V(!0),we(null),Ee(null);try{let t=await Ot(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);we(t),t.projectConfigGrouped&&Oe(t.projectConfigGrouped)}catch(e){Ee(e instanceof Error?e.message:String(e))}finally{V(!1)}}},Ht=async(t,n=!1)=>{n&&(Le.current=0),Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null);let r=++ze.current;Ie(!0),Ye(null),qe(null);try{let n=await Ot(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==ze.current)return;if(qe(n),n.reason===`latest_unavailable`&&Le.current<2){let e=++Le.current;Re.current=window.setTimeout(()=>{r===ze.current&&(Re.current=null,Ht(t))},800*e);return}n.reason!==`latest_unavailable`&&(Le.current=0),Ie(!1)}catch(e){if(r!==ze.current)return;Ye(e instanceof Error?e.message:String(e)),Ie(!1)}},Ut=()=>{ze.current+=1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ie(!1),Ae(!1)},Wt=()=>{let e=At(m?.version);Me(e),Pe(!0),Ae(!0),Ht(e,!0)},Gt=e=>{Me(e),Ht(e,!0)},Kt=(0,_.useRef)(Wt);return(0,_.useEffect)(()=>{Kt.current=Wt}),(0,_.useEffect)(()=>{let e=()=>{Et()&&(tt(`dashboard`),Kt.current())},t=Et()?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:xt.loading&&!k,healthLoading:ht.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:F,settingsSaving:R,syncing:B,maMode:H,maModeResolved:wt,maBusy:W,setMaHelpOpen:q,maHelpOpen:K,maError:ee,effortCapHelpOpen:J,setEffortCapHelpOpen:Y,shadowCallHelpOpen:ne,setShadowCallHelpOpen:re,injectionModel:ie,injectionEffort:oe,injectionEfforts:ce,injectionAvailable:ue,injectionSaving:de,multiAgentGuidanceEnabled:pe,syncCodexSubagentDefaults:he,saveInjection:Rt,effortCap:_e,subagentEffortCap:ye,effortCapSaving:xe,setEffortCap:ve,setSubagentEffortCap:be,setEffortCapSaving:Se,syncResult:Ce,syncError:Te,projectConfigWarnings:De,updateOpen:ke,updateChannel:je,setUpdateRestart:Pe,updateRestart:Ne,updateLoading:Fe,updateCheck:Ke,updateError:Je,updateJob:Xe,reconnecting:Qe,error:et,effortCapHelpTriggerRef:rt,updateTriggerRef:it,maHelpTriggerRef:at,shadowCallHelpTriggerRef:Q,effortCapHelpDialogRef:ot,updateDialogRef:st,maHelpDialogRef:ct,shadowCallHelpDialogRef:lt,filteredGroups:jt,sidecarModels:Mt,visionModels:Pt,saveSidecar:Ft,saveShadowCall:It,switchMaMode:Lt,toggleCodexAutoStart:zt,runSync:Vt,clearSyncFeedback:Bt,fetchUpdateCheck:Ht,closeUpdateDialog:Ut,openUpdateDialog:Wt,changeUpdateChannel:Gt,runUpdate:async()=>{if(Ke?.canUpdate){Ye(null);try{let t=await Ot(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:je,restart:Ne})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);Z(t.job),$e(!1),Ut()}catch(e){Ye(e instanceof Error?e.message:String(e))}}}}}function Cr(e){nt(Dt(e))}function wr({apiBase:e}){let t=Sr(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,z.jsx)(gt,{style:{marginTop:40},icon:(0,z.jsx)(se,{}),title:(0,z.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,z.jsx)($e,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,z.jsx)(Gn,{...t}),m=(0,z.jsx)(Kn,{t:n,providers:a}),h=(0,z.jsx)(_n,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,z.jsx)(on,{...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=Cr,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,z.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,z.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,z.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 Tr=`https://chatgpt.com/backend-api/codex`,Er=`openai`;function Dr(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}}var Or=new URL(Tr).protocol;function kr(e,...t){return`${Or}//${e}/${t.join(`/`)}`}var Ar={"cline-pass":{adapter:`openai-chat`,baseUrl:kr(`api.cline.bot`,`api`,`v1`)},"mimo-free":{adapter:`mimo-free`,baseUrl:kr(`api.xiaomimimo.com`,`api`,`free-ai`,`openai`,`chat`)}};function jr(e,t){let n=Ar[e];return!n||t.adapter!==n.adapter||Dr(t.baseUrl)!==Dr(n.baseUrl)}function Mr(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 Nr(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||Mr(e.baseUrl)||e.hasApiKey===!0}function Pr(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Dr(e.baseUrl)===Tr}function Fr(e,t){return e===Er&&Pr(t)}function Ir(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||Mr(e.baseUrl)}function Lr(e,t){return Fr(e,t)?`accounts`:Ir(t)?`free`:`paid`}function Rr(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??Lr(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 zr(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}Nr(a)?t.push({name:i,...a,tier:Lr(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function Br(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 Vr(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:Nr(e)?`ready`:`needs-setup`}function Hr(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!Fr(`openai`,t)||!Pr(n))return e;let r={...e};return delete r.chatgpt,r}function Ur(e){return e.authMode===`local`||Mr(e.baseUrl)}var Wr=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function Gr(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(Ur(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return Wr.some(e=>n.includes(e))?`selfHosted`:`cloud`}function Kr(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 qr(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 Jr(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 Yr(e){let t={};for(let[n,r]of Object.entries(Kr(e)))t[n]=r.length;return t}function Xr(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 Zr={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function Qr(e,t,n){let r=typeof t==`object`&&t?t:Zr,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 $r(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 ei(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 ti(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function ni(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 ri(e,t=`en`){return ni(e,t)}function ii(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function ai(e,t){let n=Vr(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 oi(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 si(e){let t=Vr(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 ci({name:e,adapter:t,baseUrl:n,cls:r}){let i=Z(),a=fn(e,{adapter:t,baseUrl:n});return(0,z.jsx)(`span`,{className:r,children:a?(0,z.jsx)(`img`,{src:a,alt:``,"aria-hidden":`true`}):(0,z.jsx)(li,{name:e,label:pn(e,i)})})}function li({name:e,label:t}){let n=[...e].reduce((e,t)=>e+t.charCodeAt(0),0)%360,r=(t.trim()[0]??e[0]??`?`).toUpperCase();return(0,z.jsx)(`span`,{className:`provider-icon-fallback`,style:{background:`hsl(${n} 55% 90%)`,color:`hsl(${n} 65% 32%)`},"aria-hidden":`true`,children:r})}function ui({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Z(),l=Ir(e),u=Ur(e),d=ai(e,c),f=pn(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,z.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,z.jsx)(ci,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,z.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,z.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,z.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,z.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,z.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,z.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,z.jsx)(Ee,{width:17,height:17,"aria-hidden":`true`})}),(0,z.jsx)(`span`,{className:si(e),title:d,"aria-hidden":`true`})]})]})}var di=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0;function fi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e,r=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||di(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...di(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]}):[],i={...di(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...di(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...di(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...di(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...di(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...di(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...r.length>0?{customWindows:r}:{},updatedAt:di(n.updatedAt)??t??Date.now()};return i.fiveHourPercent!==void 0||i.weeklyPercent!==void 0||i.monthlyPercent!==void 0||(i.customWindows?.length??0)>0?i:null}function pi(e){return fi(e?.quota,e?.updatedAt)}function mi(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=di(t.usedPercent);if(n!==void 0)return{usedPercent:n,...typeof t.incomplete==`boolean`?{incomplete:t.incomplete}:{},...di(t.excludedAccounts)===void 0?{}:{excludedAccounts:t.excludedAccounts},...di(t.nextRecoveryAt)===void 0?{}:{nextRecoveryAt:t.nextRecoveryAt},...di(t.nextRecoveryPercent)===void 0?{}:{nextRecoveryPercent:t.nextRecoveryPercent}}}function hi(e){let t=e?.aggregation;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;if(n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`)return null;let r=di(n.excludedAccounts),i=di(n.unknownPlanAccounts);if(r===void 0||i===void 0||typeof n.incomplete!=`boolean`)return null;let a=n.currentAccount&&typeof n.currentAccount==`object`&&!Array.isArray(n.currentAccount)?n.currentAccount:null,o=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=mi(t);return typeof t.label==`string`&&n?[{label:t.label,...n}]:[]}):[],s=mi(n.fiveHour),c=mi(n.weekly),l=mi(n.monthly),u=!!s||!!c||!!l||o.length>0;return{presentation:n.presentation===`aggregate`||n.presentation===`effective-account-fallback`||n.presentation===`coverage-only`?n.presentation:u?`aggregate`:`coverage-only`,incomplete:n.incomplete,excludedAccounts:r,unknownPlanAccounts:i,partialWindowAccounts:di(n.partialWindowAccounts)??0,...s?{fiveHour:s}:{},...c?{weekly:c}:{},...l?{monthly:l}:{},...o.length>0?{customWindows:o}:{},...a?{currentAccount:{...typeof a.plan==`string`||a.plan===null?{plan:a.plan}:{},quota:fi(a.quota)}}:{}}}function gi(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function _i(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 vi(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function yi(e,t){return!e||!vi(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 bi(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function xi(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 Si(e,t,n){let r=yi(e,t);if(!r)return[];let i=[];typeof r.fiveHourPercent==`number`&&i.push({rank:0,row:{windowKey:`fiveHour`,label:n(`codexAuth.fiveHour`),limitLabel:n(`quota.fiveHourLimit`),percent:r.fiveHourPercent,resetAt:r.fiveHourResetAt}}),typeof r.weeklyPercent==`number`&&i.push({rank:1,row:{windowKey:`weekly`,label:n(`codexAuth.weekly`),limitLabel:n(`quota.weeklyLimit`),percent:r.weeklyPercent,resetAt:r.weeklyResetAt}}),typeof r.monthlyPercent==`number`&&i.push({rank:4,row:{windowKey:`monthly`,label:n(`codexAuth.monthly`),limitLabel:n(`quota.monthlyLimit`),percent:r.monthlyPercent,resetAt:r.monthlyResetAt}});for(let e of r.customWindows??[]){let t=xi(e.label,n);i.push({rank:bi(e.label),row:{customLabel:e.label,label:t,limitLabel:t,percent:e.percent,resetAt:e.resetAt}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function Ci(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 wi(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function Ti(e){return e>=99.5}function Ei(e,t){return t>0&&e>=t}function Di(e,t){return Ei(e,t)||Ti(e)?`bar-warn`:`bar-green`}function Oi(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function ki(e){return{"--bar-scale":String(Oi(e)/100)}}function Ai({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1,incompleteWindowKeys:s,incompleteCustomWindowLabels:c}){let{locale:l}=Ze(),u=Si(e,t,r);return u.length===0?o?a===`stacked`?(0,z.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,z.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,z.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,z.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,z.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,z.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,z.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,z.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,z.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,z.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,z.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:u.map(e=>(0,z.jsx)(Mi,{row:e,threshold:n,t:r,locale:l,incomplete:e.windowKey?s?.has(e.windowKey)===!0:e.customLabel!==void 0&&c?.has(e.customLabel)===!0},e.limitLabel))}):(0,z.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:u.map(e=>(0,z.jsx)(ji,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:l},e.label))})}function ji({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Ti(t),s=Ei(t,r),c=Di(t,r),l=Ni(n,i,a),u=l.day||l.time?`${i(`codexAuth.resets`)} ${l.day} ${l.time}`.replace(/\s+/g,` `).trim():void 0;return(0,z.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,z.jsx)(`span`,{className:`quota-label`,title:u,children:e}),(0,z.jsx)(`div`,{className:`bar`,title:u,children:(0,z.jsx)(`div`,{className:`bar-fill ${c}`,style:ki(t)})}),(0,z.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):u,"aria-label":u,children:[s&&(0,z.jsx)(se,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function Mi({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=Ti(e.percent),o=Ei(e.percent,t),s=Di(e.percent,t),c=Pi(e.resetAt,n,r);return(0,z.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,z.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,z.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,z.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,z.jsx)(`span`,{className:`quota-window-partial`,role:`note`,"aria-label":n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),title:n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),children:n(`pws.capacity.windowPartial`)})]}),(0,z.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,z.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,z.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,z.jsx)(`div`,{className:`bar-fill ${s}`,style:ki(e.percent)})}),(0,z.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,z.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,z.jsx)(se,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function Ni(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=wi(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 Pi(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=wi(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 Fi({report:e,pending:t}){let n=Z(),{locale:r}=Ze(),i=hi(e),a=pi(e),o=i?.presentation===`aggregate`,s=new Set,c=new Set;if(o&&i){i.fiveHour?.incomplete&&s.add(`fiveHour`),i.weekly?.incomplete&&s.add(`weekly`),i.monthly?.incomplete&&s.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&c.add(e.label)}let l=o&&i?[...i.fiveHour?[{key:0,label:n(`codexAuth.fiveHour`),window:i.fiveHour}]:[],...i.weekly?[{key:1,label:n(`codexAuth.weekly`),window:i.weekly}]:[],...i.monthly?[{key:2,label:n(`codexAuth.monthly`),window:i.monthly}]:[],...(i.customWindows??[]).map((e,t)=>({key:t+3,label:e.label,window:e}))]:[],u=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),d=e=>new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(new Date(e>1e10?e:e*1e3));return(0,z.jsxs)(z.Fragment,{children:[o&&(0,z.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(a||t)&&(0,z.jsx)(Ai,{quota:a,threshold:80,t:n,layout:`stacked`,pending:t,incompleteWindowKeys:o?s:void 0,incompleteCustomWindowLabels:o?c:void 0}),i&&(0,z.jsxs)(`div`,{className:`pws-capacity-details`,children:[l.flatMap(({key:e,label:t,window:r})=>r.nextRecoveryAt!==void 0&&r.nextRecoveryPercent!==void 0?[(0,z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,z.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,d(r.nextRecoveryAt)]}),(0,z.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:u(r.nextRecoveryPercent)})})]},e)]:[]),o&&i.currentAccount?.quota&&(0,z.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,z.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,z.jsx)(Ai,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i.incomplete&&i.excludedAccounts>0&&(0,z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts,unknown:i.unknownPlanAccounts})}),i.partialWindowAccounts>0&&(0,z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function Ii({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=Z(),{locale:c}=Ze(),l=$r(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)(()=>ei(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?pi(r):null,a=r?hi(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?Ci(i):-1})}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 Xr(e).slice(0,4)},[n,d]),b=e=>{let t=ti(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,z.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,z.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,z.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,z.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,z.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,z.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,z.jsx)(Li,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,z.jsx)(Li,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,z.jsx)(Li,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,z.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,z.jsx)(se,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,z.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,z.jsx)(ci,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:pn(e.name,s)}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,z.jsx)(fe,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,z.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,z.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,z.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,z.jsx)(ci,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:pn(e.name,s)}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:s(`pws.dashboard.checkedAgo`,{time:Qr(t.updatedAt,l)})})]}),(0,z.jsx)(fe,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,z.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,z.jsx)(Fi,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,z.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,z.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,z.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,z.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,z.jsx)(Ai,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,z.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,z.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,z.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,z.jsx)(ci,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:pn(e.name,s)}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:ni(e.requests,c)})}),(0,z.jsx)(fe,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,z.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,z.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,z.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,z.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function Li({count:e,label:t,tone:n}){return(0,z.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,z.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function Ri({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Z(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,z.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,z.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,z.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,z.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,z.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,z.jsx)(`textarea`,{ref:o,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":a(`pws.jsonEditorDesc`)}),i&&(0,z.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var zi=[{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`}],Bi=18e5;function Vi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt)||t-n.updatedAt>=Bi||!(`quota`in n)||n.label!==void 0&&typeof n.label!=`string`||n.source!==void 0&&typeof n.source!=`string`?null:{...typeof n.label==`string`?{label:n.label}:{},...typeof n.source==`string`?{source:n.source}:{},updatedAt:n.updatedAt,quota:n.quota,...n.aggregation===void 0?{}:{aggregation:n.aggregation}}}function Hi(e,t=Date.now()){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n={};for(let[r,i]of Object.entries(e)){let e=Vi(i,t);r.trim()&&e&&(n[r]=e)}return n}function Ui(e){return Hi(qn(e))}function Wi(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){if(!r||typeof r!=`object`||Array.isArray(r))continue;let e=r.provider,i=Vi(r,t);typeof e==`string`&&e.trim()&&i&&(n[e]=i)}return n}function Gi({providers:e,apiBase:t,defaultProvider:n,selectedName:r,onSelect:i,onRemoveProvider:a,onAddProvider:o,onEditConfig:s,jsonEditor:c,jsonSaving:l=!1,modelsRefreshToken:u=0,activeAccountNeedsReauth:d,quotaRefreshEpoch:f=0,quotaForceRefresh:p=!1,detail:m}){let h=Z(),[g,v]=(0,_.useState)(``),[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,L]=(0,_.useState)({}),[R,B]=(0,_.useState)({}),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(!1),G=`ocx.providers.quotas.v1:${t}`,ee=`ocx.providers.usage.v1:${t}`,[te,K]=(0,_.useState)(()=>qn(ee)?.totals??{}),[q,J]=(0,_.useState)(()=>qn(ee)?.models??{}),[Y,ne]=(0,_.useState)(()=>Ui(G)??{}),[re,ie]=(0,_.useState)(()=>!qn(ee)),[ae,se]=(0,_.useState)(()=>{let e=Ui(G);return!e||Object.keys(e).length===0}),[ce,ue]=(0,_.useState)(0),X=(0,_.useRef)(null),de=I(mr(t),[t],async e=>{let n=await fetch(t+`/api/usage?range=30d`,{signal:e});if(!n.ok)throw Error(String(n.status));return await n.json()}),fe=(0,_.useMemo)(()=>Br(zr(Hr(e)),d??{}),[e,d]),pe=(0,_.useCallback)(()=>{ue(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{H(!0),(async()=>{try{let n=await St(await fetch(`${t}/api/selected-models`));if(e)return;M(Yr(n)),P(Kr(n)),L(qr(n)),B(Jr(n)),W(!1)}catch{if(e)return;W(!0)}finally{e||H(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,ce]),(0,_.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=de.data;if(e)return;if(!t){de.loading&&ie(!qn(ee));return}let n={};for(let e of t.providers??[])n[e.provider]={requests:e.requests,totalTokens:e.totalTokens};K(n);let r={};for(let e of t.models??[]){let t=e.provider;r[t]||(r[t]=[]),r[t].push({model:e.model,...e.resolvedModel?{resolvedModel:e.resolvedModel}:{},requests:e.requests,totalTokens:e.totalTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens,shareRatio:e.shareRatio,...e.estimatedCostUsd===void 0?{}:{estimatedCostUsd:e.estimatedCostUsd}})}J(r),Jn(ee,{totals:n,models:r}),ie(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,ee,de.data,de.loading]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=Ui(G);(!n||Object.keys(n).length===0)&&se(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>Ct(e)).then(t=>{if(e||!t)return;let n=Wi(t.reports);ne(n),Jn(G,n)}).catch(()=>{e||ne(e=>{let t=Hi(e)??{};return Jn(G,t),t})}).finally(()=>{e||se(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,G]),(0,_.useEffect)(()=>{if(!D)return;let e=e=>{X.current&&!X.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 me=(0,_.useMemo)(()=>[...fe.ready,...fe.needsSetup,...fe.disabled],[fe]),he=(0,_.useMemo)(()=>me.filter(Ir).length,[me]),ge=me.length-he,_e=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of me)e[Gr(t)]+=1;return e},[me]),ve=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>Rr(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=Ir(t);return!(n&&!x.free||!n&&!x.paid||!C[Gr(t)])}),T);return{ready:y.ready?t(fe.ready):[],needsSetup:y.needsSetup?t(fe.needsSetup):[],disabled:y.disabled?t(fe.disabled):[]}},[fe,g,y,x,C,T]),ye=!y.ready||!y.needsSetup||!y.disabled||!x.free||!x.paid||!C.cloud||!C.local||!C.selfHosted||!C.login||T!==`az`,be=()=>{b({ready:!0,needsSetup:!0,disabled:!0}),S({free:!0,paid:!0}),w({cloud:!0,local:!0,selfHosted:!0,login:!0}),E(`az`)},xe=(0,_.useMemo)(()=>r?me.find(e=>e.name===r)??null:null,[r,me]),Se=(0,_.useMemo)(()=>{let e=new Map;for(let t of me){let n=pn(t.name,h);e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e.entries())r>1&&t.add(n);return t},[me,h]);if(me.length===0)return(0,z.jsx)(Ki,{onAddProvider:o});let Ce=[{key:`ready`,label:h(`pws.status.ready`),count:fe.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:fe.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:fe.disabled.length}],we=[{id:`ready`,label:h(`pws.status.ready`),count:ve.ready.length,ariaLabel:h(`pws.groupReady`,{count:ve.ready.length}),items:ve.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:ve.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:ve.needsSetup.length}),items:ve.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:ve.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:ve.disabled.length}),items:ve.disabled}],Te=we.flatMap(e=>e.items.map(e=>e.name)),Ee=k&&Te.includes(k)?k:r&&Te.includes(r)?r:Te[0]??null;return(0,z.jsx)(`div`,{className:`pws-shell-container`,children:(0,z.jsxs)(`div`,{className:`pws-root`,children:[(0,z.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,z.jsxs)(`div`,{className:`pws-search-row`,children:[(0,z.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,z.jsx)(le,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,z.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,z.jsxs)(`div`,{className:`pws-filter-wrap`,ref:X,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ye||D?` pws-filter-btn--active`:``}`,onClick:()=>O(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":D,"aria-controls":`pws-provider-filters`,children:[(0,z.jsx)(De,{width:18,height:18,"aria-hidden":`true`}),ye&&(0,z.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),D&&(0,z.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,z.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),Ce.map(({key:e,label:t,count:n})=>(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:y[e],onChange:()=>b(t=>({...t,[e]:!t[e]}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:x.free,onChange:()=>S(e=>({...e,free:!e.free}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:he})]}),(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:x.paid,onChange:()=>S(e=>({...e,paid:!e.paid}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:ge})]}),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:_e.cloud},{key:`local`,label:h(`pws.type.local`),count:_e.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:_e.selfHosted},{key:`login`,label:h(`pws.type.login`),count:_e.login}].map(({key:e,label:t,count:n})=>(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:C[e],onChange:()=>w(t=>({...t,[e]:!t[e]}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,z.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:zi.map(e=>(0,z.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,z.jsx)(`div`,{className:`pws-filter-footer`,children:(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:be,disabled:!ye,children:h(`pws.resetAll`)})})]})]})]}),(0,z.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(ve).every(e=>e.length===0)&&(0,z.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:ye?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),we.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,z.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,z.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,z.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,z.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,z.jsx)(ui,{item:e,selected:r===e.name,tabbable:Ee===e.name,modelCount:j[e.name],isDefault:n===e.name,showConfigId:Se.has(pn(e.name,h)),onClick:()=>i(e.name),onFocus:()=>A(e.name)}),a&&(0,z.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,z.jsx)(oe,{width:14,height:14})})]},e.name))]},e))]})]}),(0,z.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,z.jsx)(Ri,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):xe?m?.(xe,{usageTotals:te[xe.name],modelUsage:q[xe.name],quotaReport:Y[xe.name],availableModels:N[xe.name]??[],hasLiveModels:(F[xe.name]??0)>0,selectedModels:R[xe.name]??[],modelsLoading:V,modelsLoadFailed:U,onRetryModels:pe})??(0,z.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,z.jsx)(`h3`,{children:pn(xe.name,h)}),(0,z.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,z.jsx)(Ii,{sections:fe,quotaReports:Y,usageTotals:te,usageLoading:re,quotasLoading:ae,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function Ki({onAddProvider:e}){let t=Z();return(0,z.jsx)(`div`,{className:`pws-empty-root`,children:(0,z.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,z.jsx)(`div`,{"aria-hidden":`true`,children:(0,z.jsx)(U,{style:{width:64,height:64}})}),(0,z.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,z.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:(0,z.jsx)(Ce,{width:18,height:18})}),(0,z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:(0,z.jsx)(_e,{width:18,height:18})}),(0,z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:(0,z.jsx)(ge,{width:18,height:18})}),(0,z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function qi(e){if(Fr(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||Ur(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 Ji(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 Yi({item:e,usageTotals:t,quotaReport:n,oauthEmail:r,oauth:i,apiBase:a,connectionIdentity:o,onEditSettings:s,onViewUsage:c,onUpdateProvider:l,onReauthenticate:u,onCancelLogin:d,reauthBusy:f=!1}){let p=Z(),{locale:m}=Ze(),h=$r(p),g=Vr(e),v=!!e.activeNeedsReauth,y=p(g===`ready`?`pws.status.connected`:g===`needs-setup`?v?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),b=t?.requests,x=t?.totalTokens,S=pi(n),C=JSON.stringify([a??null,e.name,e.adapter,e.baseUrl,e.authMode??null,e.apiKeyTransport??null,e.liveModels??null,e.disabled===!0,e.hasApiKey===!0,e.hasHeaders===!0,e.allowPrivateNetwork===!0,e.keyOptional===!0,e.activeNeedsReauth===!0,o??null]),[w,T]=(0,_.useState)(null),E=(0,_.useRef)(null),D=w?.key===C&&w.testing,O=w?.key===C?w.result:null;(0,_.useEffect)(()=>()=>{E.current?.key===C&&(E.current.controller.abort(),E.current=null)},[C]);let k=(0,_.useCallback)(async()=>{if(!a)return;E.current?.controller.abort();let t=new AbortController;E.current={key:C,controller:t},T({key:C,testing:!0,result:null});try{let n=await St(await fetch(`${a}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),p(`pws.connectionFailed`));if(!n)throw Error(p(`pws.connectionFailed`));t.signal.aborted||T({key:C,testing:!1,result:n})}catch(e){t.signal.aborted||T({key:C,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:p(`pws.connectionFailed`)}})}finally{E.current?.controller===t&&(E.current=null)}},[a,C,e.name,p]),A=O?.applicable===!1?`not-applicable`:O?.ok===!0?`ok`:`failed`,j=O?.applicable===!1?p(`pws.connectionNotApplicable`):O?.ok===!0?O.message||p(`pws.connectionOk`):O?.error||p(`pws.connectionFailed`);return(0,z.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,z.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.connection`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.connection`)}),(0,z.jsxs)(`dl`,{className:`pws-kv`,children:[(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`dash.status`)}),(0,z.jsxs)(`dd`,{className:g===`ready`?`pws-status-ok`:`pws-status-warn`,children:[g===`ready`?(0,z.jsx)(J,{style:{width:13,height:13},"aria-hidden":`true`}):(0,z.jsx)(se,{style:{width:13,height:13},"aria-hidden":`true`}),y]})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`modal.baseUrl`)}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.cell.auth`)}),(0,z.jsx)(`dd`,{children:r?`${oi(e,p)} · ${r}`:oi(e,p)})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`modal.defaultModel`)}),(0,z.jsx)(`dd`,{children:e.defaultModel??(0,z.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.cell.note`)}),(0,z.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),a&&(0,z.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:()=>void k(),children:p(D?`pws.testing`:`pws.testConnection`)}),O&&(0,z.jsx)(`span`,{role:`status`,className:A===`ok`?`pws-status-ok`:A===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":A,children:j})]}),s&&(0,z.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:s,children:p(`pws.editSettings`)})]}),n&&(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.rateLimits`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.rateLimits`)}),(0,z.jsx)(Fi,{report:n,pending:!1})]}),(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.authSummary`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.authSummary`)}),v?(0,z.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,z.jsx)(se,{style:{width:14,height:14},"aria-hidden":`true`}),(0,z.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:p(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?p(`pws.attention.reauthForward`):p(`pws.attention.reauth`)]}),u&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:f,onClick:()=>u(),children:p(f?`prov.waitingBrowser`:`pws.reauthenticate`)}),f&&d&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(),children:p(`common.cancel`)})]})]}):(0,z.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,z.jsx)(`span`,{className:`pws-auth-dot`}),(0,z.jsx)(`span`,{children:e.authMode===`forward`?p(`pws.passthrough`):e.authMode===`oauth`?r?p(`pws.loggedInAs`,{email:r}):i?.loggedIn?p(`pws.loggedInTitle`):p(`pws.notLoggedIn`):e.hasApiKey?p(`pws.apiKeyConfigured`):oi(e,p)})]})]})]}),(0,z.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.statsAria`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.statsTitle`)}),(0,z.jsxs)(`dl`,{className:`pws-kv`,children:[typeof b==`number`&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.stats.totalRequests`)}),(0,z.jsx)(`dd`,{className:`pws-kv-mono`,children:ni(b,m)})]}),typeof x==`number`&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.stats.totalTokens`)}),(0,z.jsx)(`dd`,{className:`pws-kv-mono`,children:ri(x,m)})]}),n&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.stats.quotaUpdated`)}),(0,z.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?gi(n.source):void 0,children:Qr(n.updatedAt,h)})]}),typeof b!=`number`&&typeof x!=`number`&&!n&&(0,z.jsx)(`div`,{className:`muted`,children:p(`pws.usageUnavailable`)})]}),c&&(0,z.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:c,children:[p(`pws.viewUsage`),` →`]}),S&&(0,z.jsx)(`div`,{className:`muted pws-stats-note`,children:p(`pws.stats.quotaTracked`)})]}),(0,z.jsx)(Xi,{item:e,onUpdateProvider:l})]})]})}function Xi({item:e,onUpdateProvider:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``)){i(!1),u(``);return}c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}},[a,e.name,e.note,t,s,n]);return r?(0,z.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,z.jsx)(`textarea`,{ref: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,z.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,z.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,z.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,z.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function Zi({item:e,apiBase:t,availableModels:n,hasLiveModels:r,selectedModels:i,modelsLoading:a=!1,modelsLoadFailed:o=!1,needsReauth:s=!1,onRetryModels:c,onOpenAccounts:l}){let u=Z(),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(``),[S,C]=(0,_.useState)([]),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(null),M=(0,_.useRef)(null),N=(0,_.useMemo)(()=>new Set(i),[i]),P=(0,_.useMemo)(()=>e.models??[],[e.models]),F=p.trim(),I=!w||!F||F.includes(`/`)||n.includes(F)||S.includes(F)||P.includes(F)||e.defaultModel===F,L=(0,_.useMemo)(()=>_i(n,e.defaultModel,d,P,S,r),[n,e.defaultModel,d,P,S,r]);(0,_.useEffect)(()=>{let n=!0;return(async()=>{try{let r=await fetch(`${t}/api/custom-models`);if(!r.ok)throw Error();let i=await r.json();if(!Array.isArray(i))throw Error(`Invalid custom model list`);if(!n)return;C(i.flatMap(t=>{if(!t||typeof t!=`object`)return[];let n=t;return n.provider===e.name&&typeof n.modelId==`string`?[n.modelId]:[]})),D(!1),y(``),T(!0)}catch{if(!n)return;C([]),T(!1),D(!0),y(u(`models.networkError`))}})(),()=>{n=!1}},[t,e.name,u,O]);let R=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let 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,G=W?L.slice(0,300):L;return(0,z.jsxs)(`div`,{className:`pws-section`,children:[(0,z.jsxs)(`div`,{className:`pws-section-head`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),L.length>0&&(0,z.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:L.length})})]}),s&&(0,z.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,z.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),U&&!s&&(0,z.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,z.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,z.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,z.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,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{V()},disabled:h||I,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,z.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,z.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:R,style:{marginLeft:8},children:u(`common.retry`)})]}),!H&&(0,z.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,z.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&H?(0,z.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,z.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):H?(0,z.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):L.length===0?(0,z.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,z.jsx)(`ul`,{className:`pws-model-list`,children:G.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,z.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,z.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,z.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,z.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,z.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),W&&(0,z.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(L.length)})})]})}function Qi({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=Z(),{locale:a}=Ze(),o=$r(i),s=t?.requests!==void 0,c=pi(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,z.jsxs)(`div`,{className:`pws-section`,children:[(0,z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,z.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:ii(f,a)}),(0,z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,z.jsx)(`span`,{className:`pws-usage-metric-value`,children:ni(t?.requests,a)}),(0,z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,z.jsx)(`span`,{className:`pws-usage-metric-value`,children:ri(t?.totalTokens,a)}),(0,z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,z.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,z.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`pws-model-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`pws.col.model`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,z.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,z.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,z.jsxs)(_.Fragment,{children:[(0,z.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,z.jsx)(`td`,{className:`mono`,children:(0,z.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,z.jsx)(`td`,{className:`num mono`,children:ii(e.estimatedCostUsd,a)}),(0,z.jsx)(`td`,{className:`num mono`,children:ri(e.totalTokens,a)}),(0,z.jsx)(`td`,{className:`num`,children:e.requests}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`div`,{className:`pws-share-bar`,children:(0,z.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,z.jsx)(`tr`,{className:`pws-model-detail`,children:(0,z.jsx)(`td`,{colSpan:5,children:(0,z.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[` `,ri(e.inputTokens,a)]})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[` `,ri(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Ai,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,z.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,z.jsx)(`dd`,{children:gi(n.source)})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,z.jsx)(`dd`,{children:Qr(n?.updatedAt,o)})]})]})]}):(0,z.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function $i(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function ea(e){return $i(e)??`account-…`}function ta(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function na(e){let t=ta(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function ra(e){return e===`reauth_required`}function ia(e){return!!e?.needsReauth||ra(e?.health?.status)}function aa(e){return e===`cooldown`}function oa(e){return e===`warning`||e===`reauth_required`}function sa(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 ca(e,t){let n=sa(t);return n?e(n):null}function la(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):ea(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 ua(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return da(e)}function da(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 fa(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var pa=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function ma(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 ha({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=Z();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,z.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,z.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,z.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,z.jsx)(Ce,{width:20}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,z.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,z.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var ga=2500;function _a(){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;ua(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)},ga))})},[i])}}function va({url:e}){let t=Z(),{outcomeFor:n,copy:r}=_a();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,z.jsxs)(`div`,{className:`login-url-block`,children:[(0,z.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,z.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,z.jsx)(ye,{style:{width:13,height:13},"aria-hidden":`true`}),(0,z.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,z.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,z.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function ya({reauthAccountId:e,authUrl:t,manualCode:n,manualCodeBusy:r,manualCodeWaiting:i,statusNotice:a,statusTone:o,flowId:s,error:c,onManualCodeChange:l,onSubmitManualCode:u,onClose:d}){let f=Z();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,z.jsx)(va,{url:t}),(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,marginTop:12},children:[(0,z.jsx)(`div`,{className:`muted text-label`,children:f(`prov.pasteRedirectHint`)}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,z.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,z.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,z.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,z.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,z.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,z.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}function ba(e){if(typeof e!=`object`||!e||Array.isArray(e))return{catalogRefreshPending:!1};let t=Object.getOwnPropertyDescriptor(e,`catalogRefreshPending`);return{catalogRefreshPending:t!==void 0&&`value`in t&&t.value===!0}}function xa({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 St(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 Ct(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(ba(n)),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 Sa({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Z(),[a,o]=(0,_.useReducer)(ma,r,pa),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=xa({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]),g=i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,z.jsx)(`dialog`,{ref:c,"aria-label":g,className:`modal-overlay`,onCancel:h,children:(0,z.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,z.jsx)(ha,{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,z.jsx)(ya,{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 Ca=[2,1,0,-1,-2],wa=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function Ta(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function Ea(e){let t=Ta(e);return t>0?`+${t}`:String(t)}function Da(e){return wa.has(e)}function Oa(e){return wa.get(e)??null}function ka(e,t){let n=Ta(t);return e(`accountPool.priorityOption`,{name:e(Oa(n)??`accountPool.priorityCustom`),value:Ea(n)})}var Aa=1e4;function ja(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Ma(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Na(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Pa(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Fa(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Ia(e,t,n){if(e<=0){let t=Na(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Ma(t)??Na(0,n)}}async function La(e,t,n=(e,t)=>fetch(e,t),r=Aa){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 Ra=3e4,za=new Map;function Ba(e,t=!0){let n=za.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),a=I(mr(e,`codex`),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d&surface=codex`,{signal:t});if(!n.ok)throw Error(`account usage load failed`);return n.json()},{enabled:t}),[o,s]=(0,_.useState)(()=>n?.activeId??null),[c,l]=(0,_.useState)(()=>n==null?`loading`:`ready`),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(0),[C,w]=(0,_.useState)(()=>n!=null),[T,E]=(0,_.useState)(0),D=(0,_.useRef)(null);D.current===null&&(D.current=new Set);let O=(0,_.useRef)(null),k=(0,_.useRef)(0),A=(0,_.useRef)(null),j=(0,_.useRef)(null);j.current===null&&(j.current=new Set);let M=(0,_.useRef)(null),N=(0,_.useRef)(null),P=(0,_.useRef)(!!n?.accounts.length),F=(0,_.useRef)(n!=null),L=(0,_.useRef)(null),R=(0,_.useRef)(null),z=(0,_.useCallback)(e=>(j.current.add(e),()=>{j.current.delete(e)}),[]),B=(0,_.useCallback)(()=>Fa(M.current?.value),[]),V=(0,_.useCallback)(()=>M.current?.value,[]),H=(0,_.useCallback)(async(t=!1)=>{let n=++k.current;S(e=>e+1);try{let r=[...j.current],a=new Map;for(let e of r)a.set(e,e.beginActiveRead());!t&&!F.current&&l(`loading`);let o=null,c,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 k.current===n&&(o=(a.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel;return{...e,...t?{logLabel:t}:{},priority:Ta(e.priority)}}),i(o),P.current=o.length>0,F.current=!0,l(`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(k.current===n){let e=i.activeCodexAccountId??null,t=A.current;t&&e!==t.id||(A.current=null,c=e,s(e)),M.current={value:i},b(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of r)e.acceptActiveRead(i,a.get(e))}return!0}catch{if(k.current===n)for(let e of r)e.rejectActiveRead();return!1}})(),[f,p]=await Promise.all([u,d]);if(k.current!==n)return!1;if(f){l(`ready`),F.current=!0;let t=za.get(e);return za.set(e,{accounts:o??t?.accounts??[],activeId:c===void 0?t?.activeId??null:c}),p}return F.current||l(`error`),!1}finally{S(e=>Math.max(0,e-1)),w(!0)}},[e]);(0,_.useEffect)(()=>{t&&O.current!==e&&(O.current=e,Promise.resolve().then(()=>{H()}))},[e,t,H]);let U=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!U||T>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{H(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,U,T,H]),(0,_.useEffect)(()=>{if(!t||T>0)return;let e=window.setInterval(()=>{H()},Ra);return()=>window.clearInterval(e)},[t,H,T]);let W=(0,_.useCallback)(()=>{let e={};return D.current.add(e),E(D.current.size),e},[]),G=(0,_.useCallback)(e=>{D.current.delete(e)&&E(D.current.size)},[]),ee=(0,_.useCallback)(async t=>{if(N.current||R.current)return{ok:!1,reason:`busy`};N.current=t??`__main__`,d(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 A.current={id:r??null},s(r??null),b(r??`__main__`),H(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{N.current=null,d(null)}},[e,H]),te=(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 H(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,H]),K=(0,_.useCallback)(async(t,n)=>{if(L.current)return{ok:!1,reason:`busy`};L.current={accountId:t},p(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,paused:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=a&&typeof a==`object`?a:{};if(i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,paused:n}:e)),Object.prototype.hasOwnProperty.call(o,`activeCodexAccountId`)){let e=o.activeCodexAccountId??null;A.current={id:e},s(e)}return n&&b(e=>e===t?null:e),H(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,p(null)}},[e,H]),q=(0,_.useCallback)(async(t,n)=>{if(R.current||N.current)return{ok:!1,reason:`busy`};R.current={accountId:t},h(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/priority`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,priority:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=Ta((a&&typeof a==`object`?a:{}).priority??n);return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,priority:o}:e)),b(null),A.current=null,H(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{R.current=null,h(null)}},[e,H]),J=(0,_.useCallback)(async()=>{if(L.current)return{ok:!1,reason:`busy`};L.current=`bulk`,v(!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;A.current={id:e},s(e)}return b(e=>e!==null&&a.has(e)?null:e),H(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,v(!1)}},[e,H]),Y=(0,_.useCallback)(async t=>{try{let n=await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`});if(!n.ok)return{ok:!1,reason:`request`};let r=ba(await n.json().catch(()=>({})));return await H(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,H]),ne=(0,_.useCallback)(async()=>await H()?{ok:!0}:{ok:!1,reason:`reload`},[H]),re=o&&o!==`__main__`?r.find(e=>e.id===o):null,ie=r.find(e=>e.isMain),ae=re??ie,oe=!ae?.paused&&ia(ae);return{accounts:(0,_.useMemo)(()=>{let e=new Map((a.data?.accounts??[]).map(e=>[e.accountLogLabel,e]));return r.map(t=>{let n=t.isMain?`main`:t.logLabel,r=n?e.get(n):void 0;return r?{...t,usage30d:r}:t})},[r,a.data]),activeId:o,loadState:c,refreshing:x>0,initialLoading:!C,switchingId:u,pauseUpdatingId:f,priorityUpdatingId:m,pausingExhausted:g,activeNeedsReauth:oe,activePinnedId:y,load:H,switchAccount:ee,setAccountPaused:K,setAccountPriority:q,pauseExhaustedAccounts:J,saveAlias:te,removeAccount:Y,syncAfterAccountAdded:ne,pauseRefresh:W,resumeRefresh:G,subscribeLoadObserver:z,readLastThreshold:B,readLastActive:V}}function Va(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 Ha({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,z.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,z.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,z.jsx)(ue,{width:10,height:10,"aria-hidden":`true`})}),(0,z.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,z.jsx)(X,{width:10,height:10,"aria-hidden":`true`})})]})}var Ua={quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function Wa({threshold:e,draft:t,strategy:n=`quota`,hydrated:r=!0,saving:i,loadError:a,feedback:o,onDraftChange:s,onEditingChange:c,onCommit:l,onCancel:u,onToggle:d,onRetry:f}){let p=Z(),m=(0,_.useRef)(!1),h=e>0,g=Ua[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,z.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,z.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,z.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,z.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,z.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,z.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,z.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c(!1),m.current){m.current=!1;return}h&&!v&&l()}},children:[a&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,z.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,z.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,z.jsx)(Ha,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(Va(t,1,1,100))},onDecrement:()=>{c(!0),s(Va(t,-1,1,100))}})]})]}),(0,z.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,z.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,z.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,z.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var Ga=[`quota`,`round-robin`,`fill-first`],Ka=`quota`,qa=new Set(Ga);function Ja(e){return typeof e==`string`&&qa.has(e)?e:Ka}function Ya(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Xa(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function Za(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:Ja(i.accountPoolStrategy??t.strategy),stickyLimit:Ya(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var Qa={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},$a={quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function eo({strategy:e,stickyDraft:t,disabled:n=!1,strategySelectId:r=`account-pool-strategy`,stickyInputId:i=`account-pool-sticky-limit`,onStrategyChange:a,onStickyDraftChange:o,onStickyCommit:s}){let c=Z(),l=Ga.map(e=>({value:e,label:c(Qa[e])}));return(0,z.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,z.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,z.jsx)(`span`,{className:`desc`,children:c($a[e])}),(0,z.jsx)(`span`,{className:`desc`,children:c(`accountPool.unboundDefinition`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsx)(ht,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,z.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,z.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,z.jsx)(`input`,{id: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,z.jsx)(Ha,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=Va(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=Va(t,-1,1,100);o(e),s(e)}})]})})]})]})}function to(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:Ja(t.accountPoolStrategy),stickyLimit:Ya(t.accountPoolStickyLimit)}}function no({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Z(),[a,o]=(0,_.useState)(Ka),[s,c]=(0,_.useState)(1),[l,u]=(0,_.useState)(`1`),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(!1),y=(0,_.useRef)(0),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),w=(0,_.useCallback)(e=>{let t=Ja(e.accountPoolStrategy),n=Ya(e.accountPoolStickyLimit);o(t),r?.(t),c(n),u(String(n)),p.current=!0,f(!0),x(!1),C(null)},[r]),T=(0,_.useCallback)(e=>{let t=to(e);t&&w({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[w]),E=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(g.current){v.current=!0;return}w(n)}catch{g.current||x(!0)}},[e,w]),D=(0,_.useCallback)(()=>{v.current&&(v.current=!1,queueMicrotask(()=>{if(g.current){v.current=!0;return}E()}))},[E]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>y.current,acceptActiveRead:(e,t)=>{if(t===y.current){if(g.current){v.current=!0;return}T(e)}},rejectActiveRead:()=>{p.current||x(!0)}});return!g.current&&n&&T(n()),e},[t,T,n]),(0,_.useEffect)(()=>{!n||t||g.current||T(n())},[n,T,t]),(0,_.useEffect)(()=>{t||E()},[E,t]);let O=(0,_.useCallback)(async t=>{if(g.current)return;let n=a,l=s;t.strategy!==void 0&&(o(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(c(t.stickyLimit),u(String(t.stickyLimit))),g.current=!0,h(!0),C(null),y.current+=1;let d=await Za(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,z.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,z.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,z.jsx)(eo,{strategy:a,stickyDraft:l,disabled:k,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{k||e===a||O({strategy:e})},onStickyDraftChange:u,onStickyCommit:e=>{if(k)return;let t=Xa(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,z.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function ro({t:e,open:t,onToggle:n,children:r}){return(0,z.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,z.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,z.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function io(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&&(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=Fa(e),r=Pa(v.current,y.current,t,x.current);r===`defer`?S.current=ja(n):r===`apply`&&T(ja(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(ja(Fa(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 La(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=Ma(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=Ia(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])}}function ao({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=Z(),a=Ta(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=Ca.map(e=>({value:String(e),label:ka(i,e)})),l=Da(a)?c:[{value:String(a),label:ka(i,a)},...c];return(0,z.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,z.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,z.jsx)(ht,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(Ta(Number.parseInt(e,10)))}),(0,z.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function oo({value:e}){let t=Z(),n=Ta(e);return n===0?null:(0,z.jsx)(`span`,{className:`badge badge-muted`,children:ka(t,n)})}var so=new Map;function co(e,t){return`${e??``}\0${JSON.stringify(t)}`}function lo(e,t){let n=co(e,t??{}),r=so.get(n);return r||(r=new Intl.NumberFormat(e,t),so.set(n,r)),r}var uo={month:`short`,day:`numeric`,year:`numeric`},fo={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},po=new Map;function mo(e,t){let n=co(e,t),r=po.get(n);return r||(r=new Intl.DateTimeFormat(e,t),po.set(n,r)),r}function ho(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:mo(t,uo).format(n)}function go(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:mo(t,fo).format(n)}function _o(e,t){return!Number.isFinite(e)||e<0?`—`:`~${lo(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function vo(e,t){return ho(e,t)}function yo(e,t){return go(e,t)}function bo(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function xo({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=bo(n),s=o<=7;return(0,z.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,z.jsxs)(`div`,{className:`credit-item-head`,children:[(0,z.jsx)(ve,{width:13}),(0,z.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,z.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,z.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,z.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:vo(t,i)})}),(0,z.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:yo(n,i),days:String(o)})})]})]})}function So({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,z.jsx)(ve,{width:12}),`0`]}):r===void 0?null:(0,z.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,z.jsx)(ve,{width:12}),r]})}function Co({t:e,paused:t,saving:n}){let r=e(`codexAuth.pause`),i=e(`codexAuth.resume`),a=e(`common.saving`),o=n?a:t?i:r,s=Math.max(r.length,i.length,a.length);return(0,z.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function wo({pool:e,activeId:t,accountModeState:n,switchActionLabel:r,threshold:i,onOpenReset:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onPriorityChange:u,priorityUpdatingId:d,switchingId:f,pinnedId:p=null,onReauth:m,onEditAlias:h,onRemove:g,onCopyDoctor:_,doctorCopyOutcomeFor:v}){let y=Z(),b=e=>!e.paused&&t===e.id;return(0,z.jsx)(z.Fragment,{children:e.map(e=>{let t=e.health?.status,x=!!e.needsReauth||ra(t),S=aa(t),C=ca(y,e.health),w=la(y,`codex`,e.id,e.health);return(0,z.jsxs)(`div`,{className:`card ${b(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,z.jsxs)(`div`,{className:`card-head`,children:[(0,z.jsx)(`span`,{className:`dot ${x?`dot-amber`:b(e)?`dot-blue`:`dot-muted`}`}),(0,z.jsx)(`strong`,{children:e.alias??e.email}),(0,z.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,z.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,title:y(`codexAuth.pausedHint`),children:y(`codexAuth.paused`)}),(0,z.jsx)(oo,{value:e.priority}),e.id===p&&!e.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,children:y(`codexAuth.pinned`)}),(0,z.jsx)(So,{t:y,account:e,onClick:()=>a(e)}),C&&(0,z.jsx)(`span`,{className:na(t),children:C}),x&&!C&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:y(`codexAuth.needsReauth`)}),b(e)&&!x&&!S&&(0,z.jsx)(`span`,{className:`badge badge-primary`,children:y(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!b(e)&&!x&&!S&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),x&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>m(e.id),children:y(`codexAuth.reauthenticate`)}),_&&oa(t)&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>_(e.id),children:(0,z.jsx)(`span`,{"aria-live":`polite`,children:fa(y,v?.(e.id))})}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?y(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${y(`codexAuth.resume`)}. ${y(`codexAuth.pausedHint`)}`:y(`codexAuth.pause`),children:[e.paused?(0,z.jsx)(ae,{width:14}):(0,z.jsx)(ie,{width:14}),(0,z.jsx)(Co,{t:y,paused:e.paused,saving:c===e.id})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h(e),children:y(`prov.editAlias`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger card-right`,"aria-label":`${y(`common.remove`)} — ${e.email}`,title:`${y(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),g(e.id)},children:(0,z.jsx)(Y,{width:14})})]}),(0,z.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,z.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,y(`prov.accountId`),`: `,ea(e.id)]}),(0,z.jsx)(ao,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:d!==null||f!==null,onChange:t=>u(e,t)})]}),w&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:w}),S&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:y(`pws.healthCooldownHint`)}),x?(0,z.jsx)(`div`,{className:`card-sub faint`,children:y(`codexAuth.tokenExpired`)}):!S&&(0,z.jsx)(Ai,{quota:e.quota,plan:e.plan,threshold:i,t:y,pending:e.quota==null})]},e.id)})})}function To({onReauth:e}){let t=Z();return(0,z.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(se,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function Eo({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,onCancel:a,onConfirm:o}){let s=Z(),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let l=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:l,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,z.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?s(`codexAuth.preparePoolTitle`):e.id===`__main__`?s(`codexAuth.switchBack`):s(`codexAuth.switchTitle`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?s(`codexAuth.preparePoolDesc`):e.id===`__main__`?s(`codexAuth.switchBackDesc`):s(`codexAuth.switchDesc`)}),(0,z.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,z.jsx)(`strong`,{children:e.id===`__main__`?t||s(`codexAuth.codexApp`):e.email}),e.plan&&(0,z.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,z.jsxs)(`div`,{className:`notice-warn`,children:[(0,z.jsx)(se,{width:14}),` `,s(`codexAuth.cacheWarning`)]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`codexAuth.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r||i,onClick:o,children:s(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function Do({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=Ze(),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,z.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:f,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,z.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,z.jsx)(`div`,{className:`confirm-icon`,children:(0,z.jsx)(se,{width:22})}),(0,z.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,z.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:vo(n[0].granted_at,l)})}),(0,z.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,z.jsx)(ve,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,z.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,z.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,z.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,z.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,z.jsx)(xo,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,z.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function Oo({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onPriorityChange:u,priorityUpdatingId:d,switchingId:f,pinnedId:p=null,onOpenReset:m,onCopyDoctor:h,doctorCopyOutcomeFor:g}){let _=e(`codexAuth.codexApp`),v=t?.id??`__main__`,y={id:`__main__`,email:t?.email||_,plan:t?.plan,isMain:!0,paused:t?.paused??!1,priority:t?.priority??0,hasCredential:!0,quota:t?.quota??null},b=!!t?.needsReauth||ra(t?.health?.status),x=aa(t?.health?.status),S=ca(e,t?.health),C=t?la(e,`codex`,v,t.health):null;return(0,z.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,z.jsxs)(`div`,{className:`card-head`,children:[(0,z.jsx)(`span`,{className:`dot ${b?`dot-amber`:`dot-green`}`}),(0,z.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,z.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,z.jsx)(So,{t:e,account:{...t,id:`__main__`},onClick:()=>m({...t,id:`__main__`})}),t?.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,z.jsx)(oo,{value:y.priority}),p===`__main__`&&!t?.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.pinned`)}),S&&(0,z.jsx)(`span`,{className:na(t?.health?.status),children:S}),b&&!S&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,z.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&!n&&!b&&!x&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(y),children:a}),h&&oa(t?.health?.status)&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>h(v),children:(0,z.jsx)(`span`,{"aria-live":`polite`,children:fa(e,g?.(v))})}),t&&(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(y),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,z.jsx)(ae,{width:14}):(0,z.jsx)(ie,{width:14}),(0,z.jsx)(Co,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,z.jsxs)(`span`,{className:`card-right`,children:[(0,z.jsx)(_e,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,z.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,z.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),t&&(0,z.jsx)(ao,{value:y.priority,selectId:`codex-account-priority-${y.id}`,disabled:d!==null||f!==null,onChange:e=>u(y,e)})]}),C&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:C}),x&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),b?(0,z.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!x&&(0,z.jsx)(Ai,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function ko({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,z.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,z.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,z.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,z.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,z.jsx)(ie,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,z.jsx)(re,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function Ao({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,z.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,z.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,z.jsxs)(`div`,{className:`card-head`,children:[(0,z.jsx)(`span`,{className:`dot dot-muted`}),(0,z.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,z.jsxs)(`span`,{className:`card-badges`,children:[(0,z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,z.jsx)(ve,{width:12}),`0`]}),(0,z.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,z.jsx)(ie,{width:14}),` `,e(`codexAuth.pause`)]}),(0,z.jsxs)(`span`,{className:`card-right`,children:[(0,z.jsx)(_e,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,z.jsxs)(`div`,{className:`card-sub`,children:[(0,z.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,z.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,z.jsx)(Ai,{quota:null,threshold:0,t:e,pending:!0})]}),(0,z.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,z.jsx)(`div`,{className:`sep-line`}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,z.jsx)(ne,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,z.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,z.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,z.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,z.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,z.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function jo(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Mo(e,t,n,r){try{let i=await Ct(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:jo(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 No=`ocx doctor`;function Po({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a,advancedExtras:o=null}){let s=Z(),c=io(e,{updated:s(`codexAuth.autoSwitchUpdated`),updateFailed:s(`codexAuth.autoSwitchUpdateFailed`),invalid:s(`codexAuth.autoSwitchThresholdInvalid`)}),[l,u]=(0,_.useState)(null),{beginServerRead:d,acceptServerRead:f,rejectServerRead:p,hydrateServerValue:m}=c,h=Ba(e,!a),g=a??h,{accounts:v,activeId:y,loadState:b,switchingId:x,pauseUpdatingId:S,priorityUpdatingId:C,pausingExhausted:w,activePinnedId:T,load:E}=g,[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(null),[F,I]=(0,_.useState)(null),[L,R]=(0,_.useState)(null),B=(0,_.useRef)(null),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(null),[G,ee]=(0,_.useState)(!1),[te,K]=(0,_.useState)(!1),[q,J]=(0,_.useState)(null),[Y,re]=(0,_.useState)(!1),ie=_a(),ae=(0,_.useCallback)((e,t=`ok`)=>{B.current&&clearTimeout(B.current),I(e),R(t),B.current=setTimeout(()=>{I(null),R(null),B.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{B.current&&clearTimeout(B.current)},[]);let oe=(0,_.useCallback)(e=>{ie.copy(No,e)},[ie]),{subscribeLoadObserver:se,readLastThreshold:ce}=g;(0,_.useEffect)(()=>se({beginActiveRead:d,acceptActiveRead:f,rejectActiveRead:p}),[se,d,f,p]),(0,_.useEffect)(()=>{let e=ce();e!==void 0&&m(e)},[ce,m]),(0,_.useEffect)(()=>{if(!k)return;let e=g.pauseRefresh();return()=>g.resumeRefresh(e)},[g,k]);let le=y&&y!==`__main__`?v.find(e=>e.id===y):null,ue=!le?.paused&&ia(le);(0,_.useEffect)(()=>{i?.(ue)},[ue,i]);let X=(0,_.useCallback)(e=>{P(e),A(!0)},[]),de=(0,_.useCallback)(()=>{A(!1),P(null)},[]),fe=(0,_.useCallback)(e=>{g.syncAfterAccountAdded(),ae(s(e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.catalogRefreshPending?`warn`:`ok`),de()},[de,g,ae,s]),pe=async e=>{let n=await g.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;ae(s(`codexAuth.switchFailed`),`err`);return}O(null);let r=n.activeId,i=r&&r!==`__main__`?v.find(e=>e.id===r)?.email??s(`pws.accountOrdinal`,{count:`1`}):s(`codexAuth.mainAccount`);ae(s(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},me=async e=>{let t=window.prompt(s(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await g.saveAlias(e.id,t);ae(s(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},he=async e=>{let t=!e.paused,n=await g.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(O(t=>t?.id===e.id?null:t),ae(s(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},ge=async(e,t)=>{if(t===e.priority)return;let n=await g.setAccountPriority(e.id,t);!n.ok&&n.reason===`busy`||ae(s(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},_e=async e=>{let t=v.find(t=>t.id===e)?.email??s(`pws.accountOrdinal`,{count:`1`});if(!window.confirm(s(`codexAuth.removeConfirm`,{id:t})))return;let n=await g.removeAccount(e);n.ok?n.catalogRefreshPending&&ae(s(`codexAuth.catalogRefreshPending`),`warn`):ae(s(`codexAuth.removeFailed`),`err`)},ve=async()=>{H(!0);try{let e=await E(!0);ae(s(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{H(!1)}},ye=async()=>{let e=await g.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||ae(e.ok?e.pausedCount>0?s(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):s(`codexAuth.pauseExhaustedNone`):s(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},be=async t=>{W(t),ee(!1),J(null),re(!0);try{let n=await Ct(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));if(n){let e=(n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime());J(e)}}catch{}finally{re(!1)}},xe=async t=>{K(!0);try{let n=await Mo(e,t,s,E);n.close&&(W(null),ee(!1)),n.toast&&ae(n.toast,n.ok?`ok`:`err`)}finally{K(!1)}},Se=v.find(e=>e.isMain),Ce=v.filter(e=>!e.isMain),we=!Se?.paused&&(!y||y===`__main__`),Te=s(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Ee=S!==null||w,De=c.threshold??0,Oe=!r;return(0,z.jsxs)(`div`,{children:[(0,z.jsx)(ko,{t:s,embedded:r,refreshingQuota:V,actionFeedback:F,actionFeedbackTone:L,pausingExhausted:w,pauseBusy:Ee,onRefresh:()=>{ve()},onPauseExhausted:()=>{ye()}}),n,(0,z.jsx)(Ao,{t:s,loadState:b,accountsCount:v.length,onRetry:()=>{E()}}),(b!==`loading`||v.length!==0)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Oo,{t:s,main:Se,isMainActive:we,accountModeState:t,threshold:De,switchActionLabel:Te,onSwitch:O,onTogglePause:he,pauseUpdatingId:S,pauseBusy:Ee,onPriorityChange:(e,t)=>{ge(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onOpenReset:be,onCopyDoctor:Oe?oe:void 0,doctorCopyOutcomeFor:Oe?ie.outcomeFor:void 0}),(0,z.jsxs)(`div`,{className:`section-sep`,children:[(0,z.jsx)(`span`,{className:`section-label`,children:s(`codexAuth.accountPool`)}),(0,z.jsx)(`div`,{className:`sep-line`}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>A(!0),children:[(0,z.jsx)(ne,{width:14}),` `,s(`codexAuth.add`)]})]}),ue&&le&&(0,z.jsx)(To,{onReauth:()=>X(le.id)}),Ce.length===0&&(0,z.jsx)(gt,{title:s(`codexAuth.noPool`)}),(0,z.jsx)(wo,{pool:Ce,activeId:y,accountModeState:t,switchActionLabel:Te,threshold:De,onOpenReset:be,onSwitch:O,onTogglePause:he,pauseUpdatingId:S,pauseBusy:Ee,onPriorityChange:(e,t)=>{ge(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onReauth:X,onEditAlias:me,onRemove:_e,onCopyDoctor:Oe?oe:void 0,doctorCopyOutcomeFor:Oe?ie.outcomeFor:void 0})]}),(0,z.jsx)(no,{apiBase:e,subscribeLoadObserver:g.subscribeLoadObserver,readLastActive:g.readLastActive,onStrategyResolved:u}),(0,z.jsxs)(ro,{t:s,open:j,onToggle:()=>M(e=>!e),children:[l!==null&&(0,z.jsx)(Wa,{threshold:c.threshold,draft:c.draft,strategy:l,hydrated:c.hydrated,saving:c.saving,loadError:c.loadError,feedback:c.feedback,onDraftChange:c.setDraft,onEditingChange:c.setEditing,onCommit:c.commit,onCancel:c.cancel,onToggle:c.toggle,onRetry:()=>{c.retry(),E()}}),o]}),D&&(0,z.jsx)(Eo,{confirm:D,mainEmail:Se?.email,accountModeState:t,switchingId:x,orderBusy:C!==null,onCancel:()=>O(null),onConfirm:()=>{pe(D.id===`__main__`?`__main__`:D.id)}}),U&&(0,z.jsx)(Do,{resetPopup:U,resetConfirm:G,creditDetails:q,creditDetailsLoading:Y,redeeming:te,onClose:()=>{W(null),ee(!1),J(null)},onShowConfirm:()=>ee(!0),onCancelConfirm:()=>ee(!1),onRedeem:()=>{xe(U.id)}}),k&&(0,z.jsx)(Sa,{apiBase:e,reauthAccountId:N??void 0,onClose:de,onAdded:fe})]})}function Fo({apiBase:e,accountCount:t}){let n=Z(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(`80`),[s,c]=(0,_.useState)(`1`),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let t=!1,n=new AbortController;return Promise.resolve().then(()=>fetch(`${e}/api/oauth/accounts/pool?provider=anthropic`,{signal:n.signal})).then(e=>{if(!e.ok)throw Error(`load`);return e.json()}).then(e=>{if(t)return;let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=Ya(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:Ja(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=Ja(r?.strategy??t.strategy),s=Ya(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,z.jsxs)(`div`,{className:`card`,style:{marginTop:12},"aria-busy":x||l,children:[(0,z.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,z.jsxs)(`div`,{style:{flex:1},children:[(0,z.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,z.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,z.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,disabled:S,"aria-pressed":g,"aria-label":n(`anthropicPool.title`),title:n(g?`anthropicPool.on`:`anthropicPool.off`),onClick:()=>{h({enabled:!g,threshold:v,strategy:y,stickyLimit:b})},children:(0,z.jsx)(`span`,{className:`toggle-knob`})})]}),(0,z.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:10,padding:`10px 16px`,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,z.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`label`,{className:`field`,style:{display:`block`,marginTop:12},children:[(0,z.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,z.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,z.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,z.jsx)(eo,{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=Xa(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,z.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}var Io=4e3,Lo=262144,Ro=[],zo=[],Bo=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Vo=new Set([`imported`,`updated`,`failed`,`unsupported`]),Ho={imported:new Set([`imported`]),updated:new Set([`updated`]),failed:new Set([`invalid_record`,`credential_rejected`,`identity_mismatch`,`missing_project`,`persist_failed`]),unsupported:new Set([`unsupported_provider`,`unsupported_format`])};function Uo(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Wo(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Go(e){if(!Uo(e)||Object.keys(e).some(e=>!Bo.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!Wo(t)||!Wo(n)||!Wo(r)||!Wo(i)||!Wo(a)||!Array.isArray(o)||o.length!==t||n+r+i+a!==t)return null;let s={imported:0,updated:0,failed:0,unsupported:0};for(let[e,t]of o.entries()){if(!Uo(t)||Object.keys(t).some(e=>![`index`,`status`,`code`].includes(e)))return null;let n=String(t.status),r=String(t.code);if(t.index!==e||!Vo.has(n)||!Ho[n]?.has(r))return null;s[n]+=1}return s.imported!==n||s.updated!==r||s.failed!==i||s.unsupported!==a?null:{importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a}}function Ko({item:e,apiBase:t,oauth:n,accounts:r=Ro,keys:i=zo,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d}){let f=Z(),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(`idle`),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),O=(0,_.useRef)(null),k=_a();(0,_.useEffect)(()=>{if(r.length===0){D(!1);return}if(!r.some(e=>e.quota==null&&!e.quotaUnavailable)){D(!1);return}D(!0);let e=window.setTimeout(()=>D(!1),Io);return()=>window.clearTimeout(e)},[r]);let A=qi({...e,hasApiKey:e.hasApiKey||i.length>0}),j=A===`oauth-accounts`,M=A===`api-keys`;if(A===`codex-accounts`)return(0,z.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(`pws.availableAccounts`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:f(`pws.availableAccounts`)}),(0,z.jsx)(`div`,{className:`pwi-auth-body`,children:(0,z.jsx)(Po,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!A||!l)return null;let N=c?.provider===e.name?c:null,P=N?.deviceCode??``,F=k.outcomeFor(P),I=f(F===`copied`?`prov.codeCopied`:F===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),L=r.length>0||n?.loggedIn===!0,R=r.find(e=>e.active&&e.needsReauth),B=!!R,V=async()=>{let t=h.trim();if(t){y(!0);try{await l.onAddApiKey(e.name,t)&&(g(``),m(!1))}finally{y(!1)}}},H=async n=>{if(!(!n||b)){x(!0),C(`idle`),T(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>Lo){C(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{C(`invalid`);return}let i=await fetch(`${t}/api/oauth/accounts/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`google-antigravity`,format:`cockpit-tools`,document:r})});if(!i.ok){C(`failed`);return}let a=Go(await i.json().catch(()=>null));if(!a){C(`failed`);return}T(a),C(`complete`);try{await l.onRetryAccounts?.(e.name)}catch{}}catch{C(`failed`)}finally{O.current&&(O.current.value=``),x(!1)}}};return(0,z.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(j?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:f(j?`pws.availableAccounts`:`pws.apiKeys`)}),(0,z.jsxs)(`div`,{className:`pwi-auth-body`,children:[j&&(0,z.jsxs)(z.Fragment,{children:[e.name===`anthropic`&&(0,z.jsx)(Fo,{apiBase:t,accountCount:r.length}),e.name===`google-antigravity`&&(0,z.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:f(`pws.cockpitImportDescription`)}),(0,z.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:f(`pws.cockpitImportFileLabel`)}),(0,z.jsx)(`input`,{ref:O,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:b,onChange:e=>{H(e.currentTarget.files?.[0])}})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:b,onClick:()=>O.current?.click(),children:f(b?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,z.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[S===`invalid`&&f(`pws.cockpitImportInvalid`),S===`failed`&&f(`pws.cockpitImportFailed`),S===`complete`&&w&&f(`pws.cockpitImportComplete`,{imported:w.importedCount,updated:w.updatedCount,failed:w.failedCount,unsupported:w.unsupportedCount})]})]}),(0,z.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,z.jsx)(`span`,{className:`pwi-auth-dot ${B?`pwi-auth-dot--warn`:L?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:`pwi-auth-status-text`,children:L?r.length>0?f(`pws.loggedInTitle`):n?.email??f(`pws.loggedInTitle`):n?.error||f(`pws.notLoggedInTitle`)}),(0,z.jsxs)(`span`,{className:`pwi-auth-actions`,children:[R&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,R.id),children:f(`pws.reauthenticate`)}),L?(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:f(`prov.logout`)}):(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,z.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`}),f(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),s&&N&&(0,z.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,z.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,z.jsx)(`div`,{className:`pwi-auth-wait-title`,children:f(`prov.waitingBrowser`)}),N.deviceCode&&(0,z.jsxs)(`div`,{className:`pwi-device-code-wrap`,children:[(0,z.jsx)(`span`,{children:f(`prov.deviceCode`)}),(0,z.jsx)(`code`,{className:`pwi-device-code`,children:N.deviceCode}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>k.copy(P,P),children:(0,z.jsx)(`span`,{"aria-live":`polite`,children:I})})]}),(0,z.jsx)(va,{url:N.url??``}),l.onCancelLogin&&(0,z.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,z.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),f(`pws.accountsLoading`)]}),a===`error`&&(0,z.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,z.jsx)(`span`,{children:f(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:f(`pws.retryAccounts`)})]}),r.length>0&&(0,z.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=Ji(r,t,f),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||ra(a),u=aa(a),d=ea(t.id),p=ca(f,t.health),m=la(f,e.name,t.id,t.health);return(0,z.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,z.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!u&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${f(`pws.accountCurrent`)}`:``}`,disabled:!!(c||u||o&&!i),children:[(0,z.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,z.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,z.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,z.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${f(`prov.accountId`)}: ${d}`].filter(Boolean).join(` · `)}),m&&(0,z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m}),u&&(0,z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:f(`pws.healthCooldownHint`)})]}),p&&(0,z.jsx)(`span`,{className:na(a),children:p}),c&&!p&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:f(`pws.reauth`)}),t.active&&(0,z.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)}),i&&(0,z.jsx)(`span`,{className:`badge badge-muted`,children:f(`pws.accountSwitching`)})]}),c&&(0,z.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`)}),(0,z.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,z.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,z.jsx)(oe,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||E&&t.quota==null)&&(0,z.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,z.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:f(`pws.accountQuotaUnavailable`)}):(0,z.jsx)(Ai,{quota:t.quota??null,plan:null,threshold:80,t:f,layout:`stacked`,pending:t.quota==null})})]},t.id)})}),a===`ready`&&L&&r.length===0&&(0,z.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:f(`pws.noAccounts`)}),L&&(0,z.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`)})]}),M&&(0,z.jsxs)(z.Fragment,{children:[i.length>0&&(0,z.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,z.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,z.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,z.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,z.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,z.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,f(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,z.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)})]}),(0,z.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,z.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,z.jsx)(oe,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),p?(0,z.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,z.jsx)(`input`,{className:`input`,type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:v}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void V(),disabled:v||!h.trim(),children:f(v?`pws.saving`:`pws.addKey`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m(!1),g(``)},children:f(`common.cancel`)})]}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>m(!0),children:f(`pws.addKey`)})]})]})]})}function qo(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 Jo(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 Yo(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Xo=`https://chatgpt.com/backend-api/codex`;function Zo(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 Qo(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 $o(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Zo(e.baseUrl)!==Xo?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function es(e){return e.id===`openai`}function ts(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function ns(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return e.responsesPath?.trim()&&(t.responsesPath=e.responsesPath.trim()),(e.authMode===`key`||e.authMode===`forward`)&&(t.authMode=e.authMode),e.authMode===`key`&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),e.adapter.trim()===`anthropic`&&e.authMode===`key`&&e.apiKeyTransport===`bearer`&&(t.apiKeyTransport=`bearer`),e.defaultModel.trim()&&(t.defaultModel=e.defaultModel.trim()),e.allowPrivateNetwork&&(t.allowPrivateNetwork=!0),t}function rs(e,t){return es(e)?is(e):{name:t.name.trim(),provider:ns(t)}}function is(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var as=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function os(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 as(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new as(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new as(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(is(i))})).ok)throw new as(`codexAuth.enableOpenaiFailed`)}var ss=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],cs=[];function ls(e){return e===void 0?``:String(e)}function us(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function ds(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function fs(e){let t=Object.entries(e?.models??{}).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.requestsPerMinute??null,t.minIntervalMs??null]);return JSON.stringify([e?.enabled===!0,e?.requestsPerMinute??null,e?.minIntervalMs??null,t])}function ps({item:e,availableModels:t=cs,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Z(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),c=jr(e.name,e),l=c?e.liveModels!==!1:!1,[u,d]=(0,_.useState)(e.adapter),[f,p]=(0,_.useState)(e.baseUrl),[m,h]=(0,_.useState)(e.defaultModel??``),[g,v]=(0,_.useState)(s),[y,b]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[x,S]=(0,_.useState)(e.note??``),[C,w]=(0,_.useState)(e.allowPrivateNetwork??!1),[T,E]=(0,_.useState)(l),[D,O]=(0,_.useState)(!1),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)(e.codexAccountMode??`pool`),[N,P]=(0,_.useState)(!1),[F,I]=(0,_.useState)(null),[L,R]=(0,_.useState)(),[B,V]=(0,_.useState)(n?`loading`:`idle`),[H,U]=(0,_.useState)(()=>`custom`),[W,G]=(0,_.useState)(e.requestPacing?.enabled===!0),[ee,te]=(0,_.useState)(()=>ls(e.requestPacing?.requestsPerMinute)),[K,q]=(0,_.useState)(()=>ls(e.requestPacing?.minIntervalMs)),[J,Y]=(0,_.useState)(()=>({...e.requestPacing?.models??{}})),[ne,re]=(0,_.useState)(``),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)(null);(0,_.useEffect)(()=>{d(e.adapter),p(e.baseUrl),h(e.defaultModel??``),v(String(e.authMode??(e.keyOptional?`local`:`key`))),b(e.apiKeyTransport??`x-api-key`),S(e.note??``),w(e.allowPrivateNetwork??!1),E(l),G(e.requestPacing?.enabled===!0),te(ls(e.requestPacing?.requestsPerMinute)),q(ls(e.requestPacing?.minIntervalMs)),Y({...e.requestPacing?.models??{}}),A(null),I(null),queueMicrotask(()=>U(Jo(L,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,l,e.requestPacing,L]),(0,_.useEffect)(()=>{M(e.codexAccountMode??`pool`)},[e.codexAccountMode]),(0,_.useEffect)(()=>{if(!n)return;let t=!1,r=e.name,i=e.baseUrl;return fetch(`${n}/api/provider-presets`).then(e=>Ct(e)).then(e=>{if(t)return;if(!e){R(void 0),V(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;R(n),V(`ready`),U(Jo(n,i))}).catch(()=>{t||(R(void 0),V(`error`))}),()=>{t=!0}},[n,e.name]),(0,_.useEffect)(()=>{if(!n)return;let t=!0,r=()=>{fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`).then(e=>Ct(e)).then(e=>{t&&e&&le(e)}).catch(()=>void 0)};r();let i=window.setInterval(r,2e3);return()=>{t=!1,window.clearInterval(i)}},[n,e.name]);let ue=(0,_.useMemo)(()=>({enabled:W,...us(ee)===void 0?{}:{requestsPerMinute:us(ee)},...ds(K)===void 0?{}:{minIntervalMs:ds(K)},...Object.keys(J).length>0?{models:J}:{}}),[K,W,J,ee]),X=u.trim()!==e.adapter||f.trim()!==e.baseUrl||m.trim()!==(e.defaultModel??``)||g!==String(e.authMode??(e.keyOptional?`local`:`key`))||u.trim()===`anthropic`&&g===`key`&&y!==(e.apiKeyTransport??`x-api-key`)||x.trim()!==(e.note??``)||C!==(e.allowPrivateNetwork??!1)||T!==l,de=fs(ue)!==fs(e.requestPacing),fe=X||de;(0,_.useEffect)(()=>(i?.(fe),()=>i?.(!1)),[fe,i]);let pe=(0,_.useMemo)(()=>{let n=new Set(t);return m.trim()&&n.add(m.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,m,e.defaultModel]),me=(0,_.useMemo)(()=>{let e=[...ss];return u&&!e.includes(u)&&e.unshift(u),e},[u]),he=mn(e.name),ge=B===`ready`&&!!(L&&L.length>0),ve=u.trim()===`anthropic`&&g===`key`,ye=e.name===`openai`?$o(e):`invalid`,be=ye===`ready`||ye===`disabled`,xe=he&&B!==`error`,Se=async()=>{if(!r)return A({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;if(N)return!1;let t=ge?Yo(L,H,f):f.trim();if(!u.trim()||!t)return A({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;O(!0),A(null);try{if(W&&!ue.requestsPerMinute&&!ue.minIntervalMs&&!ue.models)return A({ok:!1,text:o(`pws.pacingRuleRequired`)}),!1;let n=de&&!X,i=n?{requestPacing:ue}:{adapter:u.trim(),baseUrl:t,defaultModel:m.trim(),authMode:g,note:x.trim(),allowPrivateNetwork:C,...de?{requestPacing:ue}:{}};n||(c&&T!==(e.liveModels!==!1)&&(i.liveModels=T),ve?i.apiKeyTransport=y:e.apiKeyTransport!==void 0&&(i.apiKeyTransport=``));let a=await r(e.name,i);return A(a.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:a.error||o(`prov.saveFailed`)}),a.ok}finally{O(!1)}},Ce=(0,_.useRef)(Se);(0,_.useEffect)(()=>{Ce.current=Se}),(0,_.useEffect)(()=>{if(a)return a(()=>Ce.current()),()=>a(null)},[a]);let we=async e=>{if(!(N||D||e===j)){if(!r){I({ok:!1,text:o(`pws.updatesUnavailable`)});return}P(!0),I(null);try{let t=await r(`openai`,{codexAccountMode:e});t.ok?(M(e),I({ok:!0,text:o(`pws.accountModeSaved`)})):I({ok:!1,text:t.error||o(`pws.accountModeFailed`)})}catch{I({ok:!1,text:o(`pws.accountModeFailed`)})}finally{P(!1)}}},Te=()=>{d(e.adapter),p(e.baseUrl),h(e.defaultModel??``),v(s),b(e.apiKeyTransport??`x-api-key`),S(e.note??``),w(e.allowPrivateNetwork??!1),E(l),A(null),G(e.requestPacing?.enabled===!0),te(ls(e.requestPacing?.requestsPerMinute)),q(ls(e.requestPacing?.minIntervalMs)),Y({...e.requestPacing?.models??{}}),U(Jo(L,e.baseUrl))},Ee=(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,z.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,z.jsx)(_e,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,z.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),he?(0,z.jsx)(`input`,{className:`input`,value:u,readOnly:!0,disabled:!0}):(0,z.jsx)(`select`,{className:`input`,value:u,onChange:e=>d(e.target.value),children:me.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))})]}),ge?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,z.jsx)(`select`,{className:`input`,value:H,onChange:e=>{let t=e.target.value;U(t),p(qo(L,t,f))},children:L.map(e=>(0,z.jsx)(`option`,{value:e.id,children:Ee(e.id,e.label)},e.id))})]}),H===`custom`&&(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,z.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,z.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),readOnly:xe,disabled:xe})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),pe.length>0?(0,z.jsxs)(`select`,{className:`input`,value:m,onChange:e=>h(e.target.value),children:[(0,z.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),pe.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]}):(0,z.jsx)(`input`,{className:`input`,value:m,onChange:e=>h(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),he?(0,z.jsx)(`input`,{className:`input`,value:oi(e,o),readOnly:!0,disabled:!0}):(0,z.jsxs)(`select`,{className:`input`,value:g,onChange:e=>v(e.target.value),children:[(0,z.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,z.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,z.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,z.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),be&&(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`codexAuth.accountModeTitle`)}),(0,z.jsxs)(`select`,{className:`input`,value:j,disabled:N||D,onChange:e=>{let t=e.target.value;if(t!==j){if(!window.confirm(o(`pws.accountModeConfirm`))){e.target.value=j;return}we(t)}},children:[(0,z.jsx)(`option`,{value:`pool`,children:o(`codexAuth.accountModePool`)}),(0,z.jsx)(`option`,{value:`direct`,children:o(`codexAuth.accountModeDirect`)})]}),(0,z.jsx)(`span`,{className:`pwi-settings-hint`,children:o(j===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),N&&(0,z.jsx)(`span`,{className:`muted text-label`,children:o(`pws.accountSwitching`)}),F&&(0,z.jsx)(`span`,{role:F.ok?`status`:`alert`,className:F.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:F.text})]}),ve&&(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,z.jsxs)(`select`,{className:`input`,value:y,onChange:e=>b(e.target.value),children:[(0,z.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,z.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,z.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:x,onChange:e=>S(e.target.value),rows:2})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:T,disabled:!c,onChange:e=>E(e.target.checked)}),(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,z.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),(0,z.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,z.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h3`,{id:`pwi-pacing-title`,children:o(`pws.pacingTitle`)}),(0,z.jsx)(`p`,{children:o(`pws.pacingDesc`)})]}),(0,z.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:W,onChange:e=>G(e.target.checked)}),` `,o(`pws.pacingEnabled`)]})]}),(0,z.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ee,onChange:e=>te(e.target.value),placeholder:`38`})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:K,onChange:e=>q(e.target.value),placeholder:`1600`})]})]}),(0,z.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.pacingSlowerWins`)}),(0,z.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:ce?.queued??0}),` `,o(`pws.pacingQueued`)]}),(0,z.jsxs)(`span`,{children:[(0,z.jsxs)(`strong`,{children:[ce?.nextSlotInMs??0,` ms`]}),` `,o(`pws.pacingNextSlot`)]}),(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:ce?.lastModelId??o(`pws.pacingNone`)}),` `,o(`pws.pacingLastModel`)]})]}),(0,z.jsx)(`h4`,{children:o(`pws.pacingModelOverrides`)}),(0,z.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingModel`)}),(0,z.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:ne,onChange:e=>re(e.target.value)}),(0,z.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,z.jsx)(`option`,{value:e},e))})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ie,onChange:e=>ae(e.target.value)})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:oe,onChange:e=>se(e.target.value)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=ne.trim(),t=us(ie),n=ds(oe);!e||t===void 0&&n===void 0||(Y(r=>({...r,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n}}})),re(``),ae(``),se(``))},children:o(`pws.pacingAdd`)})]}),Object.entries(J).length>0&&(0,z.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(J).map(([e,t])=>(0,z.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsxs)(`span`,{children:[t.requestsPerMinute===void 0?``:`${t.requestsPerMinute} ${o(`pws.pacingRpmUnit`)}`,t.requestsPerMinute!==void 0&&t.minIntervalMs!==void 0?` · `:``,t.minIntervalMs===void 0?``:`${t.minIntervalMs} ms`]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Y(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":o(`pws.pacingRemoveModel`,{model:e}),children:o(`pws.pacingRemove`)})]},e))})]}),fe&&(0,z.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,z.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,z.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Te,disabled:D,children:o(`pws.discardSettings`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Se(),disabled:D||N,children:o(D?`pws.saving`:`pws.saveSettings`)})]})]}),k&&(0,z.jsx)(`div`,{role:k.ok?`status`:`alert`,className:k.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:k.text})]})}function ms({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Z();return(0,z.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,z.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,z.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,z.jsxs)(`div`,{className:`dialog-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function hs({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Z();return(0,z.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,z.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,z.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,z.jsxs)(`div`,{className:`dialog-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function gs({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,accountsFocusToken:g=0,accountsFocusProvider:v=null,switchingAccountId:y,keys:b,busyProvider:x,loginHint:S,authHandlers:C,onCodexActiveNeedsReauthChange:w,codexController:T,onUpdateProvider:E,isDefault:D,onRemoveProvider:O,onSetDisabled:k,onSetDefault:A}){let j=Z(),[M,N]=(0,_.useState)(`overview`),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,B]=(0,_.useState)(!1),V=(0,_.useRef)(null),[H,U]=(0,_.useState)(0),W=(0,_.useCallback)(e=>{V.current=e},[]),G=e.disabled===!0,ee=(0,_.useMemo)(()=>Ir(e),[e]),te=(0,_.useMemo)(()=>Ur(e),[e]),K=(0,_.useMemo)(()=>qi(e),[e]),q=v===e.name?g:0,J=JSON.stringify([T?.activeId??``,m?.find(e=>e.active)?.id??``,b?.find(e=>e.active)?.id??``,p?.loggedIn===void 0?``:String(p.loggedIn),p?.needsReauth===void 0?``:String(p.needsReauth),u??``]),Y=(0,_.useMemo)(()=>[{id:`overview`,label:j(`pws.tab.overview`)},{id:`models`,label:j(`pws.tab.models`)},{id:`usage`,label:j(`pws.tab.usage`)},...K?[{id:`accounts`,label:j(K===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:j(`pws.tab.settings`)}],[K,j]),ne=(0,_.useCallback)(e=>{if(P&&M===`settings`&&e!==`settings`){L(e);return}N(e)},[M,P]);q!==H&&!(q&&!K)&&(U(q),q&&K&&(P&&M===`settings`?L(`accounts`):N(`accounts`)));let re=(0,_.useCallback)(()=>{if(P&&M===`settings`){L(`deselect`);return}d()},[P,M,d]),ie=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%Y.length;else if(e.key===`ArrowLeft`)n=(t-1+Y.length)%Y.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=Y.length-1;else return;e.preventDefault(),ne(Y[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ne,Y]),ae=`pws-tab-${M}`,se=`pws-panel-${M}`;return(0,z.jsxs)(`div`,{className:`pws-detail`,children:[(0,z.jsx)(`div`,{className:`pws-detail-head`,children:(0,z.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:re,children:[(0,z.jsx)(fe,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),j(`pws.allProviders`)]})}),(0,z.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,z.jsx)(ci,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,z.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,z.jsxs)(`h2`,{className:`pws-detail-title`,children:[pn(e.name,j),te&&(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:j(`modal.badge.local`)}),!te&&ee&&(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:j(`modal.badge.free`)})]})}),(0,z.jsxs)(`div`,{className:`pws-detail-actions`,children:[!D&&!G&&A&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(e.name),children:j(`prov.setDefault`)}),O&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>O(e.name),"aria-label":j(`pws.removeConfirmTitle`),title:j(`pws.removeConfirmTitle`),children:(0,z.jsx)(oe,{style:{width:15,height:15},"aria-hidden":`true`})}),k&&(0,z.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,z.jsx)(`span`,{className:`pws-detail-toggle-label`,children:j(`pws.enabledLabel`)}),(0,z.jsx)(pt,{on:!G,onClick:()=>k(e.name,!G),disabled:D,label:j(`pws.enabledLabel`)})]})]})]}),(0,z.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:Y.map((e,t)=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":M===e.id,tabIndex:M===e.id?0:-1,className:`pws-detail-tab${M===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ne(e.id),onKeyDown:e=>ie(e,t),children:e.label},e.id))}),(0,z.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:se,"aria-labelledby":ae,tabIndex:0,children:[M===`overview`&&(0,z.jsx)(Yi,{item:e,apiBase:f,connectionIdentity:J,usageTotals:t,quotaReport:r,oauthEmail:u,oauth:p,onEditSettings:()=>ne(`settings`),onViewUsage:()=>ne(`usage`),onUpdateProvider:E,reauthBusy:x===e.name,onCancelLogin:C?.onCancelLogin?()=>void C.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);C?.onReauth(e.name,n?.id);return}ne(`accounts`)}:void 0}),M===`models`&&(0,z.jsx)(Zi,{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:K?()=>ne(`accounts`):void 0},e.name),M===`usage`&&(0,z.jsx)(Qi,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),M===`accounts`&&(0,z.jsx)(Ko,{item:e,apiBase:f,oauth:p,accounts:m,keys:b,accountLoadState:h,switchingAccountId:y,busy:x===e.name,loginHint:S,authHandlers:C,onCodexActiveNeedsReauthChange:w,codexController:T}),M===`settings`&&(0,z.jsx)(ps,{item:e,apiBase:f,availableModels:i,onUpdateProvider:E,onDirtyChange:F,onRegisterSave:W},e.name)]}),I&&(0,z.jsx)(hs,{saving:R,onCancel:()=>{R||L(null)},onDiscard:()=>{if(R)return;let e=I;L(null),F(!1),e===`deselect`?d():N(e)},onSave:()=>{(async()=>{if(!R){B(!0);try{if(!(await V.current?.()??!1))return;let e=I;L(null),F(!1),e===`deselect`?d():e&&N(e)}finally{B(!1)}}})()}})]})}var _s=new Set([`anthropic`,`google-antigravity`]),vs=new Set([`github-copilot`,`cursor`]);function ys(e){let t=e.trim().toLowerCase();return _s.has(t)?`high`:vs.has(t)?`elevated`:null}function bs(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function xs(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function Ss(e,t=!1){let n={};for(let[t,r]of Object.entries(e))ia(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function Cs(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||(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)}"a=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||(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=Ji(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})});if(i.ok)a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),A(Object.keys(y)),c(!0);else{let e=await i.json().catch(()=>({}));a(e.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})});if(!r.ok){let e=await r.json().catch(()=>({}));return a(e.error||n(`prov.keyAddFail`),!1),!1}return a(n(`prov.keyAdded`,{name:e}),!0),S(null),await Promise.all([A(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),o(),c(!0)]),!0}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){let e=await l.json().catch(()=>({}));a(e.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=Ji(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)(()=>Ss(u,l),[u,l])}}function ws(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)});if(!n.ok){let e=await n.json().catch(()=>({}));return r(e.error||s(`prov.saveFailed`),!1),!1}return 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}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 Ts={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},Es=e=>Ts[e]??e;function Ds({apiBase:e,t,aliveRef:n,accountSets:r,setAccountSets:i,setBusy:a,setStatus:o,setLoginInfo:s,setOauthStatus:c,notify:l,fetchConfig:u,fetchOauth:d,fetchAccountSets:f,fetchProviderQuotas:p,bumpModelsRefresh:m,onLoginSettled:h}){let g=(0,_.useRef)(null);g.current===null&&(g.current=new Map);let v=(0,_.useCallback)(e=>{let t=(g.current.get(e)??0)+1;return g.current.set(e,t),t},[]);return{cancelLoginOAuth:(0,_.useCallback)(async r=>{let i=v(r);try{await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:r})})}catch{}n.current&&(g.current.get(r)===i&&(a(e=>e===r?null:e),s(e=>e?.provider===r?null:e)),l(t(`prov.loginCancelled`,{provider:Es(r)}),!1))},[n,e,v,l,a,s,t]),loginOAuth:async(d,_=!1,y)=>{let b=v(d),x=y?.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,..._||x?{addAccount:!0}:{},...x?{accountId:x,reauth:!0}:{}})});if(g.current.get(d)!==b||!n.current)return;if(!a.ok){l((await a.json().catch(()=>({}))).error||t(`prov.loginFailStart`,{provider:Es(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 v=r[d]?.accounts.length??0,y=!1;for(let a=0;a<150&&n.current&&g.current.get(d)===b;a++){if(await new Promise(e=>setTimeout(e,2e3)),g.current.get(d)!==b||!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${d}`).catch(()=>null),o=a?await Ct(a)??null:null;if(!o)continue;if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:Es(d)}):t(`prov.loginError`,{provider:Es(d),error:o.error}),!1),s(null),y=!0;break}let S=o.accounts?.length??0;if(_||x?S>v||o.done===!0:o.loggedIn||o.done===!0){c(e=>({...e,[d]:o}));let e=x?o.accounts?.find(e=>e.id===x):o.accounts?.find(e=>e.active)??o.accounts?.find(e=>e.id===o.activeAccountId);if(x&&!e){l(t(`prov.loginError`,{provider:Es(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),y=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:Es(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),y=!0;break}if(o.accounts){let e=o.accounts.find(e=>e.active)?.id??null;i(t=>({...t,[d]:{activeAccountId:o.activeAccountId??e,accounts:o.accounts}}))}s(null),h?.(d);let a=Object.keys(r);if(await f(new Set(a).has(d)?a:[...a,d]),!n.current||g.current.get(d)!==b)return;_&&!x&&S<=v?l(t(`prov.loginSameAccount`,{provider:Es(d)}),!1):l(t(`prov.loginOk`,{provider:Es(d),cmd:`ocx sync`}),!0),u(),p(!0),m(),y=!0;break}}!y&&g.current.get(d)===b&&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:Es(d)}),!1),s(null))}catch{g.current.get(d)===b&&l(t(`prov.loginRequestFail`,{provider:Es(d)}),!1)}finally{n.current&&g.current.get(d)===b&&a(null)}},logoutOAuth:async n=>{v(n),a(e=>e===n?null:e),s(e=>e?.provider===n?null:e);try{if(!(await fetch(`${e}/api/oauth/logout?provider=${encodeURIComponent(n)}`,{method:`POST`})).ok){l(t(`prov.logoutFail`,{provider:Es(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:Es(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:Es(n)}),!1)}}}}async function Os(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function ks(e,t,n){switch(e.code){case`last_provider`:return t(`prov.removeLastProvider`);case`provider_has_dependent_combos`:return t(`prov.removeHasDependentCombos`,{combos:(Array.isArray(e.combos)?e.combos.filter(e=>typeof e==`string`).join(`, `):``)||`—`});case`default_provider_disabled`:return t(`prov.defaultDisabled`);default:return typeof e.error==`string`&&e.error.trim()?e.error.trim():n}}function As({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,refreshCodexAccount:u}){let d=(0,_.useCallback)(async e=>{a(e)},[a]),f=(0,_.useCallback)(async u=>{let d=u;if(!d||n.current)return;n.current=!0,a(null);let f=t(`prov.removeFail`,{name:d});try{let n=await fetch(`${e}/api/providers?name=${encodeURIComponent(d)}`,{method:`DELETE`});if(n.ok){let e=await n.json().catch(()=>({})),a=typeof e.defaultProvider==`string`?e.defaultProvider:null;o(a?t(`prov.removedDefault`,{name:d,defaultProvider:a}):t(`prov.removed`,{name:d}),!0),r===d&&i(null),s(),c(),l(!0)}else o(ks(await n.json().catch(()=>({})),t,f),!1)}catch{o(f,!1)}finally{n.current=!1}},[e,s,c,l,o,n,a,i,t,r]),p=(0,_.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 Os(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),m=(0,_.useCallback)(async(n,r)=>{try{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok)return{ok:!1,error:await Os(i,t(`prov.updateFail`))};if(await s(),Object.hasOwn(r,`codexAccountMode`)){let e=[l(!0)];u&&e.push(Promise.resolve(u())),await Promise.all(e)}return{ok:!0}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,l,u,t]);return{removeProvider:d,confirmRemoveProvider:f,setProviderDisabled:p,setDefaultProvider:(0,_.useCallback)(async n=>{try{let r=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({setDefault:!0})});return r.ok?(o(t(`prov.setDefaultSuccess`,{name:n}),!0),await s(),!0):(o(ks(await r.json().catch(()=>({})),t,t(`prov.setDefaultFail`,{name:n})),!1),!1)}catch{return o(t(`prov.setDefaultFail`,{name:n}),!1),!1}},[e,s,o,t]),updateProvider:m}}function js({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await St(await fetch(`${e}/api/config`));n(t??null),s&&t&&Jn(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await St(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 Ct(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function Ms({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Z(),a=(0,_.useId)(),o=(0,_.useId)(),s=(0,_.useRef)(null),c=(0,_.useRef)(!1),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(!1),p=ys(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`:xs(p),v=h===`anthropic`||h===`google-antigravity`;return(0,z.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,z.jsx)(`h3`,{id:a,children:i(bs(p),{provider:t})}),(0,z.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,z.jsx)(se,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,z.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,z.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,z.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,z.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function Ns(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function Ps(e){return Lr(e.id,Ns(e))}function Fs(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[Ps(n)].push(n);return t}function Is(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}var Ls={},Rs=[],zs={};function Bs({presets:e,usageRank:t=Ls,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=Rs,accountStatus:s=zs,busyProvider:c=null,onLogin:l,onCancelLogin:u,onLogout:d,onManage:f}){let p=Z(),[m,h]=(0,_.useState)(r),[g,v]=(0,_.useState)(``),y=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),b=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return y.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)})},[y,t]),x=(0,_.useMemo)(()=>Fs(b),[b])[m],S=(0,_.useMemo)(()=>Is(x,g),[x,g]),C=e=>{let t=e.codexAccountMode===`direct`?(0,z.jsx)(`span`,{className:`badge badge-green`,children:p(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,z.jsx)(`span`,{className:`badge badge-accent`,children:p(`modal.badge.pool`)}):e.auth===`oauth`?(0,z.jsx)(`span`,{className:`badge badge-accent`,children:p(`modal.badge.oauth`)}):e.auth===`forward`?(0,z.jsx)(`span`,{className:`badge badge-green`,children:p(`modal.badge.codexLogin`)}):e.auth===`local`?(0,z.jsx)(`span`,{className:`badge badge-amber`,children:p(`modal.badge.local`)}):e.keyOptional?null:(0,z.jsx)(`span`,{className:`badge badge-muted`,children:p(`modal.badge.apiKey`)}),n=(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,z.jsx)(`span`,{className:`badge badge-green`,children:p(`modal.badge.free`)}):null;return(0,z.jsxs)(z.Fragment,{children:[n,t]})};return(0,z.jsxs)(`div`,{className:`provider-catalog`,children:[(0,z.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":m===e,className:`provider-catalog-tab${m===e?` active`:``}`,onClick:()=>{h(e),v(``)},children:p(e===`accounts`?`modal.tab.accounts`:e===`free`?`modal.tab.free`:`modal.tab.paid`)},e))}),m===`accounts`&&(0,z.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:p(`modal.accountsHint`)}),(0,z.jsx)(`input`,{className:`input provider-catalog-search`,value:g,onChange:e=>v(e.target.value),placeholder:p(`modal.search`)}),(0,z.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&S.length===0&&(0,z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:p(`modal.catalogLoading`)}),m!==`accounts`&&S.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`title`,children:e.label}),(0,z.jsxs)(`div`,{className:`sub`,children:[(0,z.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,z.jsx)(`div`,{className:`provider-catalog-badges`,children:C(e)})]},e.id)),m!==`accounts`&&!n&&S.length===0&&(0,z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:p(`modal.noMatch`)}),m===`accounts`&&o.map(e=>{let t=s[e.id],n=c===e.id,r=!!t?.loggedIn,i=r?t?.email??e.statusLabel??p(`modal.accountLoggedIn`):t?.error??e.statusLabel??p(`modal.accountLoggedOut`);return(0,z.jsxs)(`div`,{className:`list-row provider-catalog-account-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`title`,children:e.label}),(0,z.jsx)(`div`,{className:`sub`,children:i})]}),(0,z.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,z.jsxs)(z.Fragment,{children:[r&&(0,z.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-auth`,children:p(`modal.accountManage`)}),l&&(0,z.jsx)(`button`,{type:`button`,className:r?`btn btn-ghost`:`btn btn-primary`,disabled:n,onClick:()=>{n||l(e.id)},children:p(n?`codexAuth.enablingOpenai`:r?`modal.accountAdd`:`modal.accountLogin`)})]}):r?(0,z.jsxs)(z.Fragment,{children:[f&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>f(e.id),children:p(`modal.accountManage`)}),l&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:n,onClick:()=>{n||l(e.id,!0)},children:p(n?`prov.waitingBrowser`:`modal.accountAdd`)}),n&&u&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:p(`common.cancel`)}),d&&!n&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(e.id),children:p(`modal.accountLogout`)})]}):n?u&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:p(`common.cancel`)}):l&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>l(e.id),children:p(`modal.accountLogin`)})})]},e.id)}),m===`accounts`&&o.length===0&&!n&&(0,z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:p(`modal.noMatch`)})]}),(0,z.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,z.jsx)(`div`,{style:{flex:1}}),m!==`accounts`&&(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:p(`modal.notListed`)})]})]})}function Vs({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,manualCode:o,manualCodeBusy:s,manualCodeMsg:c,manualCodeOk:l,onRequestLogin:u,onUseApiKeyInstead:d,onManualCodeChange:f,onSubmitManualCode:p,onBack:m}){let h=Z();return(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,z.jsx)(`div`,{className:`muted text-control`,children:e.note??h(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>u(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,z.jsx)(_e,{}),n?h(`modal.waitingBrowser`):h(`modal.logInWith`,{label:e.label})]}):(0,z.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:h(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,z.jsx)(va,{url:a}),n&&(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,z.jsx)(`div`,{className:`muted text-label`,children:h(`prov.pasteRedirectHint`)}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,z.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,z.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,z.jsx)(`div`,{className:`text-label`,style:{color:l?`var(--accent-hover)`:`var(--amber)`},children:c})]}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:d,children:h(`modal.useApiKeyInstead`)}),(0,z.jsx)(`div`,{style:{flex:1}}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}function Hs({label:e,children:t}){return(0,z.jsxs)(`label`,{style:{display:`block`},children:[(0,z.jsx)(`span`,{className:`field-label`,children:e}),t]})}function Us({preset:e,form:t,endpointChoice:n,error:r,saving:i,dup:a,isCustom:o,isLocal:s,isReservedForward:c,presetDescription:l,onFormChange:u,onEndpointChoiceChange:d,onSubmit:f,onUseOauthLogin:p,onBack:m}){let h=Z();return(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,z.jsxs)(`details`,{className:`setup-guide`,children:[(0,z.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,z.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,z.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,z.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,z.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,z.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,z.jsx)(Hs,{label:h(`modal.providerName`),children:(0,z.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Hs,{label:h(`modal.adapter`),children:(0,z.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,z.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Hs,{label:h(`modal.endpoint`),children:(0,z.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:qo(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,z.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,z.jsx)(Hs,{label:h(`modal.baseUrl`),children:(0,z.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,z.jsx)(Hs,{label:h(`modal.baseUrl`),children:(0,z.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,z.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,z.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,z.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,z.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):e.keyOptional?(0,z.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,z.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,z.jsxs)(z.Fragment,{children:[e.dashboardUrl&&(0,z.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,z.jsx)(ge,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,z.jsx)(he,{style:{width:13,height:13}})]}),(0,z.jsx)(Hs,{label:h(`modal.apiKey`),children:(0,z.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,z.jsx)(Hs,{label:h(`modal.apiKeyTransport`),children:(0,z.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,z.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,z.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,z.jsx)(Hs,{label:h(`modal.defaultModel`),children:(0,z.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,z.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,z.jsx)(`div`,{style:{flex:1}}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Ws=2e3;function Gs({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,Ws)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await Ct(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 Ks(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 qs(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 Js({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,onAccountManage:f,onOpen:p}){let m=Z(),h=(0,_.useMemo)(()=>[{id:`custom`,label:m(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[m]),[g,v]=(0,_.useReducer)(qs,a,e=>Ks(e,m(`modal.customProvider`))),y=(0,_.useRef)(!0),b=(0,_.useRef)(null),x=(0,_.useRef)(null),S=I(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),C=I(`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}),w=I(mr(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()}),T=S.data??[],E=C.data??h,D=C.loading,O=Object.fromEntries((w.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:k,form:A,saving:j,error:M,oauthBusy:N,oauthMsg:P,oauthMsgTone:F,oauthUrl:L,oauthUrlProvider:R,manualCode:B,manualCodeBusy:V,manualCodeMsg:H,manualCodeOk:U,endpointChoice:W,oauthTosPending:G}=g;(0,_.useEffect)(()=>{y.current=!0,b.current=document.activeElement,p?.();let e=x.current;if(e){let t=e.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);t&&t.focus()}return()=>{y.current=!1,b.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!G&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,G]);let ee=e=>{let t=ts(e);return t?m(t):e.note},te=e=>{let t=Jo(e.baseUrlChoices,e.baseUrl);v({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?qo(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},K=async()=>{if(!A)return;let t=k?es(k):!1,n=k?.baseUrlChoices?.length?Yo(k.baseUrlChoices,W,A.baseUrl):A.baseUrl.trim();if(!t&&!A.name.trim()){v({type:`set-error`,error:m(`modal.nameRequired`)});return}if(!t&&!n){v({type:`set-error`,error:m(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){v({type:`set-error`,error:m(`modal.baseUrlPlaceholderError`)});return}let i={...A,baseUrl:n},a;try{a=rs(k??{id:`custom`},i)}catch{v({type:`set-error`,error:m(`modal.invalidPreset`)});return}v({type:`set-saving`,saving:!0}),v({type:`set-error`,error:``});try{let t=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(!t.ok){let e=await t.json().catch(()=>({}));v({type:`set-error`,error:e.error||m(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{v({type:`set-error`,error:m(`modal.networkError`)})}finally{v({type:`set-saving`,saving:!1})}},{loginOAuth:q,submitManualCode:J}=Gs({apiBase:e,t:m,aliveRef:y,onAdded:r}),ne={setOauthBusy:e=>v({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>v({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>v({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t)=>v({type:`set-oauth-url`,url:e,providerId:t}),setManualCode:e=>v({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>v({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>v({type:`set-manual-code-msg`,msg:H,ok:e})},re=A?t.includes(A.name.trim())&&A.name.trim()!==``:!1,ie=e=>{if(!N){if(ys(e)){v({type:`set-oauth-tos-pending`,providerId:e});return}q(e,ne)}},ae=e=>{J(e,B,V,{setManualCodeBusy:e=>v({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>v({type:`set-manual-code`,code:e}),setManualCodeOk:e=>v({type:`set-manual-code-msg`,msg:H,ok:e}),setManualCodeMsg:e=>v({type:`set-manual-code-msg`,msg:e})})},oe=k?.id===`custom`,se=A?.authMode===`local`,ce=k?es(k):!1;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":m(`modal.add`),className:`modal-overlay`,children:(0,z.jsxs)(`div`,{ref:x,className:`modal-card`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:k?m(`modal.addNamed`,{label:k.label}):m(`modal.add`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":m(`common.close`),onClick:n,children:(0,z.jsx)(Y,{})})]}),k?A&&(k.auth===`oauth`&&A.authMode===`oauth`?(0,z.jsx)(Vs,{preset:k,oauthSupported:T,oauthBusy:N,oauthMsg:P,oauthMsgTone:F,oauthUrl:R===k.oauthProvider?L:``,manualCode:B,manualCodeBusy:V,manualCodeMsg:H,manualCodeOk:U,onRequestLogin:ie,onUseApiKeyInstead:()=>{v({type:`use-api-key-instead`,form:{...A,authMode:`key`}})},onManualCodeChange:e=>v({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{ae(e)},onBack:()=>v({type:`back`})}):(0,z.jsx)(Us,{preset:k,form:A,endpointChoice:W,error:M,saving:j,dup:re,isCustom:oe,isLocal:se,isReservedForward:ce,presetDescription:ee,onFormChange:e=>v({type:`set-form`,form:e}),onEndpointChoiceChange:e=>v({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{K()},onUseOauthLogin:()=>v({type:`use-oauth-login`,form:{...A,authMode:`oauth`}}),onBack:()=>v({type:`back`})})):(0,z.jsx)(Bs,{presets:E,usageRank:O,presetsLoading:D,initialTier:i,onSelectPreset:e=>te(e),onSelectCustom:()=>te(h[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:l,onCancelLogin:u,onLogout:d,onManage:f})]})}),G&&(0,z.jsx)(Ms,{providerId:G,providerLabel:k?.label??G,onCancel:()=>v({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=G;e&&(v({type:`set-oauth-tos-pending`,providerId:null}),q(e,ne))}},G)]})}function Ys({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,removeConfirmName:s,removeDefaultProvider:c,codexLoginOpen:l,jsonLeaveOpen:u,jsonSaving:d,oauthTosPending:f,onCloseAdd:p,onAdded:m,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onAccountManage:v,onOpenAdd:y,onCloseCodexLogin:b,onCodexAdded:x,onCancelRemove:S,onConfirmRemove:C,onCancelJsonLeave:w,onDiscardJson:T,onSaveJson:E,onCancelOauthTos:D,onContinueOauthTos:O}){return(0,z.jsxs)(z.Fragment,{children:[n&&(0,z.jsx)(Js,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:p,onAdded:m,accountRows:a,accountStatus:o,accountBusy:i,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onAccountManage:v,onOpen:y}),l&&(0,z.jsx)(Sa,{apiBase:e,onClose:b,onAdded:x}),s&&(0,z.jsx)(ms,{providerName:s,defaultProviderName:c,onCancel:S,onConfirm:C}),u&&w&&T&&E&&(0,z.jsx)(hs,{saving:d??!1,onCancel:w,onDiscard:T,onSave:E}),f&&(0,z.jsx)(Ms,{providerId:f.provider,providerLabel:Es(f.provider),onCancel:D,onContinue:O},`${f.provider}:${f.addAccount?`add`:`login`}`)]})}function Xs(e,t,n){return[...Qo(e.providers).map(e=>({id:e,label:pn(e,n),kind:`codex`,href:`#codex-auth`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:Es(e),kind:`oauth`}))]}function Zs(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 Qs({apiBase:e}){let t=Z(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>qn(n)),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(`err`),[p,m]=(0,_.useState)(0),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)({}),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(0),[P,F]=(0,_.useState)(null),[L,R]=(0,_.useState)({token:0,provider:null}),B=(0,_.useRef)(!0),V=(0,_.useRef)(null),H=(0,_.useRef)(!1),U=(0,_.useCallback)((e,t=!0)=>{c(e),u(t),f(t?`ok`:`err`),m(e=>e+1)},[]),W=(0,_.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),G=(0,_.useCallback)(e=>{if(e.catalogRefreshPending){c(t(`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}U(t(`codexAuth.accountAdded`),!0)},[U,t]);(0,_.useEffect)(()=>(B.current=!0,()=>{B.current=!1}),[]),(0,_.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(W,4500);return()=>window.clearTimeout(e)},[s,l,p,W]);let ee=(0,_.useCallback)(e=>{o(!1),D(null),T(e),R(t=>({token:t.token+1,provider:e}))},[]);I(`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}),I(mr(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()});let[te,K]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:q,fetchOauth:J,fetchProviderQuotas:Y}=js({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:y,notify:U,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{K(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),re=Ba(e),ie=re.activeNeedsReauth,ae=(0,_.useMemo)(()=>{let e=re.accounts;if(e.length===0&&re.loadState===`loading`)return v;let t=e.find(e=>e.isMain)??e[0],n=!!t&&!!t.email&&t.email!==`Codex App login`,r=e.some(e=>!e.isMain&&(e.hasCredential||e.email)),i=n||r,a=n?t?.email:e.find(e=>!e.isMain&&e.email)?.email??void 0;return{...v,openai:{loggedIn:i,...a?{email:a}:{},...ie?{needsReauth:!0}:{}}}},[v,re.accounts,re.loadState,ie]),{accountSets:oe,setAccountSets:se,accountLoadStates:ce,switchingAccount:le,keyPools:ue,fetchAccountSets:X,switchAccount:de,switchApiKey:fe,removeApiKey:pe,addApiKeyValue:me,editCredentialAlias:he,removeAccount:ge,activeAccountNeedsReauth:_e}=Cs({apiBase:e,t,config:r,oauthStatus:ae,aliveRef:B,notify:U,fetchConfig:q,fetchOauth:J,fetchProviderQuotas:Y,codexActiveNeedsReauth:ie}),{draft:ve,setDraft:ye,jsonEditorOpen:be,jsonSaving:xe,jsonLeaveOpen:Se,saveConfig:Ce,openJsonEditor:we,discardJsonEditor:Te,requestCloseJsonEditor:Ee,restoreJsonEditor:De,jsonIsDirty:Oe,setJsonLeaveOpen:ke}=ws({apiBase:e,config:r,notify:U,fetchConfig:q,fetchProviderQuotas:Y,onSaved:()=>N(e=>e+1),t});(0,_.useEffect)(()=>{V.current!==e&&(V.current=e,Promise.resolve().then(()=>{q(),J()}))},[e,q,J]);let Ae=()=>N(e=>e+1),{cancelLoginOAuth:je,loginOAuth:Me,logoutOAuth:Ne}=Ds({apiBase:e,t,aliveRef:B,accountSets:oe,setAccountSets:se,setBusy:x,setStatus:c,setLoginInfo:C,setOauthStatus:y,notify:U,fetchConfig:q,fetchOauth:J,fetchAccountSets:X,fetchProviderQuotas:Y,bumpModelsRefresh:Ae,onLoginSettled:ee}),{removeProvider:Pe,confirmRemoveProvider:Fe,setProviderDisabled:Ie,setDefaultProvider:Le,updateProvider:Re}=As({apiBase:e,t,removeBusyRef:H,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:U,fetchConfig:q,fetchOauth:J,fetchProviderQuotas:Y,refreshCodexAccount:()=>re.load(!0)}),ze=(e,t=!1)=>{if(b!==e){if(ys(e)){F({provider:e,addAccount:t});return}Me(e,t)}};if(!r)return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,z.jsx)(mt,{tone:d,onDismiss:W,dismissLabel:t(`common.close`),children:s}):(0,z.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,z.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,z.jsx)(`div`,{className:`providers-workspace-main`,children:(0,z.jsxs)(`p`,{className:`muted`,children:[(0,z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let Be=Xs(r,h,t),Ve=Zs(r,ae),He=e=>r.providers[e]?.authMode===`forward`;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{children:t(`nav.providers`)}),(0,z.jsx)(`div`,{className:`row`,children:(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,z.jsx)(ne,{}),t(`prov.add`)]})})]}),s&&(0,z.jsx)(mt,{tone:d,onDismiss:W,dismissLabel:t(`common.close`),children:s}),(0,z.jsx)(Gi,{onRemoveProvider:Pe,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:we,jsonEditor:{open:be,draft:ve,isDirty:Oe,onDraftChange:ye,onSave:()=>Ce(),onClose:Ee,onRestore:De},jsonSaving:xe,modelsRefreshToken:M,activeAccountNeedsReauth:_e,quotaRefreshEpoch:te.epoch,quotaForceRefresh:te.force,detail:(t,n)=>{let i=Ve[t.name]??v[t.name];return(0,z.jsx)(gs,{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:()=>T(null),apiBase:e,oauth:i,accounts:oe[t.name]?.accounts??[],keys:ue[t.name]??[],accountLoadState:ce[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:L.token,accountsFocusProvider:L.provider,switchingAccountId:le?.provider===t.name?le.accountId:null,busyProvider:b,loginHint:S,authHandlers:{onLogin:ze,onCancelLogin:je,onLogout:Ne,onReauth:(e,t)=>Me(e,!0,t),onSwitchAccount:de,onRemoveAccount:ge,onRetryAccounts:async e=>{await X([e])},onAddApiKey:me,onSwitchApiKey:fe,onRemoveApiKey:pe,onEditAlias:he},isDefault:t.name===r.defaultProvider,onRemoveProvider:Pe,onSetDisabled:Ie,onSetDefault:e=>{Le(e)},onUpdateProvider:Re,codexController:re},t.name)}}),(0,z.jsx)(Ys,{apiBase:e,config:r,adding:a,addIntent:E,busy:b,addModalAccountRows:Be,accountLoginStatus:Ve,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Se,jsonSaving:xe,oauthTosPending:P,onCloseAdd:()=>{b&&je(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),U(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),q(),J(),Y(!0),Ae()},onAccountLogin:async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=$o(n);if(i===`invalid`){U(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await os(e,i),await q()}catch(e){e instanceof as?U(t(e.i18nKey),!1):U(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{B.current&&x(e=>e===`openai`?null:e)}}j(!0);return}if(He(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&ze(n,i)},onAccountCancelLogin:e=>{je(e)},onAccountLogout:e=>{Ne(e)},onAccountManage:e=>{ee(e)},onOpenAdd:J,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),G(e),q(),J(),Y(!0),Ae()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{Fe(O)},onCancelJsonLeave:()=>{xe||ke(!1)},onDiscardJson:Te,onSaveJson:()=>{Ce()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),Me(e.provider,e.addAccount))}})]})}function $s(e){let{t}=Ze();return e.state===`stale`?(0,z.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,z.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:e.controller.restarting,onClick:()=>{e.controller.restart()},children:e.controller.restarting?t(`dash.codexRestarting`):t(`dash.codexRestart`)})]}):null}var ec=[`fresh`,`stale`,`not_running`,`unknown`],tc=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function nc(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function rc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&ec.includes(t.stateBefore)&&typeof t.code==`string`&&tc.includes(t.code)&&nc(t.requested)&&nc(t.stopped)&&nc(t.surviving)&&nc(t.failed)))return!1;let n=t.success,r=t.code,i=t.surviving,a=t.failed,o=t.stopped;return!(n!==(r!==`partially_stopped`)||n&&(i.length>0||a.length>0)||!n&&i.length===0&&a.length===0||(r===`nothing_running`||r===`enumeration_unavailable`)&&o.length>0)}function ic(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&ec.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var ac={state:null,runningCount:0};async function oc(e,t={}){let n=t.fetchFn??fetch;try{let r=await n(`${e}/api/system/codex-app-server`,{signal:t.signal});if(!r.ok)return ac;let i=await r.json().catch(()=>null);return ic(i)?{state:i.state,runningCount:i.runningCount}:ac}catch{return ac}}var sc=3e4;function cc(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function lc(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=sc,formatFailure:i=e=>`Failed to restart Codex (HTTP ${e}).`,formatUnreachable:a=()=>`Could not reach the proxy.`,formatMalformed:o=()=>`The proxy returned an unexpected response.`,formatTimeout:s=()=>`The proxy did not answer in time. It may still be working.`}=t,c;try{c=await n(`${e}/api/system/codex-restart`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return{ok:!1,message:cc(e)?s():a()}}if(!c.ok)return{ok:!1,message:i(c.status)};let l;try{l=await c.json()}catch(e){return{ok:!1,message:cc(e)?s():o()}}return rc(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function uc(e){return e===`stopped`||e===`nothing_running`}function dc(e,t={}){let{t:n}=Ze(),[r,i]=(0,_.useState)(!1),a=(0,_.useRef)(!0),o=(0,_.useRef)(t.onSettled);return(0,_.useEffect)(()=>{o.current=t.onSettled},[t.onSettled]),(0,_.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]),{restarting:r,restart:(0,_.useCallback)(async()=>{if(!confirm(n(`dash.codexRestartConfirm`)))return null;i(!0);let t=await lc(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(a.current&&i(!1),!t.ok||!t.result)return alert(t.message),null;let r=t.result;return r.code===`stopped`?alert(n(`dash.codexRestartDone`,{count:String(r.stopped.length)})):r.code===`nothing_running`?alert(n(`dash.codexRestartNothing`)):r.code===`enumeration_unavailable`?alert(n(`dash.codexRestartUnknown`)):alert(n(`dash.codexRestartPartial`,{count:String(r.surviving.length)})),a.current&&uc(r.code)&&o.current?.(r.code),r.code},[e,n])}}var fc={"gpt-5.6-sol":be,"gpt-5.6-terra":Ce,"gpt-5.6-luna":xe},pc={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function mc(e){return e.slice(e.lastIndexOf(`/`)+1)}function hc(e){return fc[e]??fc[mc(e)]??null}function gc(e){let t=hc(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:pc,"aria-hidden":!0}),e):e}function _c(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 vc(e,t,n,r){let{isEmpty:i,...a}=r,o=I(e,t,n,a);return{...o,state:_c(o,i,r.enabled!==!1)}}function yc({className:e,style:t}){return(0,z.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function bc({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,z.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,z.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,z.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,z.jsx)(yc,{})},t))]})}function xc({children:e,busy:t=!0,live:n=!0,className:r}){return(0,z.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{children:e})]})}var Sc=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,z.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,z.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,z.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,z.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,z.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},Cc=Object.freeze({"gpt-daybreak-blue-latest":`gpt-5.6-sol`});Object.freeze(Object.keys(Cc));var wc=new Set([`gpt-5.5`,`gpt-5.4`,`gpt-5.4-mini`,`gpt-5.3-codex-spark`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`]),Tc=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function Ec(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...Tc];let r=new Set(Tc),i=null;for(let e of n){let n=`${e.provider.trim()}/${e.model.trim()}`,a=t.get(n);if(a===void 0)continue;let o=a.filter(e=>r.has(e));if(i===null)i=o;else{let e=new Set(o);i=i.filter(t=>e.has(t))}}if(i===null)return[...Tc];let a=new Set(i);return Tc.filter(e=>a.has(e))}var Dc=0;function Oc(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++Dc}`}}function kc(e){return e===`disabled`?`disabled`:`auto`}var Ac=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,jc=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,Mc=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Nc(e){return Ac.test(e.trim())}function Pc(e){return`combo/${e.trim()}`}function Fc(e,t){return(typeof t==`string`?t.trim():``)||Pc(e)}function Ic(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!Mc.test(n));return{...e,alias:n?t:null,model:Fc(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function Lc(e){return typeof e==`string`&&e.trim()?e.trim():null}function Rc(e){return e===`round-robin`?`round-robin`:`failover`}function zc(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Bc(e){return typeof e==`string`&&Tc.includes(e)?e:null}function Vc(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Hc(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=Vc(t.weight);a.push(Oc(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():Fc(r,Lc(t.alias)),alias:Lc(t.alias),nativeAlias:t.nativeAlias===!0,displayName:Lc(t.displayName),strategy:Rc(t.strategy),stickyLimit:zc(t.stickyLimit),defaultEffort:Bc(t.defaultEffort),imageInput:kc(t.imageInput),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Uc(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 Wc(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 Gc(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 Kc(e,t){return e.id!==t.id||e.alias!==t.alias||e.nativeAlias!==t.nativeAlias||e.displayName!==t.displayName||e.strategy!==t.strategy||e.stickyLimit!==t.stickyLimit||e.defaultEffort!==t.defaultEffort||(e.imageInput??`auto`)!==(t.imageInput??`auto`)||e.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 qc(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.imageInput===`disabled`?{imageInput:`disabled`}:{},...e.strategy===`round-robin`?{stickyLimit:e.stickyLimit}:{},...e.alias&&e.alias.trim()?{alias:e.alias.trim()}:{},...e.nativeAlias?{nativeAlias:!0}:{},...e.displayName&&e.displayName.trim()?{displayName:e.displayName.trim()}:{}}}}function Jc(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Nc(n))return`invalidId`;if(t.existingIds.includes(n))return`duplicateId`;if(Object.hasOwn(t.providers,`combo`))return`reservedNamespace`;if(Object.hasOwn(t.providers,n))return`providerCollision`;let r=e.alias?.trim()??``,i=e.displayName?.trim()??``;if(r){if(!jc.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&Mc.test(r)&&!e.nativeAlias)return`aliasNativeFamily`;if((t.existingAliases??[]).includes(r))return`duplicateAlias`}let a=[...e.displayName??``].some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127});if(e.displayName!==null&&(i.length>128||a))return`invalidDisplayName`;if(e.nativeAlias&&!wc.has(r))return`unsupportedNativeAlias`;if(e.nativeAlias&&!i)return`missingNativeAliasDisplayName`;if(e.targets.length<1)return`noTargets`;for(let n of e.targets){if(!n.provider.trim()||!n.model.trim())return`incompleteTarget`;if(!Object.hasOwn(t.providers,n.provider.trim()))return`unknownProvider`}let o=new Set;for(let t of e.targets){let e=`${t.provider.trim()}/${t.model.trim()}`;if(o.has(e))return`duplicateTarget`;o.add(e)}if(e.strategy===`round-robin`){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 Yc(e=``){return{id:e,model:e?Pc(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,targets:[Oc()]}}function Xc(e,t){return e.length!==0&&e.every(e=>{let n=e.provider.trim(),r=e.model.trim();return!n||!r?!1:!!t.find(e=>e.provider===n&&e.id===r)?.inputModalities?.includes(`image`)})}function Zc(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function Qc(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function $c(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 el(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||$c(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 tl({value:e,onChange:t,disabled:n}){let r=Z();return(0,z.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,z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(a)},i))})}function nl({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Z(),o=i??Tc,s=t!==null&&!o.includes(t);return(0,z.jsxs)(z.Fragment,{children:[(0,z.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,z.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,z.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]}),s?(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function rl({targets:e,models:t,imageInput:n,disabled:r,onChange:i}){let a=Z(),o=Xc(e,t),s=o&&n!==`disabled`;return(0,z.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":a(`cws.capabilities`),children:[(0,z.jsx)(`span`,{className:`field-label`,children:a(`cws.capabilities`)}),(0,z.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`cwi-capability-label`,children:a(`cws.capability.imageInput`)}),(0,z.jsx)(`p`,{className:`muted cwi-capability-hint`,children:a(o?`cws.capability.imageInputHint`:`cws.capability.imageInputUnavailable`)})]}),(0,z.jsx)(pt,{on:s,onClick:()=>{o&&i({imageInput:n===`auto`?`disabled`:`auto`})},disabled:r||!o,label:a(`cws.capability.imageInput`)})]})]})}function il({targets:e,strategy:t,providers:n,models:r,onChange:i}){let a=Z(),o=Zc(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,z.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,_=el(r,p.provider,n),v=p.model&&!_.includes(p.model)?[p.model,..._]:_,y=!p.provider;return(0,z.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,z.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,z.jsx)(Te,{width:14,height:14,"aria-hidden":`true`})}),(0,z.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:m===0,"aria-label":a(`cws.target.moveUp`),onClick:()=>f(m,m-1),children:(0,z.jsx)(ue,{width:14,height:14,"aria-hidden":`true`})}),(0,z.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,z.jsx)(X,{width:14,height:14,"aria-hidden":`true`})})]}),(0,z.jsxs)(`select`,{className:`input`,value:p.provider,"aria-label":a(`cws.target.provider`),onChange:e=>{let t=e.target.value,i=el(r,t,n)[0]??``;d(m,{provider:t,model:i})},children:[(0,z.jsx)(`option`,{value:``,children:a(`cws.target.pickProvider`)}),g.map(e=>(0,z.jsx)(`option`,{value:e.name,children:e.disabled?a(`cws.target.disabled`,{name:pn(e.name,a)}):pn(e.name,a)},e.name))]}),(0,z.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,z.jsx)(`option`,{value:``,children:y?a(`cws.target.pickProviderFirst`):v.length===0?a(`cws.target.noModels`):a(`cws.target.pickModel`)}),v.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]}),t===`round-robin`&&(0,z.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=Qc(e.target.value,1,1e4);t!==void 0&&d(m,{weight:t})}}),(0,z.jsx)(`div`,{className:`cwi-target-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>i(e.filter((e,t)=>t!==m)),"aria-label":a(`common.remove`),children:(0,z.jsx)(oe,{width:14,height:14})})})]},p.clientKey??`${p.provider}:${p.model}`)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>i([...e,Oc()]),children:[(0,z.jsx)(ne,{width:14,height:14}),` `,a(`cws.target.add`)]})]})}function al({existingIds:e,existingAliases:t,providerMap:n,providers:r,models:i,onClose:a,onSubmit:o}){let s=Z(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(()=>Yc()),[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)(()=>Ec(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=Jc(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:Fc(i,a)});if(!e.ok){m(e.error||s(`cws.saveFailed`));return}}finally{f(!1)}};return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:y,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:v}),(0,z.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,z.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:s(`cws.addTitle`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:d,"aria-label":s(`common.close`),children:(0,z.jsx)(Y,{width:16,height:16})})]}),(0,z.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:s(`cws.addSubtitle`)}),p&&(0,z.jsx)($,{tone:`err`,children:p}),(0,z.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-id`,children:s(`cws.field.id`)}),(0,z.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:l.id,disabled:d,onChange:e=>u(t=>({...t,id:e.target.value,model:Fc(e.target.value,t.alias)}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.idInternalHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:s(`cws.field.alias`)}),(0,z.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:Fc(t.id,e.target.value)}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.aliasHint`)}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.idHint`,{model:l.id.trim()?Fc(l.id,l.alias):`…`})})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:s(`cws.strategy`)}),(0,z.jsx)(tl,{value:l.strategy,disabled:d,onChange:e=>u(t=>({...t,strategy:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:l.strategy===`failover`?s(`cws.strategy.failoverHint`):s(`cws.strategy.roundRobinHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:s(`cws.field.defaultEffort`)}),(0,z.jsx)(nl,{id:`cwi-new-effort`,value:l.defaultEffort,disabled:d,allowedEfforts:g,onChange:e=>u(t=>({...t,defaultEffort:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.defaultEffortHint`)})]}),l.strategy===`round-robin`&&(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:s(`cws.field.stickyLimit`)}),(0,z.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:l.stickyLimit,disabled:d,onChange:e=>{let t=Qc(e.target.value,1,100);t!==void 0&&u(e=>({...e,stickyLimit:t}))}}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.stickyLimitHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:s(`cws.targets`)}),(0,z.jsx)(il,{targets:l.targets,strategy:l.strategy,providers:r,models:i,onChange:e=>u(t=>({...t,targets:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:l.strategy===`failover`?s(`cws.targets.failoverHint`):s(`cws.targets.roundRobinHint`)})]}),(0,z.jsx)(rl,{targets:l.targets,models:i,imageInput:l.imageInput??`auto`,disabled:d,onChange:e=>u(t=>({...t,...e}))})]}),(0,z.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,disabled:d,children:s(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{b()},disabled:d,children:s(d?`common.saving`:`cws.create`)})]})]})]})}var ol=[`config`,`about`],sl=e=>`cws-detail-tab-${e}`,cl=e=>`cws-detail-panel-${e}`;function ll({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providers:a,models:o,onBack:s,onSaved:c,onRequestRemove:l,onSave:u,onDirtyChange:d}){let f=Z(),[p,m]=(0,_.useState)(`config`),h=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%ol.length;else if(e.key===`ArrowLeft`)n=(t-1+ol.length)%ol.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=ol.length-1;else return;e.preventDefault(),m(ol[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[]),[g,v]=(0,_.useState)(e),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(!1),T=!Kc(g,e),E=`${e.id}:${e.alias??``}:${e.nativeAlias}:${e.displayName??``}:${e.strategy}:${e.stickyLimit}:${e.defaultEffort}:${e.imageInput??`auto`}:${e.targets.map(e=>`${e.provider}/${e.model}:${e.weight??1}`).join(`,`)}`,D=(0,_.useMemo)(()=>{let e=new Map;for(let t of o)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[o]),O=(0,_.useMemo)(()=>Ec(g.targets,D),[g.targets,D]),k=(0,_.useCallback)(t=>{let n=t(g);v(n),d(!Kc(n,e))},[g,e,d]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{v(e),S(null),m(`config`),d(!1)},0);return()=>window.clearTimeout(t)},[E]);let A=async()=>{try{await navigator.clipboard.writeText(e.model),w(!0),window.setTimeout(()=>w(!1),1200)}catch{}},j=async()=>{let a=Jc(g,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){S({ok:!1,text:f(`cws.err.${a}`)});return}b(!0);let o=g.id.trim(),s=g.alias?.trim()||null,l=g.displayName?.trim()||null,d={...g,id:o,alias:s,displayName:l,model:Fc(o,s)},p=!t&&o!==e.id?e.id:void 0;try{let e=await u(d,t,p);if(!e.ok){S({ok:!1,text:e.error||f(`cws.saveFailed`)});return}S({ok:!0,text:t?f(`cws.created`,{model:d.model}):f(`cws.saved`)}),c(d)}finally{b(!1)}},M=t?g.id.trim()?Fc(g.id,g.alias):f(`cws.addTitle`):e.model;return(0,z.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,z.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[s&&(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:s,"aria-label":f(`cws.backToAll`),children:[(0,z.jsx)(fe,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),f(`cws.allCombos`)]}),(0,z.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:M}),!t&&(0,z.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{A()},title:f(`cws.copyModel`),children:f(C?`cws.copied`:`cws.copyModel`)}),(0,z.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&l&&(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,z.jsx)(oe,{width:14,height:14}),` `,f(`common.remove`)]}),(0,z.jsx)(`button`,{id:t?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!T||y,onClick:()=>{j()},children:f(y?`common.saving`:t?`cws.create`:`common.save`)})]})]}),x&&(0,z.jsx)($,{tone:x.ok?`ok`:`err`,children:x.text}),(0,z.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":f(`cws.tabsLabel`),children:ol.map((e,t)=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:sl(e),"aria-selected":p===e,"aria-controls":cl(e),tabIndex:p===e?0:-1,className:`btn btn-sm ${p===e?`btn-primary`:`btn-ghost`}`,onClick:()=>m(e),onKeyDown:e=>h(e,t),children:f(e===`config`?`cws.tab.config`:`cws.tab.about`)},e))}),(0,z.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:cl(`config`),"aria-labelledby":sl(`config`),hidden:p!==`config`,children:(0,z.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:f(`cws.field.id`)}),(0,z.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:g.id,disabled:y,onChange:e=>k(t=>({...t,id:e.target.value,model:Fc(e.target.value,t.alias)}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:t?f(`cws.field.idInternalHint`):f(`cws.field.idHintEdit`,{model:Fc(g.id,g.alias)})})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:f(`cws.field.alias`)}),(0,z.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:g.alias??``,placeholder:Pc(g.id.trim()||`…`),disabled:y,onChange:e=>k(t=>Ic(t,e.target.value))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.aliasHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,z.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:g.nativeAlias,disabled:y,onChange:e=>k(t=>({...t,nativeAlias:e.target.checked}))}),` `,f(`cws.field.nativeAlias`)]}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.nativeAliasHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:f(`cws.field.displayName`)}),(0,z.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:g.displayName??``,maxLength:128,disabled:y,onChange:e=>k(t=>({...t,displayName:e.target.value||null}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.displayNameHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,z.jsx)(tl,{value:g.strategy,disabled:y,onChange:e=>k(t=>({...t,strategy:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g.strategy===`failover`?f(`cws.strategy.failoverHint`):f(`cws.strategy.roundRobinHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-effort`,children:f(`cws.field.defaultEffort`)}),(0,z.jsx)(nl,{id:`cwi-effort`,value:g.defaultEffort,disabled:y,allowedEfforts:O,onChange:e=>k(t=>({...t,defaultEffort:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),g.strategy===`round-robin`&&(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-sticky`,children:f(`cws.field.stickyLimit`)}),(0,z.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:g.stickyLimit,disabled:y,onChange:e=>{let t=Qc(e.target.value,1,100);t!==void 0&&k(e=>({...e,stickyLimit:t}))}})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,z.jsx)(il,{targets:g.targets,strategy:g.strategy,providers:a,models:o,onChange:e=>k(t=>({...t,targets:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g.strategy===`failover`?f(`cws.targets.failoverHint`):f(`cws.targets.roundRobinHint`)})]}),(0,z.jsx)(rl,{targets:g.targets,models:o,imageInput:g.imageInput??`auto`,disabled:y,onChange:e=>k(t=>({...t,...e}))})]})}),(0,z.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:cl(`about`),"aria-labelledby":sl(`about`),hidden:p!==`about`,tabIndex:0,children:(0,z.jsxs)(`section`,{className:`pwi-section`,children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:f(`cws.aboutTitle`)}),(0,z.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:f(`cws.aboutBody`)})]})})]})}function ul({model:e,onCancel:t,onConfirm:n}){let r=Z(),i=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,z.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,z.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,z.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,z.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function dl({onKeep:e,onDiscard:t}){let n=Z(),r=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]);let i=(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,z.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,z.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,z.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,z.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function fl(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:`cws.attention.few`)}function pl({combos:e,cataloguedComboIds:t,onSelect:n,onAdd:r}){let i=Z(),a=Uc(e),o=Gc(e,{cataloguedComboIds:t});return(0,z.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,z.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,z.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:i(`cws.overviewTitle`)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,children:[(0,z.jsx)(ne,{width:14,height:14}),` `,i(`cws.add`)]})]}),(0,z.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:i(`cws.overviewBlurb`)}),(0,z.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,z.jsx)(`strong`,{children:e.length}),(0,z.jsx)(`span`,{children:i(`cws.count.total`)})]}),(0,z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,z.jsx)(`strong`,{children:a.failover.length}),(0,z.jsx)(`span`,{children:i(`cws.count.failover`)})]}),(0,z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,z.jsx)(`strong`,{children:a.roundRobin.length}),(0,z.jsx)(`span`,{children:i(`cws.count.roundRobin`)})]})]}),(0,z.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.howTitle`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.howTitle`)}),(0,z.jsx)(`p`,{className:`muted`,style:{margin:0},children:i(`cws.howBody`)})]}),o.length>0&&(0,z.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.attentionTitle`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.attentionTitle`)}),(0,z.jsx)(`div`,{className:`cwi-attention-list`,children:o.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>n(e.id),children:[(0,z.jsx)(se,{width:14,height:14,"aria-hidden":`true`}),(0,z.jsx)(`code`,{className:`chip`,children:e.model}),(0,z.jsx)(`span`,{className:`muted`,children:fl(e.reason,i)}),(0,z.jsx)(fe,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function ml({combos:e,providers:t,models:n,cataloguedComboIds:r,loading:i,onRefresh:a,onSave:o,onRemove:s,onAdd:c,adding:l,onCloseAdd:u,onCreated:d}){let f=Z(),p=(0,_.useMemo)(()=>Object.fromEntries(t.map(e=>[e.name,{disabled:e.disabled}])),[t]),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(void 0),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),T=(0,_.useMemo)(()=>Yc(),[]),E=(0,_.useMemo)(()=>Wc(e,m),[e,m]),D=(0,_.useMemo)(()=>Uc(E),[E]),O=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),k=g&&e.some(e=>e.id===g)?g:null,A=e.find(e=>e.id===k)??null,j=A&&C?.id===A.id?C:A,[M,N]=(0,_.useState)(!1),P=[],F=[];if(j)for(let t of e)t.id!==j.id&&(P.push(t.id),t.alias&&F.push(t.alias));let I=(0,_.useCallback)(e=>{if(e!==k){if(!M){v(e),w(null);return}b(e)}},[k,M]),L=()=>{y!==void 0&&(v(y),w(null),N(!1),b(void 0))},R=()=>b(void 0),B=y!==void 0&&M,V=!i&&e.length===0;return(0,z.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,z.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":f(`cws.railAria`),children:[(0,z.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`combos-workspace-rail-title`,children:f(`nav.combos`)}),(0,z.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,z.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,z.jsx)(ne,{width:14,height:14}),` `,f(`cws.add`)]})]}),(0,z.jsx)(`div`,{className:`cwi-search-row`,children:(0,z.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,z.jsx)(le,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,z.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,z.jsx)(`div`,{className:`combos-workspace-rail-list`,children:E.length===0&&e.length>0?(0,z.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:f(`cws.noSearchResults`)}):(0,z.jsx)(z.Fragment,{children:[[`failover`,D.failover,`cws.group.failover`],[`round-robin`,D.roundRobin,`cws.group.roundRobin`]].map(([e,t,n])=>t.length>0?(0,z.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,z.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,z.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),f(n),(0,z.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${k===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>I(e.id),"aria-current":k===e.id?`true`:void 0,children:[(0,z.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,z.jsx)(we,{width:16,height:16})}),(0,z.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,z.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?f(`cws.targetCountOne`):f(`cws.targetCount`,{count:e.targets.length})}),(0,z.jsx)(fe,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,z.jsx)(`div`,{className:`combos-workspace-main`,children:j?(0,z.jsx)(ll,{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,z.jsx)(ll,{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,z.jsx)(pl,{combos:e,cataloguedComboIds:r,onSelect:e=>I(e),onAdd:c})}),l&&!V&&(0,z.jsx)(al,{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,z.jsx)(ul,{model:e.find(e=>e.id===x)?.model??Pc(x),onCancel:()=>S(null),onConfirm:()=>{(async()=>{let e=await s(x);S(null),e.ok&&(k===x&&(v(null),w(null)),a())})()}}),B&&(0,z.jsx)(dl,{onKeep:R,onDiscard:L})]})}function hl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function gl(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function _l(e){return qn(e)}function vl({apiBase:e,active:t=!0,onCountChange:n}){let r=Z(),i=`ocx.combos.workspace.v1:${e}`,a=(0,_.useMemo)(()=>_l(i),[i]),[o,s]=(0,_.useState)(a??null),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),m=(e,t)=>{l(e),d(t)};(0,_.useEffect)(()=>{if(!c||!u)return;let e=window.setTimeout(()=>{l(``),d(!1)},5e3);return()=>window.clearTimeout(e)},[c,u]);let h=(0,_.useCallback)(async t=>{let[n,r,a]=await Promise.all([fetch(`${e}/api/combos`,{signal:t}),fetch(`${e}/api/config`,{signal:t}),fetch(`${e}/api/models`,{signal:t})]);if(!n.ok||!r.ok||!a.ok)throw Error(`combo workspace load failed`);let o=await n.json(),c=await r.json(),l=await a.json(),u=Array.isArray(l)?l:Array.isArray(l?.models)?l.models:[],d=Hc(o),f=c.providers??{},p=Hr(f),m=Object.entries(f).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:!Object.hasOwn(p,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl})),h=[],g=new Set;for(let e of u){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.provider!=`string`||typeof t.id!=`string`)continue;let n=t.provider.trim(),r=t.id.trim();if(!n||!r)continue;if(n===`combo`){g.add(r);continue}if(t.disabled===!0)continue;let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0,a=Array.isArray(t.inputModalities)?t.inputModalities.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):void 0;h.push({provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{},...a&&a.length>0?{inputModalities:a}:{}})}for(let[e,t]of Object.entries(f)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;!n||t.disabled||h.some(t=>t.provider===e&&t.id===n)||h.push({provider:e,id:n,namespaced:`${e}/${n}`})}let _={combos:d,providers:m,models:h,cataloguedComboIds:[...g]};return Jn(i,_),s(_),_},[e,i]),g=vc(i,[e],h,{isEmpty:()=>!1,initialData:a??void 0,enabled:t}),{state:v}=g,y=v.data??o??void 0,b=y?.combos??[];(0,_.useEffect)(()=>{y&&n?.(b.length)},[b.length,y,n]);let x=y?.providers??[],S=y?.models??[],C=new Set(y?.cataloguedComboIds??[]),w=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(qc(t,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=hl(o);if(!a.ok||s||!gl(o)){let e=s||r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(i?r(`cws.renamed`,{from:Pc(i),to:t.model}):n?r(`cws.created`,{model:t.model}):r(`cws.saved`),!0),{ok:!0}}catch{let e=r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}},T=async t=>{try{let n=await fetch(`${e}/api/combos?id=${encodeURIComponent(t)}`,{method:`DELETE`}),i=n.ok?await n.json():await n.json().catch(()=>null),a=hl(i);if(!n.ok||a||!gl(i)){let e=a||r(`cws.removeFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(r(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=r(`cws.removeFailed`);return m(e,!1),{ok:!1,error:e}}};if(v.showSkeleton&&!y)return(0,z.jsx)(bc,{label:r(`cws.loading`),rows:5});if(v.kind===`failed-cold`&&!y){let e=v.error instanceof Error?v.error.message:r(`cws.loadFailed`);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g.refresh(),children:r(`common.retry`)})]})}return(0,z.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,z.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,z.jsx)($,{tone:u?`ok`:`err`,children:c})}),v.showError&&(0,z.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,z.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,z.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":v.refreshing,children:[(0,z.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:v.refreshing?r(`common.loading`):``}),(0,z.jsx)(ml,{combos:b,providers:x,models:S,cataloguedComboIds:C,loading:!1,onRefresh:()=>g.refresh(),onSave:w,onRemove:T,onAdd:()=>p(!0),adding:f,onCloseAdd:()=>p(!1),onCreated:()=>g.refresh()})]})]})}var yl=0;function bl(){return yl+=1,`candidate-${yl}`}function xl(e,t){return{provider:e,model:t,key:bl()}}function Sl(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))continue;let e=typeof n.suiteId==`string`?n.suiteId.trim():``,r=n.evidenceLayer;!e||r!==`protocol_conformance`&&r!==`live_route_compatibility`||t.push({suiteId:e,evidenceLayer:r})}return t}function Cl(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:Sl(t.requiredSuites)};return(t.minStatus===`PROBED`||t.minStatus===`VERIFIED`)&&(n.minStatus=t.minStatus),typeof t.maxEvidenceAgeMs==`number`&&Number.isFinite(t.maxEvidenceAgeMs)&&t.maxEvidenceAgeMs>=0&&(n.maxEvidenceAgeMs=t.maxEvidenceAgeMs),(t.unknownEvidence===`allow`||t.unknownEvidence===`penalize`||t.unknownEvidence===`exclude`)&&(n.unknownEvidence=t.unknownEvidence),(t.degradedEvidence===`allow`||t.degradedEvidence===`penalize`||t.degradedEvidence===`exclude`)&&(n.degradedEvidence=t.degradedEvidence),n}var wl={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},Tl={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function El(e){return e===!0?`true`:e===!1?`false`:``}function Dl(e){return e===void 0?``:String(e)}function Ol(e=``,t=``){return{id:``,alias:``,candidates:[xl(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...wl},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...Tl},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function kl(e){let t=Cl(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:bl()})),require:{minContextWindow:Dl(e.require.minContextWindow),minQuotaHeadroom:Dl(e.require.minQuotaHeadroom),tools:El(e.require.tools),imageInput:El(e.require.imageInput),structuredOutput:El(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:El(e.require.localOnly),remoteAllowed:El(e.require.remoteAllowed),encryptedCodexTasks:El(e.require.encryptedCodexTasks)},optimize:{latency:String(e.optimize.latency),health:String(e.optimize.health),cost:String(e.optimize.cost),quota:String(e.optimize.quota)},limits:{maxEstimatedCostUsd:Dl(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:Dl(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function Al(e){let t=e.trim();return t?Number(t):void 0}function jl(e){if(e===`true`)return!0;if(e===`false`)return!1}function Ml(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Nl(e,t,n){let r=Ml({minContextWindow:Al(e.require.minContextWindow),minQuotaHeadroom:Al(e.require.minQuotaHeadroom),tools:jl(e.require.tools),imageInput:jl(e.require.imageInput),structuredOutput:jl(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:jl(e.require.localOnly),remoteAllowed:jl(e.require.remoteAllowed),encryptedCodexTasks:jl(e.require.encryptedCodexTasks)}),i=Al(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?Ml({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:Al(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=Ml({maxEstimatedCostUsd:i,onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:void 0});return{mode:t,id:e.id.trim(),...t===`update`&&n?{expectedRevision:n}:{},profile:{...e.alias.trim()?{alias:e.alias.trim()}:{},candidates:e.candidates.map(e=>({provider:e.provider.trim(),model:e.model.trim()})),...Object.keys(r).length>0?{require:r}:{},optimize:{latency:Number(e.optimize.latency),health:Number(e.optimize.health),cost:Number(e.optimize.cost),quota:Number(e.optimize.quota)},...Object.keys(o).length>0?{limits:o}:{},unknownEvidence:{...e.unknownEvidence},...a&&Object.keys(a).length>0?{compatibility:a}:{}}}}function Pl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;if(typeof t==`string`&&t.trim())return t;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.message;if(typeof e==`string`&&e.trim())return e}}function Fl(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Il(e,t){return e.filter(e=>e.provider===t)}var Ll={en:{maxEvidenceAgeMs:`Maximum evidence age (ms)`,unknownEvidence:`Unknown evidence`,degradedEvidence:`Degraded evidence`},de:{maxEvidenceAgeMs:`Maximales Evidenzalter (ms)`,unknownEvidence:`Unbekannte Evidenz`,degradedEvidence:`Eingeschränkte Evidenz`},ko:{maxEvidenceAgeMs:`최대 증거 유효 기간 (ms)`,unknownEvidence:`알 수 없는 증거`,degradedEvidence:`저하된 증거`},zh:{maxEvidenceAgeMs:`证据最大有效期(毫秒)`,unknownEvidence:`未知证据`,degradedEvidence:`降级证据`},"zh-TW":{maxEvidenceAgeMs:`證據最大有效期限(毫秒)`,unknownEvidence:`未知證據`,degradedEvidence:`降級證據`},ru:{maxEvidenceAgeMs:`Максимальный возраст доказательств (мс)`,unknownEvidence:`Неизвестные доказательства`,degradedEvidence:`Ухудшенные доказательства`},ja:{maxEvidenceAgeMs:`エビデンスの最大有効期間 (ms)`,unknownEvidence:`不明なエビデンス`,degradedEvidence:`低下したエビデンス`},tr:{maxEvidenceAgeMs:`Maksimum kanıt yaşı (ms)`,unknownEvidence:`Bilinmeyen kanıt`,degradedEvidence:`Bozulmuş kanıt`}},Rl=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],zl=[`reasoningEffort`,`serviceTier`],Bl={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},Vl=Object.keys(Bl),Hl=[`latency`,`health`,`cost`,`quota`],Ul=[`capability`,`health`,`quota`,`cost`],Wl=[`allow`,`penalize`,`exclude`],Gl=[`allow`,`exclude`];function Kl(e){return`${e.evidenceLayer}:${e.suiteId}`}function ql(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Jl(e){let t=new Set,n=[];for(let r of e){if(!ql(r))continue;let e=typeof r.suiteId==`string`?r.suiteId.trim():``,i=r.evidenceLayer;if(!e||i!==`protocol_conformance`&&i!==`live_route_compatibility`)continue;let a={suiteId:e,evidenceLayer:i},o=Kl(a);t.has(o)||(t.add(o),n.push({...a,key:o}))}return n.sort((e,t)=>{let n=e.evidenceLayer.localeCompare(t.evidenceLayer);return n===0?e.suiteId.localeCompare(t.suiteId):n})}function Yl(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function Xl(e,t){return e===void 0?t:`${Math.round(e)}ms`}function Zl(e,t){return e==null?t:`${Math.round(e*100)}%`}function Ql(e,t,n){switch(e){case`satisfied`:return t(`routing.capOutcome.satisfied`);case`exceeded`:return t(`routing.capOutcome.exceeded`);case`unknown-allowed`:return t(`routing.capOutcome.unknown-allowed`);case`unknown-excluded`:return t(`routing.capOutcome.unknown-excluded`);default:return n}}function $l(e,t){switch(e){case`capability-unsatisfied`:return t(`routing.exclusion.capability-unsatisfied`);case`unknown-capability`:return t(`routing.exclusion.unknown-capability`);case`cost-limit`:return t(`routing.exclusion.cost-limit`);case`cost-limit-unknown`:return t(`routing.exclusion.cost-limit-unknown`);case`cooldown`:return t(`routing.exclusion.cooldown`);case`unknown-health`:return t(`routing.exclusion.unknown-health`);case`unknown-quota`:return t(`routing.exclusion.unknown-quota`);case`unknown-price`:return t(`routing.exclusion.unknown-price`);default:return t(`routing.exclusion.other`,{code:e})}}function eu(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>ql(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&ql(e.require)&&ql(e.optimize)&&ql(e.limits)&&ql(e.unknownEvidence):!1).map(e=>{let t=Cl(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function tu(e){let t=Array.isArray(e)?e:e&&typeof e==`object`&&Array.isArray(e.models)?e.models:[],n=new Set,r=[];for(let e of t){if(!e||typeof e!=`object`||Array.isArray(e))continue;let t=typeof e.provider==`string`?e.provider.trim():``,i=typeof e.id==`string`?e.id.trim():``;if(!t||!i||t===`combo`||t===`policy`||e.disabled===!0)continue;let a=JSON.stringify([t,i]);n.has(a)||(n.add(a),r.push({provider:t,id:i}))}return r}function nu(e,t,n){let r=n??t;if(r){let t=e.find(e=>e.id===r);if(t)return t}return e[0]??null}function ru({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=Ze(),a=Ll[r],o=i(`routing.unavailable`),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)({}),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(``),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,B]=(0,_.useState)(``),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)([]),[G,ee]=(0,_.useState)(!1),te=(0,_.useRef)(null),K=(0,_.useRef)(0),q=(0,_.useRef)(null),J=(0,_.useRef)(!0),Y=(0,_.useCallback)(()=>{J.current=!1,q.current?.abort(),K.current++},[]),ne=(0,_.useRef)(0),re=(0,_.useCallback)((e,t)=>{T({message:e,ok:t})},[]);(0,_.useEffect)(()=>{if(!w?.ok)return;let e=window.setTimeout(()=>T(null),5e3);return()=>window.clearTimeout(e)},[w]);let ie=(0,_.useCallback)(()=>{ne.current+=1,L(null),B(``),H(!1)},[]),ae=(0,_.useCallback)(e=>{te.current=e,x(e),C(e?kl(e):null),T(null),ie()},[ie]),oe=(0,_.useCallback)(async t=>{if(!J.current)return;q.current?.abort();let n=new AbortController;q.current=n;let{signal:r}=n,i=++K.current;y(``);try{let[n,a,o,s,l]=await Promise.all([fetch(`${e}/api/routing-profiles`,{signal:r}),fetch(`${e}/api/routing-analytics`,{signal:r}),fetch(`${e}/api/config`,{signal:r}),fetch(`${e}/api/models`,{signal:r}),fetch(`${e}/api/lab/catalog`,{signal:r})]);if(!n.ok)throw Error(`load-${n.status}`);let[d,p,h,_,v]=await Promise.all([n.json(),a.ok?a.json():Promise.resolve(null),o.ok?o.json():Promise.resolve({}),s.ok?s.json():Promise.resolve([]),l.ok?l.json().catch(()=>null):Promise.resolve(null)]);if(i!==K.current)return;let y=eu(d),b=te.current,S=nu(y,b?.id??null,t),w=h.providers??{},T=Object.entries(w).filter(([,e])=>e.disabled!==!0).map(([e])=>e).sort((e,t)=>e<t?-1:+(e>t)),E=Object.fromEntries(Object.entries(w).filter(([,e])=>e.disabled!==!0&&typeof e.defaultModel==`string`).map(([e,t])=>[e,t.defaultModel.trim()]));te.current=S,c(y),x(S),C(S?kl(S):null),u(p),f(T),m(E),g(tu(_)),v&&Array.isArray(v.scenarios)?(W(Jl(v.scenarios)),ee(!1)):(W([]),ee(!0)),(!b||!S||b.id!==S.id||b.revision!==S.revision)&&ie()}catch(e){if(i!==K.current||r.aborted)return;y(e instanceof Error?e.message:String(e))}finally{q.current===n&&(q.current=null)}},[e,ie]);(0,_.useEffect)(()=>{if(!t){Y();return}J.current=!0;let e=window.setTimeout(()=>void oe(),0);return()=>{window.clearTimeout(e),Y()}},[t,Y,oe]),(0,_.useEffect)(()=>{n?.(s.length)},[n,s.length]);let se=d[0]??``,ce=p[se]??Il(h,se)[0]?.id??``,le=()=>{te.current=null,x(null),C(Ol(se,ce)),T(null),ie()},ue=()=>{if(b){C(kl(b)),T(null);return}ae(s[0]??null)},X=async()=>{if(!(!S||E)){D(!0),T(null);try{let t=Nl(S,b?`update`:`create`,b?.revision),n=await fetch(`${e}/api/routing-profiles`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await Ct(n);if(!n.ok){let e=await n.json().catch(()=>null);re(Pl(e)??i(`routing.loadFailed`),!1);return}if(!Fl(r)){re(Pl(r)??i(`routing.loadFailed`),!1);return}await oe(t.id),re(i(`common.ok`),!0)}catch(e){re(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},de=async()=>{if(!(!b||E)&&window.confirm(i(`routing.removeConfirm`,{id:b.id}))){D(!0),T(null);try{let t=await fetch(`${e}/api/routing-profiles?id=${encodeURIComponent(b.id)}`,{method:`DELETE`}),n=await Ct(t);if(!t.ok){let e=await t.json().catch(()=>null);re(Pl(e)??i(`routing.loadFailed`),!1);return}if(!Fl(n)){re(Pl(n)??i(`routing.loadFailed`),!1);return}te.current=null,await oe(),re(i(`common.ok`),!0)}catch(e){re(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},fe=(e,t,n)=>{C(r=>{if(!r)return r;let i=r.candidates.map((r,i)=>i===e?t===`provider`?{...r,provider:n,model:p[n]??Il(h,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},pe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,xl(se,ce)]})},me=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},he=async()=>{if(!b)return;let t=++ne.current;H(!0),L(null),B(``);try{let n={},r=O.trim()?Number(O.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),A&&(n.toolsRequired=!0),M&&(n.imageInputRequired=!0),P&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:b.id,evidence:n})});if(t!==ne.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==ne.current)return;B(Pl(e)??i(`routing.dryRunError`,{status:a.status}));return}let o=await a.json();if(t!==ne.current)return;L(o)}catch(e){if(t!==ne.current)return;B(e instanceof Error?e.message:String(e))}finally{t===ne.current&&H(!1)}},ge=S?.candidates.map(e=>Il(h,e.provider))??[];return(0,z.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,z.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:le,children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void oe(),children:i(`common.retry`)})]}),v?(0,z.jsxs)($,{tone:`err`,children:[i(`routing.loadFailed`),`: `,v]}):null,w?(0,z.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,s.length>0?(0,z.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:s.map(e=>(0,z.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>ae(e),"aria-pressed":b?.id===e.id,children:(0,z.jsxs)(`div`,{className:`card-badges`,children:[(0,z.jsx)(`strong`,{children:e.id}),(0,z.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,z.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),X()},children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,b?.model??(0,z.jsx)(`code`,{children:`policy/…`})]}),b?(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,b.revision]}):null]}),(0,z.jsxs)(`div`,{className:`model-grid`,children:[(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`id`}),(0,z.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`alias`}),(0,z.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[S.candidates.map((e,t)=>{let n=[...new Set([e.provider,...d])].filter(Boolean),r=`routing-model-options-${t}`;return(0,z.jsxs)(`div`,{className:`model-card`,children:[(0,z.jsxs)(`div`,{className:`model-grid`,children:[(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`provider`}),(0,z.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>fe(t,`provider`,e.target.value),children:[(0,z.jsx)(`option`,{value:``,disabled:!0,children:i(`routing.none`)}),n.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`model`}),(0,z.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>fe(t,`model`,e.target.value)}),(0,z.jsx)(`datalist`,{id:r,children:ge[t]?.map(e=>(0,z.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S.candidates.length===1,onClick:()=>me(t),"aria-label":i(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:i(`common.remove`)})]},e.key)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:pe,children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,z.jsxs)(`div`,{className:`model-grid`,children:[Vl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:Bl[e].min,max:Bl[e].max,step:Bl[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),zl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Rl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,z.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,z.jsx)(`option`,{value:`true`,children:i(`routing.yes`)}),(0,z.jsx)(`option`,{value:`false`,children:i(`routing.no`)})]})]},e))]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,z.jsx)(`div`,{className:`model-grid`,children:Hl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,required:!0,value:S.optimize[e],onChange:t=>C(n=>n&&{...n,optimize:{...n.optimize,[e]:t.target.value}})})]},e))})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,value:S.limits.maxEstimatedCostUsd,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,maxEstimatedCostUsd:e.target.value}})})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`onUnknownCost`}),(0,z.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Gl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,z.jsx)(`div`,{className:`model-grid`,children:Ul.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Wl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:S.compatibility.enabled,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),i(`routing.compatibility.enabled`)]}),S.compatibility.enabled?(0,z.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,z.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),G?(0,z.jsx)(`div`,{style:{marginTop:6},children:(0,z.jsx)($,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,U.length>0?(0,z.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:U.map(e=>(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:Yl(S.compatibility.requiredSuites,e),onChange:t=>C(n=>{if(!n)return n;let r=t.target.checked?[...n.compatibility.requiredSuites,{suiteId:e.suiteId,evidenceLayer:e.evidenceLayer}]:n.compatibility.requiredSuites.filter(t=>t.suiteId!==e.suiteId||t.evidenceLayer!==e.evidenceLayer);return{...n,compatibility:{...n.compatibility,requiredSuites:r}}})}),(0,z.jsxs)(`span`,{children:[e.suiteId,` `,(0,z.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,z.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,z.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,z.jsx)(`option`,{value:`PROBED`,children:i(`lab.verdict.PROBED`)}),(0,z.jsx)(`option`,{value:`VERIFIED`,children:i(`lab.verdict.VERIFIED`)})]})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[a.maxEvidenceAgeMs,(0,z.jsx)(`input`,{className:`input`,type:`number`,min:0,value:S.compatibility.maxEvidenceAgeMs,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,maxEvidenceAgeMs:e.target.value}})})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[a.unknownEvidence,(0,z.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Wl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[a.degradedEvidence,(0,z.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Wl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,z.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:i(E?`common.saving`:`common.save`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:ue,children:i(`common.cancel`)}),b?(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void de(),children:i(`common.remove`)}):null]})]}):null,(0,z.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,z.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,z.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,z.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),ie()}})]}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),ie()}}),i(`routing.dryRunTools`)]}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),ie()}}),i(`routing.dryRunImage`)]}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),ie()}}),i(`routing.dryRunStructured`)]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||V,onClick:()=>void he(),children:i(`routing.dryRunRun`)}),R?(0,z.jsx)($,{tone:`err`,children:R}):null,I?(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`routing.candidate`)}),(0,z.jsx)(`th`,{children:i(`routing.eligible`)}),(0,z.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,z.jsx)(`th`,{children:i(`routing.costCap`)}),(0,z.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,z.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,z.jsxs)(`tr`,{children:[(0,z.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,z.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,z.jsx)(`td`,{children:e.exclusions.map(e=>$l(e.code,i)).join(`, `)||i(`routing.none`)}),(0,z.jsx)(`td`,{children:Ql(e.cost?.capOutcome,i,o)}),(0,z.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):o})]},`${e.provider}/${e.model}`))})]}):null]}),(0,z.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,z.jsx)(`h3`,{children:i(`routing.analytics`)}),l?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`card-badges`,children:[(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,l.totalRequests]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,Zl(l.successRate,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,Zl(l.fallbackRate,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,Xl(l.durationMs.p50,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,Xl(l.durationMs.p95,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,Xl(l.durationMs.p99,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,l.cooldownTriggeringFailures]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,l.confidence??o]}),l.historyTruncated?(0,z.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`routing.candidate`)}),(0,z.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,z.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,z.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,z.jsx)(`tbody`,{children:l.breakdown.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,z.jsx)(`td`,{children:e.requests}),(0,z.jsx)(`td`,{children:Zl(e.successRate,o)}),(0,z.jsx)(`td`,{children:Xl(e.p50DurationMs,o)})]},`${e.provider}/${e.model}`))})]})]}):(0,z.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var iu=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],au=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],ou=[`present`,`corrupt`,`purged_unavailable`];function su(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function cu(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function lu(e){return e===null||typeof e==`string`}function uu(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function du(e){if(!su(e)||typeof e.projectionAvailable!=`boolean`||e.projectionIncompatible!==void 0&&typeof e.projectionIncompatible!=`boolean`)return null;for(let t of[`sqliteSchemaVersion`,`builtAtMs`,`eventCount`,`subjectCount`,`observationCount`,`claimCount`,`verdictCount`,`artifactCount`,`corruptionCount`])if(!uu(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function fu(e){return!su(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!iu.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||e.suiteId.length===0||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.projectionSpecVersion!=`string`||typeof e.verdict!=`string`||!au.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!cu(e.scenarioManifestDigests)||!lu(e.claimSourceDigest)||!cu(e.contributingEventIds)||!cu(e.contradictingEventIds)||!cu(e.notes)?null:e}function pu(e){return!su(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(fu).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function mu(e){return!su(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>su(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function hu(e){return!su(e)||!su(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function gu(e){return!su(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!iu.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.scenarioId!=`string`||typeof e.scenarioVersion!=`string`||typeof e.scenarioManifestDigest!=`string`||typeof e.outcome!=`string`||typeof e.completedAt!=`number`||!Number.isFinite(e.completedAt)||typeof e.executionMode!=`string`||typeof e.excluded!=`boolean`||!lu(e.exclusionReason)?null:e}function _u(e){return!su(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(gu).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function vu(e){if(!su(e)||!su(e.event))return null;let t={...e.event};return delete t.payload_json,typeof t.eventKind!=`string`||typeof t.eventId!=`string`||typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt)||typeof t.producer!=`string`||typeof t.producerVersion!=`string`||typeof t.excluded!=`boolean`||!lu(t.exclusionReason)?null:t}function yu(e){if(!su(e)||!su(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!ou.includes(t.status)||!lu(t.artifactClass)||!lu(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!lu(t.lastError)?null:t}function bu(e){let t={},n=e.subjectQuery.trim();return e.layer&&(t.layer=e.layer),e.verdict&&(t.verdict=e.verdict),n&&(t.subjectId=n),e.suiteId.trim()&&(t.suiteId=e.suiteId.trim()),t}function xu(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function Su(e,t){let n=new Map(t.map(e=>[e.subjectId,e.subjectKind])),r=new Map;for(let t of e){let e=r.get(t.subjectId);e||(e={subjectId:t.subjectId,subjectKind:n.get(t.subjectId)??``,byLayer:xu()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function Cu(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function wu(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function Tu(e){let t=new Set;e.suiteManifestDigest&&t.add(e.suiteManifestDigest);for(let n of e.scenarioManifestDigests)n&&t.add(n);return e.claimSourceDigest&&t.add(e.claimSourceDigest),[...t]}var Eu=50,Du=200,Ou=6,ku=200;async function Au(e,t,n){return St(await fetch(`${e}${t}`,{signal:n}))}function ju(e,t){let n=new URLSearchParams({limit:String(Eu)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Mu=class extends Error{};function Nu(){return new Mu}function Pu(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw Nu()}function Fu(e){if(!su(e)||!Array.isArray(e.verdicts))throw Nu();let t=pu(e);if(t.verdicts.length!==e.verdicts.length)throw Nu();return Pu(e,t.hasMore,t.nextCursor),t}function Iu(e){if(!su(e)||!Array.isArray(e.subjects))throw Nu();let t=mu(e);if(t.subjects.length!==e.subjects.length)throw Nu();return Pu(e,t.hasMore,t.nextCursor),t}function Lu(e){if(!su(e)||!Array.isArray(e.observations))throw Nu();let t=_u(e);if(t.observations.length!==e.observations.length)throw Nu();return Pu(e,t.hasMore,t.nextCursor),t}async function Ru(e,t){let n=du(await Au(e,`/api/lab/status`,t));if(!n)throw Nu();return n}async function zu(e,t,n,r){return Fu(await Au(e,`/api/lab/verdicts?${ju({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Bu(e,t,n){return Iu(await Au(e,`/api/lab/subjects?${ju({},t)}`,n))}async function Vu(e){let t=[],n=new Set,r;for(let i=0;i<Du;i++){let i=await e(r);if(t.push(...i.rows),!i.hasMore)return{rows:t,truncated:!1};let a=i.nextCursor;if(!a||n.has(a)||a===r)throw new Mu;n.add(a),r=a}return{rows:t,truncated:!0}}async function Hu(e,t){return Vu(async n=>{let r=await Bu(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function Uu(e,t,n){let r=hu(await Au(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw Nu();return r}async function Wu(e,t,n,r){return Lu(await Au(e,`/api/lab/observations?${ju({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Gu(e,t,n){return Vu(async r=>{let i=await Wu(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Ku(e,t,n){let r=vu(await Au(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw Nu();return r}async function qu(e,t,n){let r=yu(await Au(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw Nu();return r}function Ju(e){if(!su(e)||e.verificationStatus!==`not_verification`||!su(e.summary))throw Nu();let t=e.summary;if(t.verificationStatus!==`not_verification`||typeof t.subjectId!=`string`||typeof t.recentProductionAttempts!=`number`||typeof t.recentSuccessfulAttempts!=`number`||typeof t.recentRouteErrorSignals!=`number`||t.lastObservedProductionAttempt!==void 0&&typeof t.lastObservedProductionAttempt!=`number`)throw Nu();return{verificationStatus:`not_verification`,summary:t}}async function Yu(e,t,n){return Ju(await Au(e,`/api/lab/production-signals?${ju({subjectId:t})}`,n))}function Xu(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function Zu(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function Qu(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function $u(e){if(!su(e)||!Xu(e,[`evidence`,`trustClass`,`locallyVerified`])||e.trustClass!==`community_untrusted_v1`||e.locallyVerified!==!1||!Array.isArray(e.evidence)||e.evidence.length>4096)return null;let t=[];for(let n of e.evidence){if(!su(n)||!Xu(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!Zu(n.bundleId)||!Zu(n.publisherKeyId)||!Qu(n.activeRecordCount)||!Qu(n.revokedRecordCount))return null;t.push({trustClass:`community_untrusted_v1`,status:`cryptographically_valid`,bundleId:n.bundleId,publisherKeyId:n.publisherKeyId,activeRecordCount:n.activeRecordCount,revokedRecordCount:n.revokedRecordCount})}return{evidence:t,trustClass:`community_untrusted_v1`,locallyVerified:!1}}async function ed(e,t){let n=$u(await Au(e,`/api/lab/public/community`,t));if(!n)throw Nu();return n}async function td(e,t,n){let[r,i]=await Promise.all([Ru(e,n),ed(e,n).catch(e=>{if(n.aborted)throw e;return null})]);if(!r.projectionAvailable)return{status:r,verdicts:[],subjects:[],subjectsTruncated:!1,hasMore:!1,community:i};let[a,o]=await Promise.all([zu(e,t,void 0,n),Hu(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function nd(e,t,n,r){return zu(e,t,n,r)}async function rd(e,t,n,r){let i=e.slice(0,ku),a=[],o=0,s=async()=>{for(;;){if(n.aborted)throw new DOMException(`Aborted`,`AbortError`);let e=o++;if(e>=i.length)return;try{a.push(await r(i[e]))}catch(e){if(n.aborted)throw e}}},c=Math.min(t,i.length);return await Promise.all(Array.from({length:c},()=>s())),a}async function id(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=Tu(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([Uu(e,t.subjectId,n),Gu(e,a,n),rd(r,Ou,n,t=>Ku(e,t,n)),rd(i,Ou,n,t=>qu(e,t,n)),Yu(e,t.subjectId,n).catch(e=>{if(n.aborted)throw e;return null})]);return{subject:o,observations:s.rows,observationsTruncated:s.truncated,events:c,artifacts:l,production:u}}var ad={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},od={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},sd={UNKNOWN:`lab.verdict.UNKNOWN`,CLAIMED:`lab.verdict.CLAIMED`,PROBED:`lab.verdict.PROBED`,VERIFIED:`lab.verdict.VERIFIED`,DEGRADED:`lab.verdict.DEGRADED`,BLOCKED:`lab.verdict.BLOCKED`,UNSUPPORTED:`lab.verdict.UNSUPPORTED`},cd={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function ld(e,t){if(!(e instanceof Error))return t;let n=e.message;return n===`Failed to fetch`||n.includes(`NetworkError`)||n.includes(`network error`)?t:n||t}function ud({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,z.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,z.jsx)(`span`,{children:n}),(0,z.jsx)(`span`,{className:`suite`,children:t})]}):(0,z.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,z.jsx)(`span`,{children:n}),(0,z.jsx)(`span`,{className:`suite`,children:t})]})}function dd({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,z.jsx)(`span`,{className:`muted`,children:`-`}):(0,z.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,z.jsx)(ud,{verdict:e.verdict,caption:e.suiteId,label:t(sd[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function fd({data:e,t,locale:n}){let{status:r}=e,i=[{label:t(`lab.subjectCount`),value:String(r.subjectCount??0)},{label:t(`lab.verdictCount`),value:String(r.verdictCount??0)},{label:t(`lab.observationCount`),value:String(r.observationCount??0)},{label:t(`lab.eventCount`),value:String(r.eventCount??0)}];return r.builtAtMs&&i.push({label:t(`lab.builtAt`),value:wu(r.builtAtMs,n)}),(0,z.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,z.jsxs)(`div`,{className:`lab-status-card`,children:[(0,z.jsx)(`span`,{className:`label`,children:e.label}),(0,z.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function pd({community:e,locale:t}){if(!e||e.evidence.length===0)return null;let n=e.evidence.reduce((e,t)=>e+t.activeRecordCount,0),r=e.evidence.reduce((e,t)=>e+t.revokedRecordCount,0);return(0,z.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,z.jsx)(`h3`,{className:`lab-matrix-title`,children:Re(t,`community.title`)}),(0,z.jsx)(`p`,{className:`muted`,children:Re(t,`community.notLocalVerdict`)}),(0,z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:Re(t,`community.bundles`)}),(0,z.jsx)(`dd`,{children:e.evidence.length})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:Re(t,`community.activeRecords`)}),(0,z.jsx)(`dd`,{children:n})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:Re(t,`community.revokedRecords`)}),(0,z.jsx)(`dd`,{children:r})]})]})]})}function md({verdict:e,detail:t,loading:n,error:r,t:i,locale:a,onClose:o}){let s=new Set([...e.contributingEventIds,...e.contradictingEventIds]).size;return(0,z.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,z.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,z.jsx)(`h3`,{children:Cu(e.subjectId)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,z.jsx)(`dd`,{children:i(ad[e.evidenceLayer])})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,z.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,z.jsx)(`dd`,{children:i(sd[e.verdict])})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,z.jsx)(`dd`,{children:wu(e.asOf,a)})]})]}),n&&(0,z.jsx)(xc,{busy:!0,children:i(`common.loading`)}),r&&(0,z.jsx)($,{tone:`err`,children:r}),t&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,z.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,z.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,z.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,z.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,z.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,z.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,z.jsx)(`dd`,{children:wu(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,z.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,z.jsx)(`span`,{children:e.outcome}),(0,z.jsx)(`span`,{className:`muted`,children:wu(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,z.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,z.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,z.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`mono`,title:e.digest,children:Cu(e.digest)}),(0,z.jsx)(`span`,{children:e.artifactClass??`-`}),(0,z.jsx)(`span`,{children:Re(a,cd[e.status])})]},e.digest))})]})]})]})}function hd({apiBase:e,active:t=!0,onCountChange:n}){let{t:r,locale:i}=Ze(),[a,o]=(0,_.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),T=(0,_.useMemo)(()=>bu(a),[a]),E=JSON.stringify(T),D=(0,_.useCallback)(t=>td(e,T,t),[e,T]),O=vc(`lab-matrix:${e}:${E}`,[e,E],D,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:t,pauseWhenHidden:!0}),k=(0,_.useCallback)(()=>{S.current?.abort(),S.current=null,c(null),u(null),f(!1)},[]),A=(0,_.useCallback)(()=>{w.current=null,C.current?.abort(),C.current=null,m(null),g(null),x(null),y(!1)},[]);(0,_.useEffect)(()=>{S.current?.abort()},[O.data]),(0,_.useEffect)(()=>()=>{S.current?.abort(),C.current?.abort()},[]);let j=(0,_.useCallback)(e=>{A(),k(),o(e)},[A,k]),M=s!==null&&s.baseData===O.data&&s.queryKey===E?s:null,N=l!==null&&l.baseData===O.data&&l.queryKey===E?l.message:null,P=(0,_.useMemo)(()=>{if(!t||!O.data?.status.projectionAvailable)return null;let e=O.data.status.verdictCount;return typeof e==`number`?e:O.data.verdicts.length+(M?.verdicts.length??0)},[t,O.data,M]);(0,_.useEffect)(()=>{n?.(P)},[n,P]);let F=(0,_.useMemo)(()=>O.data?[...O.data.verdicts,...M?.verdicts??[]]:[],[O.data,M]),I=(0,_.useMemo)(()=>O.data?Su(F,O.data.subjects):[],[F,O.data]),L=(0,_.useCallback)(async()=>{let t=M?.nextCursor??O.data?.nextCursor,n=O.data;if(!t||!n||d)return;S.current?.abort();let i=new AbortController;S.current=i;let a=E;u(null),f(!0);try{let r=await nd(e,T,t,i.signal);if(i.signal.aborted)return;c(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...r.verdicts],nextCursor:r.nextCursor,hasMore:r.hasMore}})}catch(e){i.signal.aborted||u({baseData:n,queryKey:a,message:ld(e,r(`lab.loadFailed`))})}finally{S.current===i&&(S.current=null,f(!1))}},[e,d,T,E,O.data,r,M]),R=(0,_.useCallback)(async n=>{if(!t)return;C.current?.abort();let i=new AbortController;C.current=i,w.current=n.projectionKey,m(n),g(null),x(null),y(!0);try{let t=await id(e,n,i.signal);!i.signal.aborted&&w.current===n.projectionKey&&g(t)}catch(e){!i.signal.aborted&&w.current===n.projectionKey&&x(ld(e,r(`lab.detailLoadFailed`)))}finally{C.current===i&&(C.current=null,!i.signal.aborted&&w.current===n.projectionKey&&y(!1))}},[t,e,r]),B=O.refresh,V=(0,_.useCallback)(()=>{A(),k(),B({forceLoading:!0})},[A,B,k]),H=t?p:null,U=M?M.hasMore:O.data?.hasMore??!1,W=[{value:``,label:r(`lab.filter.all`)},...iu.map(e=>({value:e,label:r(ad[e])}))],G=[{value:``,label:r(`lab.filter.all`)},...au.map(e=>({value:e,label:r(sd[e])}))],ee=[{value:``,label:r(`lab.filter.all`)},...(O.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${Cu(e.subjectId)} · ${e.subjectKind}`}))];if(O.state.showSkeleton)return(0,z.jsx)(bc,{label:r(`lab.loading`),rows:5});let te=O.state.showError?ld(O.error,r(`lab.loadFailed`)):null,K=O.data?.status,q=K&&!K.projectionAvailable,J=K?.projectionIncompatible===!0;return(0,z.jsxs)(`div`,{className:`lab-page`,children:[(0,z.jsx)(`div`,{className:`lab-toolbar`,children:(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:V,disabled:O.refreshing,children:[(0,z.jsx)(re,{}),r(`lab.refresh`)]})}),O.refreshing&&!O.state.showSkeleton&&(0,z.jsx)(xc,{busy:!0,live:!te,children:r(`common.loading`)}),te&&(0,z.jsx)($,{tone:`err`,children:te}),J&&(0,z.jsx)($,{tone:`err`,children:r(`lab.projectionIncompatible`)}),q&&!J&&(0,z.jsx)(gt,{title:r(`lab.projectionUnavailable`)}),O.data&&(0,z.jsx)(pd,{community:O.data.community,locale:i}),O.data&&K?.projectionAvailable&&!J&&(0,z.jsxs)(`div`,{className:`lab-layout`,children:[(0,z.jsxs)(`div`,{className:`lab-main`,children:[(0,z.jsx)(fd,{data:O.data,t:r,locale:i}),(0,z.jsxs)(`div`,{className:`lab-filters`,children:[(0,z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,z.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:r(`lab.filter.layer`)}),(0,z.jsx)(ht,{id:`lab-filter-layer`,value:a.layer,options:W,onChange:e=>j(t=>({...t,layer:e})),label:r(`lab.filter.layer`),portal:!1})]}),(0,z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,z.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:r(`lab.filter.verdict`)}),(0,z.jsx)(ht,{id:`lab-filter-verdict`,value:a.verdict,options:G,onChange:e=>j(t=>({...t,verdict:e})),label:r(`lab.filter.verdict`),portal:!1})]}),(0,z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,z.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:r(`lab.filter.subject`)}),(0,z.jsx)(ht,{id:`lab-filter-subject`,value:a.subjectQuery,options:ee,onChange:e=>j(t=>({...t,subjectQuery:e})),label:r(`lab.filter.subject`),portal:!1})]})]}),I.length===0?(0,z.jsx)(gt,{title:r(`lab.empty`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,z.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.matrixTitle`)}),(0,z.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,z.jsxs)(`table`,{className:`lab-matrix`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,z.jsx)(`th`,{children:r(`lab.subjectKind`)}),iu.map(e=>(0,z.jsx)(`th`,{children:r(od[e])},e))]})}),(0,z.jsx)(`tbody`,{children:I.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`subject`,title:e.subjectId,children:Cu(e.subjectId)}),(0,z.jsx)(`td`,{className:`kind`,children:e.subjectKind||Re(i,`subjectKindUnknown`)}),iu.map(t=>(0,z.jsx)(`td`,{children:(0,z.jsx)(dd,{rows:e.byLayer[t],t:r,selectedKey:H?.projectionKey??null,onSelect:e=>{R(e)}})},t))]},e.subjectId))})]})})]}),(0,z.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,z.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.verdictsTitle`)}),(0,z.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,z.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,z.jsx)(`th`,{children:r(`lab.col.layer`)}),(0,z.jsx)(`th`,{children:r(`lab.col.suite`)}),(0,z.jsx)(`th`,{children:r(`lab.col.verdict`)}),(0,z.jsx)(`th`,{children:r(`lab.col.asOf`)})]})}),(0,z.jsx)(`tbody`,{children:F.map(e=>{let t=H?.projectionKey===e.projectionKey;return(0,z.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,z.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":Re(i,`selectVerdict`,{subject:Cu(e.subjectId)}),onClick:()=>{R(e)},children:Cu(e.subjectId)})}),(0,z.jsx)(`td`,{children:r(ad[e.evidenceLayer])}),(0,z.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,z.jsx)(`td`,{children:(0,z.jsx)(ud,{verdict:e.verdict,caption:e.suiteId,label:r(sd[e.verdict])})}),(0,z.jsx)(`td`,{children:wu(e.asOf,i)})]},e.projectionKey)})})]})})]}),N&&(0,z.jsx)($,{tone:`err`,children:N}),U&&(0,z.jsx)(`div`,{className:`lab-load-more`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{L()},children:r(d?`common.loading`:`lab.loadMore`)})})]})]}),H&&(0,z.jsx)(md,{verdict:H,detail:h,loading:v,error:b,t:r,locale:i,onClose:A})]})]})}var gd=[`catalog`,`combos`,`routing`,`compatibility`];function _d(e){return e===`catalog`?`models`:`models/${e}`}function vd(e=window.location.hash){let t=et(e);return t===`models/combos`||t===`combos`||t.startsWith(`combos/`)?`combos`:t===`models/routing`||t===`routing`||t.startsWith(`routing/`)?`routing`:t===`models/compatibility`||t===`lab`||t.startsWith(`lab/`)?`compatibility`:`catalog`}function yd(e){nt(_d(e))}function bd(e){return`models-tab-${e}`}function xd(e){return`models-panel-${e}`}var Sd={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function Cd({tab:e,onSelect:t,meta:n}){let r=Z(),i=(0,_.useRef)(null);i.current===null&&(i.current=new Map);let a=e=>{t(e),window.requestAnimationFrame(()=>{i.current.get(e)?.focus({preventScroll:!0})})},o=t=>{let n=gd.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+gd.length)%gd.length:t.key===`ArrowRight`?r=(n+1)%gd.length:t.key===`Home`?r=0:t.key===`End`&&(r=gd.length-1),r!==null&&(t.preventDefault(),a(gd[r]))};return(0,z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:gd.map(t=>{let s=t===e,c=n?.[t];return(0,z.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:bd(t),"aria-selected":s,"aria-controls":xd(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(Sd[t]),c?(0,z.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function wd(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??[],contextWindow:n?.contextWindow,modelContextWindows:n?.modelContextWindows,discovery:n?.discovery}}).sort((e,t)=>e.native===t.native?e.provider.localeCompare(t.provider):e.native?-1:1)}function Td(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ed(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Dd(e){if(!Td(e))throw Error(`invalid selected models response`);let t=e.selected;if(!Td(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ed(t)]))}async function Od(e,t=fetch,n){let r=await t(`${e}/api/selected-models`,n?{signal:n}:void 0);if(!r.ok)throw Error(`selected models HTTP ${r.status}`);return Dd(await r.json())}function kd(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Ad(e,t,n,r,i){return kd(e,t,n,r)&&!i}async function jd(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 Md(e,t){return e===t}function Nd(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 Pd=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Fd=Array.from({length:18},(e,t)=>1e5+t*5e4),Id=new Set(Fd),Ld=`custom`,Rd=[4,8,16,32,64,128,256,500,1e3],zd=new Set(Rd),Bd=`ocx-models-collapsed:v2`;function Vd(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function Hd(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ud(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);Ad(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?gn(a.namespaced,r):a.namespaced})}return i}function Wd(e=localStorage){try{let t=e.getItem(Bd);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 Gd(e,t=localStorage){try{t.setItem(Bd,JSON.stringify([...e]))}catch{}}function Kd({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Z(),i=e&&t?.status===`failed`?t:void 0;return(0,z.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,z.jsx)(ce,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,z.jsxs)(`span`,{children:[i&&n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${Nd(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>nt(`providers`),children:r(`models.openProviderSettings`)})]})]})}var qd={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function Jd(e){let t=e.replace(/[_,\s]/g,``);if(!t)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}function Yd({apiBase:e,restartEpoch:t=0}){let[n,r]=(0,_.useState)(null),i=(0,_.useRef)(!0);(0,_.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,_.useCallback)(t=>{oc(e,{signal:t}).then(e=>{t?.aborted||!i.current||r(e.state)})},[e]),{restarting:o,restart:s}=dc(e,{onSettled:()=>a()});(0,_.useEffect)(()=>{let e=new AbortController;return a(e.signal),()=>e.abort()},[a,t]);let[c,l]=(0,_.useState)(vd),[u,d]=(0,_.useState)(()=>new Set([vd()])),f=(0,_.useCallback)(e=>{l(e),d(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,_.useEffect)(()=>{let e=()=>f(vd());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[f]);let p=(0,_.useCallback)(e=>{yd(e),f(e)},[f]),m=c===`catalog`,[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),S=Z(),C=`ocx.models.catalog.v1:${e}`,w=(0,_.useMemo)(()=>qn(C),[C]),[T,E]=(0,_.useState)(()=>w?.models??[]),[D,O]=(0,_.useState)(()=>w?.providers??[]),[k,A]=(0,_.useState)(()=>new Set(w?.disabled??[])),[j,M]=(0,_.useState)(()=>w?.selectedModels??null),[N,P]=(0,_.useState)({}),[F,I]=(0,_.useState)({}),[R,B]=(0,_.useState)(()=>w?.contextCaps??{}),[V,H]=(0,_.useState)(()=>w?.contextCapValue??35e4),[W,G]=(0,_.useState)(``),[ee,te]=(0,_.useState)(!1),[K,q]=(0,_.useState)({}),[Y,ne]=(0,_.useState)({}),ie=Wd(),[ae,oe]=(0,_.useState)(()=>ie??new Set),le=(0,_.useRef)(ie===null),[ue,X]=(0,_.useState)(``),[de,pe]=(0,_.useState)(!1),[me,he]=(0,_.useState)(0),ge=(e,t)=>{pe(e),X(t),he(e=>e+1)};(0,_.useEffect)(()=>{if(!ue)return;let e=setTimeout(()=>X(``),de?6e3:8e3);return()=>clearTimeout(e)},[ue,de,me]);let[_e,ve]=(0,_.useState)(!1),ye=(0,_.useRef)(!1),be=(0,_.useRef)(0),xe=(0,_.useRef)(!1),[Se,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)(!0),[Ee,De]=(0,_.useState)(!1),[Oe,ke]=(0,_.useState)(``),Ae=(0,_.useRef)(!1),[je,Me]=(0,_.useState)(``),[Ne,Pe]=(0,_.useState)(!1),[Fe,Ie]=(0,_.useState)(!1),[Le,Re]=(0,_.useState)(!1),[ze,Be]=(0,_.useState)(`add`),[Ve,He]=(0,_.useState)(``),[Ue,We]=(0,_.useState)(``),[Ge,Ke]=(0,_.useState)(``),[qe,Je]=(0,_.useState)(``),[Ye,Xe]=(0,_.useState)(``),[Ze,Qe]=(0,_.useState)(!1),[$e,et]=(0,_.useState)([`text`]),[tt,nt]=(0,_.useState)(!1),[rt,it]=(0,_.useState)([]),at=(0,_.useRef)(!1),[Q,ot]=(0,_.useState)(!1),[st,ct]=(0,_.useState)(``),[lt,ut]=(0,_.useState)(null),[dt,ft]=(0,_.useState)([]),[mt,vt]=(0,_.useState)(``),[yt,bt]=(0,_.useState)(``),[xt,wt]=(0,_.useState)({}),[Tt,Et]=(0,_.useState)({contextWindow:null,modelContextWindows:{}}),[Dt,Ot]=(0,_.useState)(new Set),[kt,At]=(0,_.useState)(!1),[jt,Mt]=(0,_.useState)(!1),[Nt,Pt]=(0,_.useState)(``),[Ft,It]=(0,_.useState)(null),Lt=(0,_.useRef)(null),[Rt,zt]=(0,_.useState)(null),[Bt,Vt]=(0,_.useState)(!1),[Ht,Ut]=(0,_.useState)(null);(0,_.useEffect)(()=>()=>{Lt.current&&clearTimeout(Lt.current)},[]);let Wt=(0,_.useMemo)(()=>Ud(T,k,j??{},S),[T,k,j,S]),Gt=(0,_.useMemo)(()=>{let e=new Set(Wt.map(e=>e.value));return Yt(T.filter(t=>e.has(t.namespaced)),Rt?.model)},[T,Rt?.model,Wt]),Kt=(0,_.useCallback)(async()=>{try{let t=await Ct(await fetch(`${e}/api/shadow-call-settings`));t&&zt(t)}catch{}},[e]),qt=(0,_.useCallback)(async()=>{if(!Ae.current)try{let t=await fetch(`${e}/api/v2`);if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){Ce(null);return}let n=await Ct(t);if(!n||typeof n.enabled!=`boolean`){Ce(null);return}Ce({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{Ce(null)}finally{Te(!1)}},[e]),Jt=(0,_.useCallback)(async t=>{let[n,r,i,a]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),Od(e,fetch,t)]),[o,s,c]=await Promise.all([St(n),St(r),St(i)]);if(o===void 0||s===void 0||c===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let l=Hd(o),u=typeof s.value==`number`&&Number.isFinite(s.value)&&s.value>0?s.value:typeof s.cap==`number`&&Number.isFinite(s.cap)&&s.cap>0?s.cap:void 0,d=u===void 0?35e4:u,f={models:o,providers:c,selectedModels:a,disabled:[...l],contextCaps:s.caps??{},contextCapValue:d};return Jn(C,f),f},[e,C]),Xt=(0,_.useCallback)(e=>{let t=wd(e.models,e.providers);Ut(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),E(e.models),O(e.providers),A(new Set(e.disabled)),M(e.selectedModels),H(e.contextCapValue),B(e.contextCaps)},[]),Zt=vc(C,[e],async e=>{let t=await Jt(e);if(e.aborted)throw Error(`models request aborted`);return Xt(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:w??void 0,enabled:m}),Qt=Zt.state,$t=(0,_.useCallback)(async(e=!1)=>{if(xe.current&&!e)return!1;xe.current=!0;let t=++be.current;try{let e=await Jt(new AbortController().signal);return Md(t,be.current)?(Xt(e),L(C,e),!0):!1}catch{return!1}finally{Md(t,be.current)&&(xe.current=!1)}},[Xt,C,Jt]);(0,_.useEffect)(()=>{if(!m)return;let e=window.setTimeout(()=>{Kt(),qt()},0),t=window.setInterval(()=>{Ae.current||qt()},1e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[m,Kt,qt]);let en=(0,_.useMemo)(()=>wd(T,D),[T,D]),tn=T.length>0||Qt.data!==void 0,nn=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;ut(e.provider),ft(t),vt(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));bt(r),wt(i),Et({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Ot(new Set),At(!1),Pt(``)},on=e=>{vt(e)},sn=async()=>{if(!lt)return;let t=Jd(yt);if(!en.find(e=>e.provider===lt)){Pt(S(`models.contextSaveFailed`));return}if(kt&&t===void 0){Pt(S(`models.contextInvalid`));return}let n={};for(let e of Dt){let t=Jd(xt[e]??``);if(t===void 0){Pt(S(`models.contextInvalid`));return}t!==(Tt.modelContextWindows[e]??null)&&(n[e]=t)}let r=kt&&t!==Tt.contextWindow;if(!r&&Object.keys(n).length===0){ut(null),ge(!0,S(`models.contextUnchanged`));return}Mt(!0),Pt(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await St(await fetch(`${e}/api/providers?name=${encodeURIComponent(lt)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),S(`models.contextSaveFailed`))}catch(e){Pt(e instanceof Error?e.message:S(`models.contextSaveFailed`));return}finally{Mt(!1)}ut(null),ge(!0,S(`models.contextSaved`)),await $t(!0)};(0,_.useEffect)(()=>{if(!le.current||en.length===0)return;le.current=!1;let e=new Set(en.map(e=>e.provider));oe(e),Gd(e)},[en]);let cn=(0,_.useMemo)(()=>j?T.filter(e=>Ad(j,e.provider,e.id,e.native===!0,k.has(e.namespaced))).length:0,[k,T,j]),ln=(0,_.useMemo)(()=>({catalog:tn?S(`models.active`,{active:cn,total:T.length}):void 0,combos:h===null?void 0:String(h),routing:v===null?void 0:String(v),compatibility:b===null?void 0:String(b)}),[tn,h,b,cn,T.length,v,S]),un=async(t,n,r,i)=>{++be.current,ve(!0),ye.current=!0,X(``);let a=null;try{(await jd(e,t,n,r,i)).ok||(a=`models.saveFailed`)}catch{a=`models.networkError`}finally{let e=await $t(!0);a?(pe(!1),X(S(a))):e&&(pe(!0),X(S(`models.applied`))),ve(!1),ye.current=!1}},dn=async t=>{ve(!0),ye.current=!0,X(``);let n=R[t]===void 0;try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,enabled:n})});try{let e=await St(r,S(`models.capSaveFailed`));B(e?.caps??{}),pe(!0),X(S(`models.capApplied`)),await $t(!0)}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{ve(!1),ye.current=!1}},fn=e=>{oe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Gd(n),n})},mn=e=>{oe(()=>{let t=e?new Set(en.map(e=>e.provider)):new Set;return Gd(t),t})},_n=async t=>{ve(!0),ye.current=!0,X(``);try{let n=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await St(n,S(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&H(e.value),B(e?.caps??{}),pe(!0),X(S(`models.capApplied`)),await $t(!0)}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{ve(!1),ye.current=!1}},vn=(0,_.useMemo)(()=>{let e=en.filter(e=>!e.native);return e.length>0&&e.every(e=>R[e.provider]===V)&&Object.keys(R).every(e=>R[e]===V)},[en,R,V]),yn=e=>{!Number.isSafeInteger(e)||e<=0||_n(vn?{value:e,setAll:!0}:{value:e})},bn=(e,t)=>{if(t===`custom`){q(t=>({...t,[e]:!0})),ne(t=>({...t,[e]:String(R[e]??V)}));return}q(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==R[e]&&_n({provider:e,enabled:!0,value:n})},xn=e=>{let t=Number((Y[e]??``).replace(/[_,\s]/g,``));if(!Number.isSafeInteger(t)||t<=0){ge(!1,S(`models.capSaveFailed`));return}q(t=>({...t,[e]:!1})),_n({provider:e,enabled:!0,value:t})},Sn=e=>{if(e===`custom`){te(!0),G(String(V));return}te(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==V&&yn(t)},Cn=()=>{let e=Number(W.replace(/[_,\s]/g,``));if(!Number.isSafeInteger(e)||e<=0){ge(!1,S(`models.capSaveFailed`));return}te(!1),yn(e)},wn=()=>{_n({setAll:!vn})},Tn=async t=>{if(!(!Rt||Bt)){Vt(!0),zt({...Rt,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Vt(!1)}}},En=async t=>{if(!(!Se||Ae.current)&&Se.multiAgentMode!==t){De(!0),Ae.current=!0,ke(``),X(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})});try{let e=await St(n,S(`models.saveFailed`));qt(),pe(!0),X(S(`models.v2Applied`)),ke((e?.warnings??[]).join(` `))}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{De(!1),Ae.current=!1}}},Dn=async t=>{if(!(!Se||Ae.current)){if(!Number.isInteger(t)||t<1){ge(!1,S(`models.v2ThreadsInvalid`));return}if(Se.maxConcurrentThreadsPerSession!==t){De(!0),Ae.current=!0,ke(``),X(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:t})});try{let e=await St(n,S(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){pe(!1),X(S(`models.saveFailed`));return}Ce({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`}),pe(!0),X(S(`models.v2ThreadsApplied`)),Pe(!1)}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{De(!1),Ae.current=!1}}}},On=e=>{if(e===`custom`){Pe(!0),Me(String(Se?.maxConcurrentThreadsPerSession??``));return}Pe(!1),Dn(Number(e))},kn=(e,t)=>{Lt.current&&clearTimeout(Lt.current),Lt.current=setTimeout(()=>{It({namespaced:e,rect:t.getBoundingClientRect()})},300)},An=(e,t)=>{Lt.current&&clearTimeout(Lt.current),It({namespaced:e,rect:t.getBoundingClientRect()})},jn=()=>{Lt.current&&clearTimeout(Lt.current),Lt.current=setTimeout(()=>It(null),120)},Mn=()=>{Lt.current&&clearTimeout(Lt.current)},Nn=async(t,n,r,i,a,o)=>{ot(!0),ct(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,modelId:n,displayName:r,contextWindow:i,inputModalities:a,reasoningEfforts:o})});try{await St(s,S(`models.customSaveFailed`)),Re(!1),ge(!0,S(`models.customAdded`)),await $t(!0)}catch(e){ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{ct(S(`models.networkError`))}finally{ot(!1)}},Pn=async(t,n)=>{ot(!0),ct(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await St(r,S(`models.customSaveFailed`)),Re(!1),ge(!0,S(`models.customUpdated`)),await $t(!0)}catch(e){ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{ct(S(`models.networkError`))}finally{ot(!1)}},Fn=async t=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(ge(!0,S(`models.customDeleted`)),await $t(!0)):ge(!1,S(`models.customSaveFailed`))}catch{ge(!1,S(`models.networkError`))}},In=Qt.data??w,Ln=Qt.kind===`failed-cold`?Qt.error instanceof Error?Qt.error.message:S(`models.loadFail`):null,Rn=Qt.showSkeleton&&!In,zn=j??{},Bn=e=>{let{provider:t,rows:n,native:r,liveModels:i,discovery:a}=e,o=ae.has(t),s=e=>Ad(zn,t,e.id,e.native===!0,k.has(e.namespaced)),c=n.filter(s).length,l=R[t]!==void 0,u=R[t]??V,d=r,f=i&&a?.status===`failed`?a:void 0,p=(N[t]??``).trim().toLowerCase(),m=p?n.filter(e=>e.id.toLowerCase().includes(p)):n,h=m.toSorted((e,t)=>Number(!s(e))-Number(!s(t))),g=F[t]??60,_=h.slice(0,g),v=m.length-_.length,y=n.length>0,b=!y||n.every(s),x=!y||n.every(e=>!s(e)),C=e=>{y&&un(`provider`,t,n.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,z.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,z.jsxs)(`div`,{className:`row group-head models-provider-head${o?``:` open`}`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>fn(t),"aria-expanded":!o,style:{flex:1,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,z.jsx)(fe,{style:{width:14,height:14,color:`var(--muted)`,transform:o?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,z.jsx)(`span`,{className:`text-body font-semibold`,children:hn(t)}),d&&(0,z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.nativeGroupLabel`)}),f&&(0,z.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:Nd(S,f),children:S(`models.discoveryFailedBadge`)}),(0,z.jsx)(`span`,{className:`muted mono text-label`,children:S(`models.active`,{active:c,total:n.length})})]}),(0,z.jsxs)(`div`,{className:`row models-provider-actions`,children:[!d&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>nn(e),"aria-haspopup":`dialog`,children:S(`models.contextSettings`)}),!d&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),Be(`add`),He(t),We(``),Ke(``),Je(``),Xe(``),Qe(!1),et([`text`]),nt(!1),it([]),at.current=!1,ct(``),Re(!0)},"aria-label":S(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:_e||b,onClick:()=>C(!0),children:S(`models.allOn`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:_e||x,onClick:()=>C(!1),children:S(`models.allOff`)}),!d&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(pt,{on:l,onClick:()=>dn(t),disabled:_e,label:S(`models.capValue`,{value:Vd(u)})}),l&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(ht,{value:K[t]?`custom`:String(u),options:[...!Id.has(u)&&!K[t]?[{value:String(u),label:Vd(u)}]:[],...Fd.map(e=>({value:String(e),label:Vd(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>bn(t,e),disabled:_e,label:S(`models.capValue`,{value:Vd(u)})}),K[t]&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:Y[t]??``,onChange:e=>ne(n=>({...n,[t]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&xn(t)},disabled:_e,"aria-label":S(`models.customPlaceholder`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>xn(t),disabled:_e,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]})]})]})]})]}),!o&&(0,z.jsxs)(`div`,{className:`models-provider-body`,children:[d&&(0,z.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:S(`models.nativeHint`)}),n.length===0&&(0,z.jsx)(Kd,{liveModels:i,discovery:a,showFailureBadge:!1}),n.length>30&&(0,z.jsx)(`input`,{className:`input`,placeholder:S(`models.search`),value:N[t]??``,onChange:e=>P(n=>({...n,[t]:e.target.value})),"aria-label":S(`models.search`)}),_.map(e=>{let n=!s(e);return(0,z.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>kn(e.namespaced,t.currentTarget),onMouseLeave:jn,onFocus:t=>An(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||It(null)},children:[(0,z.jsxs)(`div`,{className:`row models-model-row`,children:[(0,z.jsx)(pt,{on:!n,onClick:()=>void un(`models`,t,[{id:e.id,native:e.native===!0}],n),disabled:_e,label:e.native?e.id:e.namespaced}),(0,z.jsx)(`code`,{className:`mono text-control`,style:{color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:e.native?gc(e.id):gn(e.namespaced,S)}),e.custom&&(0,z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.customBadge`)}),e.contextCapped&&(0,z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.contextCappedValue`,{value:Vd(e.contextCap??V)})})]}),Ft?.namespaced===e.namespaced&&(()=>{let t=Ft.rect,r=t.bottom+4,i=r+360>window.innerHeight;return(0,z.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:t.left+24,...i?{bottom:window.innerHeight-t.top+4}:{top:r}},onMouseEnter:Mn,onMouseLeave:jn,children:[(0,z.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,z.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,z.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:S(`models.customBadge`)}),(0,z.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipProvider`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:pn(e.provider,S)}),(e.contextWindow||e.contextCap)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipContext`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:Vd(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipModalities`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipStatus`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:S(n?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,z.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{Be(`edit`),He(e.provider),We(e.customId),Ke(e.id),Je(e.displayName??``),Xe(e.contextWindow?String(e.contextWindow):``),Qe(!1),et(e.inputModalities??[`text`]),nt(Array.isArray(e.reasoningEfforts)),it(e.reasoningEfforts??[]),at.current=Array.isArray(e.reasoningEfforts),ct(``),Re(!0),It(null)},children:S(`models.customEdit`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{window.confirm(S(`models.customDeleteConfirm`,{name:e.displayName??e.id}))&&Fn(e.customId),It(null)},children:S(`models.customDelete`)})]})]})})()]},e.namespaced)}),v>0&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>I(e=>({...e,[t]:g+60})),className:`btn btn-ghost btn-sm models-show-more`,children:S(`models.showMore`,{n:v})})]})]},t)},Vn=Ht?en.filter(e=>e.provider===Ht):en,Hn=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`models-control-top-row`,children:[(0,z.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!Rt||void 0,children:[(0,z.jsxs)(`span`,{className:`models-shadow-label`,children:[S(`models.shadowCallIntercept`),` `,(0,z.jsx)(_t,{content:S(`models.shadowCallInterceptHint`,{models:rn(Rt?.sourceModels)}),side:`top`,maxWidth:320,children:(0,z.jsx)(`span`,{style:{cursor:`help`},"aria-label":S(`models.shadowCallInterceptHint`,{models:rn(Rt?.sourceModels)}),children:`ⓘ`})})]}),(0,z.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:S(`models.shadowCallOriginal`,{models:an(Rt?.sourceModels)})}),(0,z.jsx)(pt,{on:Rt?.enabled??!1,onClick:()=>void Tn({enabled:!Rt?.enabled}),disabled:!Rt||Bt,label:S(`models.shadowCallIntercept`)}),(0,z.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,z.jsx)(ht,{value:Rt?.model??``,options:Gt,onChange:e=>{zt(t=>t&&{...t,model:e}),Tn({model:e})},disabled:!Rt||Bt||!Rt.enabled,label:S(`models.shadowCallIntercept`)})})]}),(we||Se)&&(0,z.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2Label`)}),(0,z.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Se?.multiAgentMode??`default`)===e,className:`btn btn-sm${(Se?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(Se?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(Se?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!Se||Ee,onClick:()=>void En(e),children:S(`models.v2Mode_${e}`)},e))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!Se,onClick:()=>Ie(!0),"aria-label":S(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,z.jsx)(ce,{width:14,height:14,"aria-hidden":`true`})})]})]}),Se&&(Se.enabled||Se.agentsMaxThreadsConflict||Oe)&&(0,z.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[Se.enabled&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2ThreadsLabel`)}),(0,z.jsx)(ht,{value:Ne?`custom`:Se.maxConcurrentThreadsPerSession!==null&&Se.maxConcurrentThreadsPerSession!==void 0?zd.has(Se.maxConcurrentThreadsPerSession)?String(Se.maxConcurrentThreadsPerSession):`custom`:``,options:[...Se.maxConcurrentThreadsPerSession===null||Se.maxConcurrentThreadsPerSession===void 0?[{value:``,label:S(`models.v2ThreadsDefault`)}]:[],...Se.maxConcurrentThreadsPerSession!==null&&Se.maxConcurrentThreadsPerSession!==void 0&&!zd.has(Se.maxConcurrentThreadsPerSession)&&!Ne?[{value:`custom`,label:String(Se.maxConcurrentThreadsPerSession)}]:[],...Rd.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>On(e),disabled:Ee,label:S(`models.v2ThreadsLabel`)}),Ne&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:je,onChange:e=>Me(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Dn(Number(je.replace(/[_,\s]/g,``)))},disabled:Ee,"aria-label":S(`models.v2ThreadsLabel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:Ee,onClick:()=>{Dn(Number(je.replace(/[_,\s]/g,``)))},children:S(`models.v2ThreadsApply`)})]})]}),Se.enabled&&Se.agentsMaxThreadsConflict&&(0,z.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:S(`models.v2Conflict`)}),Oe&&(0,z.jsx)(`span`,{className:`muted text-label`,children:Oe})]}),(0,z.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:S(`models.contextCapLabel`)}),(0,z.jsx)(ht,{value:ee?Ld:String(V),options:[...!Id.has(V)&&!ee?[{value:String(V),label:Vd(V)}]:[],...Fd.map(e=>({value:String(e),label:Vd(e)})),{value:Ld,label:S(`models.custom`)}],onChange:e=>Sn(e),disabled:_e,label:S(`models.contextCapLabel`)}),ee&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:W,onChange:e=>G(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Cn()},disabled:_e,"aria-label":S(`models.customPlaceholder`)}),(0,z.jsx)(`button`,{type:`button`,onClick:Cn,disabled:_e,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]}),(0,z.jsx)(pt,{on:vn,onClick:wn,disabled:_e,label:S(`models.setAll`)}),(0,z.jsx)(`span`,{className:`muted text-label leading-body`,children:S(`models.setAllHint`,{value:Vd(V)})})]}),(()=>{let e=T.filter(e=>e.custom).length;return e===0?null:(0,z.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,z.jsx)(`span`,{className:`models-chip mono text-caption`,children:S(`models.customSummary`,{count:e})})})})(),(0,z.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,z.jsx)(ce,{width:15,height:15,"aria-hidden":`true`}),(0,z.jsx)(`span`,{children:S(`models.orderHint`)})]})]}),Un=(0,z.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>mn(!0),disabled:_e,children:[(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`}),` `,S(`models.collapseAll`)]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>mn(!1),disabled:_e,children:[(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,S(`models.expandAll`)]})]}),Wn=(0,z.jsx)(z.Fragment,{children:en.length===0&&(0,z.jsx)(gt,{icon:(0,z.jsx)(U,{}),title:S(`models.noRouted`),children:S(`models.noRoutedHint`)})}),Gn=(0,z.jsxs)(z.Fragment,{children:[Fe&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.v2Label`),onClick:()=>Ie(!1),onKeyDown:e=>{e.key===`Escape`&&Ie(!1)},children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:S(`models.v2Label`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ie(!1),"aria-label":S(`common.close`),children:`×`})]}),(0,z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:S(`models.v2Help`)}),(0,z.jsx)(`div`,{className:`models-help-link`,children:(0,z.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:S(`models.v2DocsLink`)})}),(0,z.jsx)(`div`,{className:`modal-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Ie(!1),children:S(`common.ok`)})})]})}),lt&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.contextSettings`),onClick:()=>{jt||ut(null)},onKeyDown:e=>{e.key===`Escape`&&!jt&&ut(null)},children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:S(`models.contextSettingsTitle`,{provider:pn(lt,S)})}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ut(null),disabled:jt,"aria-label":S(`common.close`),children:`×`})]}),Nt&&(0,z.jsx)($,{tone:`err`,children:Nt}),(0,z.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:S(`models.contextHint`)}),(0,z.jsxs)(`div`,{className:`models-context-fields`,children:[(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextDefault`),(0,z.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:yt,onChange:e=>{bt(e.target.value),At(!0)},disabled:jt,placeholder:S(`models.contextAutomatic`),autoFocus:!0})]}),dt.length>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.contextModel`),(0,z.jsx)(ht,{value:mt,options:dt.map(e=>({value:e,label:e})),onChange:on,disabled:jt,label:S(`models.contextModel`)})]}),(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextModelOverride`),(0,z.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:xt[mt]??``,onChange:e=>{wt(t=>({...t,[mt]:e.target.value})),Ot(e=>new Set(e).add(mt))},disabled:jt,placeholder:S(`models.contextAutomatic`)})]})]})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ut(null),disabled:jt,children:S(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void sn(),disabled:jt,children:S(jt?`models.customSaving`:`models.customApply`)})]})]})}),Le&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.customAdd`),onClick:()=>{Q||Re(!1)},onKeyDown:e=>{e.key===`Escape`&&!Q&&Re(!1)},children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:S(ze===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:pn(Ve,S)})}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Re(!1),disabled:Q,"aria-label":S(`common.close`),children:`×`})]}),st&&(0,z.jsx)($,{tone:`err`,children:st}),(0,z.jsxs)(`div`,{className:`models-field-stack`,children:[(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldModelId`),(0,z.jsx)(`input`,{className:`input`,value:Ge,onChange:e=>Ke(e.target.value),disabled:Q,placeholder:S(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldDisplayName`),(0,z.jsx)(`input`,{className:`input`,value:qe,onChange:e=>Je(e.target.value),disabled:Q,placeholder:S(`models.customFieldDisplayNamePlaceholder`)})]}),(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldContext`),(0,z.jsxs)(`div`,{className:`row models-field-row`,children:[(0,z.jsx)(ht,{value:Ze?`custom`:Ye,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:S(`models.custom`)}],onChange:e=>{if(e===`custom`){Qe(!0);return}Qe(!1),Xe(e)},disabled:Q,label:S(`models.customFieldContext`)}),Ze&&(0,z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:Ye,onChange:e=>Xe(e.target.value),disabled:Q,placeholder:S(`models.customPlaceholder`),"aria-label":S(`models.customFieldContext`)})]})]}),(0,z.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldModalities`),(0,z.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:$e.includes(e),onChange:t=>{et(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Q}),(0,z.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,z.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldReasoning`),(0,z.jsx)(`div`,{className:`row models-field-row`,children:(0,z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:tt,onChange:e=>{if(nt(e.target.checked),e.target.checked&&!at.current){at.current=!0;let e=T.find(e=>e.provider===Ve&&e.id===Ge),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;it(t??[...Pd])}},disabled:Q}),(0,z.jsx)(`span`,{className:`text-control`,children:S(`models.customFieldReasoningOverride`)})]})}),tt&&(0,z.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:Pd.map(e=>(0,z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:rt.includes(e),onChange:t=>{it(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Q}),(0,z.jsx)(`span`,{className:`text-control`,children:S(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Re(!1),disabled:Q,children:S(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Q||!Ge.trim(),onClick:()=>{let e=Ge.trim(),t=qe.trim(),n=Ye?Number(Ye.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;if(ze===`add`){let n=tt?rt:void 0;Nn(Ve,e,t||void 0,r,$e.length>0?$e:void 0,n)}else Pn(Ue,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:$e,reasoningEfforts:tt?rt:null})},children:S(Q?`models.customSaving`:ze===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),Kn=(0,z.jsxs)(`div`,{className:`models-workspace-shell`,children:[ue&&(0,z.jsxs)(`div`,{className:`action-toast notice ${de?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[de?(0,z.jsx)(J,{}):(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{children:ue})]}),Qt.showError&&(0,z.jsx)($,{tone:`err`,children:S(`models.loadFail`)}),(0,z.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":Qt.refreshing||void 0,children:[(0,z.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":S(`nav.models`),children:[(0,z.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,z.jsx)(`span`,{className:`models-workspace-rail-title`,children:S(`models.workspace.providers`)}),(0,z.jsx)(`span`,{className:`models-workspace-rail-count`,children:en.length})]}),(0,z.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ht===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ut(null),"aria-current":Ht===null?`true`:void 0,children:[(0,z.jsx)(`span`,{className:`models-workspace-rail-name`,children:S(`models.workspace.allProviders`)}),(0,z.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:cn,total:T.length})})]}),en.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>Ad(zn,t,e.id,e.native===!0,k.has(e.namespaced))).length;return(0,z.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ht===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ut(t),"aria-current":Ht===t?`true`:void 0,children:[(0,z.jsx)(`span`,{className:`models-workspace-rail-name`,children:pn(t,S)}),(0,z.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,z.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":S(`models.workspace.mainAria`),children:[Hn,Un,(0,z.jsx)(`div`,{className:`models-provider-list`,children:Vn.map(e=>Bn(e))}),en.length===0&&Wn]})]}),Gn]});return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{children:S(`nav.models`)}),(0,z.jsx)(`div`,{className:`page-head-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{s()},disabled:o,"aria-label":S(o?`dash.codexRestarting`:`dash.codexRestart`),title:S(o?`dash.codexRestarting`:`dash.codexRestart`),children:(0,z.jsx)(re,{})})})]}),(0,z.jsx)($s,{state:n,controller:{restarting:o,restart:s}}),(0,z.jsx)(Cd,{tab:c,onSelect:p,meta:ln}),(0,z.jsx)(`p`,{className:`page-sub`,children:S(qd[c])}),(0,z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:xd(`catalog`),"aria-labelledby":bd(`catalog`),hidden:c!==`catalog`,children:(0,z.jsx)(Sc,{pageName:S(`models.tab.catalog`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:Rn?(0,z.jsx)(bc,{label:S(`models.loading`),rows:5}):Ln===null?Kn:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:Ln}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Zt.refresh(),children:S(`common.retry`)})]})})}),(0,z.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:xd(`combos`),"aria-labelledby":bd(`combos`),hidden:c!==`combos`,children:u.has(`combos`)&&(0,z.jsx)(Sc,{pageName:S(`models.tab.combos`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,z.jsx)(vl,{apiBase:e,active:c===`combos`,onCountChange:g})})}),(0,z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:xd(`routing`),"aria-labelledby":bd(`routing`),hidden:c!==`routing`,children:u.has(`routing`)&&(0,z.jsx)(Sc,{pageName:S(`models.tab.routing`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,z.jsx)(ru,{apiBase:e,active:c===`routing`,onCountChange:y})})}),(0,z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:xd(`compatibility`),"aria-labelledby":bd(`compatibility`),hidden:c!==`compatibility`,children:u.has(`compatibility`)&&(0,z.jsx)(Sc,{pageName:S(`models.tab.compatibility`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,z.jsx)(hd,{apiBase:e,active:c===`compatibility`,onCountChange:x})})})]})}var Xd=`section`;function Zd(e,t){return[e,Xd,t].join(`-`)}function Qd(e){return[e,Xd,``].join(`-`)}var $d=1200;function ef({scope:e,items:t,ariaLabel:n}){let[r,i]=(0,_.useState)(t[0]?.id??``),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useCallback)(()=>{a.current=null,o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),c=(0,_.useCallback)(()=>{s();let n=null,r=1/0;for(let i of t){let t=document.getElementById(Zd(e,i.id));if(!t)continue;let a=Math.abs(t.getBoundingClientRect().top-72);a<r&&(r=a,n=i.id)}n&&i(n)},[s,t,e]);(0,_.useEffect)(()=>()=>s(),[s]),(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(Zd(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=a.current;if(n){let r=document.getElementById(Zd(e,n));t.some(e=>e.isIntersecting&&e.target===r)&&(s(),i(n));return}let r=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!r)return;let o=r.target.id.slice(Qd(e).length);i(e=>e===o?e:o)},{rootMargin:`-72px 0px -60% 0px`,threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[s,t,e]);let l=t=>{let n=document.getElementById(Zd(e,t));n&&(a.current=t,o.current!==null&&clearTimeout(o.current),o.current=setTimeout(c,$d),i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,z.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,z.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":Zd(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>l(t.id),children:[t.label,t.meta?(0,z.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function tf({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s,ultraMode:c,ultraSaving:l,onUltraModeSave:u,ultraLoadFailed:d,onUltraModeRetry:f}){let p=Z(),m=(c.hintText??``).trim().length>0;return(0,z.jsxs)(`div`,{className:`swi-delegation`,children:[d&&(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeLoadFail`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`common.retry`)})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`sub.delegation.model`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.delegation.modelHint`)})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,z.jsx)(ht,{value:e,options:[{value:``,label:p(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:gn(`${e.provider}/${e.model}`,p)}))],onChange:e=>s({model:e||null,effort:t||null}),disabled:o,label:p(`dash.injectionLabel`),align:`right`}),e&&n.length>0&&(0,z.jsx)(ht,{value:t,options:[{value:``,label:p(`dash.injectionEffortNone`)},...n.map(e=>({value:e,label:e}))],onChange:t=>s({model:e||null,effort:t||null}),disabled:o,label:p(`dash.injectionEffortLabel`),align:`right`})]})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`dash.syncCodexSubagentDefaults`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>s({syncCodexSubagentDefaults:!a}),disabled:o||!e,"aria-label":p(`dash.syncCodexSubagentDefaults`),"aria-pressed":a,children:(0,z.jsx)(`span`,{className:`knob`})})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`dash.multiAgentGuidance`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.multiAgentGuidanceHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":p(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,z.jsx)(`span`,{className:`knob`})})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${m?`on`:``}`,onClick:()=>u({multiAgentModeHintText:m?null:rf}),disabled:o||l||!m&&!c.multiAgentV2Enabled,"aria-label":p(`sub.ultraMode`),"aria-pressed":m,children:(0,z.jsx)(`span`,{className:`knob`})}),!c.multiAgentV2Enabled&&(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeV2Required`)})]}),m&&(0,z.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,z.jsx)(nf,{initialHint:c.hintText??``,disabled:o||l,onSave:u,preset:`Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning sub-agents no longer applies. Delegate independent sub-tasks to sub-agents whenever parallel work would materially improve speed or quality — do not serialize work that can run concurrently. Each sub-agent runs in its own context and can use all available tools; prefer spawning specialists over doing everything yourself. This mode remains active until a later multi-agent mode developer message changes it.`,labels:{text:p(`sub.ultraModeText`),preset:p(`sub.ultraModePreset`),save:p(`common.save`)}},c.hintText)})]})}function nf({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,_.useState)(e);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`textarea`,{className:`input swi-ultra-mode-textarea`,value:a,onChange:e=>o(e.target.value),disabled:t,rows:4,"aria-label":i.text}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>o(r),disabled:t,children:i.preset}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{a.trim().length!==0&&n({multiAgentModeHintText:a})},disabled:t||a.trim().length===0,children:i.save})]})}var rf=`Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning sub-agents no longer applies. Delegate independent sub-tasks to sub-agents whenever parallel work would materially improve speed or quality — do not serialize work that can run concurrently. Each sub-agent runs in its own context and can use all available tools; prefer spawning specialists over doing everything yourself. This mode remains active until a later multi-agent mode developer message changes it.`;function af({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=Z(),[c,l]=(0,_.useState)(``),u=(0,_.useMemo)(()=>new Set(t),[t]),d=t.length>=5,f=(0,_.useMemo)(()=>{let t=c.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,c]),p=(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]);return(0,z.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,z.jsx)(ef,{scope:`subagents`,items:p,ariaLabel:s(`sub.sections`)}),(0,z.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,z.jsxs)(`section`,{id:Zd(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,z.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,z.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,z.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,z.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,z.jsx)(ce,{width:15,height:15,"aria-hidden":`true`}),(0,z.jsx)(`span`,{children:(0,z.jsx)($e,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,z.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,z.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,z.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,z.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,z.jsx)(`span`,{className:`swi-featured-name`,children:gc(e)}),(0,z.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,z.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,z.jsx)(ue,{})}),(0,z.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,z.jsx)(X,{})}),(0,z.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,z.jsx)(Y,{})})]})]},e))}),(0,z.jsx)(`div`,{className:`swi-save-row`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,z.jsxs)(`section`,{id:Zd(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,z.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,z.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,z.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,z.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,z.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,z.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,z.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,z.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,z.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,z.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,z.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,z.jsx)(W,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:gc(e)})]}),(0,z.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,z.jsx)(J,{style:{width:14,height:14}}):(0,z.jsx)(ne,{style:{width:14,height:14}})})]},e)})})]})]}),(0,z.jsxs)(`section`,{id:Zd(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,z.jsx)(`div`,{className:`swi-featured-head`,children:(0,z.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,z.jsx)(tf,{model:o.model,effort:o.effort,efforts:o.efforts,available:o.available,guidanceEnabled:o.guidanceEnabled,syncCodexDefaults:o.syncCodexDefaults,saving:o.saving,onSave:o.onSave,ultraMode:o.ultraMode,ultraSaving:o.ultraSaving,onUltraModeSave:o.onUltraModeSave,ultraLoadFailed:o.ultraLoadFailed,onUltraModeRetry:o.onUltraModeRetry})]})]})]})}function of(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=rr(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 Ot(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`);let n=await fetch(`${e}/api/injection-model`);v(await Ot(n))}catch{}finally{i(!1)}}},[e,v,r])}}function sf(e){return qn(e)}function cf({apiBase:e}){let t=Z(),n=`ocx.subagents.v1:${e}`,r=sf(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=of(e),[m,h]=(0,_.useState)({enabled:!1,hintText:null,multiAgentV2Enabled:!1}),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),x=(0,_.useRef)(0),S=(0,_.useRef)(e);(0,_.useEffect)(()=>{S.current=e,x.current++},[e]);let C=(0,_.useCallback)(async n=>{if(S.current!==e)return!1;let r=++x.current,i=await St(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));return!i||n?.aborted||r!==x.current||S.current!==e?!1:(b(!1),h({enabled:i.enabled??!1,hintText:i.multiAgentModeHintText??null,multiAgentV2Enabled:i.enabled===!0&&i.multiAgentMode===`v2`}),!0)},[e,t]);(0,_.useEffect)(()=>{let e=new AbortController;return(async()=>{await C(e.signal)})().catch(()=>{e.signal.aborted||(l(!1),b(!0),s(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[C,t]);let w=async n=>{if(g)return;let r=e;v(!0),s(``);try{if(await St(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),S.current!==r||!await C())return;l(!0),s(t(`sub.ultraModeSaved`))}catch(e){if(S.current!==r)return;l(!1),s(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{v(!1)}},T=(0,_.useCallback)(async()=>{try{if(!await C())return;l(!1),s(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{l(!1),b(!0),s(t(`sub.ultraModeLoadFail`))}},[C,t]),E=(0,_.useCallback)(async()=>{let r=await St(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),Jn(n,s),s},[e,n,t]),D=vc(n,[e],E,{isEmpty:()=>!1,initialData:r??void 0}),{state:O}=D,k=D.refresh,A=O.data??r,j=A?.available??[],M=e=>{u||(s(``),a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e]))},N=(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)})},P=async()=>{if(!(u||f.current)){f.current=!0,d(!0),s(``);try{let r=await St(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),Jn(n,{available:j,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)}}};if(O.showSkeleton&&!A)return(0,z.jsx)(bc,{label:t(`sub.loading`),rows:4});if(O.kind===`failed-cold`){let e=O.error instanceof Error?O.error.message:t(`sub.loadFail`);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:t(`common.retry`)})]})}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,z.jsx)($,{tone:c?`ok`:`err`,children:o}),O.showError&&(0,z.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),(0,z.jsx)(af,{available:j,chosen:i,busy:u,onToggle:M,onMove:N,onSave:()=>{P()},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)},ultraMode:m,ultraSaving:g,onUltraModeSave:e=>{w(e)},ultraLoadFailed:y,onUltraModeRetry:()=>{T()}}})]})}function lf(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 uf(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 df(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var ff=(e,t)=>Math.abs(e-t)<1.01,pf=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},mf,hf=()=>{if(mf!==void 0)return mf;if(typeof navigator>`u`)return mf=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return mf=!0;let e=navigator.maxTouchPoints;return mf=navigator.platform===`MacIntel`&&e!==void 0&&e>0},gf=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},_f=e=>e,vf=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},yf=(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(gf(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(gf(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},bf={passive:!0},xf=typeof window>`u`||`onscrollend`in window,Sf=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&xf,o=0,s=a?null:pf(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,bf),a&&r.addEventListener(`scrollend`,u,bf),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Cf=(e,t)=>Sf(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),wf=(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`]},Tf=(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})},Ef=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:_f,rangeExtractor:vf,onChange:()=>{},measureElement:wf,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=e>0?s[0]?.key??n.getItemKey(0):null,l=e>0?s[e-1]?.key??n.getItemKey(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==c||t.getItemKey(o-1)!==l)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>e&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==l)&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=!1,s=0;if(r&&this.scrollOffset!==null){let[e,t]=r,n=this.getMeasurements(),{count:i,getItemKey:a}=this.options,c=0;for(;c<i&&a(c)!==e;)c++;if(c<i){let e=n[c];if(e){let n=Math.max(0,e.start+t);n!==this.scrollOffset&&(s=n-this.scrollOffset,this.scrollOffset=n,o=!0)}}}(o||i)&&(this.pendingScrollAnchor=[o?r[0]:null,o?r[1]:0,i,s])},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=uf(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.targetWindow=this.scrollElement&&`ownerDocument`in this.scrollElement?this.scrollElement.ownerDocument.defaultView:this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{if(t&&this._intendedScrollOffset===null&&e===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;let n=this.getScrollOffset();this.scrollDirection=t?n===e?this.scrollDirection:n<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!hf()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,bf),e.addEventListener(`touchend`,n,bf),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&&(hf()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?i!==0&&(this._iosDeferredAdjustment+=i):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),r&&this.scrollToEnd({behavior:r})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;if(this._iosDeferredAdjustment<0&&e>=t-1){this._iosDeferredAdjustment=0;return}let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=uf(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(e,t,n,r,i,a,o,s)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s}),{key:!1}),this.getMeasurements=uf(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s},c)=>{let l=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let u=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=e*2,a=this._flatMeasurements;if(!a||a.length<i){let e=new Float64Array(i);a&&u>0&&e.set(a.subarray(0,u*2)),a=e,this._flatMeasurements=a}let o;if(u===0)o=t+n;else{let e=u-1;o=a[e*2]+a[e*2+1]+s}for(let t=u;t<e;t++){let e=r(t),n=l.get(e),i=typeof n==`number`?n:this.options.estimateSize(t);a[t*2]=o,a[t*2+1]=i,o+=i+s}let c=lf(e,a,r);return this.measurementsCache=c,c}let d=this.measurementsCache.slice(0,u),f=Array(a).fill(void 0),p=new Float64Array(a),m=0;for(let e=0;e<u;e++){let t=d[e];t&&(f[t.lane]===void 0&&m++,f[t.lane]=e,p[t.lane]=t.end)}for(let i=u;i<e;i++){let e=r(i),c=this.laneAssignments.get(i),u,h,g=o===`estimate`||l.has(e);if(c!==void 0&&this.options.lanes>1){u=c;let e=f[u],r=e===void 0?void 0:d[e];h=r?r.end+s:t+n}else if(m===a){let e=0,t=p[0],n=f[0];for(let r=1;r<a;r++){let i=p[r];(i<t||i===t&&f[r]<n)&&(e=r,t=i,n=f[r])}u=e,h=t+s,g&&this.laneAssignments.set(i,u)}else u=i%this.options.lanes,h=t+n,g&&this.laneAssignments.set(i,u);let _=l.get(e),v=typeof _==`number`?_:this.options.estimateSize(i),y=h+v;d[i]={index:i,start:h,size:v,end:y,key:e,lane:u},f[u]===void 0&&m++,f[u]=i,p[u]=y}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=uf(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=kf(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=uf(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=this.itemSizeCache.get(i)??n,s=t-o;if(s!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,c=a?this.getTotalSize():0,l=this.getScrollOffset()+this.scrollAdjustments,u=this.itemSizeCache.has(i)?r+o<=l&&this.scrollDirection!==`backward`:r<l,d=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?u:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},s,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++;let f=!1;a?f=this.applyScrollAdjustment(this.getTotalSize()-c):d&&(f=this.applyScrollAdjustment(s)),this.notify(f)}},this.getVirtualItems=uf(()=>[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 df(t[Df(0,t.length-1,r?e=>n[e*2]:e=>df(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`){if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t]}if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0;let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0,e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:e=`auto`}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}applyScrollAdjustment(e,t){return e===0?!1:hf()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=e,!1):(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&ff(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()}},Df=(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 Of(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 kf(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=Of(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=Df(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 Af=typeof document<`u`?_.useLayoutEffect:_.useEffect;function jf({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`}},s=e=>{let t=a.current;if(!t.enabled||!t.container)return;o(e);let n=!!e.options.horizontal,r=t.mode===`transform`,i=n?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let a of c){let o=a.start-s,c=e.elementsCache.get(a.key);c&&t.lastPositions.get(c)!==o&&(t.lastPositions.set(c,o),r?c.style.transform=n?`translate3d(${o}px, 0, 0)`:`translate3d(0, ${o}px, 0)`:c.style[i]=`${o}px`)}},c={...r,onChange:(t,n)=>{var o;let c=a.current,l=!0;if(c.enabled){s(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,rt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=_.useState(()=>{let e=new Ef(c);return Object.assign(e,{containerRef:t=>{let n=a.current;if(n.container=t,n.lastSize=null,t&&n.enabled){let r=e.getTotalSize();n.lastSize=r;let i=e.options.horizontal?`width`:`height`;t.style[i]=`${r}px`}}})});return l.setOptions(c),Af(()=>l._didMount(),[]),Af(()=>(o(l),l._willUpdate())),Af(()=>{s(l)}),l}function Mf(e){return jf({observeElementRect:yf,observeElementOffset:Cf,scrollToFn:Tf,...e})}var Nf=32;function Pf(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Ff(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 If(e){let t=e.trim();if(t&&!Ff(t)&&!(t.length>4096))return Pf(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,Nf)}function Lf(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r||n!==void 0&&e===n:!1}var Rf={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 正文。`},"zh-TW":{label:`錯誤請求`,description:`代理無法理解該請求。重試前請檢查模型、訊息結構、標頭和 JSON 本文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`},ru:{label:`Некорректный запрос`,description:`Прокси не смог интерпретировать запрос. Перед повторной попыткой проверьте модель, формат сообщений, заголовки и тело JSON.`},ja:{label:`不正なリクエスト`,description:`プロキシがリクエストを解釈できませんでした。再試行前にモデル、メッセージ形式、ヘッダー、JSON 本文を確認してください。`},tr:{label:`Hatalı istek`,description:`Proxy isteği anlayamadı. Yeniden denemeden önce modeli, mesaj yapısını, başlıkları ve JSON gövdesini kontrol edin.`}},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 使用的账号/提供商凭据。`},"zh-TW":{label:`未授權`,description:`憑證缺失、已過期或無效。請重新登入,或重新整理 opencodex 使用的帳號/供應商憑證。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`},ru:{label:`Не авторизован`,description:`Учётные данные отсутствуют, истекли или недействительны. Войдите заново или обновите учётные данные аккаунта или провайдера, которые использует opencodex.`},ja:{label:`認証が必要`,description:`認証情報が不在・期限切れ・無効です。opencodex が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`},tr:{label:`Yetkisiz erişim`,description:`Kimlik bilgileri eksik, süresi dolmuş veya geçersiz. opencodex tarafından kullanılan hesap veya sağlayıcı kimlik bilgilerini yeniden doğrulayın.`}},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:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},"zh-TW":{label:`需要付款`,description:`上游供應商因帳單、額度或方案許可權不可用而拒絕了請求。請儲值、更新帳單資訊或切換供應商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`},ru:{label:`Требуется оплата`,description:`Вышестоящий провайдер отклонил запрос из-за проблем с оплатой, кредитами или доступом по тарифному плану. Пополните баланс, обновите платёжные данные или переключитесь на другого провайдера.`},ja:{label:`支払いが必要`,description:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`},tr:{label:`Ödeme gerekli`,description:`Yukarı akış sağlayıcısı faturalandırma, kredi veya plan erişimi bulunmadığından isteği reddetti. Kredi ekleyin, ödeme bilgilerini güncelleyin veya sağlayıcı değiştirin.`}},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 密钥无效。`},"zh-TW":{label:`禁止存取`,description:`帳號已認證,但無權使用此模型或操作。常見原因是方案/訂閱限制(例如 Ollama Cloud Pro)、組織策略或模型許可權——不一定是 API 金鑰無效。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key.`},ru:{label:`Доступ запрещён`,description:`Аккаунт аутентифицирован, но не имеет права использовать эту модель или операцию. Часто причина — ограничение тарифа или подписки (например, Ollama Cloud Pro), политика организации или права доступа к модели, а не обязательно неверный API-ключ.`},ja:{label:`アクセス禁止`,description:`アカウントは認証済みですがこのモデルや操作の使用が許可されていません。多くはプラン/サブスクリプション制限(例: Ollama Cloud Pro)、組織ポリシー、モデル権限であり、API キーが不正とは限りません。`},tr:{label:`Erişim yasaklandı`,description:`Hesabın kimliği doğrulandı ancak bu modeli veya işlemi kullanma izni yok. Genellikle plan/abonelik sınırı (örn. Ollama Cloud Pro), organizasyon politikası veya model izni kaynaklıdır.`}},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 提供商配置。`},"zh-TW":{label:`未找到`,description:`找不到請求的路由、模型、帳號或上游資源。請確認模型名稱和 opencodex 供應商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`},ru:{label:`Не найдено`,description:`Запрошенный маршрут, модель, аккаунт или вышестоящий ресурс не найден. Проверьте имя модели и конфигурацию провайдера в opencodex.`},ja:{label:`見つかりません`,description:`要求されたルート、モデル、アカウント、上流リソースが見つかりませんでした。モデル名と opencodex プロバイダー設定を確認してください。`},tr:{label:`Bulunamadı`,description:`İstenen rota, model, hesap veya yukarı akış kaynağı bulunamadı. Model adını ve opencodex sağlayıcı yapılandırmasını doğrulayın.`}},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:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},"zh-TW":{label:`請求逾時`,description:`代理或上游供應商未能在限定時間內完成請求。請縮小請求後重試,或切換供應商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`},ru:{label:`Тайм-аут запроса`,description:`Обработка запроса заняла слишком много времени, и прокси или вышестоящий провайдер не успел её завершить. Повторите попытку с меньшим запросом или через другого провайдера.`},ja:{label:`リクエストタイムアウト`,description:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`},tr:{label:`İstek zaman aşımı`,description:`Proxy veya yukarı akış sağlayıcısı isteği tamamlayamadan zaman aşımına uğradı. Daha küçük bir istek veya farklı bir sağlayıcı ile tekrar deneyin.`}},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:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},"zh-TW":{label:`狀態衝突`,description:`請求與當前帳號、會話或供應商狀態衝突。請重新整理會話,或等待當前操作完成後重試。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`},ru:{label:`Конфликт`,description:`Запрос конфликтует с текущим состоянием аккаунта, сессии или провайдера. Обновите сессию или повторите попытку после завершения текущей операции.`},ja:{label:`状態の衝突`,description:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`},tr:{label:`Durum çakışması`,description:`İstek mevcut hesap, oturum veya sağlayıcı durumuyla çakışıyor. Oturumu yenileyin veya aktif işlem bittikten sonra tekrar deneyin.`}},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、文件大小或对话历史。`},"zh-TW":{label:`請求過大`,description:`提示、附件或生成的負載超過了代理或上游限制。請減少 token、檔案大小或對話歷史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`},ru:{label:`Слишком большой запрос`,description:`Промпт, вложения или сформированная полезная нагрузка превышают лимит прокси или вышестоящего провайдера. Сократите количество токенов, размер файлов или историю диалога.`},ja:{label:`リクエストが大きすぎます`,description:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`},tr:{label:`İstek çok büyük`,description:`İstemi, ekler veya oluşturulan veri proxy ya da yukarı akış sınırını aşıyor. Jeton sayısını, dosya boyutunu veya sohbet geçmişini azaltın.`}},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:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},"zh-TW":{label:`內容無效`,description:`供應商接受了請求格式,但拒絕了其中的內容。請檢查模型選項、工具定義、訊息角色和不支援的欄位。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`},ru:{label:`Недопустимое содержимое`,description:`Провайдер принял формат запроса, но отклонил его содержимое. Проверьте параметры модели, определения инструментов, роли сообщений и неподдерживаемые поля.`},ja:{label:`内容の検証失敗`,description:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`},tr:{label:`Geçersiz içerik`,description:`Sağlayıcı istek formatını kabul etti ancak içeriğini reddetti. Model seçeneklerini, araç tanımlarını, mesaj rollerini ve desteklenmeyen alanları kontrol edin.`}},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 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},"zh-TW":{label:`供應商依賴失敗`,description:`opencodex 路由請求時,必需的上游依賴失敗。請稍後重試,或切換到另一個已配置的供應商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`},ru:{label:`Сбой зависимости провайдера`,description:`Необходимая вышестоящая зависимость дала сбой, пока opencodex маршрутизировал запрос. Повторите попытку позже или переключитесь на другого настроенного провайдера.`},ja:{label:`プロバイダー依存の失敗`,description:`opencodex がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı bağımlılığı başarısız`,description:`opencodex isteği yönlendirirken gerekli bir yukarı akış bağımlılığı başarısız oldu. Daha sonra tekrar deneyin veya başka bir sağlayıcıya geçin.`}},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:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},"zh-TW":{label:`限流`,description:`已達到上游供應商的速率或額度限制。請等待額度視窗重設,或切換帳號/供應商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`},ru:{label:`Превышен лимит запросов`,description:`Достигнут лимит скорости или квота вышестоящего провайдера. Дождитесь сброса окна квоты или переключитесь на другой аккаунт или провайдера.`},ja:{label:`レート制限`,description:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`},tr:{label:`Oran sınırı aşıldı`,description:`Yukarı akış sağlayıcısının hız veya kota sınırına ulaşıldı. Kota penceresinin sıfırlanmasını bekleyin ya da hesap/sağlayıcı değiştirin.`}},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 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},"zh-TW":{label:`客戶端已取消`,description:`opencodex 完成路由前,客戶端已斷開連線或取消請求。如果不是有意取消,請重試。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`},ru:{label:`Запрос закрыт клиентом`,description:`Клиент отключился или отменил запрос до того, как opencodex завершил его маршрутизацию. Если отмена была случайной, повторите попытку.`},ja:{label:`クライアントがリクエストをクローズ`,description:`opencodex がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`},tr:{label:`İstemci isteği kapattı`,description:`opencodex yönlendirmeyi bitirmeden önce istemci bağlantıyı kesti veya isteği iptal etti. İptal kazara yapıldıysa tekrar deneyin.`}},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 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},"zh-TW":{label:`代理錯誤`,description:`opencodex 處理請求時發生內部錯誤。請先重試一次;如果重複出現,請檢查代理日誌。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`},ru:{label:`Ошибка прокси`,description:`В opencodex произошла внутренняя ошибка при обработке запроса. Повторите попытку один раз; если ошибка повторяется, проверьте логи прокси.`},ja:{label:`プロキシエラー`,description:`opencodex がリクエスト処理中に内部エラーに遭遇しました。1 回再試行し、繰り返す場合はプロキシログを確認してください。`},tr:{label:`Proxy hatası`,description:`opencodex isteği işlerken dahili bir hatayla karşılaştı. Bir kez tekrar deneyin, tekrarlarsa proxy günlüklerini kontrol edin.`}},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:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},"zh-TW":{label:`上游回應錯誤`,description:`上游供應商透過代理返回了無效或失敗的回應。請重試,或將請求路由到其他供應商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Некорректный ответ провайдера`,description:`Вышестоящий провайдер вернул через прокси недействительный или ошибочный ответ. Повторите попытку или направьте запрос другому провайдеру.`},ja:{label:`上流レスポンス不良`,description:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Kötü yukarı akış yanıtı`,description:`Yukarı akış sağlayıcısı proxy üzerinden geçersiz veya başarısız bir yanıt döndürdü. Tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}},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:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},"zh-TW":{label:`供應商不可用`,description:`代理或上游供應商暫時不可用或過載。請稍後重試,或切換供應商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`},ru:{label:`Провайдер недоступен`,description:`Прокси или вышестоящий провайдер временно недоступен или перегружен. Немного подождите, затем повторите попытку или смените провайдера.`},ja:{label:`プロバイダー利用不可`,description:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`},tr:{label:`Sağlayıcı kullanılamıyor`,description:`Proxy veya yukarı akış sağlayıcısı geçici olarak kullanılamıyor veya aşırı yüklü. Kısa bir süre bekleyip tekrar deneyin ya da sağlayıcı değiştirin.`}},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:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},"zh-TW":{label:`上游逾時`,description:`上游供應商未在代理逾時前回應。請縮小請求後重試,或選擇回應更快的供應商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`},ru:{label:`Тайм-аут вышестоящего провайдера`,description:`Вышестоящий провайдер не ответил до истечения тайм-аута прокси. Повторите попытку с меньшим запросом или выберите более быстрого провайдера.`},ja:{label:`上流タイムアウト`,description:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`},tr:{label:`Yukarı akış zaman aşımı`,description:`Yukarı akış sağlayıcısı proxy zaman aşımı süresinden önce yanıt vermedi. Daha küçük bir istekle tekrar deneyin veya daha hızlı bir sağlayıcı seçin.`}},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:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},"zh-TW":{label:`供應商過載`,description:`上游供應商過載或容量受限。請等待後重試,或切換到其他帳號/供應商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`},ru:{label:`Провайдер перегружен`,description:`Вышестоящий провайдер перегружен или ограничен по мощности. Подождите и повторите попытку либо переключитесь на другой аккаунт или провайдера.`},ja:{label:`プロバイダー過負荷`,description:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı aşırı yüklü`,description:`Yukarı akış sağlayıcısı aşırı yüklü veya kapasitesi sınırlı. Bekleyip tekrar deneyin veya başka bir hesap/sağlayıcıya geçin.`}}},zf={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:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},"zh-TW":{label:`請求錯誤`,description:`代理或上游供應商拒絕了該請求。請檢查請求結構、憑證、模型名稱和供應商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`},ru:{label:`Ошибка запроса`,description:`Прокси или вышестоящий провайдер отклонил запрос. Проверьте структуру запроса, учётные данные, имя модели и конфигурацию провайдера.`},ja:{label:`リクエストエラー`,description:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`},tr:{label:`İstek hatası`,description:`Proxy veya yukarı akış sağlayıcısı isteği reddetti. İstek yapısını, kimlik bilgilerini, model adını ve sağlayıcı yapılandırmasını kontrol edin.`}},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 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},"zh-TW":{label:`伺服器或上游錯誤`,description:`opencodex 或上游供應商處理請求時失敗。請稍後重試,或將請求路由到其他供應商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Ошибка сервера или провайдера`,description:`opencodex или вышестоящий провайдер завершил обработку запроса с ошибкой. Повторите попытку позже или направьте запрос другому провайдеру.`},ja:{label:`サーバーまたは上流エラー`,description:`opencodex または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Sunucu veya yukarı akış hatası`,description:`opencodex veya bir yukarı akış sağlayıcısı isteği işlerken başarısız oldu. Daha sonra tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}}};function Bf(e){return e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function Vf(e,t){if(e<400)return null;let n=Bf(t);return(Rf[Math.trunc(e)]??(e<500?zf.client:zf.server))[n]}var Hf=[`provider`,`usage`,`injection`];function Uf(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function Wf(e){return new Date(e).toLocaleTimeString()}function Gf(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function Kf(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function qf({entries:e}){let{t}=Ze();return(0,z.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,z.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,z.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,z.jsx)(`div`,{style:{overflowX:`auto`},children:(0,z.jsxs)(`table`,{className:`table text-label`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,z.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,z.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,z.jsx)(`th`,{children:`thinking`}),(0,z.jsx)(`th`,{children:`effort`}),(0,z.jsx)(`th`,{children:`beta`}),(0,z.jsx)(`th`,{children:`metadata`}),(0,z.jsx)(`th`,{children:`system`})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`muted mono`,children:Wf(e.at)}),(0,z.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,z.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,z.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,z.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,z.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,z.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,z.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,z.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,z.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function Jf({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=Ze();return e?n?r.length===0?(0,z.jsxs)(`div`,{className:`empty`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,z.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,z.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,z.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Uf(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,z.jsxs)(`div`,{className:`empty`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function Yf({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=Ze();return(0,z.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,z.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=Kf(e,n);return(0,z.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,z.jsx)(pt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,z.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,z.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,z.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function Xf({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=Ze();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,z.jsx)(`h2`,{children:o(`debug.title`)}),(0,z.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,z.jsx)(re,{}),` `,o(`debug.refresh`)]}),(0,z.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function Zf(e){return`debug-settings:${e}`}function Qf({apiBase:e,embedded:t,active:n=!0}){let{t:r}=Ze(),i=`ocx.debug.settings.v1:${e}`,a=qn(i),o=Zf(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(`provider`),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useRef)(0),y=(0,_.useRef)(0),b=(0,_.useRef)(0),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=vc(o,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Jn(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),T=w.state,E=w.data??a??null,D=I(`debug-claude-inbound:${e}`,[e,E?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:n&&!!E?.claude}).data??[],O=Mf({count:d.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),k=(0,_.useCallback)(e=>Gf(E,e),[E]);(0,_.useEffect)(()=>{if(!E||k(l))return;let e=Hf.find(k);if(!e)return;let t=window.setTimeout(()=>u(e),0);return()=>window.clearTimeout(t)},[E,l,k]);let A=k(l),j=l===`provider`?`${e}/api/debug/logs`:l===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,M=(0,_.useCallback)(async(e,t)=>{let n=++b.current;if(!A){n===b.current&&(f([]),v.current=0);return}g(!0);try{let r=new URLSearchParams({limit:`500`});!e&&v.current>0&&r.set(`after`,String(v.current));let i=await fetch(`${j}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==b.current)return;let a=await i.json();if(t?.aborted||n!==b.current||a.length===0)return;f(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===b.current&&g(!1)}},[j,A]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${l}:${A}`,r=C.current!==t;if(C.current=t,!r&&d.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&f([]),M(!0,i.signal)},0);return()=>{window.clearTimeout(a),b.current+=1,i.abort()}},[n,e,l,A]);let N=(0,_.useEffectEvent)(e=>{M(e)});(0,_.useEffect)(()=>{if(!n||!p||!A)return;let e=setInterval(()=>N(!1),1e3);return()=>clearInterval(e)},[n,p,A]),(0,_.useEffect)(()=>{p&&d.length>0&&O.scrollToIndex(d.length-1,{align:`end`})},[d,p,O]);let P=async t=>{let n=++y.current;c(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let a=await r.json();if(n!==y.current)return;Jn(i,a),L(o,a)}catch{}},a=(x.current??Promise.resolve()).then(r,r);x.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===y.current&&c(!1)}},F=async(e,t)=>{await P({[e]:t})},R=async()=>{await P({reset:!0})};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Xf,{embedded:t,refreshing:h,streamEnabled:A,follow:p,onRefresh:()=>void M(!0),onFollowChange:m}),!E&&T.showError?(0,z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,z.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:r(`common.retry`)})]}):T.showSkeleton&&!E?(0,z.jsx)(bc,{label:r(`debug.loading`),rows:3}):E?(0,z.jsx)(Yf,{debug:E,debugBusy:s,stream:l,onSetFlag:(e,t)=>{F(e,t)},onReset:()=>{R()},onStreamChange:u}):null,E&&T.showError&&(0,z.jsx)($,{tone:`err`,children:r(`debug.loadFailed`)}),E?.claude&&(0,z.jsx)(qf,{entries:D}),(0,z.jsx)(Jf,{debug:!!E,stream:l,streamEnabled:A,entries:d,scrollContainerRef:S,lineVirtualizer:O})]})}function $f(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function ep(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function tp(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),ep(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),ep(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function np(e){return e.requestedSpeedLabel||void 0}function rp(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 ip(e){return e===void 0||typeof e==`string`}function ap(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!ip(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!ip(e.profile.id)||!ip(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!ip(e.selected.provider)||!ip(e.selected.model)||!ip(e.selected.reason)))return!1;if(e.candidates===void 0)return!0;if(!Array.isArray(e.candidates))return!1;for(let t of e.candidates){if(!t||typeof t!=`object`||!ip(t.provider)||!ip(t.model)||t.eligible!==void 0&&typeof t.eligible!=`boolean`)return!1;if(t.exclusions!==void 0){if(!Array.isArray(t.exclusions))return!1;for(let e of t.exclusions)if(!e||typeof e!=`object`||!ip(e.code))return!1}}return!0}function op(e){if(e.routeDecision===void 0||ap(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function sp(e){return`ocx.logs.list.v1:${e}`}function cp(e){if(!Array.isArray(e))return null;for(let t of e)if(!t||typeof t!=`object`||typeof t.timestamp!=`number`||typeof t.model!=`string`||typeof t.provider!=`string`||typeof t.status!=`number`||typeof t.durationMs!=`number`||!ap(t.routeDecision))return null;return e}function lp(e){return e===`cursor`||e.startsWith(`cursor-`)}function up(e,t){if(!e.usage)return;let n=pp(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(lp(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function dp(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 fp(e){let t=dp(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function pp(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 mp(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 hp(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function gp(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 _p(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 vp(e,t){return!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var yp=3,bp={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`},xp={usage_estimated:`logs.detail.estimate.usage_estimated`,cache_detail_missing:`logs.detail.estimate.cache_detail_missing`,expected_price_overlay:`logs.detail.estimate.expected_price_overlay`,provider_cost_overlay:`logs.detail.estimate.provider_cost_overlay`},Sp={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"oauth-401":`logs.detail.attempt.recovery.oauth401`,"key-429":`logs.detail.attempt.recovery.key429`,"rate-limit-429":`logs.detail.attempt.recovery.rateLimit429`,"anthropic-oauth-429":`logs.detail.attempt.recovery.anthropicOauth429`,"image-413":`logs.detail.attempt.recovery.image413`,"empty-completion":`logs.detail.attempt.recovery.emptyCompletion`};function Cp(e){return bp[e]}function wp(e){return xp[e]}function Tp(e){return Sp[e]??`logs.detail.attempt.recovery.unknown`}function Ep(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function Dp(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Op(e,t,n){let r=n?{timeZone:n}:void 0;try{return{date:new Date(e).toLocaleDateString(t,r),time:new Date(e).toLocaleTimeString(t,r)}}catch{return{date:new Date(e).toLocaleDateString(t),time:new Date(e).toLocaleTimeString(t)}}}function kp(e,t,n){let{date:r,time:i}=Op(e,t,n);return`${r} ${i}`}function Ap(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 jp(e){let t=0,n=0,r=0,i=0;for(let a of e){let e=dp(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 Mp({apiBase:e}){let{t,locale:n}=Ze(),r=sp(e),i=cp(qn(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(`all`),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(),h=(0,_.useRef)(null),g=Ue.find(e=>e.code===n)?.htmlLang,[v,y]=(0,_.useState)();(0,_.useEffect)(()=>{let t=new AbortController,n=!1;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{n||!e||typeof e.timeZone==`string`&&e.timeZone.trim()&&y(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[b,x]=(0,_.useState)($f),[S,C]=(0,_.useState)(()=>$f()===`debug`);(0,_.useEffect)(()=>{let e=()=>x($f());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{b===`debug`&&C(!0)},[b]);let w=ep,T=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/logs?limit=2000`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let i=await n.json(),a=(Array.isArray(i)?i:i.logs??[]).map(op);return Jn(r,a),a},[e,r]),E=vc(r,[e],T,{isEmpty:e=>e.length===0,enabled:b===`logs`,pollMs:a?2e3:void 0,initialData:i??void 0}),D=E.state,O=D.data??i??[],k=E.refresh,A=!E.refreshing&&D.showError,j=!E.refreshing&&!D.showError&&D.data!==void 0,[M,N]=(0,_.useState)({error:null,count:0});j&&M.count!==0?N({error:null,count:0}):A&&M.error!==D.error&&N(e=>({error:D.error,count:e.count+1}));let P=M.count>=yp||!a&&A,F=s?Vf(s.status,n):null,I=d.trim();(0,_.useEffect)(()=>{let e=!1;if(!I){m(void 0);return}return If(I).then(t=>{e||m(t)}),()=>{e=!0}},[I]);let L=O.filter(e=>rp(e,l)&&(!I||Lf(e.conversationId,I,p))),R=I?jp(L):null,B=Mf({count:L.length,getScrollElement:()=>h.current,estimateSize:()=>44,overscan:15}),V=B.getVirtualItems(),H=V.length>0?V[0].start:0,U=V.length>0?B.getTotalSize()-V[V.length-1].end:0;return(0,z.jsxs)(`div`,{className:`logs-page`,children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{children:t(`nav.logs`)}),b===`logs`&&(0,z.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,z.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":b===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:b===`logs`?0:-1,className:`page-tab${b===`logs`?` page-tab--active`:``}`,onClick:()=>w(`logs`),onKeyDown:tp,children:t(`logs.tabLogs`)}),(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":b===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:b===`debug`?0:-1,className:`page-tab${b===`debug`?` page-tab--active`:``}`,onClick:()=>w(`debug`),onKeyDown:tp,children:t(`logs.tabDebug`)})]}),S&&(0,z.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:b!==`debug`,children:(0,z.jsx)(Qf,{apiBase:e,embedded:!0,active:b===`debug`})}),(0,z.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:b!==`logs`,children:[(0,z.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,z.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,z.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm${l===e?` btn-primary`:` btn-ghost`}`,style:{background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},onClick:()=>u(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,z.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,z.jsx)(`input`,{type:`search`,className:`input mono`,value:d,onChange:e=>f(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),I&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f(``),children:t(`logs.filter.conversation.clear`)})]}),R&&(0,z.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,z.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:R.requests,tokens:bn(R.totalTokens,g??n),cost:vp(R.estimatedCostUsd,g)}),` `,(0,z.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),R.unpricedRequests+R.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:R.unpricedRequests,unmetered:R.unmeteredRequests})}`:``]})]})}),D.kind===`failed-cold`&&(0,z.jsxs)($,{tone:`err`,children:[D.error instanceof Error?`${t(`logs.loadError`)} ${D.error.message}`:t(`logs.loadError`),` `,(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k({forceLoading:!0}),disabled:D.refreshing,children:t(`common.retry`)})]}),P&&O.length>0&&(0,z.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k({forceLoading:!0}),disabled:E.refreshing,children:t(`common.retry`)})]}),D.kind===`failed-cold`?null:D.showSkeleton&&O.length===0?(0,z.jsx)(bc,{label:t(`common.loading`),rows:6}):L.length===0?(0,z.jsx)(gt,{title:t(`logs.noRequests`)}):(0,z.jsx)(z.Fragment,{children:(0,z.jsx)(`div`,{ref:h,className:`tbl-wrap logs-table-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:t(`logs.col.time`)}),(0,z.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,z.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,z.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,z.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,z.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,z.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,z.jsx)(`th`,{children:t(`logs.col.status`)}),(0,z.jsx)(`th`,{children:t(`logs.col.request`)}),(0,z.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,z.jsxs)(`tbody`,{children:[H>0&&(0,z.jsx)(`tr`,{children:(0,z.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:H}})}),V.map(e=>{let r=L[L.length-1-e.index],i=hp(r),a=Op(r.timestamp,g,v);return(0,z.jsxs)(`tr`,{"data-index":e.index,ref:B.measureElement,children:[(0,z.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,z.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,z.jsx)(`span`,{children:a.date}),(0,z.jsx)(`span`,{children:a.time})]})}),(0,z.jsx)(`td`,{className:`num mono log-col-tokens`,title:up(r,t),children:(()=>{let e=fp(r),{read:i,write:a}=pp(r);return e===void 0?(0,z.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,z.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,z.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,bn(e,n)]}),i!==void 0&&i>0&&(0,z.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,bn(i,n)]}),a!==void 0&&a>0&&(0,z.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,bn(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,z.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(lp(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,z.jsx)(`td`,{className:`num mono log-col-rate`,children:gp(r.displayMetrics?.tokPerSecond,g)}),(0,z.jsx)(`td`,{className:`num mono log-col-cost`,children:_p(r.displayMetrics?.cost,g)}),(0,z.jsx)(`td`,{className:`mono log-col-model`,title:Ap(r),children:(0,z.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,z.jsx)(`span`,{children:gc(r.resolvedModel??r.model)}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,z.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,z.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),np(r)&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:np(r)})]})}),(0,z.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,z.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,z.jsx)(`span`,{children:mp(r)}),i&&(0,z.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,z.jsx)(`td`,{className:`muted`,children:pn(r.provider,t)}),(0,z.jsx)(`td`,{children:(0,z.jsxs)(`span`,{className:`log-status-cell`,children:[(0,z.jsx)(`span`,{className:`mono font-semibold`,style:{color:Dp(r.status)},children:r.status}),(0,z.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>c(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,z.jsx)(`td`,{className:`muted mono`,children:(0,z.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,z.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),U>0&&(0,z.jsx)(`tr`,{children:(0,z.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:U}})})]})]})})}),s&&(0,z.jsx)(Pp,{detail:s,detailInfo:F,localeCode:n,localeTag:g,serverTimeZone:v,t,onClose:()=>c(null),onFilterConversation:e=>{f(e),c(null)}})]})]})}function Np(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 Pp({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Np(!0),[l,u]=(0,_.useState)(!1),d=pp(e),f=e.displayMetrics?.cost,p=hp(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,z.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,z.jsx)(`span`,{className:`mono`,style:{color:Dp(e.status)},children:e.status}),t&&(0,z.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,z.jsx)(Y,{})})]}),t&&(0,z.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,z.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,z.jsx)(`span`,{className:`mono`,children:kp(e.timestamp,r,i)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,z.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,z.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,z.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,z.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,z.jsx)(`span`,{className:`mono`,children:gc(e.resolvedModel??e.model)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,z.jsx)(`span`,{children:pn(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[mp(e),p?` (${p})`:``]})]}),e.errorCode&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,z.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,z.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,z.jsx)(`span`,{className:`mono`,children:(e.routeDecision.candidates??[]).map(e=>`${typeof e.provider==`string`&&e.provider.length>0?e.provider:`–`}/${typeof e.model==`string`&&e.model.length>0?e.model:`–`}${e.eligible===!0?` ✓`:e.eligible===!1?` ✗`:` ?`}`).join(` `)||`–`})]}):(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,z.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,z.jsx)(`span`,{className:`mono`,children:gp(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Cp(e.displayMetrics.tokPerSecond.reason))})]}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,z.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.total,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.input,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.cacheRead,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.cacheWrite,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.output,r)}),f.estimate.price&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,z.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,z.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Ep(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,z.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,z.jsx)(`li`,{children:a(wp(e))},e))})]}):(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,z.jsx)(`span`,{className:`mono`,children:`—`}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,z.jsx)(`span`,{children:f?.kind===`unavailable`?a(Cp(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,z.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,z.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{className:`num`,children:`#`}),(0,z.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,z.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,z.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,z.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,z.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,z.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=hp(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(Tp(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(Cp(t.reason)):a(`logs.detail.attempt.completed`));return(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,z.jsxs)(`td`,{children:[(0,z.jsx)(`span`,{children:pn(e.provider,a)}),(0,z.jsx)(`br`,{}),(0,z.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`br`,{}),(0,z.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[mp(e),n?` (${n})`:``]})]}),i&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`br`,{}),(0,z.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Ep(i.status))]})]})]}),(0,z.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,z.jsx)(`td`,{className:`num mono`,children:gp(e.displayMetrics?.tokPerSecond,r)}),(0,z.jsx)(`td`,{className:`num mono`,children:_p(t,r)}),(0,z.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,z.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.usage?bn(e.usage.inputTokens,n):`—`}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.usage?bn(e.usage.outputTokens,n):`—`}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,z.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:bn(d.read,n)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,z.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:bn(d.write,n)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:bn(e.usage.reasoningOutputTokens,n)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,z.jsx)(`span`,{className:`mono`,children:fp(e)===void 0?`—`:bn(fp(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,z.jsx)(`span`,{className:`mono`,children:bn(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,z.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,z.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,z.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function Fp(e){return`${Math.round(e*100)}%`}function Ip(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 Lp(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 Rp(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 zp(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Bp(e){let t=Rp(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?zp(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 Vp({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,z.jsxs)(`div`,{className:`usage-filters`,children:[(0,z.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,z.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,z.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,z.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,z.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,z.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(e===`all`?`usage.range.available`:`usage.range.${e}`);return(0,z.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 Hp({summary:e,activeDays:t,locale:n,t:r}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:bn(e.totalTokens,n)})]}),(0,z.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:bn(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,z.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,bn(e.cacheCreationInputTokens??0,n)]})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:Fp(e.coverageRatio)})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,z.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,z.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,z.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:_o(e.estimatedCostUsd,n)}),(0,z.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,z.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function Up({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,z.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,z.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,z.jsx)(`div`,{className:`daybar-track`,children:(0,z.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,z.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Ip(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,z.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,z.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,z.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,z.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,z.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Ip(e.model,e.provider)}}),(0,z.jsx)(`span`,{className:`daybar-tip-name`,children:gc(e.model)}),(0,z.jsx)(`span`,{className:`daybar-tip-val`,children:bn(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,z.jsx)(`span`,{className:`daybar-count`,children:bn(e.totalTokens,t)}),(0,z.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function Wp({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,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,z.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,z.jsx)(Up,{weekBars:n,locale:r,t:i}):(0,z.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,z.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,z.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,z.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,z.jsxs)(`div`,{className:`heatmap-body`,children:[(0,z.jsxs)(`div`,{className:`heatmap-days`,children:[(0,z.jsx)(`span`,{}),(0,z.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,z.jsx)(`span`,{}),(0,z.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,z.jsx)(`span`,{}),(0,z.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,z.jsx)(`span`,{})]}),(0,z.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,z.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,z.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,z.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,z.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,z.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:bn(e.totalTokens,r)})}),(0,z.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,z.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,z.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,z.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,z.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function Gp({title:e,titleId:t,children:n}){return(0,z.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,z.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function Kp({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,z.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`logs.col.model`)}),(0,z.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,z.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`mono`,children:gc(e.model)}),(0,z.jsx)(`td`,{className:`muted`,children:pn(e.provider,i)}),(0,z.jsx)(`td`,{className:`num`,children:e.requests}),(0,z.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,z.jsx)(`td`,{className:`num mono`,children:bn(e.totalTokens,r)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`div`,{className:`usage-bar`,children:(0,z.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,z.jsxs)(Gp,{title:s,titleId:c,children:[(0,z.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function qp({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,z.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`mono`,children:pn(e.provider,n)}),(0,z.jsx)(`td`,{className:`num`,children:e.requests}),(0,z.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,z.jsx)(`td`,{className:`num mono`,children:bn(e.totalTokens,t)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`div`,{className:`usage-bar`,children:(0,z.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,z.jsx)(Gp,{title:i,titleId:a,children:o}):(0,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,z.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function Jp({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,z.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,z.jsx)(Gp,{title:r,titleId:i,children:a}):(0,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,z.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function Yp({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,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Hp,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,z.jsx)(Wp,{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,z.jsx)(Kp,{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,z.jsx)(qp,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Fp(e.summary.coverageRatio):`—`,body:e?(0,z.jsx)(Jp,{summary:e.summary,t:u,workspace:!0}):null}];return(0,z.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,z.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,z.jsx)(ef,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,z.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,z.jsx)(gt,{title:u(`usage.empty`)}):f.map(e=>(0,z.jsx)(`div`,{id:Zd(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var Xp=new Map;function Zp(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function Qp(e,t,n){let r=Zp(e,t,n);return Xp.get(r)??qn(r)}function $p(e,t,n,r){let i=Zp(e,t,n);Xp.set(i,r),Jn(i,r)}function em({apiBase:e}){let{t,locale:n}=Ze(),[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 $p(e,r,a,i),i},[e,r,a]),u=Zp(e,r,a),d=Qp(e,r,a),f=vc(u,[e,r,a],l,{isEmpty:()=>!1,initialData:d??void 0}),{state:p}=f,m=p.data??d??null,h=(0,_.useMemo)(()=>Bp(m?.days??[]),[m?.days]),g=(0,_.useMemo)(()=>Lp(m?.days??[]),[m?.days]),v=(0,_.useMemo)(()=>(m?.days??[]).filter(e=>e.requests>0).length,[m?.days]),y=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(m?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[m?.models,s]),b=(0,_.useMemo)(()=>(m?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[m?.providers]);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,z.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,z.jsx)(Vp,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),p.showSkeleton&&!m?(0,z.jsx)(bc,{label:t(`usage.loading`),rows:5}):p.kind===`failed-cold`?(0,z.jsxs)($,{tone:`err`,children:[p.error instanceof Error?`${t(`usage.loadError`)} ${p.error.message}`:t(`usage.loadError`),` `,(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,z.jsxs)(z.Fragment,{children:[p.showError&&(0,z.jsx)($,{tone:`err`,children:t(`usage.loadError`)}),m?.historyTruncated&&(0,z.jsx)($,{tone:`warn`,children:(()=>{let e=tm(m.snapshotWindowStart),n=tm(m.snapshotWindowEnd);return e!==null&&n!==null?t(`usage.historyTruncatedWindow`,{start:e,end:n}):t(`usage.historyTruncated`)})()}),(0,z.jsx)(Yp,{data:m,heatmap:h,weekBars:g,activeDays:v,filteredModels:y,modelQuery:s,onModelQuery:c,sortedProviders:b,range:r,locale:n,t})]})]})}function tm(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function nm(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 rm={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 im(e,t){let n=rm[e.key];return n?t(n):e.label}function am(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function om(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function sm({report:e,locale:t}){let n=Z(),[r,i]=(0,_.useState)(null),a=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),o=a.find(e=>e.key===r)??null,s=(0,_.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),c=(0,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,z.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,z.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":n(`storage.section.buckets`),children:[(0,z.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,z.jsx)(`span`,{className:`storage-workspace-rail-title`,children:n(`storage.section.buckets`)}),(0,z.jsx)(`span`,{className:`storage-workspace-rail-count`,children:a.length})]}),(0,z.jsx)(`div`,{className:`storage-workspace-rail-list`,children:a.length===0?(0,z.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:n(`storage.empty`)}):a.map(e=>(0,z.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,z.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,z.jsx)(`span`,{className:`storage-workspace-rail-name`,children:im(e,n)}),(0,z.jsx)(`span`,{className:`storage-workspace-rail-size`,children:nm(e.bytes,t)})]}),(0,z.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,n(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,z.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":o?im(o,n):n(`storage.section.largest`),children:o?(0,z.jsxs)(`div`,{className:`stw-detail`,children:[(0,z.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,z.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>i(null),children:[(0,z.jsx)(fe,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),n(`modal.back`)]})}),(0,z.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,z.jsx)(`h2`,{className:`stw-detail-title`,children:im(o,n)}),(0,z.jsxs)(`dl`,{className:`stw-kv`,children:[(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.size`)}),(0,z.jsx)(`dd`,{className:`stw-kv-mono`,children:nm(o.bytes,t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.files`)}),(0,z.jsx)(`dd`,{className:`stw-kv-mono`,children:o.fileCount.toLocaleString(t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.oldest`)}),(0,z.jsx)(`dd`,{children:am(o.oldest,t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.newest`)}),(0,z.jsx)(`dd`,{children:am(o.newest,t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,z.jsx)(`dd`,{className:`stw-kv-mono`,children:om(o,t,n)})]})]}),(o.largest?.length??0)>0&&(0,z.jsxs)(`div`,{className:`stw-section`,children:[(0,z.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),o.largest.map(e=>(0,z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,z.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,z.jsx)(`span`,{className:`stw-file-size`,children:nm(e.bytes,t)})]},e.path))]})]})]}):(0,z.jsxs)(`div`,{className:`stw-overview`,children:[(0,z.jsxs)(`div`,{className:`stw-summary`,children:[(0,z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,z.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.total`)}),(0,z.jsx)(`div`,{className:`stw-summary-value`,children:nm(e.total.bytes,t)})]}),(0,z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,z.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.files`)}),(0,z.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,z.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.home`)}),(0,z.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),s.length>0?(0,z.jsxs)(`div`,{className:`stw-section`,children:[(0,z.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),s.map(e=>{let r=c.get(e.bucketKey);return(0,z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,z.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),r&&(0,z.jsx)(`span`,{className:`stw-file-bucket`,children:im(r,n)}),(0,z.jsx)(`span`,{className:`stw-file-size`,children:nm(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,z.jsxs)(`p`,{className:`stw-hint`,children:[(0,z.jsx)(q,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),n(`storage.workspace.selectBucket`)]})]})})]})}var cm=1024**3,lm=[10,25,50],um=(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 dm({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`)))}let r=await t.json();s(r),l(!0)}catch(e){v(um(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:nm(a.bytes,t)})),r()}catch(e){v(um(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,z.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,z.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,z.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,z.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,z.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,z.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,z.jsx)(`div`,{className:`storage-manual-panel__presets`,children:lm.map(e=>(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,z.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,z.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:nm(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,z.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,z.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,z.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,z.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,z.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,z.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,z.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,z.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,z.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,z.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 fm({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=vc(`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:nm(a.bytes,t)})),r()}catch(e){p(um(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,z.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,z.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,z.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,z.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,z.jsx)(xc,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,z.jsx)(bc,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,z.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,z.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,z.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,z.jsx)(`th`,{})]})}),(0,z.jsx)(`tbody`,{children:x.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`muted`,children:w(e)}),(0,z.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,z.jsx)(`td`,{className:`num mono`,children:nm(e.bytes,t)}),(0,z.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,z.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,z.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:nm(c.bytes,t),id:c.id})}),f&&(0,z.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,z.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,z.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function pm(e){let{job:t,...n}=e;return n}function mm(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/cm*100)/100));return e.target.reduceToBytes===void 0?{policy:pm(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:pm(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/cm*100)/100))}}async function hm(e){await new Promise(t=>window.setTimeout(t,e))}function gm({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=qn(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=mm(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,Jn(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*cm)}}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*cm)},target:n,schedule:s.schedule,mode:s.mode}},L=async t=>{let r=I();if(!r){y(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),y(null),g(null);try{let t=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i)});if(!t.ok){y(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){y(n(`storage.policy.saveFailed`));return}M(r.policy),g(n(`storage.policy.saved`))}catch{y(n(`storage.policy.saveFailed`))}finally{f(!1)}},R=async()=>{O.current?.abort();let i=new AbortController;O.current=i;let{signal:a}=i;m(!0),y(null),g(null);try{let i=I();if(!i){y(n(`storage.policy.invalid`));return}let o=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i),signal:a});if(a.aborted)return;if(!o.ok){y(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){y(n(`storage.policy.saveFailed`));return}M(s.policy);let c=await fetch(`${e}/api/storage/cleanup-policy/run`,{method:`POST`,signal:a});if(a.aborted)return;if(c.status===409){let e=await c.json().catch(()=>({}));if(a.aborted)return;e.policy&&M(e.policy),y(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&M(e.policy),e.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}y(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&M(l.policy),l.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){y(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await hm(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=pm(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:nm(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:nm(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,z.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,z.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,z.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,z.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,z.jsx)(`div`,{className:`storage-policy-enable`,children:(0,z.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,z.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void L({enabled:!s.enabled}),children:(0,z.jsx)(`span`,{className:`toggle-knob`})}),(0,z.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,z.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,z.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,z.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,z.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,z.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,z.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value: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,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,z.jsx)(Ha,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(Va(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(Va(E,-.1,0,1e4,.1))}})]})]})]}),(0,z.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,z.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,z.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,z.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,z.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,z.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value: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,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,z.jsx)(Ha,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(Va(S,1,1,100))},onDecrement:()=>{N(),C(Va(S,-1,1,100))}})]})]}),(0,z.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,z.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,z.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,z.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value: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,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,z.jsx)(Ha,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(Va(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(Va(w,-.1,0,1e4,.1))}})]})]})]}),(0,z.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,z.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,z.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,z.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,z.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,z.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,z.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,z.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,z.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,z.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,z.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,z.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,z.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,z.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,z.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,z.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[B(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:nm(s.lastRun.freedBytes,t)})}`:``]})]}),(0,z.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,z.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,z.jsx)(`span`,{className:`storage-policy-meta-value`,children:B(s.nextRun)})]})]}),(0,z.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,z.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,z.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,z.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function _m({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,z.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,z.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,z.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,z.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,z.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,z.jsx)(gm,{apiBase:e,locale:t,t:n,onDone:o}),(0,z.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,z.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,z.jsx)(dm,{apiBase:e,locale:t,t:n,onDone:o}):(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,z.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,z.jsx)(fm,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function vm({apiBase:e}){let{t,locale:n}=Ze(),r=`ocx.storage.report.v1:${e}`,i=qn(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 Jn(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=vc(`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,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,z.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,z.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,z.jsx)(re,{}),` `,t(`storage.refresh`)]})]})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,z.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,z.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,z.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,z.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,z.jsx)(bc,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,z.jsx)(z.Fragment,{children:(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,z.jsxs)(z.Fragment,{children:[m.showError&&(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,z.jsx)(gt,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,z.jsx)(sm,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,z.jsx)(xc,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,z.jsx)(_m,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}var ym=`/api/codex-auth/features/default-mode-request-user-input`;function bm({apiBase:e}){let t=Z(),[n,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(0),h=(0,_.useCallback)(async()=>{if(f.current)return;let t=++m.current;try{let n=await fetch(`${e}${ym}`);if(!n.ok)throw Error(`load`);let i=await n.json();if(f.current||t!==m.current)return;p.current=i.enabled===!0,r(p.current),a(!0),l(!1)}catch{!f.current&&t===m.current&&l(!0)}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=window.setInterval(()=>{h()},3e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[h]);let g=(0,_.useCallback)(async()=>{if(f.current||!i||c)return;let n=!p.current,o=p.current;p.current=n,r(n),f.current=!0,s(!0),d(null),m.current++;try{let i=await fetch(`${e}${ym}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await St(i)??{};if(o.ok!==!0)throw Error(String(i.status));p.current=o.enabled===!0,r(p.current),a(!0),d({tone:`ok`,message:t(o.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){p.current=o,r(o);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);d({tone:`err`,message:n})}finally{f.current=!1,s(!1)}},[e,i,c,t]),v=o||!i||c;return(0,z.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,z.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,z.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,z.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,z.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
|
|
53
|
+
`))&&(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,z.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,z.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,z.jsx)(K,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?Mn(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??An(r):null,x=r?jn(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,z.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,z.jsxs)(`div`,{className:`mem-head`,children:[(0,z.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,z.jsx)(K,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,z.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,z.jsxs)(`span`,{className:`mem-inflight`,children:[(0,z.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,z.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?Dn(t).format(w):`—`})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,z.jsx)(Pn,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,z.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,z.jsx)(Nn,{label:n(`dash.mem.rss`),value:r?On(r.rss,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.jsHeap`),value:r?On(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:On(r.heapTotal,t)}):void 0}),(0,z.jsx)(Nn,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?On(r.jscHeap.heapSize,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${On(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,z.jsxs)(`details`,{style:{marginTop:10},children:[(0,z.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,z.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,z.jsxs)(`div`,{className:`stat-row`,children:[(0,z.jsx)(Nn,{label:n(`dash.mem.observed`),value:b===null?`—`:`${On(b,t)} (${x})`}),(0,z.jsx)(Nn,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:On(r.external,t)}),(0,z.jsx)(Nn,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:On(r.arrayBuffers,t)})]}),(0,z.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,z.jsxs)(`div`,{className:`stat-row`,children:[(0,z.jsx)(Nn,{label:n(`dash.mem.storeEntries`),value:C?Dn(t).format(C.count):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.storeTotal`),value:C?On(C.totalBytes,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.storeLargest`),value:C?On(C.largestBytes,t):`—`}),(0,z.jsx)(Nn,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:kn(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,z.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,z.jsx)(Nn,{label:n(`dash.mem.threshold`),value:On(r.watchdog.warnThresholdBytes,t)}),(0,z.jsx)(Nn,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,z.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,z.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,z.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,z.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,z.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function zn({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,z.jsx)(`div`,{className:`panel`,children:(0,z.jsxs)(`div`,{className:`injection-head`,children:[(0,z.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,z.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,z.jsx)(ce,{width:13,height:13,"aria-hidden":`true`})})]}),(0,z.jsx)(ht,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...kt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Ot(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({effortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.effortCapLabel`),align:`right`}),(0,z.jsx)(ht,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...kt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Ot(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subagentEffortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.subagentEffortCapLabel`),align:`right`})]})})}function Bn({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,z.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,z.jsx)(ht,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:gn(`${e.provider}/${e.model}`,t)}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`),align:`right`}),n&&i.length>0&&(0,z.jsx)(ht,{value:r,options:[{value:``,label:t(`dash.injectionEffortNone`)},...i.map(e=>({value:e,label:e}))],onChange:e=>{s({model:n||null,effort:e||null})},disabled:o,label:t(`dash.injectionEffortLabel`),align:`right`}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>nt(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function Vn({d:e}){let{t,runSync:n,syncing:r,updateTriggerRef:i,openUpdateDialog:a,updateLoading:o,updateOpen:s,syncResult:c,syncError:l,updateJob:u,reconnecting:d,clearSyncFeedback:f}=e,p=!!c&&(!!c.warning||!!c.nativeSubagentDefaultsWarning||!!c.staleAppServerHint),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(null);(0,_.useEffect)(()=>(g.current&&=(clearTimeout(g.current),null),(c||l)&&!p&&(g.current=setTimeout(()=>{g.current=null,h(!0),f()},l?8e3:6e3)),()=>{g.current&&clearTimeout(g.current)}),[c,l,p,f]);let v=()=>{h(!1),n()},y=()=>{h(!0),f()};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,z.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,z.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,z.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,z.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:r,children:[(0,z.jsx)(re,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,z.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})]})]}),u&&(0,z.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,z.jsx)(se,{}):(0,z.jsx)(re,{}),(0,z.jsxs)(`span`,{children:[Mt(u.status,t),u.latestVersion?` ${t(`dash.updateVersionTransition`,{currentVersion:u.currentVersion,latestVersion:u.latestVersion})}`:``,d?` ${t(`dash.updateReconnecting`)}`:``,u.error?` ${u.error}`:``]})]})]}),!m&&c&&(0,z.jsxs)(`div`,{className:`action-toast notice ${p?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[p?(0,z.jsx)(se,{}):(0,z.jsx)(J,{}),(0,z.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,z.jsxs)(z.Fragment,{children:[` `,(0,z.jsx)($e,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,z.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,z.jsx)(Y,{width:13,height:13,"aria-hidden":`true`})})]}),!m&&l&&(0,z.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})}),(0,z.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,z.jsx)(Y,{width:13,height:13,"aria-hidden":`true`})})]})]})}function Hn({t:e,open:t,triggerRef:n,onClose:r,maxValue:i,maxInvalid:a,timeoutValue:o,timeoutInvalid:s,disabled:c,setMaxDraft:l,setMaxInvalid:u,setTimeoutDraft:d,setTimeoutInvalid:f,commitMaxDescriptions:p,commitTimeout:m}){let h=(0,_.useRef)(null),g=(0,_.useRef)(null),[v,y]=(0,_.useState)(),b=(0,_.useCallback)(()=>{n.current&&y(ft(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,_.useLayoutEffect)(()=>{if(!t)return;b();let e=()=>b();return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[t,b,a,s]),(0,_.useEffect)(()=>{if(!t)return;let e=e=>{let t=e.target;if(h.current?.contains(t)||n.current?.contains(t))return;let i=document.activeElement;i&&h.current?.contains(i)&&i.blur(),r()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t,r,n]),(0,_.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),r(),n.current?.focus())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,r,n]),(0,_.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,z.jsxs)(`div`,{ref:h,id:`dash-vision-advanced-popover`,className:`dash-vision-advanced-popover`,role:`dialog`,"aria-modal":`false`,"aria-label":e(`dash.visionAdvancedPopover`),style:{...v,zIndex:60},children:[(0,z.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,z.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,z.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,z.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,z.jsx)(`input`,{ref:g,className:`input mono codex-auto-switch-input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:i,disabled:c,"aria-invalid":a||void 0,"aria-label":e(`dash.visionMaxDescriptions`),"aria-describedby":a?`dash-vision-max-error dash-vision-max-label`:`dash-vision-max-label`,onChange:e=>{u(!1),l(e.target.value)},onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),p(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),l(null),u(!1)))}})}),a&&(0,z.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,z.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,z.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,z.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:Bt,max:zt,step:1e3,inputMode:`numeric`,value:o,disabled:c,"aria-invalid":s||void 0,"aria-label":e(`dash.visionTimeout`),"aria-describedby":s?`dash-vision-timeout-error dash-vision-timeout-label`:`dash-vision-timeout-label`,onChange:e=>{f(!1),d(e.target.value)},onBlur:e=>m(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),m(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),d(null),f(!1)))}}),(0,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,z.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:Bt,max:zt})})]})]}):null}function Un({d:e}){let{t,settings:n,settingsSaving:r,toggleCodexAutoStart:i,sidecar:a,sidecarSaving:o,sidecarModels:s,visionModels:c,models:l,saveSidecar:u,shadowCall:d,shadowCallSaving:f,shadowCallHelpTriggerRef:p,shadowCallHelpOpen:m,setShadowCallHelpOpen:h,saveShadowCall:g}=e,v=a?.vision.enabled!==!1,y=v?a?.vision.model??`gpt-5.4-mini`:``,b=a?.vision.reasoning??`low`,x=Wt(l,y),S=Kt(x,b),C=String(a?.vision.maxDescriptionsPerTurn??8),w=String(a?.vision.timeoutMs??Rt),[T,E]=(0,_.useState)(null),[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),F=(0,_.useRef)(null),I=T??C,L=D??w,R=(e=I)=>{let t=Vt(e);if(t===void 0){E(e),A(!0);return}A(!1),E(null),t!==(a?.vision.maxDescriptionsPerTurn??8)&&u(It(t))},B=(e=L)=>{let t=Ht(e);if(t===void 0){O(e),M(!0);return}M(!1),O(null),t!==(a?.vision.timeoutMs??Rt)&&u(Lt(t))};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`panel`,children:(0,z.jsxs)(`div`,{className:`spread`,children:[(0,z.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,z.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,z.jsx)(`span`,{className:`knob`})})]})}),(0,z.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,z.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!a||void 0,children:[(0,z.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,z.jsx)(ht,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{u({webSearch:{model:e,backend:Xt(l,e)}})},disabled:!a||o,label:t(`dash.sidecarModel`),align:`right`}),(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},title:t(`dash.webSearchStreamHint`),children:[(0,z.jsx)(`span`,{className:`muted setting-hint`,children:t(`dash.webSearchStream`)}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${a?.webSearch.streamRoutedModelOutput?`on`:``}`,onClick:()=>{u({webSearch:{streamRoutedModelOutput:!a?.webSearch.streamRoutedModelOutput}})},disabled:!a||o,"aria-label":t(`dash.webSearchStream`),"aria-pressed":a?.webSearch.streamRoutedModelOutput===!0,children:(0,z.jsx)(`span`,{className:`knob`})})]})]})]}),(0,z.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!a||void 0,children:[(0,z.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,z.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,z.jsxs)(`div`,{className:`dash-vision-select-row`,children:[(0,z.jsx)(ht,{value:y,options:[{value:``,label:t(`dash.visionOff`)},...c],onChange:e=>{if(e===``){u(Ft(!1));return}let t=Kt(Wt(l,e),S),n={vision:{model:e,backend:Zt(l,c,e),reasoning:t}};v||(n.vision={...n.vision,enabled:!0}),u(n)},disabled:!a||o,label:t(`dash.sidecarModel`)}),(0,z.jsx)(ht,{value:S,options:Gt(x,S).map(e=>({value:e,label:e})),onChange:e=>{u(Pt(e))},disabled:!v||!a||o,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),(0,z.jsx)(`div`,{className:`dash-vision-advanced-row`,children:(0,z.jsxs)(`button`,{type:`button`,ref:F,className:`dash-vision-advanced-trigger`,onClick:()=>P(e=>!e),disabled:!v||!a||o,"aria-expanded":N,"aria-haspopup":`dialog`,"aria-controls":`dash-vision-advanced-popover`,children:[(0,z.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,style:{transform:N?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,rt.createPortal)((0,z.jsx)(Hn,{t,open:N,triggerRef:F,onClose:()=>P(!1),maxValue:I,maxInvalid:k,timeoutValue:L,timeoutInvalid:j,disabled:!v||!a||o,setMaxDraft:E,setMaxInvalid:A,setTimeoutDraft:O,setTimeoutInvalid:M,commitMaxDescriptions:R,commitTimeout:B}),document.body)]})]}),(0,z.jsx)(`div`,{className:`panel`,"aria-busy":!d||void 0,children:(0,z.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,z.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,z.jsx)(`button`,{ref:p,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:()=>h(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":m,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,z.jsx)(ce,{width:13,height:13,"aria-hidden":`true`})}),(0,z.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${an(d?.sourceModels)}`})]}),(0,z.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,z.jsx)(`button`,{type:`button`,className:`switch ${d?.enabled?`on`:``}`,onClick:()=>g({enabled:!d?.enabled}),disabled:!d||f,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":d?.enabled??!1,children:(0,z.jsx)(`span`,{className:`knob`})}),(0,z.jsx)(ht,{value:d?.model??``,options:Yt(l,d?.model).map(e=>e.value===``?e:{...e,label:gn(e.value,t)}),onChange:e=>{g({model:e})},disabled:!d||f||!d?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function Wn(e){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(zn,{apiBase:e.apiBase,d:e}),(0,z.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,z.jsx)(Bn,{apiBase:e.apiBase,d:e}),(0,z.jsx)(Vn,{d:e})]}),(0,z.jsx)(Un,{d:e}),(0,z.jsx)(Rn,{apiBase:e.apiBase})]})}function Gn(e){return(0,z.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,z.jsx)(Sn,{...e}),(0,z.jsx)(Wn,{...e})]})}function Kn({t:e,providers:t}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,z.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,z.jsx)(gt,{title:(0,z.jsx)($e,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:e(`dash.col.name`)}),(0,z.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,z.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,z.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,z.jsx)(`tbody`,{children:t.map(t=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`font-semibold`,children:pn(t.name,e)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,z.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,z.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}function qn(e){try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Jn(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function Yn(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function Xn(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Zn(e,t){return{request:++e.current,mutation:t.current}}var Qn=2e3;function $n(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function er(e){return e?e.stale&&e.status!==`error`:!1}function tr(e,t){return!t||e!==null&&e!==`error`?e:t.status}var nr=3e4;function rr(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function ir(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function ar(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=$n(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(ir(e,t))throw e;return{status:`error`,stale:!1}}}async function or(e,t){try{return(await Ct(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function sr(e,t){return Ot(await fetch(`${e}/api/models`,{signal:t}))}async function cr(e,t){return Ot(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function lr(e,t,n){let{request:r,mutation:i}=Zn(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 Ot(a),c;try{if(o.ok){let e=await o.json();Xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else Xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{Xn({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}return{sidecar:s,shadowCall:c}}async function ur(e,t,n){let{request:r,mutation:i}=Zn(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Ot(await fetch(`${e}/api/settings`,{signal:t})),o,s;return Xn({request:r,mutation:i},{request:n.settingsRequestEpochRef.current,mutation:n.settingsMutationEpochRef.current,mutationInFlight:n.settingsMutationInFlightRef.current})&&(o=a,s=a.startupHealth),{settings:o,startupHealthSeed:s}}async function dr(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(ir(e,t))throw e;return{maMode:`default`}}}async function fr(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await Ot(n),providers:await Ot(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function pr(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={...rr(e),injectionEfforts:e.efforts??[],injectionAvailable:e.available??[]}}}catch{}let a;try{if(r?.ok){let e=await r.json();a={effortCap:e.effortCap??``,subagentEffortCap:e.subagentEffortCap??``}}}catch{}return{injection:i,effortCaps:a}}function mr(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}var hr=`ocx.dash.controls.v1:`,gr=`ocx.dash.overview.v1:`,_r=`ocx.dash.usage30d.v1:`,vr=`ocx.dash.startup.v1:`,yr=`ocx.dash.maMode.v1:`;function br(e){let t=new Map;for(let n of e){let e=t.get(n.provider);e?e.push(n):t.set(n.provider,[n])}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t))}function xr(e){return`${hr}${e}`}function Sr(e){let{locale:t,t:n}=Ze(),[r,i]=(0,_.useState)(Tt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>qn(xr(e)),[e]),u=(0,_.useMemo)(()=>qn(`${gr}${e}`),[e]),d=(0,_.useMemo)(()=>qn(`${_r}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=qn(`${vr}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>qn(`${yr}${e}`),[e]),[m,h]=(0,_.useState)(()=>u?.health??null),[g,v]=(0,_.useState)(()=>f),[y,b]=(0,_.useState)(()=>u?.providers??[]),[x,S]=(0,_.useState)([]),[C,w]=(0,_.useState)(()=>l?.settings??null),[T,E]=(0,_.useState)(()=>l?.sidecar??null),[D,O]=(0,_.useState)(()=>l?.shadowCall??null),[k,A]=(0,_.useState)(()=>d),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),[F,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(()=>p??`default`),[W,G]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(null),[K,q]=(0,_.useState)(!1),[J,Y]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)([]),[ue,X]=(0,_.useState)([]),[de,fe]=(0,_.useState)(!1),[pe,me]=(0,_.useState)(!0),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(``),[ye,be]=(0,_.useState)(``),[xe,Se]=(0,_.useState)(!1),[Ce,we]=(0,_.useState)(null),[Te,Ee]=(0,_.useState)(null),[De,Oe]=(0,_.useState)([]),[ke,Ae]=(0,_.useState)(!1),[je,Me]=(0,_.useState)(`latest`),[Ne,Pe]=(0,_.useState)(!0),[Fe,Ie]=(0,_.useState)(!1),Le=(0,_.useRef)(0),Re=(0,_.useRef)(null),ze=(0,_.useRef)(0),Be=(0,_.useRef)(0),Ve=(0,_.useRef)(0),He=(0,_.useRef)(!1),Ue=(0,_.useRef)(0),We=(0,_.useRef)(0),Ge=(0,_.useRef)(!1),[Ke,qe]=(0,_.useState)(null),[Je,Ye]=(0,_.useState)(null),[Xe,Z]=(0,_.useState)(null),[Qe,$e]=(0,_.useState)(!1),[et,nt]=(0,_.useState)(!1),rt=(0,_.useRef)(null),it=(0,_.useRef)(null),at=(0,_.useRef)(null),Q=(0,_.useRef)(null),ot=en(J,rt),st=en(ke,it),ct=en(K,at),lt=en(ne,Q);(0,_.useEffect)(()=>{let e=()=>i(Tt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{ze.current+=1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null)},[]);let ut=(0,_.useRef)(f),dt=(0,_.useRef)(0),ft=(0,_.useRef)({settingsRequestEpochRef:Be,settingsMutationEpochRef:Ve,settingsMutationInFlightRef:He,shadowCallRequestEpochRef:Ue,shadowCallMutationEpochRef:We,shadowCallMutationInFlightRef:Ge}).current,pt=I(`dashboard-startup-health:${e}`,[e],t=>ar(e,t),{pollMs:3e4}),$=er(pt.data),mt=pt.refresh;(0,_.useEffect)(()=>{if(!$)return;let e=window.setTimeout(()=>{mt()},Qn);return()=>window.clearTimeout(e)},[$,mt]);let ht=I(`dashboard-overview:${e}`,[e],t=>fr(e,t),{pollMs:5e3}),gt=m!==null||ht.data!==void 0,_t=I(`dashboard-ma-mode:${e}`,[e],t=>dr(e,t),{pollMs:5e3}),vt=I(`dashboard-sidecars:${e}`,[e],async t=>{let n=dt.current;return{...await lr(e,t,ft),startupHealthGeneration:n}},{pollMs:5e3}),yt=I(`dashboard-settings:${e}`,[e],async t=>{let n=dt.current;return{...await ur(e,t,ft),startupHealthGeneration:n}},{pollMs:5e3}),bt=I(`dashboard-multi-agent:${e}`,[e],t=>pr(e,t),{pollMs:5e3,enabled:gt}),xt=I(mr(e),[e],t=>cr(e,t),{enabled:gt}),St=I(`dashboard-diagnostics:${e}`,[e],t=>or(e,t),{pollMs:nr,enabled:gt}),Ct=I(`dashboard-models:${e}`,[e,et],t=>sr(e,t),{enabled:gt&&!et});(0,_.useEffect)(()=>{if(pt.data!==void 0){let t=pt.data;dt.current+=1,v(t.status),ut.current=t.status,t.status!==`error`&&!t.stale&&Jn(`${vr}${e}`,t.status)}},[pt.data,e]),(0,_.useEffect)(()=>{let t=ht.data;t&&(t.health&&(h(t.health),b(t.providers),Jn(`${gr}${e}`,{health:t.health,providers:t.providers})),nt(t.error))},[ht.data,e]),(0,_.useEffect)(()=>{_t.data!==void 0&&(U(_t.data.maMode),Jn(`${yr}${e}`,_t.data.maMode))},[_t.data,e]);let wt=_t.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=bt.data;e&&(e.injection&&(me(e.injection.multiAgentGuidanceEnabled),ge(e.injection.syncCodexSubagentDefaults),ae(e.injection.injectionModel),se(e.injection.injectionEffort),le(e.injection.injectionEfforts),X(e.injection.injectionAvailable)),e.effortCaps&&(ve(e.effortCaps.effortCap),be(e.effortCaps.subagentEffortCap)))},[bt.data]),(0,_.useEffect)(()=>{let t=vt.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=qn(xr(e))??{};Jn(xr(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[vt.data,e]),(0,_.useEffect)(()=>{let t=yt.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===dt.current){let n=tr(ut.current,t.startupHealthSeed);v(n),ut.current=n,n&&Jn(`${vr}${e}`,n)}if(t.settings!==void 0){let n=qn(xr(e))??{};Jn(xr(e),{...n,settings:t.settings})}}},[yt.data,e]),(0,_.useEffect)(()=>{xt.data!==void 0&&(A(xt.data),Jn(`${_r}${e}`,xt.data))},[xt.data,e]),(0,_.useEffect)(()=>{St.data&&Oe(St.data)},[St.data]),(0,_.useEffect)(()=>{Ct.data&&S(Ct.data),L(Ct.loading)},[Ct.data,Ct.loading]),(0,_.useEffect)(()=>()=>{Be.current+=1,Ue.current+=1},[]);let Dt=I(Xe?.id&&Xe.restart?`update-job:${e}:${Xe.id}`:`update-job:idle:${e}`,[e,Xe?.id,Xe?.restart,Xe?.latestVersion],async t=>{if(!Xe?.id||!Xe.restart)return{reconnecting:!1};let n=Xe.latestVersion;try{let r=await Ot(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Xe.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Ot(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:!!(Xe?.id&&Xe.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=Dt.data;e&&(`job`in e&&e.job&&Z(e.job),$e(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[Dt.data]);let kt=(0,_.useMemo)(()=>br(x),[x]),jt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return kt;let t=[];for(let[n,r]of kt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[kt,a]),Mt=(0,_.useMemo)(()=>{let e=qt(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]),Pt=(0,_.useMemo)(()=>Jt(T?.visionModels,x,T?.vision?.model,T?.vision?.backend),[T?.visionModels,x,T?.vision]),Ft=async t=>{if(!T||j)return;let n=T,r={webSearch:Nt(T.webSearch,t.webSearch),vision:Nt(T.vision,t.vision),...T.visionModels?{visionModels:T.visionModels}:{}};M(!0),E(r);try{let n=await Ot(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,...n.visionModels?{visionModels:n.visionModels}:{}});let r=qn(xr(e))??{};Jn(xr(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{}}})}catch{E(n)}finally{M(!1)}};async function It(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),Ge.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`);We.current+=1}catch{O(n)}finally{Ge.current=!1,P(!1)}}let Lt=async t=>{if(!(W||H===t)){G(!0),te(null);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})});if(r.ok)U(t),Jn(`${yr}${e}`,t);else{let e=n(`dash.maSwitchFailed`,{status:String(r.status)});try{let t=await r.json();e=typeof t.error==`string`&&t.error||typeof t.message==`string`&&t.message||e}catch{}te(e)}}catch(e){te(e instanceof Error?e.message:n(`dash.maNetworkError`))}finally{G(!1)}}},Rt=async t=>{if(!de){fe(!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 Ot(await fetch(`${e}/api/injection-model`)),r=rr(n);me(r.multiAgentGuidanceEnabled),ge(r.syncCodexSubagentDefaults),ae(r.injectionModel),se(r.injectionEffort),Array.isArray(n.efforts)&&le(n.efforts),Array.isArray(n.available)&&X(n.available)}catch{}finally{fe(!1)}}},zt=async()=>{if(!C||R)return;let t=!C.codexAutoStart;z(!0),He.current=!0,w({...C,codexAutoStart:t});try{let n=await Ot(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Ve.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),nt(!0)}finally{He.current=!1,z(!1)}},Bt=(0,_.useCallback)(()=>{we(null),Ee(null)},[]),Vt=async()=>{if(!B){V(!0),we(null),Ee(null);try{let t=await Ot(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);we(t),t.projectConfigGrouped&&Oe(t.projectConfigGrouped)}catch(e){Ee(e instanceof Error?e.message:String(e))}finally{V(!1)}}},Ht=async(t,n=!1)=>{n&&(Le.current=0),Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null);let r=++ze.current;Ie(!0),Ye(null),qe(null);try{let n=await Ot(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==ze.current)return;if(qe(n),n.reason===`latest_unavailable`&&Le.current<2){let e=++Le.current;Re.current=window.setTimeout(()=>{r===ze.current&&(Re.current=null,Ht(t))},800*e);return}n.reason!==`latest_unavailable`&&(Le.current=0),Ie(!1)}catch(e){if(r!==ze.current)return;Ye(e instanceof Error?e.message:String(e)),Ie(!1)}},Ut=()=>{ze.current+=1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ie(!1),Ae(!1)},Wt=()=>{let e=At(m?.version);Me(e),Pe(!0),Ae(!0),Ht(e,!0)},Gt=e=>{Me(e),Ht(e,!0)},Kt=(0,_.useRef)(Wt);return(0,_.useEffect)(()=>{Kt.current=Wt}),(0,_.useEffect)(()=>{let e=()=>{Et()&&(tt(`dashboard`),Kt.current())},t=Et()?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:xt.loading&&!k,healthLoading:ht.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:F,settingsSaving:R,syncing:B,maMode:H,maModeResolved:wt,maBusy:W,setMaHelpOpen:q,maHelpOpen:K,maError:ee,effortCapHelpOpen:J,setEffortCapHelpOpen:Y,shadowCallHelpOpen:ne,setShadowCallHelpOpen:re,injectionModel:ie,injectionEffort:oe,injectionEfforts:ce,injectionAvailable:ue,injectionSaving:de,multiAgentGuidanceEnabled:pe,syncCodexSubagentDefaults:he,saveInjection:Rt,effortCap:_e,subagentEffortCap:ye,effortCapSaving:xe,setEffortCap:ve,setSubagentEffortCap:be,setEffortCapSaving:Se,syncResult:Ce,syncError:Te,projectConfigWarnings:De,updateOpen:ke,updateChannel:je,setUpdateRestart:Pe,updateRestart:Ne,updateLoading:Fe,updateCheck:Ke,updateError:Je,updateJob:Xe,reconnecting:Qe,error:et,effortCapHelpTriggerRef:rt,updateTriggerRef:it,maHelpTriggerRef:at,shadowCallHelpTriggerRef:Q,effortCapHelpDialogRef:ot,updateDialogRef:st,maHelpDialogRef:ct,shadowCallHelpDialogRef:lt,filteredGroups:jt,sidecarModels:Mt,visionModels:Pt,saveSidecar:Ft,saveShadowCall:It,switchMaMode:Lt,toggleCodexAutoStart:zt,runSync:Vt,clearSyncFeedback:Bt,fetchUpdateCheck:Ht,closeUpdateDialog:Ut,openUpdateDialog:Wt,changeUpdateChannel:Gt,runUpdate:async()=>{if(Ke?.canUpdate){Ye(null);try{let t=await Ot(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:je,restart:Ne})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);Z(t.job),$e(!1),Ut()}catch(e){Ye(e instanceof Error?e.message:String(e))}}}}}function Cr(e){nt(Dt(e))}function wr({apiBase:e}){let t=Sr(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,z.jsx)(gt,{style:{marginTop:40},icon:(0,z.jsx)(se,{}),title:(0,z.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,z.jsx)($e,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,z.jsx)(Gn,{...t}),m=(0,z.jsx)(Kn,{t:n,providers:a}),h=(0,z.jsx)(_n,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,z.jsx)(on,{...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=Cr,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,z.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,z.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,z.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 Tr=`https://chatgpt.com/backend-api/codex`,Er=`openai`;function Dr(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}}var Or=new URL(Tr).protocol;function kr(e,...t){return`${Or}//${e}/${t.join(`/`)}`}var Ar={"cline-pass":{adapter:`openai-chat`,baseUrl:kr(`api.cline.bot`,`api`,`v1`)},"mimo-free":{adapter:`mimo-free`,baseUrl:kr(`api.xiaomimimo.com`,`api`,`free-ai`,`openai`,`chat`)}};function jr(e,t){let n=Ar[e];return!n||t.adapter!==n.adapter||Dr(t.baseUrl)!==Dr(n.baseUrl)}function Mr(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 Nr(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||Mr(e.baseUrl)||e.hasApiKey===!0}function Pr(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Dr(e.baseUrl)===Tr}function Fr(e,t){return e===Er&&Pr(t)}function Ir(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||Mr(e.baseUrl)}function Lr(e,t){return Fr(e,t)?`accounts`:Ir(t)?`free`:`paid`}function Rr(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??Lr(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 zr(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}Nr(a)?t.push({name:i,...a,tier:Lr(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function Br(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 Vr(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:Nr(e)?`ready`:`needs-setup`}function Hr(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!Fr(`openai`,t)||!Pr(n))return e;let r={...e};return delete r.chatgpt,r}function Ur(e){return e.authMode===`local`||Mr(e.baseUrl)}var Wr=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function Gr(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(Ur(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return Wr.some(e=>n.includes(e))?`selfHosted`:`cloud`}function Kr(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 qr(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 Jr(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 Yr(e){let t={};for(let[n,r]of Object.entries(Kr(e)))t[n]=r.length;return t}function Xr(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 Zr={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function Qr(e,t,n){let r=typeof t==`object`&&t?t:Zr,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 $r(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 ei(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 ti(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function ni(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 ri(e,t=`en`){return ni(e,t)}function ii(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function ai(e,t){let n=Vr(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 oi(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 si(e){let t=Vr(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 ci({name:e,adapter:t,baseUrl:n,cls:r}){let i=Z(),a=fn(e,{adapter:t,baseUrl:n});return(0,z.jsx)(`span`,{className:r,children:a?(0,z.jsx)(`img`,{src:a,alt:``,"aria-hidden":`true`}):(0,z.jsx)(li,{name:e,label:pn(e,i)})})}function li({name:e,label:t}){let n=[...e].reduce((e,t)=>e+t.charCodeAt(0),0)%360,r=(t.trim()[0]??e[0]??`?`).toUpperCase();return(0,z.jsx)(`span`,{className:`provider-icon-fallback`,style:{background:`hsl(${n} 55% 90%)`,color:`hsl(${n} 65% 32%)`},"aria-hidden":`true`,children:r})}function ui({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Z(),l=Ir(e),u=Ur(e),d=ai(e,c),f=pn(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,z.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,z.jsx)(ci,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,z.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,z.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,z.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,z.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,z.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,z.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,z.jsx)(Ee,{width:17,height:17,"aria-hidden":`true`})}),(0,z.jsx)(`span`,{className:si(e),title:d,"aria-hidden":`true`})]})]})}var di=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0;function fi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e,r=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||di(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...di(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]}):[],i={...di(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...di(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...di(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...di(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...di(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...di(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...r.length>0?{customWindows:r}:{},updatedAt:di(n.updatedAt)??t??Date.now()};return i.fiveHourPercent!==void 0||i.weeklyPercent!==void 0||i.monthlyPercent!==void 0||(i.customWindows?.length??0)>0?i:null}function pi(e){return fi(e?.quota,e?.updatedAt)}function mi(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=di(t.usedPercent);if(n!==void 0)return{usedPercent:n,...typeof t.incomplete==`boolean`?{incomplete:t.incomplete}:{},...di(t.excludedAccounts)===void 0?{}:{excludedAccounts:t.excludedAccounts},...di(t.nextRecoveryAt)===void 0?{}:{nextRecoveryAt:t.nextRecoveryAt},...di(t.nextRecoveryPercent)===void 0?{}:{nextRecoveryPercent:t.nextRecoveryPercent}}}function hi(e){let t=e?.aggregation;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;if(n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`)return null;let r=di(n.excludedAccounts),i=di(n.unknownPlanAccounts);if(r===void 0||i===void 0||typeof n.incomplete!=`boolean`)return null;let a=n.currentAccount&&typeof n.currentAccount==`object`&&!Array.isArray(n.currentAccount)?n.currentAccount:null,o=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=mi(t);return typeof t.label==`string`&&n?[{label:t.label,...n}]:[]}):[],s=mi(n.fiveHour),c=mi(n.weekly),l=mi(n.monthly),u=!!s||!!c||!!l||o.length>0;return{presentation:n.presentation===`aggregate`||n.presentation===`effective-account-fallback`||n.presentation===`coverage-only`?n.presentation:u?`aggregate`:`coverage-only`,incomplete:n.incomplete,excludedAccounts:r,unknownPlanAccounts:i,partialWindowAccounts:di(n.partialWindowAccounts)??0,...s?{fiveHour:s}:{},...c?{weekly:c}:{},...l?{monthly:l}:{},...o.length>0?{customWindows:o}:{},...a?{currentAccount:{...typeof a.plan==`string`||a.plan===null?{plan:a.plan}:{},quota:fi(a.quota)}}:{}}}function gi(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function _i(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 vi(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function yi(e,t){return!e||!vi(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 bi(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function xi(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 Si(e,t,n){let r=yi(e,t);if(!r)return[];let i=[];typeof r.fiveHourPercent==`number`&&i.push({rank:0,row:{windowKey:`fiveHour`,label:n(`codexAuth.fiveHour`),limitLabel:n(`quota.fiveHourLimit`),percent:r.fiveHourPercent,resetAt:r.fiveHourResetAt}}),typeof r.weeklyPercent==`number`&&i.push({rank:1,row:{windowKey:`weekly`,label:n(`codexAuth.weekly`),limitLabel:n(`quota.weeklyLimit`),percent:r.weeklyPercent,resetAt:r.weeklyResetAt}}),typeof r.monthlyPercent==`number`&&i.push({rank:4,row:{windowKey:`monthly`,label:n(`codexAuth.monthly`),limitLabel:n(`quota.monthlyLimit`),percent:r.monthlyPercent,resetAt:r.monthlyResetAt}});for(let e of r.customWindows??[]){let t=xi(e.label,n);i.push({rank:bi(e.label),row:{customLabel:e.label,label:t,limitLabel:t,percent:e.percent,resetAt:e.resetAt}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function Ci(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 wi(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function Ti(e){return e>=99.5}function Ei(e,t){return t>0&&e>=t}function Di(e,t){return Ei(e,t)||Ti(e)?`bar-warn`:`bar-green`}function Oi(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function ki(e){return{"--bar-scale":String(Oi(e)/100)}}function Ai({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1,incompleteWindowKeys:s,incompleteCustomWindowLabels:c}){let{locale:l}=Ze(),u=Si(e,t,r);return u.length===0?o?a===`stacked`?(0,z.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,z.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,z.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,z.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,z.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,z.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,z.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,z.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,z.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,z.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,z.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,z.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:u.map(e=>(0,z.jsx)(Mi,{row:e,threshold:n,t:r,locale:l,incomplete:e.windowKey?s?.has(e.windowKey)===!0:e.customLabel!==void 0&&c?.has(e.customLabel)===!0},e.limitLabel))}):(0,z.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:u.map(e=>(0,z.jsx)(ji,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:l},e.label))})}function ji({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Ti(t),s=Ei(t,r),c=Di(t,r),l=Ni(n,i,a),u=l.day||l.time?`${i(`codexAuth.resets`)} ${l.day} ${l.time}`.replace(/\s+/g,` `).trim():void 0,d=l.day!==``||l.time!==``;return(0,z.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,z.jsx)(`span`,{className:`quota-label`,title:u,children:e}),(0,z.jsx)(`span`,{className:`quota-reset-label`,children:d?i(`codexAuth.resets`):``}),(0,z.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,z.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,z.jsx)(`div`,{className:`bar`,title:u,children:(0,z.jsx)(`div`,{className:`bar-fill ${c}`,style:ki(t)})}),(0,z.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):u,"aria-label":u,children:[s&&(0,z.jsx)(se,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function Mi({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=Ti(e.percent),o=Ei(e.percent,t),s=Di(e.percent,t),c=Pi(e.resetAt,n,r);return(0,z.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,z.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,z.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,z.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,z.jsx)(`span`,{className:`quota-window-partial`,role:`note`,"aria-label":n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),title:n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),children:n(`pws.capacity.windowPartial`)})]}),(0,z.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,z.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,z.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,z.jsx)(`div`,{className:`bar-fill ${s}`,style:ki(e.percent)})}),(0,z.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,z.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,z.jsx)(se,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function Ni(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=wi(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 Pi(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=wi(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 Fi({report:e,pending:t}){let n=Z(),{locale:r}=Ze(),i=hi(e),a=pi(e),o=i?.presentation===`aggregate`,s=new Set,c=new Set;if(o&&i){i.fiveHour?.incomplete&&s.add(`fiveHour`),i.weekly?.incomplete&&s.add(`weekly`),i.monthly?.incomplete&&s.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&c.add(e.label)}let l=o&&i?[...i.fiveHour?[{key:0,label:n(`codexAuth.fiveHour`),window:i.fiveHour}]:[],...i.weekly?[{key:1,label:n(`codexAuth.weekly`),window:i.weekly}]:[],...i.monthly?[{key:2,label:n(`codexAuth.monthly`),window:i.monthly}]:[],...(i.customWindows??[]).map((e,t)=>({key:t+3,label:e.label,window:e}))]:[],u=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),d=e=>new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(new Date(e>1e10?e:e*1e3));return(0,z.jsxs)(z.Fragment,{children:[o&&(0,z.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(a||t)&&(0,z.jsx)(Ai,{quota:a,threshold:80,t:n,layout:`stacked`,pending:t,incompleteWindowKeys:o?s:void 0,incompleteCustomWindowLabels:o?c:void 0}),i&&(0,z.jsxs)(`div`,{className:`pws-capacity-details`,children:[l.flatMap(({key:e,label:t,window:r})=>r.nextRecoveryAt!==void 0&&r.nextRecoveryPercent!==void 0?[(0,z.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,z.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,d(r.nextRecoveryAt)]}),(0,z.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:u(r.nextRecoveryPercent)})})]},e)]:[]),o&&i.currentAccount?.quota&&(0,z.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,z.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,z.jsx)(Ai,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i.incomplete&&i.excludedAccounts>0&&(0,z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts,unknown:i.unknownPlanAccounts})}),i.partialWindowAccounts>0&&(0,z.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function Ii({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=Z(),{locale:c}=Ze(),l=$r(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)(()=>ei(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?pi(r):null,a=r?hi(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?Ci(i):-1})}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 Xr(e).slice(0,4)},[n,d]),b=e=>{let t=ti(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,z.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,z.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,z.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,z.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,z.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,z.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,z.jsx)(Li,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,z.jsx)(Li,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,z.jsx)(Li,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,z.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,z.jsx)(se,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,z.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,z.jsx)(ci,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:pn(e.name,s)}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,z.jsx)(fe,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,z.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,z.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,z.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,z.jsx)(ci,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:pn(e.name,s)}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:s(`pws.dashboard.checkedAgo`,{time:Qr(t.updatedAt,l)})})]}),(0,z.jsx)(fe,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,z.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,z.jsx)(Fi,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,z.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,z.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,z.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,z.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,z.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,z.jsx)(Ai,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,z.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,z.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,z.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,z.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,z.jsx)(ci,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-name`,children:pn(e.name,s)}),(0,z.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:ni(e.requests,c)})}),(0,z.jsx)(fe,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,z.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,z.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,z.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,z.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,z.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function Li({count:e,label:t,tone:n}){return(0,z.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,z.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,z.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function Ri({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Z(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,z.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,z.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,z.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,z.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,z.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,z.jsx)(`textarea`,{ref:o,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":a(`pws.jsonEditorDesc`)}),i&&(0,z.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var zi=[{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`}],Bi=18e5;function Vi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt)||t-n.updatedAt>=Bi||!(`quota`in n)||n.label!==void 0&&typeof n.label!=`string`||n.source!==void 0&&typeof n.source!=`string`?null:{...typeof n.label==`string`?{label:n.label}:{},...typeof n.source==`string`?{source:n.source}:{},updatedAt:n.updatedAt,quota:n.quota,...n.aggregation===void 0?{}:{aggregation:n.aggregation}}}function Hi(e,t=Date.now()){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n={};for(let[r,i]of Object.entries(e)){let e=Vi(i,t);r.trim()&&e&&(n[r]=e)}return n}function Ui(e){return Hi(qn(e))}function Wi(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){if(!r||typeof r!=`object`||Array.isArray(r))continue;let e=r.provider,i=Vi(r,t);typeof e==`string`&&e.trim()&&i&&(n[e]=i)}return n}function Gi({providers:e,apiBase:t,defaultProvider:n,selectedName:r,onSelect:i,onRemoveProvider:a,onAddProvider:o,onEditConfig:s,jsonEditor:c,jsonSaving:l=!1,modelsRefreshToken:u=0,activeAccountNeedsReauth:d,quotaRefreshEpoch:f=0,quotaForceRefresh:p=!1,detail:m}){let h=Z(),[g,v]=(0,_.useState)(``),[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,L]=(0,_.useState)({}),[R,B]=(0,_.useState)({}),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(!1),G=`ocx.providers.quotas.v1:${t}`,ee=`ocx.providers.usage.v1:${t}`,[te,K]=(0,_.useState)(()=>qn(ee)?.totals??{}),[q,J]=(0,_.useState)(()=>qn(ee)?.models??{}),[Y,ne]=(0,_.useState)(()=>Ui(G)??{}),[re,ie]=(0,_.useState)(()=>!qn(ee)),[ae,se]=(0,_.useState)(()=>{let e=Ui(G);return!e||Object.keys(e).length===0}),[ce,ue]=(0,_.useState)(0),X=(0,_.useRef)(null),de=I(mr(t),[t],async e=>{let n=await fetch(t+`/api/usage?range=30d`,{signal:e});if(!n.ok)throw Error(String(n.status));return await n.json()}),fe=(0,_.useMemo)(()=>Br(zr(Hr(e)),d??{}),[e,d]),pe=(0,_.useCallback)(()=>{ue(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{H(!0),(async()=>{try{let n=await St(await fetch(`${t}/api/selected-models`));if(e)return;M(Yr(n)),P(Kr(n)),L(qr(n)),B(Jr(n)),W(!1)}catch{if(e)return;W(!0)}finally{e||H(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,ce]),(0,_.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=de.data;if(e)return;if(!t){de.loading&&ie(!qn(ee));return}let n={};for(let e of t.providers??[])n[e.provider]={requests:e.requests,totalTokens:e.totalTokens};K(n);let r={};for(let e of t.models??[]){let t=e.provider;r[t]||(r[t]=[]),r[t].push({model:e.model,...e.resolvedModel?{resolvedModel:e.resolvedModel}:{},requests:e.requests,totalTokens:e.totalTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens,shareRatio:e.shareRatio,...e.estimatedCostUsd===void 0?{}:{estimatedCostUsd:e.estimatedCostUsd}})}J(r),Jn(ee,{totals:n,models:r}),ie(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,ee,de.data,de.loading]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=Ui(G);(!n||Object.keys(n).length===0)&&se(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>Ct(e)).then(t=>{if(e||!t)return;let n=Wi(t.reports);ne(n),Jn(G,n)}).catch(()=>{e||ne(e=>{let t=Hi(e)??{};return Jn(G,t),t})}).finally(()=>{e||se(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,G]),(0,_.useEffect)(()=>{if(!D)return;let e=e=>{X.current&&!X.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 me=(0,_.useMemo)(()=>[...fe.ready,...fe.needsSetup,...fe.disabled],[fe]),he=(0,_.useMemo)(()=>me.filter(Ir).length,[me]),ge=me.length-he,_e=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of me)e[Gr(t)]+=1;return e},[me]),ve=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>Rr(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=Ir(t);return!(n&&!x.free||!n&&!x.paid||!C[Gr(t)])}),T);return{ready:y.ready?t(fe.ready):[],needsSetup:y.needsSetup?t(fe.needsSetup):[],disabled:y.disabled?t(fe.disabled):[]}},[fe,g,y,x,C,T]),ye=!y.ready||!y.needsSetup||!y.disabled||!x.free||!x.paid||!C.cloud||!C.local||!C.selfHosted||!C.login||T!==`az`,be=()=>{b({ready:!0,needsSetup:!0,disabled:!0}),S({free:!0,paid:!0}),w({cloud:!0,local:!0,selfHosted:!0,login:!0}),E(`az`)},xe=(0,_.useMemo)(()=>r?me.find(e=>e.name===r)??null:null,[r,me]),Se=(0,_.useMemo)(()=>{let e=new Map;for(let t of me){let n=pn(t.name,h);e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e.entries())r>1&&t.add(n);return t},[me,h]);if(me.length===0)return(0,z.jsx)(Ki,{onAddProvider:o});let Ce=[{key:`ready`,label:h(`pws.status.ready`),count:fe.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:fe.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:fe.disabled.length}],we=[{id:`ready`,label:h(`pws.status.ready`),count:ve.ready.length,ariaLabel:h(`pws.groupReady`,{count:ve.ready.length}),items:ve.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:ve.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:ve.needsSetup.length}),items:ve.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:ve.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:ve.disabled.length}),items:ve.disabled}],Te=we.flatMap(e=>e.items.map(e=>e.name)),Ee=k&&Te.includes(k)?k:r&&Te.includes(r)?r:Te[0]??null;return(0,z.jsx)(`div`,{className:`pws-shell-container`,children:(0,z.jsxs)(`div`,{className:`pws-root`,children:[(0,z.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,z.jsxs)(`div`,{className:`pws-search-row`,children:[(0,z.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,z.jsx)(le,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,z.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,z.jsxs)(`div`,{className:`pws-filter-wrap`,ref:X,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ye||D?` pws-filter-btn--active`:``}`,onClick:()=>O(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":D,"aria-controls":`pws-provider-filters`,children:[(0,z.jsx)(De,{width:18,height:18,"aria-hidden":`true`}),ye&&(0,z.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),D&&(0,z.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,z.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),Ce.map(({key:e,label:t,count:n})=>(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:y[e],onChange:()=>b(t=>({...t,[e]:!t[e]}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:x.free,onChange:()=>S(e=>({...e,free:!e.free}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:he})]}),(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:x.paid,onChange:()=>S(e=>({...e,paid:!e.paid}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:ge})]}),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:_e.cloud},{key:`local`,label:h(`pws.type.local`),count:_e.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:_e.selfHosted},{key:`login`,label:h(`pws.type.login`),count:_e.login}].map(({key:e,label:t,count:n})=>(0,z.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:C[e],onChange:()=>w(t=>({...t,[e]:!t[e]}))}),(0,z.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,z.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,z.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,z.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:zi.map(e=>(0,z.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,z.jsx)(`div`,{className:`pws-filter-footer`,children:(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:be,disabled:!ye,children:h(`pws.resetAll`)})})]})]})]}),(0,z.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(ve).every(e=>e.length===0)&&(0,z.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:ye?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),we.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,z.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,z.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,z.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,z.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,z.jsx)(ui,{item:e,selected:r===e.name,tabbable:Ee===e.name,modelCount:j[e.name],isDefault:n===e.name,showConfigId:Se.has(pn(e.name,h)),onClick:()=>i(e.name),onFocus:()=>A(e.name)}),a&&(0,z.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,z.jsx)(oe,{width:14,height:14})})]},e.name))]},e))]})]}),(0,z.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,z.jsx)(Ri,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):xe?m?.(xe,{usageTotals:te[xe.name],modelUsage:q[xe.name],quotaReport:Y[xe.name],availableModels:N[xe.name]??[],hasLiveModels:(F[xe.name]??0)>0,selectedModels:R[xe.name]??[],modelsLoading:V,modelsLoadFailed:U,onRetryModels:pe})??(0,z.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,z.jsx)(`h3`,{children:pn(xe.name,h)}),(0,z.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,z.jsx)(Ii,{sections:fe,quotaReports:Y,usageTotals:te,usageLoading:re,quotasLoading:ae,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function Ki({onAddProvider:e}){let t=Z();return(0,z.jsx)(`div`,{className:`pws-empty-root`,children:(0,z.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,z.jsx)(`div`,{"aria-hidden":`true`,children:(0,z.jsx)(U,{style:{width:64,height:64}})}),(0,z.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,z.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:(0,z.jsx)(Ce,{width:18,height:18})}),(0,z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:(0,z.jsx)(_e,{width:18,height:18})}),(0,z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,z.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:(0,z.jsx)(ge,{width:18,height:18})}),(0,z.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,z.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function qi(e){if(Fr(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||Ur(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 Ji(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 Yi({item:e,usageTotals:t,quotaReport:n,oauthEmail:r,oauth:i,apiBase:a,connectionIdentity:o,onEditSettings:s,onViewUsage:c,onUpdateProvider:l,onReauthenticate:u,onCancelLogin:d,reauthBusy:f=!1}){let p=Z(),{locale:m}=Ze(),h=$r(p),g=Vr(e),v=!!e.activeNeedsReauth,y=p(g===`ready`?`pws.status.connected`:g===`needs-setup`?v?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),b=t?.requests,x=t?.totalTokens,S=pi(n),C=JSON.stringify([a??null,e.name,e.adapter,e.baseUrl,e.authMode??null,e.apiKeyTransport??null,e.liveModels??null,e.disabled===!0,e.hasApiKey===!0,e.hasHeaders===!0,e.allowPrivateNetwork===!0,e.keyOptional===!0,e.activeNeedsReauth===!0,o??null]),[w,T]=(0,_.useState)(null),E=(0,_.useRef)(null),D=w?.key===C&&w.testing,O=w?.key===C?w.result:null;(0,_.useEffect)(()=>()=>{E.current?.key===C&&(E.current.controller.abort(),E.current=null)},[C]);let k=(0,_.useCallback)(async()=>{if(!a)return;E.current?.controller.abort();let t=new AbortController;E.current={key:C,controller:t},T({key:C,testing:!0,result:null});try{let n=await St(await fetch(`${a}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),p(`pws.connectionFailed`));if(!n)throw Error(p(`pws.connectionFailed`));t.signal.aborted||T({key:C,testing:!1,result:n})}catch(e){t.signal.aborted||T({key:C,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:p(`pws.connectionFailed`)}})}finally{E.current?.controller===t&&(E.current=null)}},[a,C,e.name,p]),A=O?.applicable===!1?`not-applicable`:O?.ok===!0?`ok`:`failed`,j=O?.applicable===!1?p(`pws.connectionNotApplicable`):O?.ok===!0?O.message||p(`pws.connectionOk`):O?.error||p(`pws.connectionFailed`);return(0,z.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,z.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.connection`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.connection`)}),(0,z.jsxs)(`dl`,{className:`pws-kv`,children:[(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`dash.status`)}),(0,z.jsxs)(`dd`,{className:g===`ready`?`pws-status-ok`:`pws-status-warn`,children:[g===`ready`?(0,z.jsx)(J,{style:{width:13,height:13},"aria-hidden":`true`}):(0,z.jsx)(se,{style:{width:13,height:13},"aria-hidden":`true`}),y]})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`modal.baseUrl`)}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.cell.auth`)}),(0,z.jsx)(`dd`,{children:r?`${oi(e,p)} · ${r}`:oi(e,p)})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`modal.defaultModel`)}),(0,z.jsx)(`dd`,{children:e.defaultModel??(0,z.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.cell.note`)}),(0,z.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),a&&(0,z.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:()=>void k(),children:p(D?`pws.testing`:`pws.testConnection`)}),O&&(0,z.jsx)(`span`,{role:`status`,className:A===`ok`?`pws-status-ok`:A===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":A,children:j})]}),s&&(0,z.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:s,children:p(`pws.editSettings`)})]}),n&&(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.rateLimits`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.rateLimits`)}),(0,z.jsx)(Fi,{report:n,pending:!1})]}),(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.authSummary`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.authSummary`)}),v?(0,z.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,z.jsx)(se,{style:{width:14,height:14},"aria-hidden":`true`}),(0,z.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:p(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?p(`pws.attention.reauthForward`):p(`pws.attention.reauth`)]}),u&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:f,onClick:()=>u(),children:p(f?`prov.waitingBrowser`:`pws.reauthenticate`)}),f&&d&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(),children:p(`common.cancel`)})]})]}):(0,z.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,z.jsx)(`span`,{className:`pws-auth-dot`}),(0,z.jsx)(`span`,{children:e.authMode===`forward`?p(`pws.passthrough`):e.authMode===`oauth`?r?p(`pws.loggedInAs`,{email:r}):i?.loggedIn?p(`pws.loggedInTitle`):p(`pws.notLoggedIn`):e.hasApiKey?p(`pws.apiKeyConfigured`):oi(e,p)})]})]})]}),(0,z.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,z.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.statsAria`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.statsTitle`)}),(0,z.jsxs)(`dl`,{className:`pws-kv`,children:[typeof b==`number`&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.stats.totalRequests`)}),(0,z.jsx)(`dd`,{className:`pws-kv-mono`,children:ni(b,m)})]}),typeof x==`number`&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.stats.totalTokens`)}),(0,z.jsx)(`dd`,{className:`pws-kv-mono`,children:ri(x,m)})]}),n&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:p(`pws.stats.quotaUpdated`)}),(0,z.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?gi(n.source):void 0,children:Qr(n.updatedAt,h)})]}),typeof b!=`number`&&typeof x!=`number`&&!n&&(0,z.jsx)(`div`,{className:`muted`,children:p(`pws.usageUnavailable`)})]}),c&&(0,z.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:c,children:[p(`pws.viewUsage`),` →`]}),S&&(0,z.jsx)(`div`,{className:`muted pws-stats-note`,children:p(`pws.stats.quotaTracked`)})]}),(0,z.jsx)(Xi,{item:e,onUpdateProvider:l})]})]})}function Xi({item:e,onUpdateProvider:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``)){i(!1),u(``);return}c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}},[a,e.name,e.note,t,s,n]);return r?(0,z.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,z.jsx)(`textarea`,{ref: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,z.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,z.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,z.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,z.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function Zi({item:e,apiBase:t,availableModels:n,hasLiveModels:r,selectedModels:i,modelsLoading:a=!1,modelsLoadFailed:o=!1,needsReauth:s=!1,onRetryModels:c,onOpenAccounts:l}){let u=Z(),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(``),[S,C]=(0,_.useState)([]),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(null),M=(0,_.useRef)(null),N=(0,_.useMemo)(()=>new Set(i),[i]),P=(0,_.useMemo)(()=>e.models??[],[e.models]),F=p.trim(),I=!w||!F||F.includes(`/`)||n.includes(F)||S.includes(F)||P.includes(F)||e.defaultModel===F,L=(0,_.useMemo)(()=>_i(n,e.defaultModel,d,P,S,r),[n,e.defaultModel,d,P,S,r]);(0,_.useEffect)(()=>{let n=!0;return(async()=>{try{let r=await fetch(`${t}/api/custom-models`);if(!r.ok)throw Error();let i=await r.json();if(!Array.isArray(i))throw Error(`Invalid custom model list`);if(!n)return;C(i.flatMap(t=>{if(!t||typeof t!=`object`)return[];let n=t;return n.provider===e.name&&typeof n.modelId==`string`?[n.modelId]:[]})),D(!1),y(``),T(!0)}catch{if(!n)return;C([]),T(!1),D(!0),y(u(`models.networkError`))}})(),()=>{n=!1}},[t,e.name,u,O]);let R=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let 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,G=W?L.slice(0,300):L;return(0,z.jsxs)(`div`,{className:`pws-section`,children:[(0,z.jsxs)(`div`,{className:`pws-section-head`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),L.length>0&&(0,z.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:L.length})})]}),s&&(0,z.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,z.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),U&&!s&&(0,z.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,z.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,z.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,z.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,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{V()},disabled:h||I,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,z.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,z.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:R,style:{marginLeft:8},children:u(`common.retry`)})]}),!H&&(0,z.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,z.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&H?(0,z.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,z.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):H?(0,z.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):L.length===0?(0,z.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,z.jsx)(`ul`,{className:`pws-model-list`,children:G.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,z.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,z.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,z.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,z.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,z.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),W&&(0,z.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(L.length)})})]})}function Qi({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=Z(),{locale:a}=Ze(),o=$r(i),s=t?.requests!==void 0,c=pi(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,z.jsxs)(`div`,{className:`pws-section`,children:[(0,z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,z.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:ii(f,a)}),(0,z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,z.jsx)(`span`,{className:`pws-usage-metric-value`,children:ni(t?.requests,a)}),(0,z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,z.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,z.jsx)(`span`,{className:`pws-usage-metric-value`,children:ri(t?.totalTokens,a)}),(0,z.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,z.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,z.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`pws-model-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`pws.col.model`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,z.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,z.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,z.jsxs)(_.Fragment,{children:[(0,z.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,z.jsx)(`td`,{className:`mono`,children:(0,z.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,z.jsx)(`td`,{className:`num mono`,children:ii(e.estimatedCostUsd,a)}),(0,z.jsx)(`td`,{className:`num mono`,children:ri(e.totalTokens,a)}),(0,z.jsx)(`td`,{className:`num`,children:e.requests}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`div`,{className:`pws-share-bar`,children:(0,z.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,z.jsx)(`tr`,{className:`pws-model-detail`,children:(0,z.jsx)(`td`,{colSpan:5,children:(0,z.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[` `,ri(e.inputTokens,a)]})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[` `,ri(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,z.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,z.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Ai,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,z.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,z.jsx)(`dd`,{children:gi(n.source)})]}),(0,z.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,z.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,z.jsx)(`dd`,{children:Qr(n?.updatedAt,o)})]})]})]}):(0,z.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function $i(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function ea(e){return $i(e)??`account-…`}function ta(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function na(e){let t=ta(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function ra(e){return e===`reauth_required`}function ia(e){return!!e?.needsReauth||ra(e?.health?.status)}function aa(e){return e===`cooldown`}function oa(e){return e===`warning`||e===`reauth_required`}function sa(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 ca(e,t){let n=sa(t);return n?e(n):null}function la(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):ea(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 ua(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return da(e)}function da(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 fa(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var pa=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function ma(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 ha({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=Z();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,z.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,z.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,z.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,z.jsx)(Ce,{width:20}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,z.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,z.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var ga=2500;function _a(){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;ua(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)},ga))})},[i])}}function va({url:e}){let t=Z(),{outcomeFor:n,copy:r}=_a();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,z.jsxs)(`div`,{className:`login-url-block`,children:[(0,z.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,z.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,z.jsx)(ye,{style:{width:13,height:13},"aria-hidden":`true`}),(0,z.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,z.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,z.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function ya({reauthAccountId:e,authUrl:t,manualCode:n,manualCodeBusy:r,manualCodeWaiting:i,statusNotice:a,statusTone:o,flowId:s,error:c,onManualCodeChange:l,onSubmitManualCode:u,onClose:d}){let f=Z();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,z.jsx)(va,{url:t}),(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,marginTop:12},children:[(0,z.jsx)(`div`,{className:`muted text-label`,children:f(`prov.pasteRedirectHint`)}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,z.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,z.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,z.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,z.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,z.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,z.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}function ba(e){if(typeof e!=`object`||!e||Array.isArray(e))return{catalogRefreshPending:!1};let t=Object.getOwnPropertyDescriptor(e,`catalogRefreshPending`);return{catalogRefreshPending:t!==void 0&&`value`in t&&t.value===!0}}function xa({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 St(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 Ct(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(ba(n)),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 Sa({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Z(),[a,o]=(0,_.useReducer)(ma,r,pa),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=xa({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]),g=i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,z.jsx)(`dialog`,{ref:c,"aria-label":g,className:`modal-overlay`,onCancel:h,children:(0,z.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,z.jsx)(ha,{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,z.jsx)(ya,{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 Ca=[2,1,0,-1,-2],wa=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function Ta(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function Ea(e){let t=Ta(e);return t>0?`+${t}`:String(t)}function Da(e){return wa.has(e)}function Oa(e){return wa.get(e)??null}function ka(e,t){let n=Ta(t);return e(`accountPool.priorityOption`,{name:e(Oa(n)??`accountPool.priorityCustom`),value:Ea(n)})}var Aa=1e4;function ja(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Ma(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Na(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Pa(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function Fa(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Ia(e,t,n){if(e<=0){let t=Na(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Ma(t)??Na(0,n)}}async function La(e,t,n=(e,t)=>fetch(e,t),r=Aa){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 Ra=3e4,za=new Map;function Ba(e,t=!0){let n=za.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),a=I(mr(e,`codex`),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d&surface=codex`,{signal:t});if(!n.ok)throw Error(`account usage load failed`);return n.json()},{enabled:t}),[o,s]=(0,_.useState)(()=>n?.activeId??null),[c,l]=(0,_.useState)(()=>n==null?`loading`:`ready`),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(0),[C,w]=(0,_.useState)(()=>n!=null),[T,E]=(0,_.useState)(0),D=(0,_.useRef)(null);D.current===null&&(D.current=new Set);let O=(0,_.useRef)(null),k=(0,_.useRef)(0),A=(0,_.useRef)(null),j=(0,_.useRef)(null);j.current===null&&(j.current=new Set);let M=(0,_.useRef)(null),N=(0,_.useRef)(null),P=(0,_.useRef)(!!n?.accounts.length),F=(0,_.useRef)(n!=null),L=(0,_.useRef)(null),R=(0,_.useRef)(null),z=(0,_.useCallback)(e=>(j.current.add(e),()=>{j.current.delete(e)}),[]),B=(0,_.useCallback)(()=>Fa(M.current?.value),[]),V=(0,_.useCallback)(()=>M.current?.value,[]),H=(0,_.useCallback)(async(t=!1)=>{let n=++k.current;S(e=>e+1);try{let r=[...j.current],a=new Map;for(let e of r)a.set(e,e.beginActiveRead());!t&&!F.current&&l(`loading`);let o=null,c,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 k.current===n&&(o=(a.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel;return{...e,...t?{logLabel:t}:{},priority:Ta(e.priority)}}),i(o),P.current=o.length>0,F.current=!0,l(`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(k.current===n){let e=i.activeCodexAccountId??null,t=A.current;t&&e!==t.id||(A.current=null,c=e,s(e)),M.current={value:i},b(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of r)e.acceptActiveRead(i,a.get(e))}return!0}catch{if(k.current===n)for(let e of r)e.rejectActiveRead();return!1}})(),[f,p]=await Promise.all([u,d]);if(k.current!==n)return!1;if(f){l(`ready`),F.current=!0;let t=za.get(e);return za.set(e,{accounts:o??t?.accounts??[],activeId:c===void 0?t?.activeId??null:c}),p}return F.current||l(`error`),!1}finally{S(e=>Math.max(0,e-1)),w(!0)}},[e]);(0,_.useEffect)(()=>{t&&O.current!==e&&(O.current=e,Promise.resolve().then(()=>{H()}))},[e,t,H]);let U=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!U||T>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{H(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,U,T,H]),(0,_.useEffect)(()=>{if(!t||T>0)return;let e=window.setInterval(()=>{H()},Ra);return()=>window.clearInterval(e)},[t,H,T]);let W=(0,_.useCallback)(()=>{let e={};return D.current.add(e),E(D.current.size),e},[]),G=(0,_.useCallback)(e=>{D.current.delete(e)&&E(D.current.size)},[]),ee=(0,_.useCallback)(async t=>{if(N.current||R.current)return{ok:!1,reason:`busy`};N.current=t??`__main__`,d(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 A.current={id:r??null},s(r??null),b(r??`__main__`),H(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{N.current=null,d(null)}},[e,H]),te=(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 H(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,H]),K=(0,_.useCallback)(async(t,n)=>{if(L.current)return{ok:!1,reason:`busy`};L.current={accountId:t},p(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,paused:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=a&&typeof a==`object`?a:{};if(i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,paused:n}:e)),Object.prototype.hasOwnProperty.call(o,`activeCodexAccountId`)){let e=o.activeCodexAccountId??null;A.current={id:e},s(e)}return n&&b(e=>e===t?null:e),H(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,p(null)}},[e,H]),q=(0,_.useCallback)(async(t,n)=>{if(R.current||N.current)return{ok:!1,reason:`busy`};R.current={accountId:t},h(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/priority`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,priority:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=Ta((a&&typeof a==`object`?a:{}).priority??n);return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,priority:o}:e)),b(null),A.current=null,H(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{R.current=null,h(null)}},[e,H]),J=(0,_.useCallback)(async()=>{if(L.current)return{ok:!1,reason:`busy`};L.current=`bulk`,v(!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;A.current={id:e},s(e)}return b(e=>e!==null&&a.has(e)?null:e),H(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,v(!1)}},[e,H]),Y=(0,_.useCallback)(async t=>{try{let n=await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`});if(!n.ok)return{ok:!1,reason:`request`};let r=ba(await n.json().catch(()=>({})));return await H(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,H]),ne=(0,_.useCallback)(async()=>await H()?{ok:!0}:{ok:!1,reason:`reload`},[H]),re=o&&o!==`__main__`?r.find(e=>e.id===o):null,ie=r.find(e=>e.isMain),ae=re??ie,oe=!ae?.paused&&ia(ae);return{accounts:(0,_.useMemo)(()=>{let e=new Map((a.data?.accounts??[]).map(e=>[e.accountLogLabel,e]));return r.map(t=>{let n=t.isMain?`main`:t.logLabel,r=n?e.get(n):void 0;return r?{...t,usage30d:r}:t})},[r,a.data]),activeId:o,loadState:c,refreshing:x>0,initialLoading:!C,switchingId:u,pauseUpdatingId:f,priorityUpdatingId:m,pausingExhausted:g,activeNeedsReauth:oe,activePinnedId:y,load:H,switchAccount:ee,setAccountPaused:K,setAccountPriority:q,pauseExhaustedAccounts:J,saveAlias:te,removeAccount:Y,syncAfterAccountAdded:ne,pauseRefresh:W,resumeRefresh:G,subscribeLoadObserver:z,readLastThreshold:B,readLastActive:V}}function Va(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 Ha({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,z.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,z.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,z.jsx)(ue,{width:10,height:10,"aria-hidden":`true`})}),(0,z.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,z.jsx)(X,{width:10,height:10,"aria-hidden":`true`})})]})}var Ua={quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function Wa({threshold:e,draft:t,strategy:n=`quota`,hydrated:r=!0,saving:i,loadError:a,feedback:o,onDraftChange:s,onEditingChange:c,onCommit:l,onCancel:u,onToggle:d,onRetry:f}){let p=Z(),m=(0,_.useRef)(!1),h=e>0,g=Ua[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,z.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,z.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,z.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,z.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,z.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,z.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,z.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c(!1),m.current){m.current=!1;return}h&&!v&&l()}},children:[a&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,z.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,z.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,z.jsx)(Ha,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(Va(t,1,1,100))},onDecrement:()=>{c(!0),s(Va(t,-1,1,100))}})]})]}),(0,z.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,z.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,z.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,z.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var Ga=[`quota`,`round-robin`,`fill-first`],Ka=`quota`,qa=new Set(Ga);function Ja(e){return typeof e==`string`&&qa.has(e)?e:Ka}function Ya(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Xa(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function Za(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:Ja(i.accountPoolStrategy??t.strategy),stickyLimit:Ya(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var Qa={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},$a={quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function eo({strategy:e,stickyDraft:t,disabled:n=!1,strategySelectId:r=`account-pool-strategy`,stickyInputId:i=`account-pool-sticky-limit`,onStrategyChange:a,onStickyDraftChange:o,onStickyCommit:s}){let c=Z(),l=Ga.map(e=>({value:e,label:c(Qa[e])}));return(0,z.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,z.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,z.jsx)(`span`,{className:`desc`,children:c($a[e])}),(0,z.jsx)(`span`,{className:`desc`,children:c(`accountPool.unboundDefinition`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsx)(ht,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,z.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,z.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,z.jsx)(`input`,{id: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,z.jsx)(Ha,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=Va(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=Va(t,-1,1,100);o(e),s(e)}})]})})]})]})}function to(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:Ja(t.accountPoolStrategy),stickyLimit:Ya(t.accountPoolStickyLimit)}}function no({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Z(),[a,o]=(0,_.useState)(Ka),[s,c]=(0,_.useState)(1),[l,u]=(0,_.useState)(`1`),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(!1),y=(0,_.useRef)(0),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),w=(0,_.useCallback)(e=>{let t=Ja(e.accountPoolStrategy),n=Ya(e.accountPoolStickyLimit);o(t),r?.(t),c(n),u(String(n)),p.current=!0,f(!0),x(!1),C(null)},[r]),T=(0,_.useCallback)(e=>{let t=to(e);t&&w({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[w]),E=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(g.current){v.current=!0;return}w(n)}catch{g.current||x(!0)}},[e,w]),D=(0,_.useCallback)(()=>{v.current&&(v.current=!1,queueMicrotask(()=>{if(g.current){v.current=!0;return}E()}))},[E]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>y.current,acceptActiveRead:(e,t)=>{if(t===y.current){if(g.current){v.current=!0;return}T(e)}},rejectActiveRead:()=>{p.current||x(!0)}});return!g.current&&n&&T(n()),e},[t,T,n]),(0,_.useEffect)(()=>{!n||t||g.current||T(n())},[n,T,t]),(0,_.useEffect)(()=>{t||E()},[E,t]);let O=(0,_.useCallback)(async t=>{if(g.current)return;let n=a,l=s;t.strategy!==void 0&&(o(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(c(t.stickyLimit),u(String(t.stickyLimit))),g.current=!0,h(!0),C(null),y.current+=1;let d=await Za(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,z.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,z.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,z.jsx)(eo,{strategy:a,stickyDraft:l,disabled:k,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{k||e===a||O({strategy:e})},onStickyDraftChange:u,onStickyCommit:e=>{if(k)return;let t=Xa(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,z.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function ro({t:e,open:t,onToggle:n,children:r}){return(0,z.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,z.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,z.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function io(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&&(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=Fa(e),r=Pa(v.current,y.current,t,x.current);r===`defer`?S.current=ja(n):r===`apply`&&T(ja(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(ja(Fa(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 La(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=Ma(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=Ia(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])}}function ao({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=Z(),a=Ta(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=Ca.map(e=>({value:String(e),label:ka(i,e)})),l=Da(a)?c:[{value:String(a),label:ka(i,a)},...c];return(0,z.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,z.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,z.jsx)(ht,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(Ta(Number.parseInt(e,10)))}),(0,z.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function oo({value:e}){let t=Z(),n=Ta(e);return n===0?null:(0,z.jsx)(`span`,{className:`badge badge-muted`,children:ka(t,n)})}var so=new Map;function co(e,t){return`${e??``}\0${JSON.stringify(t)}`}function lo(e,t){let n=co(e,t??{}),r=so.get(n);return r||(r=new Intl.NumberFormat(e,t),so.set(n,r)),r}var uo={month:`short`,day:`numeric`,year:`numeric`},fo={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},po=new Map;function mo(e,t){let n=co(e,t),r=po.get(n);return r||(r=new Intl.DateTimeFormat(e,t),po.set(n,r)),r}function ho(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:mo(t,uo).format(n)}function go(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:mo(t,fo).format(n)}function _o(e,t){return!Number.isFinite(e)||e<0?`—`:`~${lo(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function vo(e,t){return ho(e,t)}function yo(e,t){return go(e,t)}function bo(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function xo({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=bo(n),s=o<=7;return(0,z.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,z.jsxs)(`div`,{className:`credit-item-head`,children:[(0,z.jsx)(ve,{width:13}),(0,z.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,z.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,z.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,z.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:vo(t,i)})}),(0,z.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:yo(n,i),days:String(o)})})]})]})}function So({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,z.jsx)(ve,{width:12}),`0`]}):r===void 0?null:(0,z.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,z.jsx)(ve,{width:12}),r]})}function Co({t:e,paused:t,saving:n}){let r=e(`codexAuth.pause`),i=e(`codexAuth.resume`),a=e(`common.saving`),o=n?a:t?i:r,s=Math.max(r.length,i.length,a.length);return(0,z.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function wo({pool:e,activeId:t,accountModeState:n,switchActionLabel:r,threshold:i,onOpenReset:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onPriorityChange:u,priorityUpdatingId:d,switchingId:f,pinnedId:p=null,onReauth:m,onEditAlias:h,onRemove:g,onCopyDoctor:_,doctorCopyOutcomeFor:v}){let y=Z(),b=e=>!e.paused&&t===e.id;return(0,z.jsx)(z.Fragment,{children:e.map(e=>{let t=e.health?.status,x=!!e.needsReauth||ra(t),S=aa(t),C=ca(y,e.health),w=la(y,`codex`,e.id,e.health);return(0,z.jsxs)(`div`,{className:`card ${b(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,z.jsxs)(`div`,{className:`card-head`,children:[(0,z.jsx)(`span`,{className:`dot ${x?`dot-amber`:b(e)?`dot-blue`:`dot-muted`}`}),(0,z.jsx)(`strong`,{children:e.alias??e.email}),(0,z.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,z.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,title:y(`codexAuth.pausedHint`),children:y(`codexAuth.paused`)}),(0,z.jsx)(oo,{value:e.priority}),e.id===p&&!e.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,children:y(`codexAuth.pinned`)}),(0,z.jsx)(So,{t:y,account:e,onClick:()=>a(e)}),C&&(0,z.jsx)(`span`,{className:na(t),children:C}),x&&!C&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:y(`codexAuth.needsReauth`)}),b(e)&&!x&&!S&&(0,z.jsx)(`span`,{className:`badge badge-primary`,children:y(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!b(e)&&!x&&!S&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),x&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>m(e.id),children:y(`codexAuth.reauthenticate`)}),_&&oa(t)&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>_(e.id),children:(0,z.jsx)(`span`,{"aria-live":`polite`,children:fa(y,v?.(e.id))})}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?y(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${y(`codexAuth.resume`)}. ${y(`codexAuth.pausedHint`)}`:y(`codexAuth.pause`),children:[e.paused?(0,z.jsx)(ae,{width:14}):(0,z.jsx)(ie,{width:14}),(0,z.jsx)(Co,{t:y,paused:e.paused,saving:c===e.id})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h(e),children:y(`prov.editAlias`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger card-right`,"aria-label":`${y(`common.remove`)} — ${e.email}`,title:`${y(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),g(e.id)},children:(0,z.jsx)(Y,{width:14})})]}),(0,z.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,z.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,y(`prov.accountId`),`: `,ea(e.id)]}),(0,z.jsx)(ao,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:d!==null||f!==null,onChange:t=>u(e,t)})]}),w&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:w}),S&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:y(`pws.healthCooldownHint`)}),x?(0,z.jsx)(`div`,{className:`card-sub faint`,children:y(`codexAuth.tokenExpired`)}):!S&&(0,z.jsx)(Ai,{quota:e.quota,plan:e.plan,threshold:i,t:y,pending:e.quota==null})]},e.id)})})}function To({onReauth:e}){let t=Z();return(0,z.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(se,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function Eo({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,onCancel:a,onConfirm:o}){let s=Z(),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let l=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:l,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,z.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?s(`codexAuth.preparePoolTitle`):e.id===`__main__`?s(`codexAuth.switchBack`):s(`codexAuth.switchTitle`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?s(`codexAuth.preparePoolDesc`):e.id===`__main__`?s(`codexAuth.switchBackDesc`):s(`codexAuth.switchDesc`)}),(0,z.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,z.jsx)(`strong`,{children:e.id===`__main__`?t||s(`codexAuth.codexApp`):e.email}),e.plan&&(0,z.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,z.jsxs)(`div`,{className:`notice-warn`,children:[(0,z.jsx)(se,{width:14}),` `,s(`codexAuth.cacheWarning`)]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`codexAuth.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r||i,onClick:o,children:s(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function Do({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=Ze(),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,z.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:f,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,z.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,z.jsx)(`div`,{className:`confirm-icon`,children:(0,z.jsx)(se,{width:22})}),(0,z.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,z.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:vo(n[0].granted_at,l)})}),(0,z.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,z.jsx)(ve,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,z.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,z.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,z.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,z.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,z.jsx)(xo,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,z.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,z.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function Oo({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onPriorityChange:u,priorityUpdatingId:d,switchingId:f,pinnedId:p=null,onOpenReset:m,onCopyDoctor:h,doctorCopyOutcomeFor:g}){let _=e(`codexAuth.codexApp`),v=t?.id??`__main__`,y={id:`__main__`,email:t?.email||_,plan:t?.plan,isMain:!0,paused:t?.paused??!1,priority:t?.priority??0,hasCredential:!0,quota:t?.quota??null},b=!!t?.needsReauth||ra(t?.health?.status),x=aa(t?.health?.status),S=ca(e,t?.health),C=t?la(e,`codex`,v,t.health):null;return(0,z.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,z.jsxs)(`div`,{className:`card-head`,children:[(0,z.jsx)(`span`,{className:`dot ${b?`dot-amber`:`dot-green`}`}),(0,z.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,z.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,z.jsx)(So,{t:e,account:{...t,id:`__main__`},onClick:()=>m({...t,id:`__main__`})}),t?.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,z.jsx)(oo,{value:y.priority}),p===`__main__`&&!t?.paused&&(0,z.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.pinned`)}),S&&(0,z.jsx)(`span`,{className:na(t?.health?.status),children:S}),b&&!S&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,z.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&!n&&!b&&!x&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(y),children:a}),h&&oa(t?.health?.status)&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>h(v),children:(0,z.jsx)(`span`,{"aria-live":`polite`,children:fa(e,g?.(v))})}),t&&(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(y),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,z.jsx)(ae,{width:14}):(0,z.jsx)(ie,{width:14}),(0,z.jsx)(Co,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,z.jsxs)(`span`,{className:`card-right`,children:[(0,z.jsx)(_e,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,z.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,z.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),t&&(0,z.jsx)(ao,{value:y.priority,selectId:`codex-account-priority-${y.id}`,disabled:d!==null||f!==null,onChange:e=>u(y,e)})]}),C&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:C}),x&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),b?(0,z.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!x&&(0,z.jsx)(Ai,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function ko({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,z.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,z.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,z.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,z.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,z.jsx)(ie,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,z.jsx)(re,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function Ao({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,z.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,z.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,z.jsxs)(`div`,{className:`card-head`,children:[(0,z.jsx)(`span`,{className:`dot dot-muted`}),(0,z.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,z.jsxs)(`span`,{className:`card-badges`,children:[(0,z.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,z.jsx)(ve,{width:12}),`0`]}),(0,z.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,z.jsx)(ie,{width:14}),` `,e(`codexAuth.pause`)]}),(0,z.jsxs)(`span`,{className:`card-right`,children:[(0,z.jsx)(_e,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,z.jsxs)(`div`,{className:`card-sub`,children:[(0,z.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,z.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,z.jsx)(Ai,{quota:null,threshold:0,t:e,pending:!0})]}),(0,z.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,z.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,z.jsx)(`div`,{className:`sep-line`}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,z.jsx)(ne,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,z.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,z.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,z.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,z.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,z.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function jo(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function Mo(e,t,n,r){try{let i=await Ct(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:jo(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 No=`ocx doctor`;function Po({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a,advancedExtras:o=null}){let s=Z(),c=io(e,{updated:s(`codexAuth.autoSwitchUpdated`),updateFailed:s(`codexAuth.autoSwitchUpdateFailed`),invalid:s(`codexAuth.autoSwitchThresholdInvalid`)}),[l,u]=(0,_.useState)(null),{beginServerRead:d,acceptServerRead:f,rejectServerRead:p,hydrateServerValue:m}=c,h=Ba(e,!a),g=a??h,{accounts:v,activeId:y,loadState:b,switchingId:x,pauseUpdatingId:S,priorityUpdatingId:C,pausingExhausted:w,activePinnedId:T,load:E}=g,[D,O]=(0,_.useState)(null),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(null),[F,I]=(0,_.useState)(null),[L,R]=(0,_.useState)(null),B=(0,_.useRef)(null),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(null),[G,ee]=(0,_.useState)(!1),[te,K]=(0,_.useState)(!1),[q,J]=(0,_.useState)(null),[Y,re]=(0,_.useState)(!1),ie=_a(),ae=(0,_.useCallback)((e,t=`ok`)=>{B.current&&clearTimeout(B.current),I(e),R(t),B.current=setTimeout(()=>{I(null),R(null),B.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{B.current&&clearTimeout(B.current)},[]);let oe=(0,_.useCallback)(e=>{ie.copy(No,e)},[ie]),{subscribeLoadObserver:se,readLastThreshold:ce}=g;(0,_.useEffect)(()=>se({beginActiveRead:d,acceptActiveRead:f,rejectActiveRead:p}),[se,d,f,p]),(0,_.useEffect)(()=>{let e=ce();e!==void 0&&m(e)},[ce,m]),(0,_.useEffect)(()=>{if(!k)return;let e=g.pauseRefresh();return()=>g.resumeRefresh(e)},[g,k]);let le=y&&y!==`__main__`?v.find(e=>e.id===y):null,ue=!le?.paused&&ia(le);(0,_.useEffect)(()=>{i?.(ue)},[ue,i]);let X=(0,_.useCallback)(e=>{P(e),A(!0)},[]),de=(0,_.useCallback)(()=>{A(!1),P(null)},[]),fe=(0,_.useCallback)(e=>{g.syncAfterAccountAdded(),ae(s(e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.catalogRefreshPending?`warn`:`ok`),de()},[de,g,ae,s]),pe=async e=>{let n=await g.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;ae(s(`codexAuth.switchFailed`),`err`);return}O(null);let r=n.activeId,i=r&&r!==`__main__`?v.find(e=>e.id===r)?.email??s(`pws.accountOrdinal`,{count:`1`}):s(`codexAuth.mainAccount`);ae(s(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},me=async e=>{let t=window.prompt(s(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await g.saveAlias(e.id,t);ae(s(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},he=async e=>{let t=!e.paused,n=await g.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(O(t=>t?.id===e.id?null:t),ae(s(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},ge=async(e,t)=>{if(t===e.priority)return;let n=await g.setAccountPriority(e.id,t);!n.ok&&n.reason===`busy`||ae(s(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},_e=async e=>{let t=v.find(t=>t.id===e)?.email??s(`pws.accountOrdinal`,{count:`1`});if(!window.confirm(s(`codexAuth.removeConfirm`,{id:t})))return;let n=await g.removeAccount(e);n.ok?n.catalogRefreshPending&&ae(s(`codexAuth.catalogRefreshPending`),`warn`):ae(s(`codexAuth.removeFailed`),`err`)},ve=async()=>{H(!0);try{let e=await E(!0);ae(s(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{H(!1)}},ye=async()=>{let e=await g.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||ae(e.ok?e.pausedCount>0?s(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):s(`codexAuth.pauseExhaustedNone`):s(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},be=async t=>{W(t),ee(!1),J(null),re(!0);try{let n=await Ct(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));if(n){let e=(n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime());J(e)}}catch{}finally{re(!1)}},xe=async t=>{K(!0);try{let n=await Mo(e,t,s,E);n.close&&(W(null),ee(!1)),n.toast&&ae(n.toast,n.ok?`ok`:`err`)}finally{K(!1)}},Se=v.find(e=>e.isMain),Ce=v.filter(e=>!e.isMain),we=!Se?.paused&&(!y||y===`__main__`),Te=s(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Ee=S!==null||w,De=c.threshold??0,Oe=!r;return(0,z.jsxs)(`div`,{children:[(0,z.jsx)(ko,{t:s,embedded:r,refreshingQuota:V,actionFeedback:F,actionFeedbackTone:L,pausingExhausted:w,pauseBusy:Ee,onRefresh:()=>{ve()},onPauseExhausted:()=>{ye()}}),n,(0,z.jsx)(Ao,{t:s,loadState:b,accountsCount:v.length,onRetry:()=>{E()}}),(b!==`loading`||v.length!==0)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Oo,{t:s,main:Se,isMainActive:we,accountModeState:t,threshold:De,switchActionLabel:Te,onSwitch:O,onTogglePause:he,pauseUpdatingId:S,pauseBusy:Ee,onPriorityChange:(e,t)=>{ge(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onOpenReset:be,onCopyDoctor:Oe?oe:void 0,doctorCopyOutcomeFor:Oe?ie.outcomeFor:void 0}),(0,z.jsxs)(`div`,{className:`section-sep`,children:[(0,z.jsx)(`span`,{className:`section-label`,children:s(`codexAuth.accountPool`)}),(0,z.jsx)(`div`,{className:`sep-line`}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>A(!0),children:[(0,z.jsx)(ne,{width:14}),` `,s(`codexAuth.add`)]})]}),ue&&le&&(0,z.jsx)(To,{onReauth:()=>X(le.id)}),Ce.length===0&&(0,z.jsx)(gt,{title:s(`codexAuth.noPool`)}),(0,z.jsx)(wo,{pool:Ce,activeId:y,accountModeState:t,switchActionLabel:Te,threshold:De,onOpenReset:be,onSwitch:O,onTogglePause:he,pauseUpdatingId:S,pauseBusy:Ee,onPriorityChange:(e,t)=>{ge(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onReauth:X,onEditAlias:me,onRemove:_e,onCopyDoctor:Oe?oe:void 0,doctorCopyOutcomeFor:Oe?ie.outcomeFor:void 0})]}),(0,z.jsx)(no,{apiBase:e,subscribeLoadObserver:g.subscribeLoadObserver,readLastActive:g.readLastActive,onStrategyResolved:u}),(0,z.jsxs)(ro,{t:s,open:j,onToggle:()=>M(e=>!e),children:[l!==null&&(0,z.jsx)(Wa,{threshold:c.threshold,draft:c.draft,strategy:l,hydrated:c.hydrated,saving:c.saving,loadError:c.loadError,feedback:c.feedback,onDraftChange:c.setDraft,onEditingChange:c.setEditing,onCommit:c.commit,onCancel:c.cancel,onToggle:c.toggle,onRetry:()=>{c.retry(),E()}}),o]}),D&&(0,z.jsx)(Eo,{confirm:D,mainEmail:Se?.email,accountModeState:t,switchingId:x,orderBusy:C!==null,onCancel:()=>O(null),onConfirm:()=>{pe(D.id===`__main__`?`__main__`:D.id)}}),U&&(0,z.jsx)(Do,{resetPopup:U,resetConfirm:G,creditDetails:q,creditDetailsLoading:Y,redeeming:te,onClose:()=>{W(null),ee(!1),J(null)},onShowConfirm:()=>ee(!0),onCancelConfirm:()=>ee(!1),onRedeem:()=>{xe(U.id)}}),k&&(0,z.jsx)(Sa,{apiBase:e,reauthAccountId:N??void 0,onClose:de,onAdded:fe})]})}function Fo({apiBase:e,accountCount:t}){let n=Z(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(`80`),[s,c]=(0,_.useState)(`1`),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let t=!1,n=new AbortController;return Promise.resolve().then(()=>fetch(`${e}/api/oauth/accounts/pool?provider=anthropic`,{signal:n.signal})).then(e=>{if(!e.ok)throw Error(`load`);return e.json()}).then(e=>{if(t)return;let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=Ya(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:Ja(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=Ja(r?.strategy??t.strategy),s=Ya(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,z.jsxs)(`div`,{className:`card`,style:{marginTop:12},"aria-busy":x||l,children:[(0,z.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,z.jsxs)(`div`,{style:{flex:1},children:[(0,z.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,z.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,z.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,disabled:S,"aria-pressed":g,"aria-label":n(`anthropicPool.title`),title:n(g?`anthropicPool.on`:`anthropicPool.off`),onClick:()=>{h({enabled:!g,threshold:v,strategy:y,stickyLimit:b})},children:(0,z.jsx)(`span`,{className:`toggle-knob`})})]}),(0,z.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:10,padding:`10px 16px`,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,z.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`label`,{className:`field`,style:{display:`block`,marginTop:12},children:[(0,z.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,z.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,z.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,z.jsx)(eo,{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=Xa(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,z.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}var Io=4e3,Lo=262144,Ro=[],zo=[],Bo=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Vo=new Set([`imported`,`updated`,`failed`,`unsupported`]),Ho={imported:new Set([`imported`]),updated:new Set([`updated`]),failed:new Set([`invalid_record`,`credential_rejected`,`identity_mismatch`,`missing_project`,`persist_failed`]),unsupported:new Set([`unsupported_provider`,`unsupported_format`])};function Uo(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Wo(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Go(e){if(!Uo(e)||Object.keys(e).some(e=>!Bo.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!Wo(t)||!Wo(n)||!Wo(r)||!Wo(i)||!Wo(a)||!Array.isArray(o)||o.length!==t||n+r+i+a!==t)return null;let s={imported:0,updated:0,failed:0,unsupported:0};for(let[e,t]of o.entries()){if(!Uo(t)||Object.keys(t).some(e=>![`index`,`status`,`code`].includes(e)))return null;let n=String(t.status),r=String(t.code);if(t.index!==e||!Vo.has(n)||!Ho[n]?.has(r))return null;s[n]+=1}return s.imported!==n||s.updated!==r||s.failed!==i||s.unsupported!==a?null:{importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a}}function Ko({item:e,apiBase:t,oauth:n,accounts:r=Ro,keys:i=zo,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d}){let f=Z(),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(`idle`),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),O=(0,_.useRef)(null),k=_a();(0,_.useEffect)(()=>{if(r.length===0){D(!1);return}if(!r.some(e=>e.quota==null&&!e.quotaUnavailable)){D(!1);return}D(!0);let e=window.setTimeout(()=>D(!1),Io);return()=>window.clearTimeout(e)},[r]);let A=qi({...e,hasApiKey:e.hasApiKey||i.length>0}),j=A===`oauth-accounts`,M=A===`api-keys`;if(A===`codex-accounts`)return(0,z.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(`pws.availableAccounts`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:f(`pws.availableAccounts`)}),(0,z.jsx)(`div`,{className:`pwi-auth-body`,children:(0,z.jsx)(Po,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!A||!l)return null;let N=c?.provider===e.name?c:null,P=N?.deviceCode??``,F=k.outcomeFor(P),I=f(F===`copied`?`prov.codeCopied`:F===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),L=r.length>0||n?.loggedIn===!0,R=r.find(e=>e.active&&e.needsReauth),B=!!R,V=async()=>{let t=h.trim();if(t){y(!0);try{await l.onAddApiKey(e.name,t)&&(g(``),m(!1))}finally{y(!1)}}},H=async n=>{if(!(!n||b)){x(!0),C(`idle`),T(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>Lo){C(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{C(`invalid`);return}let i=await fetch(`${t}/api/oauth/accounts/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`google-antigravity`,format:`cockpit-tools`,document:r})});if(!i.ok){C(`failed`);return}let a=Go(await i.json().catch(()=>null));if(!a){C(`failed`);return}T(a),C(`complete`);try{await l.onRetryAccounts?.(e.name)}catch{}}catch{C(`failed`)}finally{O.current&&(O.current.value=``),x(!1)}}};return(0,z.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":f(j?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:f(j?`pws.availableAccounts`:`pws.apiKeys`)}),(0,z.jsxs)(`div`,{className:`pwi-auth-body`,children:[j&&(0,z.jsxs)(z.Fragment,{children:[e.name===`anthropic`&&(0,z.jsx)(Fo,{apiBase:t,accountCount:r.length}),e.name===`google-antigravity`&&(0,z.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:f(`pws.cockpitImportDescription`)}),(0,z.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:f(`pws.cockpitImportFileLabel`)}),(0,z.jsx)(`input`,{ref:O,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:b,onChange:e=>{H(e.currentTarget.files?.[0])}})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:b,onClick:()=>O.current?.click(),children:f(b?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,z.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[S===`invalid`&&f(`pws.cockpitImportInvalid`),S===`failed`&&f(`pws.cockpitImportFailed`),S===`complete`&&w&&f(`pws.cockpitImportComplete`,{imported:w.importedCount,updated:w.updatedCount,failed:w.failedCount,unsupported:w.unsupportedCount})]})]}),(0,z.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,z.jsx)(`span`,{className:`pwi-auth-dot ${B?`pwi-auth-dot--warn`:L?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:`pwi-auth-status-text`,children:L?r.length>0?f(`pws.loggedInTitle`):n?.email??f(`pws.loggedInTitle`):n?.error||f(`pws.notLoggedInTitle`)}),(0,z.jsxs)(`span`,{className:`pwi-auth-actions`,children:[R&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,R.id),children:f(`pws.reauthenticate`)}),L?(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:f(`prov.logout`)}):(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,z.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`}),f(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),s&&N&&(0,z.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,z.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,z.jsx)(`div`,{className:`pwi-auth-wait-title`,children:f(`prov.waitingBrowser`)}),N.deviceCode&&(0,z.jsxs)(`div`,{className:`pwi-device-code-wrap`,children:[(0,z.jsx)(`span`,{children:f(`prov.deviceCode`)}),(0,z.jsx)(`code`,{className:`pwi-device-code`,children:N.deviceCode}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>k.copy(P,P),children:(0,z.jsx)(`span`,{"aria-live":`polite`,children:I})})]}),(0,z.jsx)(va,{url:N.url??``}),l.onCancelLogin&&(0,z.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,z.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,z.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),f(`pws.accountsLoading`)]}),a===`error`&&(0,z.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,z.jsx)(`span`,{children:f(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:f(`pws.retryAccounts`)})]}),r.length>0&&(0,z.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=Ji(r,t,f),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||ra(a),u=aa(a),d=ea(t.id),p=ca(f,t.health),m=la(f,e.name,t.id,t.health);return(0,z.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,z.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!u&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${f(`pws.accountCurrent`)}`:``}`,disabled:!!(c||u||o&&!i),children:[(0,z.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,z.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,z.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,z.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${f(`prov.accountId`)}: ${d}`].filter(Boolean).join(` · `)}),m&&(0,z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m}),u&&(0,z.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:f(`pws.healthCooldownHint`)})]}),p&&(0,z.jsx)(`span`,{className:na(a),children:p}),c&&!p&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:f(`pws.reauth`)}),t.active&&(0,z.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)}),i&&(0,z.jsx)(`span`,{className:`badge badge-muted`,children:f(`pws.accountSwitching`)})]}),c&&(0,z.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`)}),(0,z.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,z.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,z.jsx)(oe,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||E&&t.quota==null)&&(0,z.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,z.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:f(`pws.accountQuotaUnavailable`)}):(0,z.jsx)(Ai,{quota:t.quota??null,plan:null,threshold:80,t:f,layout:`stacked`,pending:t.quota==null})})]},t.id)})}),a===`ready`&&L&&r.length===0&&(0,z.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:f(`pws.noAccounts`)}),L&&(0,z.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`)})]}),M&&(0,z.jsxs)(z.Fragment,{children:[i.length>0&&(0,z.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,z.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,z.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,z.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,z.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,z.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,f(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,z.jsx)(`span`,{className:`badge badge-primary`,children:f(`prov.accountActive`)})]}),(0,z.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,z.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,z.jsx)(oe,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),p?(0,z.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,z.jsx)(`input`,{className:`input`,type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:f(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:v}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void V(),disabled:v||!h.trim(),children:f(v?`pws.saving`:`pws.addKey`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m(!1),g(``)},children:f(`common.cancel`)})]}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>m(!0),children:f(`pws.addKey`)})]})]})]})}function qo(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 Jo(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 Yo(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Xo=`https://chatgpt.com/backend-api/codex`;function Zo(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 Qo(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 $o(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Zo(e.baseUrl)!==Xo?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function es(e){return e.id===`openai`}function ts(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function ns(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return e.responsesPath?.trim()&&(t.responsesPath=e.responsesPath.trim()),(e.authMode===`key`||e.authMode===`forward`)&&(t.authMode=e.authMode),e.authMode===`key`&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),e.adapter.trim()===`anthropic`&&e.authMode===`key`&&e.apiKeyTransport===`bearer`&&(t.apiKeyTransport=`bearer`),e.defaultModel.trim()&&(t.defaultModel=e.defaultModel.trim()),e.allowPrivateNetwork&&(t.allowPrivateNetwork=!0),t}function rs(e,t){return es(e)?is(e):{name:t.name.trim(),provider:ns(t)}}function is(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var as=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function os(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 as(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new as(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new as(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(is(i))})).ok)throw new as(`codexAuth.enableOpenaiFailed`)}var ss=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],cs=[];function ls(e){return e===void 0?``:String(e)}function us(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function ds(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function fs(e){let t=Object.entries(e?.models??{}).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.requestsPerMinute??null,t.minIntervalMs??null]);return JSON.stringify([e?.enabled===!0,e?.requestsPerMinute??null,e?.minIntervalMs??null,t])}function ps({item:e,availableModels:t=cs,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Z(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),c=jr(e.name,e),l=c?e.liveModels!==!1:!1,[u,d]=(0,_.useState)(e.adapter),[f,p]=(0,_.useState)(e.baseUrl),[m,h]=(0,_.useState)(e.defaultModel??``),[g,v]=(0,_.useState)(s),[y,b]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[x,S]=(0,_.useState)(e.note??``),[C,w]=(0,_.useState)(e.allowPrivateNetwork??!1),[T,E]=(0,_.useState)(l),[D,O]=(0,_.useState)(!1),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)(e.codexAccountMode??`pool`),[N,P]=(0,_.useState)(!1),[F,I]=(0,_.useState)(null),[L,R]=(0,_.useState)(),[B,V]=(0,_.useState)(n?`loading`:`idle`),[H,U]=(0,_.useState)(()=>`custom`),[W,G]=(0,_.useState)(e.requestPacing?.enabled===!0),[ee,te]=(0,_.useState)(()=>ls(e.requestPacing?.requestsPerMinute)),[K,q]=(0,_.useState)(()=>ls(e.requestPacing?.minIntervalMs)),[J,Y]=(0,_.useState)(()=>({...e.requestPacing?.models??{}})),[ne,re]=(0,_.useState)(``),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)(null);(0,_.useEffect)(()=>{d(e.adapter),p(e.baseUrl),h(e.defaultModel??``),v(String(e.authMode??(e.keyOptional?`local`:`key`))),b(e.apiKeyTransport??`x-api-key`),S(e.note??``),w(e.allowPrivateNetwork??!1),E(l),G(e.requestPacing?.enabled===!0),te(ls(e.requestPacing?.requestsPerMinute)),q(ls(e.requestPacing?.minIntervalMs)),Y({...e.requestPacing?.models??{}}),A(null),I(null),queueMicrotask(()=>U(Jo(L,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,l,e.requestPacing,L]),(0,_.useEffect)(()=>{M(e.codexAccountMode??`pool`)},[e.codexAccountMode]),(0,_.useEffect)(()=>{if(!n)return;let t=!1,r=e.name,i=e.baseUrl;return fetch(`${n}/api/provider-presets`).then(e=>Ct(e)).then(e=>{if(t)return;if(!e){R(void 0),V(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;R(n),V(`ready`),U(Jo(n,i))}).catch(()=>{t||(R(void 0),V(`error`))}),()=>{t=!0}},[n,e.name]),(0,_.useEffect)(()=>{if(!n)return;let t=!0,r=()=>{fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`).then(e=>Ct(e)).then(e=>{t&&e&&le(e)}).catch(()=>void 0)};r();let i=window.setInterval(r,2e3);return()=>{t=!1,window.clearInterval(i)}},[n,e.name]);let ue=(0,_.useMemo)(()=>({enabled:W,...us(ee)===void 0?{}:{requestsPerMinute:us(ee)},...ds(K)===void 0?{}:{minIntervalMs:ds(K)},...Object.keys(J).length>0?{models:J}:{}}),[K,W,J,ee]),X=u.trim()!==e.adapter||f.trim()!==e.baseUrl||m.trim()!==(e.defaultModel??``)||g!==String(e.authMode??(e.keyOptional?`local`:`key`))||u.trim()===`anthropic`&&g===`key`&&y!==(e.apiKeyTransport??`x-api-key`)||x.trim()!==(e.note??``)||C!==(e.allowPrivateNetwork??!1)||T!==l,de=fs(ue)!==fs(e.requestPacing),fe=X||de;(0,_.useEffect)(()=>(i?.(fe),()=>i?.(!1)),[fe,i]);let pe=(0,_.useMemo)(()=>{let n=new Set(t);return m.trim()&&n.add(m.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,m,e.defaultModel]),me=(0,_.useMemo)(()=>{let e=[...ss];return u&&!e.includes(u)&&e.unshift(u),e},[u]),he=mn(e.name),ge=B===`ready`&&!!(L&&L.length>0),ve=u.trim()===`anthropic`&&g===`key`,ye=e.name===`openai`?$o(e):`invalid`,be=ye===`ready`||ye===`disabled`,xe=he&&B!==`error`,Se=async()=>{if(!r)return A({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;if(N)return!1;let t=ge?Yo(L,H,f):f.trim();if(!u.trim()||!t)return A({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;O(!0),A(null);try{if(W&&!ue.requestsPerMinute&&!ue.minIntervalMs&&!ue.models)return A({ok:!1,text:o(`pws.pacingRuleRequired`)}),!1;let n=de&&!X,i=n?{requestPacing:ue}:{adapter:u.trim(),baseUrl:t,defaultModel:m.trim(),authMode:g,note:x.trim(),allowPrivateNetwork:C,...de?{requestPacing:ue}:{}};n||(c&&T!==(e.liveModels!==!1)&&(i.liveModels=T),ve?i.apiKeyTransport=y:e.apiKeyTransport!==void 0&&(i.apiKeyTransport=``));let a=await r(e.name,i);return A(a.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:a.error||o(`prov.saveFailed`)}),a.ok}finally{O(!1)}},Ce=(0,_.useRef)(Se);(0,_.useEffect)(()=>{Ce.current=Se}),(0,_.useEffect)(()=>{if(a)return a(()=>Ce.current()),()=>a(null)},[a]);let we=async e=>{if(!(N||D||e===j)){if(!r){I({ok:!1,text:o(`pws.updatesUnavailable`)});return}P(!0),I(null);try{let t=await r(`openai`,{codexAccountMode:e});t.ok?(M(e),I({ok:!0,text:o(`pws.accountModeSaved`)})):I({ok:!1,text:t.error||o(`pws.accountModeFailed`)})}catch{I({ok:!1,text:o(`pws.accountModeFailed`)})}finally{P(!1)}}},Te=()=>{d(e.adapter),p(e.baseUrl),h(e.defaultModel??``),v(s),b(e.apiKeyTransport??`x-api-key`),S(e.note??``),w(e.allowPrivateNetwork??!1),E(l),A(null),G(e.requestPacing?.enabled===!0),te(ls(e.requestPacing?.requestsPerMinute)),q(ls(e.requestPacing?.minIntervalMs)),Y({...e.requestPacing?.models??{}}),U(Jo(L,e.baseUrl))},Ee=(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,z.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,z.jsx)(_e,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,z.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),he?(0,z.jsx)(`input`,{className:`input`,value:u,readOnly:!0,disabled:!0}):(0,z.jsx)(`select`,{className:`input`,value:u,onChange:e=>d(e.target.value),children:me.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))})]}),ge?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,z.jsx)(`select`,{className:`input`,value:H,onChange:e=>{let t=e.target.value;U(t),p(qo(L,t,f))},children:L.map(e=>(0,z.jsx)(`option`,{value:e.id,children:Ee(e.id,e.label)},e.id))})]}),H===`custom`&&(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,z.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,z.jsx)(`input`,{className:`input`,value:f,onChange:e=>p(e.target.value),readOnly:xe,disabled:xe})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),pe.length>0?(0,z.jsxs)(`select`,{className:`input`,value:m,onChange:e=>h(e.target.value),children:[(0,z.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),pe.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]}):(0,z.jsx)(`input`,{className:`input`,value:m,onChange:e=>h(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),he?(0,z.jsx)(`input`,{className:`input`,value:oi(e,o),readOnly:!0,disabled:!0}):(0,z.jsxs)(`select`,{className:`input`,value:g,onChange:e=>v(e.target.value),children:[(0,z.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,z.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,z.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,z.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),be&&(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`codexAuth.accountModeTitle`)}),(0,z.jsxs)(`select`,{className:`input`,value:j,disabled:N||D,onChange:e=>{let t=e.target.value;if(t!==j){if(!window.confirm(o(`pws.accountModeConfirm`))){e.target.value=j;return}we(t)}},children:[(0,z.jsx)(`option`,{value:`pool`,children:o(`codexAuth.accountModePool`)}),(0,z.jsx)(`option`,{value:`direct`,children:o(`codexAuth.accountModeDirect`)})]}),(0,z.jsx)(`span`,{className:`pwi-settings-hint`,children:o(j===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),N&&(0,z.jsx)(`span`,{className:`muted text-label`,children:o(`pws.accountSwitching`)}),F&&(0,z.jsx)(`span`,{role:F.ok?`status`:`alert`,className:F.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:F.text})]}),ve&&(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,z.jsxs)(`select`,{className:`input`,value:y,onChange:e=>b(e.target.value),children:[(0,z.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,z.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,z.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:x,onChange:e=>S(e.target.value),rows:2})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:T,disabled:!c,onChange:e=>E(e.target.checked)}),(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,z.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),(0,z.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,z.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h3`,{id:`pwi-pacing-title`,children:o(`pws.pacingTitle`)}),(0,z.jsx)(`p`,{children:o(`pws.pacingDesc`)})]}),(0,z.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:W,onChange:e=>G(e.target.checked)}),` `,o(`pws.pacingEnabled`)]})]}),(0,z.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ee,onChange:e=>te(e.target.value),placeholder:`38`})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:K,onChange:e=>q(e.target.value),placeholder:`1600`})]})]}),(0,z.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.pacingSlowerWins`)}),(0,z.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:ce?.queued??0}),` `,o(`pws.pacingQueued`)]}),(0,z.jsxs)(`span`,{children:[(0,z.jsxs)(`strong`,{children:[ce?.nextSlotInMs??0,` ms`]}),` `,o(`pws.pacingNextSlot`)]}),(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:ce?.lastModelId??o(`pws.pacingNone`)}),` `,o(`pws.pacingLastModel`)]})]}),(0,z.jsx)(`h4`,{children:o(`pws.pacingModelOverrides`)}),(0,z.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingModel`)}),(0,z.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:ne,onChange:e=>re(e.target.value)}),(0,z.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,z.jsx)(`option`,{value:e},e))})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ie,onChange:e=>ae(e.target.value)})]}),(0,z.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,z.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:oe,onChange:e=>se(e.target.value)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=ne.trim(),t=us(ie),n=ds(oe);!e||t===void 0&&n===void 0||(Y(r=>({...r,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n}}})),re(``),ae(``),se(``))},children:o(`pws.pacingAdd`)})]}),Object.entries(J).length>0&&(0,z.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(J).map(([e,t])=>(0,z.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsxs)(`span`,{children:[t.requestsPerMinute===void 0?``:`${t.requestsPerMinute} ${o(`pws.pacingRpmUnit`)}`,t.requestsPerMinute!==void 0&&t.minIntervalMs!==void 0?` · `:``,t.minIntervalMs===void 0?``:`${t.minIntervalMs} ms`]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Y(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":o(`pws.pacingRemoveModel`,{model:e}),children:o(`pws.pacingRemove`)})]},e))})]}),fe&&(0,z.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,z.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,z.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Te,disabled:D,children:o(`pws.discardSettings`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Se(),disabled:D||N,children:o(D?`pws.saving`:`pws.saveSettings`)})]})]}),k&&(0,z.jsx)(`div`,{role:k.ok?`status`:`alert`,className:k.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:k.text})]})}function ms({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Z();return(0,z.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,z.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,z.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,z.jsxs)(`div`,{className:`dialog-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function hs({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Z();return(0,z.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,z.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,z.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,z.jsxs)(`div`,{className:`dialog-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function gs({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,accountsFocusToken:g=0,accountsFocusProvider:v=null,switchingAccountId:y,keys:b,busyProvider:x,loginHint:S,authHandlers:C,onCodexActiveNeedsReauthChange:w,codexController:T,onUpdateProvider:E,isDefault:D,onRemoveProvider:O,onSetDisabled:k,onSetDefault:A}){let j=Z(),[M,N]=(0,_.useState)(`overview`),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,B]=(0,_.useState)(!1),V=(0,_.useRef)(null),[H,U]=(0,_.useState)(0),W=(0,_.useCallback)(e=>{V.current=e},[]),G=e.disabled===!0,ee=(0,_.useMemo)(()=>Ir(e),[e]),te=(0,_.useMemo)(()=>Ur(e),[e]),K=(0,_.useMemo)(()=>qi(e),[e]),q=v===e.name?g:0,J=JSON.stringify([T?.activeId??``,m?.find(e=>e.active)?.id??``,b?.find(e=>e.active)?.id??``,p?.loggedIn===void 0?``:String(p.loggedIn),p?.needsReauth===void 0?``:String(p.needsReauth),u??``]),Y=(0,_.useMemo)(()=>[{id:`overview`,label:j(`pws.tab.overview`)},{id:`models`,label:j(`pws.tab.models`)},{id:`usage`,label:j(`pws.tab.usage`)},...K?[{id:`accounts`,label:j(K===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:j(`pws.tab.settings`)}],[K,j]),ne=(0,_.useCallback)(e=>{if(P&&M===`settings`&&e!==`settings`){L(e);return}N(e)},[M,P]);q!==H&&!(q&&!K)&&(U(q),q&&K&&(P&&M===`settings`?L(`accounts`):N(`accounts`)));let re=(0,_.useCallback)(()=>{if(P&&M===`settings`){L(`deselect`);return}d()},[P,M,d]),ie=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%Y.length;else if(e.key===`ArrowLeft`)n=(t-1+Y.length)%Y.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=Y.length-1;else return;e.preventDefault(),ne(Y[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ne,Y]),ae=`pws-tab-${M}`,se=`pws-panel-${M}`;return(0,z.jsxs)(`div`,{className:`pws-detail`,children:[(0,z.jsx)(`div`,{className:`pws-detail-head`,children:(0,z.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:re,children:[(0,z.jsx)(fe,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),j(`pws.allProviders`)]})}),(0,z.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,z.jsx)(ci,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,z.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,z.jsxs)(`h2`,{className:`pws-detail-title`,children:[pn(e.name,j),te&&(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:j(`modal.badge.local`)}),!te&&ee&&(0,z.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:j(`modal.badge.free`)})]})}),(0,z.jsxs)(`div`,{className:`pws-detail-actions`,children:[!D&&!G&&A&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(e.name),children:j(`prov.setDefault`)}),O&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>O(e.name),"aria-label":j(`pws.removeConfirmTitle`),title:j(`pws.removeConfirmTitle`),children:(0,z.jsx)(oe,{style:{width:15,height:15},"aria-hidden":`true`})}),k&&(0,z.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,z.jsx)(`span`,{className:`pws-detail-toggle-label`,children:j(`pws.enabledLabel`)}),(0,z.jsx)(pt,{on:!G,onClick:()=>k(e.name,!G),disabled:D,label:j(`pws.enabledLabel`)})]})]})]}),(0,z.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:Y.map((e,t)=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":M===e.id,tabIndex:M===e.id?0:-1,className:`pws-detail-tab${M===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ne(e.id),onKeyDown:e=>ie(e,t),children:e.label},e.id))}),(0,z.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:se,"aria-labelledby":ae,tabIndex:0,children:[M===`overview`&&(0,z.jsx)(Yi,{item:e,apiBase:f,connectionIdentity:J,usageTotals:t,quotaReport:r,oauthEmail:u,oauth:p,onEditSettings:()=>ne(`settings`),onViewUsage:()=>ne(`usage`),onUpdateProvider:E,reauthBusy:x===e.name,onCancelLogin:C?.onCancelLogin?()=>void C.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);C?.onReauth(e.name,n?.id);return}ne(`accounts`)}:void 0}),M===`models`&&(0,z.jsx)(Zi,{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:K?()=>ne(`accounts`):void 0},e.name),M===`usage`&&(0,z.jsx)(Qi,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),M===`accounts`&&(0,z.jsx)(Ko,{item:e,apiBase:f,oauth:p,accounts:m,keys:b,accountLoadState:h,switchingAccountId:y,busy:x===e.name,loginHint:S,authHandlers:C,onCodexActiveNeedsReauthChange:w,codexController:T}),M===`settings`&&(0,z.jsx)(ps,{item:e,apiBase:f,availableModels:i,onUpdateProvider:E,onDirtyChange:F,onRegisterSave:W},e.name)]}),I&&(0,z.jsx)(hs,{saving:R,onCancel:()=>{R||L(null)},onDiscard:()=>{if(R)return;let e=I;L(null),F(!1),e===`deselect`?d():N(e)},onSave:()=>{(async()=>{if(!R){B(!0);try{if(!(await V.current?.()??!1))return;let e=I;L(null),F(!1),e===`deselect`?d():e&&N(e)}finally{B(!1)}}})()}})]})}var _s=new Set([`anthropic`,`google-antigravity`]),vs=new Set([`github-copilot`,`cursor`]);function ys(e){let t=e.trim().toLowerCase();return _s.has(t)?`high`:vs.has(t)?`elevated`:null}function bs(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function xs(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function Ss(e,t=!1){let n={};for(let[t,r]of Object.entries(e))ia(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function Cs(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||(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)}"a=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||(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=Ji(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})});if(i.ok)a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),A(Object.keys(y)),c(!0);else{let e=await i.json().catch(()=>({}));a(e.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})});if(!r.ok){let e=await r.json().catch(()=>({}));return a(e.error||n(`prov.keyAddFail`),!1),!1}return a(n(`prov.keyAdded`,{name:e}),!0),S(null),await Promise.all([A(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),o(),c(!0)]),!0}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){let e=await l.json().catch(()=>({}));a(e.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=Ji(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)(()=>Ss(u,l),[u,l])}}function ws(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)});if(!n.ok){let e=await n.json().catch(()=>({}));return r(e.error||s(`prov.saveFailed`),!1),!1}return 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}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 Ts={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},Es=e=>Ts[e]??e;function Ds({apiBase:e,t,aliveRef:n,accountSets:r,setAccountSets:i,setBusy:a,setStatus:o,setLoginInfo:s,setOauthStatus:c,notify:l,fetchConfig:u,fetchOauth:d,fetchAccountSets:f,fetchProviderQuotas:p,bumpModelsRefresh:m,onLoginSettled:h}){let g=(0,_.useRef)(null);g.current===null&&(g.current=new Map);let v=(0,_.useCallback)(e=>{let t=(g.current.get(e)??0)+1;return g.current.set(e,t),t},[]);return{cancelLoginOAuth:(0,_.useCallback)(async r=>{let i=v(r);try{await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:r})})}catch{}n.current&&(g.current.get(r)===i&&(a(e=>e===r?null:e),s(e=>e?.provider===r?null:e)),l(t(`prov.loginCancelled`,{provider:Es(r)}),!1))},[n,e,v,l,a,s,t]),loginOAuth:async(d,_=!1,y)=>{let b=v(d),x=y?.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,..._||x?{addAccount:!0}:{},...x?{accountId:x,reauth:!0}:{}})});if(g.current.get(d)!==b||!n.current)return;if(!a.ok){l((await a.json().catch(()=>({}))).error||t(`prov.loginFailStart`,{provider:Es(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 v=r[d]?.accounts.length??0,y=!1;for(let a=0;a<150&&n.current&&g.current.get(d)===b;a++){if(await new Promise(e=>setTimeout(e,2e3)),g.current.get(d)!==b||!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${d}`).catch(()=>null),o=a?await Ct(a)??null:null;if(!o)continue;if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:Es(d)}):t(`prov.loginError`,{provider:Es(d),error:o.error}),!1),s(null),y=!0;break}let S=o.accounts?.length??0;if(_||x?S>v||o.done===!0:o.loggedIn||o.done===!0){c(e=>({...e,[d]:o}));let e=x?o.accounts?.find(e=>e.id===x):o.accounts?.find(e=>e.active)??o.accounts?.find(e=>e.id===o.activeAccountId);if(x&&!e){l(t(`prov.loginError`,{provider:Es(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),y=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:Es(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),y=!0;break}if(o.accounts){let e=o.accounts.find(e=>e.active)?.id??null;i(t=>({...t,[d]:{activeAccountId:o.activeAccountId??e,accounts:o.accounts}}))}s(null),h?.(d);let a=Object.keys(r);if(await f(new Set(a).has(d)?a:[...a,d]),!n.current||g.current.get(d)!==b)return;_&&!x&&S<=v?l(t(`prov.loginSameAccount`,{provider:Es(d)}),!1):l(t(`prov.loginOk`,{provider:Es(d),cmd:`ocx sync`}),!0),u(),p(!0),m(),y=!0;break}}!y&&g.current.get(d)===b&&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:Es(d)}),!1),s(null))}catch{g.current.get(d)===b&&l(t(`prov.loginRequestFail`,{provider:Es(d)}),!1)}finally{n.current&&g.current.get(d)===b&&a(null)}},logoutOAuth:async n=>{v(n),a(e=>e===n?null:e),s(e=>e?.provider===n?null:e);try{if(!(await fetch(`${e}/api/oauth/logout?provider=${encodeURIComponent(n)}`,{method:`POST`})).ok){l(t(`prov.logoutFail`,{provider:Es(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:Es(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:Es(n)}),!1)}}}}async function Os(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function ks(e,t,n){switch(e.code){case`last_provider`:return t(`prov.removeLastProvider`);case`provider_has_dependent_combos`:return t(`prov.removeHasDependentCombos`,{combos:(Array.isArray(e.combos)?e.combos.filter(e=>typeof e==`string`).join(`, `):``)||`—`});case`default_provider_disabled`:return t(`prov.defaultDisabled`);default:return typeof e.error==`string`&&e.error.trim()?e.error.trim():n}}function As({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,refreshCodexAccount:u}){let d=(0,_.useCallback)(async e=>{a(e)},[a]),f=(0,_.useCallback)(async u=>{let d=u;if(!d||n.current)return;n.current=!0,a(null);let f=t(`prov.removeFail`,{name:d});try{let n=await fetch(`${e}/api/providers?name=${encodeURIComponent(d)}`,{method:`DELETE`});if(n.ok){let e=await n.json().catch(()=>({})),a=typeof e.defaultProvider==`string`?e.defaultProvider:null;o(a?t(`prov.removedDefault`,{name:d,defaultProvider:a}):t(`prov.removed`,{name:d}),!0),r===d&&i(null),s(),c(),l(!0)}else o(ks(await n.json().catch(()=>({})),t,f),!1)}catch{o(f,!1)}finally{n.current=!1}},[e,s,c,l,o,n,a,i,t,r]),p=(0,_.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 Os(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),m=(0,_.useCallback)(async(n,r)=>{try{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok)return{ok:!1,error:await Os(i,t(`prov.updateFail`))};if(await s(),Object.hasOwn(r,`codexAccountMode`)){let e=[l(!0)];u&&e.push(Promise.resolve(u())),await Promise.all(e)}return{ok:!0}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,l,u,t]);return{removeProvider:d,confirmRemoveProvider:f,setProviderDisabled:p,setDefaultProvider:(0,_.useCallback)(async n=>{try{let r=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({setDefault:!0})});return r.ok?(o(t(`prov.setDefaultSuccess`,{name:n}),!0),await s(),!0):(o(ks(await r.json().catch(()=>({})),t,t(`prov.setDefaultFail`,{name:n})),!1),!1)}catch{return o(t(`prov.setDefaultFail`,{name:n}),!1),!1}},[e,s,o,t]),updateProvider:m}}function js({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await St(await fetch(`${e}/api/config`));n(t??null),s&&t&&Jn(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await St(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 Ct(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function Ms({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Z(),a=(0,_.useId)(),o=(0,_.useId)(),s=(0,_.useRef)(null),c=(0,_.useRef)(!1),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(!1),p=ys(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`:xs(p),v=h===`anthropic`||h===`google-antigravity`;return(0,z.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,z.jsx)(`h3`,{id:a,children:i(bs(p),{provider:t})}),(0,z.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,z.jsx)(se,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,z.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,z.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,z.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,z.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function Ns(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function Ps(e){return Lr(e.id,Ns(e))}function Fs(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[Ps(n)].push(n);return t}function Is(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}var Ls={},Rs=[],zs={};function Bs({presets:e,usageRank:t=Ls,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=Rs,accountStatus:s=zs,busyProvider:c=null,onLogin:l,onCancelLogin:u,onLogout:d,onManage:f}){let p=Z(),[m,h]=(0,_.useState)(r),[g,v]=(0,_.useState)(``),y=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),b=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return y.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)})},[y,t]),x=(0,_.useMemo)(()=>Fs(b),[b])[m],S=(0,_.useMemo)(()=>Is(x,g),[x,g]),C=e=>{let t=e.codexAccountMode===`direct`?(0,z.jsx)(`span`,{className:`badge badge-green`,children:p(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,z.jsx)(`span`,{className:`badge badge-accent`,children:p(`modal.badge.pool`)}):e.auth===`oauth`?(0,z.jsx)(`span`,{className:`badge badge-accent`,children:p(`modal.badge.oauth`)}):e.auth===`forward`?(0,z.jsx)(`span`,{className:`badge badge-green`,children:p(`modal.badge.codexLogin`)}):e.auth===`local`?(0,z.jsx)(`span`,{className:`badge badge-amber`,children:p(`modal.badge.local`)}):e.keyOptional?null:(0,z.jsx)(`span`,{className:`badge badge-muted`,children:p(`modal.badge.apiKey`)}),n=(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,z.jsx)(`span`,{className:`badge badge-green`,children:p(`modal.badge.free`)}):null;return(0,z.jsxs)(z.Fragment,{children:[n,t]})};return(0,z.jsxs)(`div`,{className:`provider-catalog`,children:[(0,z.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":m===e,className:`provider-catalog-tab${m===e?` active`:``}`,onClick:()=>{h(e),v(``)},children:p(e===`accounts`?`modal.tab.accounts`:e===`free`?`modal.tab.free`:`modal.tab.paid`)},e))}),m===`accounts`&&(0,z.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:p(`modal.accountsHint`)}),(0,z.jsx)(`input`,{className:`input provider-catalog-search`,value:g,onChange:e=>v(e.target.value),placeholder:p(`modal.search`)}),(0,z.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&S.length===0&&(0,z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:p(`modal.catalogLoading`)}),m!==`accounts`&&S.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`title`,children:e.label}),(0,z.jsxs)(`div`,{className:`sub`,children:[(0,z.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,z.jsx)(`div`,{className:`provider-catalog-badges`,children:C(e)})]},e.id)),m!==`accounts`&&!n&&S.length===0&&(0,z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:p(`modal.noMatch`)}),m===`accounts`&&o.map(e=>{let t=s[e.id],n=c===e.id,r=!!t?.loggedIn,i=r?t?.email??e.statusLabel??p(`modal.accountLoggedIn`):t?.error??e.statusLabel??p(`modal.accountLoggedOut`);return(0,z.jsxs)(`div`,{className:`list-row provider-catalog-account-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`title`,children:e.label}),(0,z.jsx)(`div`,{className:`sub`,children:i})]}),(0,z.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,z.jsxs)(z.Fragment,{children:[r&&(0,z.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-auth`,children:p(`modal.accountManage`)}),l&&(0,z.jsx)(`button`,{type:`button`,className:r?`btn btn-ghost`:`btn btn-primary`,disabled:n,onClick:()=>{n||l(e.id)},children:p(n?`codexAuth.enablingOpenai`:r?`modal.accountAdd`:`modal.accountLogin`)})]}):r?(0,z.jsxs)(z.Fragment,{children:[f&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>f(e.id),children:p(`modal.accountManage`)}),l&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:n,onClick:()=>{n||l(e.id,!0)},children:p(n?`prov.waitingBrowser`:`modal.accountAdd`)}),n&&u&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:p(`common.cancel`)}),d&&!n&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(e.id),children:p(`modal.accountLogout`)})]}):n?u&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(e.id),children:p(`common.cancel`)}):l&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>l(e.id),children:p(`modal.accountLogin`)})})]},e.id)}),m===`accounts`&&o.length===0&&!n&&(0,z.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:p(`modal.noMatch`)})]}),(0,z.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,z.jsx)(`div`,{style:{flex:1}}),m!==`accounts`&&(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:p(`modal.notListed`)})]})]})}function Vs({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,manualCode:o,manualCodeBusy:s,manualCodeMsg:c,manualCodeOk:l,onRequestLogin:u,onUseApiKeyInstead:d,onManualCodeChange:f,onSubmitManualCode:p,onBack:m}){let h=Z();return(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,z.jsx)(`div`,{className:`muted text-control`,children:e.note??h(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>u(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,z.jsx)(_e,{}),n?h(`modal.waitingBrowser`):h(`modal.logInWith`,{label:e.label})]}):(0,z.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:h(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,z.jsx)(va,{url:a}),n&&(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[(0,z.jsx)(`div`,{className:`muted text-label`,children:h(`prov.pasteRedirectHint`)}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8},children:[(0,z.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,z.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,z.jsx)(`div`,{className:`text-label`,style:{color:l?`var(--accent-hover)`:`var(--amber)`},children:c})]}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:d,children:h(`modal.useApiKeyInstead`)}),(0,z.jsx)(`div`,{style:{flex:1}}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}function Hs({label:e,children:t}){return(0,z.jsxs)(`label`,{style:{display:`block`},children:[(0,z.jsx)(`span`,{className:`field-label`,children:e}),t]})}function Us({preset:e,form:t,endpointChoice:n,error:r,saving:i,dup:a,isCustom:o,isLocal:s,isReservedForward:c,presetDescription:l,onFormChange:u,onEndpointChoiceChange:d,onSubmit:f,onUseOauthLogin:p,onBack:m}){let h=Z();return(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,z.jsxs)(`details`,{className:`setup-guide`,children:[(0,z.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,z.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,z.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,z.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,z.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,z.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,z.jsx)(Hs,{label:h(`modal.providerName`),children:(0,z.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Hs,{label:h(`modal.adapter`),children:(0,z.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,z.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Hs,{label:h(`modal.endpoint`),children:(0,z.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:qo(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,z.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,z.jsx)(Hs,{label:h(`modal.baseUrl`),children:(0,z.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,z.jsx)(Hs,{label:h(`modal.baseUrl`),children:(0,z.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,z.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,z.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,z.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,z.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,z.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):e.keyOptional?(0,z.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,z.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,z.jsxs)(z.Fragment,{children:[e.dashboardUrl&&(0,z.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,z.jsx)(ge,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,z.jsx)(he,{style:{width:13,height:13}})]}),(0,z.jsx)(Hs,{label:h(`modal.apiKey`),children:(0,z.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,z.jsx)(Hs,{label:h(`modal.apiKeyTransport`),children:(0,z.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,z.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,z.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,z.jsx)(Hs,{label:h(`modal.defaultModel`),children:(0,z.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,z.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,z.jsx)(`div`,{style:{flex:1}}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Ws=2e3;function Gs({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,Ws)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await Ct(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 Ks(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 qs(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 Js({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,onAccountManage:f,onOpen:p}){let m=Z(),h=(0,_.useMemo)(()=>[{id:`custom`,label:m(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[m]),[g,v]=(0,_.useReducer)(qs,a,e=>Ks(e,m(`modal.customProvider`))),y=(0,_.useRef)(!0),b=(0,_.useRef)(null),x=(0,_.useRef)(null),S=I(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),C=I(`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}),w=I(mr(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()}),T=S.data??[],E=C.data??h,D=C.loading,O=Object.fromEntries((w.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:k,form:A,saving:j,error:M,oauthBusy:N,oauthMsg:P,oauthMsgTone:F,oauthUrl:L,oauthUrlProvider:R,manualCode:B,manualCodeBusy:V,manualCodeMsg:H,manualCodeOk:U,endpointChoice:W,oauthTosPending:G}=g;(0,_.useEffect)(()=>{y.current=!0,b.current=document.activeElement,p?.();let e=x.current;if(e){let t=e.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);t&&t.focus()}return()=>{y.current=!1,b.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!G&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,G]);let ee=e=>{let t=ts(e);return t?m(t):e.note},te=e=>{let t=Jo(e.baseUrlChoices,e.baseUrl);v({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?qo(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},K=async()=>{if(!A)return;let t=k?es(k):!1,n=k?.baseUrlChoices?.length?Yo(k.baseUrlChoices,W,A.baseUrl):A.baseUrl.trim();if(!t&&!A.name.trim()){v({type:`set-error`,error:m(`modal.nameRequired`)});return}if(!t&&!n){v({type:`set-error`,error:m(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){v({type:`set-error`,error:m(`modal.baseUrlPlaceholderError`)});return}let i={...A,baseUrl:n},a;try{a=rs(k??{id:`custom`},i)}catch{v({type:`set-error`,error:m(`modal.invalidPreset`)});return}v({type:`set-saving`,saving:!0}),v({type:`set-error`,error:``});try{let t=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(!t.ok){let e=await t.json().catch(()=>({}));v({type:`set-error`,error:e.error||m(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{v({type:`set-error`,error:m(`modal.networkError`)})}finally{v({type:`set-saving`,saving:!1})}},{loginOAuth:q,submitManualCode:J}=Gs({apiBase:e,t:m,aliveRef:y,onAdded:r}),ne={setOauthBusy:e=>v({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>v({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>v({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t)=>v({type:`set-oauth-url`,url:e,providerId:t}),setManualCode:e=>v({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>v({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>v({type:`set-manual-code-msg`,msg:H,ok:e})},re=A?t.includes(A.name.trim())&&A.name.trim()!==``:!1,ie=e=>{if(!N){if(ys(e)){v({type:`set-oauth-tos-pending`,providerId:e});return}q(e,ne)}},ae=e=>{J(e,B,V,{setManualCodeBusy:e=>v({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>v({type:`set-manual-code`,code:e}),setManualCodeOk:e=>v({type:`set-manual-code-msg`,msg:H,ok:e}),setManualCodeMsg:e=>v({type:`set-manual-code-msg`,msg:e})})},oe=k?.id===`custom`,se=A?.authMode===`local`,ce=k?es(k):!1;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":m(`modal.add`),className:`modal-overlay`,children:(0,z.jsxs)(`div`,{ref:x,className:`modal-card`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:k?m(`modal.addNamed`,{label:k.label}):m(`modal.add`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":m(`common.close`),onClick:n,children:(0,z.jsx)(Y,{})})]}),k?A&&(k.auth===`oauth`&&A.authMode===`oauth`?(0,z.jsx)(Vs,{preset:k,oauthSupported:T,oauthBusy:N,oauthMsg:P,oauthMsgTone:F,oauthUrl:R===k.oauthProvider?L:``,manualCode:B,manualCodeBusy:V,manualCodeMsg:H,manualCodeOk:U,onRequestLogin:ie,onUseApiKeyInstead:()=>{v({type:`use-api-key-instead`,form:{...A,authMode:`key`}})},onManualCodeChange:e=>v({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{ae(e)},onBack:()=>v({type:`back`})}):(0,z.jsx)(Us,{preset:k,form:A,endpointChoice:W,error:M,saving:j,dup:re,isCustom:oe,isLocal:se,isReservedForward:ce,presetDescription:ee,onFormChange:e=>v({type:`set-form`,form:e}),onEndpointChoiceChange:e=>v({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{K()},onUseOauthLogin:()=>v({type:`use-oauth-login`,form:{...A,authMode:`oauth`}}),onBack:()=>v({type:`back`})})):(0,z.jsx)(Bs,{presets:E,usageRank:O,presetsLoading:D,initialTier:i,onSelectPreset:e=>te(e),onSelectCustom:()=>te(h[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:l,onCancelLogin:u,onLogout:d,onManage:f})]})}),G&&(0,z.jsx)(Ms,{providerId:G,providerLabel:k?.label??G,onCancel:()=>v({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=G;e&&(v({type:`set-oauth-tos-pending`,providerId:null}),q(e,ne))}},G)]})}function Ys({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,removeConfirmName:s,removeDefaultProvider:c,codexLoginOpen:l,jsonLeaveOpen:u,jsonSaving:d,oauthTosPending:f,onCloseAdd:p,onAdded:m,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onAccountManage:v,onOpenAdd:y,onCloseCodexLogin:b,onCodexAdded:x,onCancelRemove:S,onConfirmRemove:C,onCancelJsonLeave:w,onDiscardJson:T,onSaveJson:E,onCancelOauthTos:D,onContinueOauthTos:O}){return(0,z.jsxs)(z.Fragment,{children:[n&&(0,z.jsx)(Js,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:p,onAdded:m,accountRows:a,accountStatus:o,accountBusy:i,onAccountLogin:h,onAccountCancelLogin:g,onAccountLogout:_,onAccountManage:v,onOpen:y}),l&&(0,z.jsx)(Sa,{apiBase:e,onClose:b,onAdded:x}),s&&(0,z.jsx)(ms,{providerName:s,defaultProviderName:c,onCancel:S,onConfirm:C}),u&&w&&T&&E&&(0,z.jsx)(hs,{saving:d??!1,onCancel:w,onDiscard:T,onSave:E}),f&&(0,z.jsx)(Ms,{providerId:f.provider,providerLabel:Es(f.provider),onCancel:D,onContinue:O},`${f.provider}:${f.addAccount?`add`:`login`}`)]})}function Xs(e,t,n){return[...Qo(e.providers).map(e=>({id:e,label:pn(e,n),kind:`codex`,href:`#codex-auth`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:Es(e),kind:`oauth`}))]}function Zs(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 Qs({apiBase:e}){let t=Z(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>qn(n)),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(`err`),[p,m]=(0,_.useState)(0),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)({}),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(0),[P,F]=(0,_.useState)(null),[L,R]=(0,_.useState)({token:0,provider:null}),B=(0,_.useRef)(!0),V=(0,_.useRef)(null),H=(0,_.useRef)(!1),U=(0,_.useCallback)((e,t=!0)=>{c(e),u(t),f(t?`ok`:`err`),m(e=>e+1)},[]),W=(0,_.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),G=(0,_.useCallback)(e=>{if(e.catalogRefreshPending){c(t(`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}U(t(`codexAuth.accountAdded`),!0)},[U,t]);(0,_.useEffect)(()=>(B.current=!0,()=>{B.current=!1}),[]),(0,_.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(W,4500);return()=>window.clearTimeout(e)},[s,l,p,W]);let ee=(0,_.useCallback)(e=>{o(!1),D(null),T(e),R(t=>({token:t.token+1,provider:e}))},[]);I(`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}),I(mr(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()});let[te,K]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:q,fetchOauth:J,fetchProviderQuotas:Y}=js({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:y,notify:U,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{K(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),re=Ba(e),ie=re.activeNeedsReauth,ae=(0,_.useMemo)(()=>{let e=re.accounts;if(e.length===0&&re.loadState===`loading`)return v;let t=e.find(e=>e.isMain)??e[0],n=!!t&&!!t.email&&t.email!==`Codex App login`,r=e.some(e=>!e.isMain&&(e.hasCredential||e.email)),i=n||r,a=n?t?.email:e.find(e=>!e.isMain&&e.email)?.email??void 0;return{...v,openai:{loggedIn:i,...a?{email:a}:{},...ie?{needsReauth:!0}:{}}}},[v,re.accounts,re.loadState,ie]),{accountSets:oe,setAccountSets:se,accountLoadStates:ce,switchingAccount:le,keyPools:ue,fetchAccountSets:X,switchAccount:de,switchApiKey:fe,removeApiKey:pe,addApiKeyValue:me,editCredentialAlias:he,removeAccount:ge,activeAccountNeedsReauth:_e}=Cs({apiBase:e,t,config:r,oauthStatus:ae,aliveRef:B,notify:U,fetchConfig:q,fetchOauth:J,fetchProviderQuotas:Y,codexActiveNeedsReauth:ie}),{draft:ve,setDraft:ye,jsonEditorOpen:be,jsonSaving:xe,jsonLeaveOpen:Se,saveConfig:Ce,openJsonEditor:we,discardJsonEditor:Te,requestCloseJsonEditor:Ee,restoreJsonEditor:De,jsonIsDirty:Oe,setJsonLeaveOpen:ke}=ws({apiBase:e,config:r,notify:U,fetchConfig:q,fetchProviderQuotas:Y,onSaved:()=>N(e=>e+1),t});(0,_.useEffect)(()=>{V.current!==e&&(V.current=e,Promise.resolve().then(()=>{q(),J()}))},[e,q,J]);let Ae=()=>N(e=>e+1),{cancelLoginOAuth:je,loginOAuth:Me,logoutOAuth:Ne}=Ds({apiBase:e,t,aliveRef:B,accountSets:oe,setAccountSets:se,setBusy:x,setStatus:c,setLoginInfo:C,setOauthStatus:y,notify:U,fetchConfig:q,fetchOauth:J,fetchAccountSets:X,fetchProviderQuotas:Y,bumpModelsRefresh:Ae,onLoginSettled:ee}),{removeProvider:Pe,confirmRemoveProvider:Fe,setProviderDisabled:Ie,setDefaultProvider:Le,updateProvider:Re}=As({apiBase:e,t,removeBusyRef:H,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:U,fetchConfig:q,fetchOauth:J,fetchProviderQuotas:Y,refreshCodexAccount:()=>re.load(!0)}),ze=(e,t=!1)=>{if(b!==e){if(ys(e)){F({provider:e,addAccount:t});return}Me(e,t)}};if(!r)return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,z.jsx)(mt,{tone:d,onDismiss:W,dismissLabel:t(`common.close`),children:s}):(0,z.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,z.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,z.jsx)(`div`,{className:`providers-workspace-main`,children:(0,z.jsxs)(`p`,{className:`muted`,children:[(0,z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let Be=Xs(r,h,t),Ve=Zs(r,ae),He=e=>r.providers[e]?.authMode===`forward`;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{children:t(`nav.providers`)}),(0,z.jsx)(`div`,{className:`row`,children:(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,z.jsx)(ne,{}),t(`prov.add`)]})})]}),s&&(0,z.jsx)(mt,{tone:d,onDismiss:W,dismissLabel:t(`common.close`),children:s}),(0,z.jsx)(Gi,{onRemoveProvider:Pe,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:we,jsonEditor:{open:be,draft:ve,isDirty:Oe,onDraftChange:ye,onSave:()=>Ce(),onClose:Ee,onRestore:De},jsonSaving:xe,modelsRefreshToken:M,activeAccountNeedsReauth:_e,quotaRefreshEpoch:te.epoch,quotaForceRefresh:te.force,detail:(t,n)=>{let i=Ve[t.name]??v[t.name];return(0,z.jsx)(gs,{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:()=>T(null),apiBase:e,oauth:i,accounts:oe[t.name]?.accounts??[],keys:ue[t.name]??[],accountLoadState:ce[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:L.token,accountsFocusProvider:L.provider,switchingAccountId:le?.provider===t.name?le.accountId:null,busyProvider:b,loginHint:S,authHandlers:{onLogin:ze,onCancelLogin:je,onLogout:Ne,onReauth:(e,t)=>Me(e,!0,t),onSwitchAccount:de,onRemoveAccount:ge,onRetryAccounts:async e=>{await X([e])},onAddApiKey:me,onSwitchApiKey:fe,onRemoveApiKey:pe,onEditAlias:he},isDefault:t.name===r.defaultProvider,onRemoveProvider:Pe,onSetDisabled:Ie,onSetDefault:e=>{Le(e)},onUpdateProvider:Re,codexController:re},t.name)}}),(0,z.jsx)(Ys,{apiBase:e,config:r,adding:a,addIntent:E,busy:b,addModalAccountRows:Be,accountLoginStatus:Ve,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Se,jsonSaving:xe,oauthTosPending:P,onCloseAdd:()=>{b&&je(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),U(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),q(),J(),Y(!0),Ae()},onAccountLogin:async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=$o(n);if(i===`invalid`){U(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await os(e,i),await q()}catch(e){e instanceof as?U(t(e.i18nKey),!1):U(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{B.current&&x(e=>e===`openai`?null:e)}}j(!0);return}if(He(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&ze(n,i)},onAccountCancelLogin:e=>{je(e)},onAccountLogout:e=>{Ne(e)},onAccountManage:e=>{ee(e)},onOpenAdd:J,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),G(e),q(),J(),Y(!0),Ae()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{Fe(O)},onCancelJsonLeave:()=>{xe||ke(!1)},onDiscardJson:Te,onSaveJson:()=>{Ce()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),Me(e.provider,e.addAccount))}})]})}function $s(e){let{t}=Ze();return e.state===`stale`?(0,z.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,z.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:e.controller.restarting,onClick:()=>{e.controller.restart()},children:e.controller.restarting?t(`dash.codexRestarting`):t(`dash.codexRestart`)})]}):null}var ec=[`fresh`,`stale`,`not_running`,`unknown`],tc=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function nc(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function rc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&ec.includes(t.stateBefore)&&typeof t.code==`string`&&tc.includes(t.code)&&nc(t.requested)&&nc(t.stopped)&&nc(t.surviving)&&nc(t.failed)))return!1;let n=t.success,r=t.code,i=t.surviving,a=t.failed,o=t.stopped;return!(n!==(r!==`partially_stopped`)||n&&(i.length>0||a.length>0)||!n&&i.length===0&&a.length===0||(r===`nothing_running`||r===`enumeration_unavailable`)&&o.length>0)}function ic(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&ec.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var ac={state:null,runningCount:0};async function oc(e,t={}){let n=t.fetchFn??fetch;try{let r=await n(`${e}/api/system/codex-app-server`,{signal:t.signal});if(!r.ok)return ac;let i=await r.json().catch(()=>null);return ic(i)?{state:i.state,runningCount:i.runningCount}:ac}catch{return ac}}var sc=3e4;function cc(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function lc(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=sc,formatFailure:i=e=>`Failed to restart Codex (HTTP ${e}).`,formatUnreachable:a=()=>`Could not reach the proxy.`,formatMalformed:o=()=>`The proxy returned an unexpected response.`,formatTimeout:s=()=>`The proxy did not answer in time. It may still be working.`}=t,c;try{c=await n(`${e}/api/system/codex-restart`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return{ok:!1,message:cc(e)?s():a()}}if(!c.ok)return{ok:!1,message:i(c.status)};let l;try{l=await c.json()}catch(e){return{ok:!1,message:cc(e)?s():o()}}return rc(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function uc(e){return e===`stopped`||e===`nothing_running`}function dc(e,t={}){let{t:n}=Ze(),[r,i]=(0,_.useState)(!1),a=(0,_.useRef)(!0),o=(0,_.useRef)(t.onSettled);return(0,_.useEffect)(()=>{o.current=t.onSettled},[t.onSettled]),(0,_.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]),{restarting:r,restart:(0,_.useCallback)(async()=>{if(!confirm(n(`dash.codexRestartConfirm`)))return null;i(!0);let t=await lc(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(a.current&&i(!1),!t.ok||!t.result)return alert(t.message),null;let r=t.result;return r.code===`stopped`?alert(n(`dash.codexRestartDone`,{count:String(r.stopped.length)})):r.code===`nothing_running`?alert(n(`dash.codexRestartNothing`)):r.code===`enumeration_unavailable`?alert(n(`dash.codexRestartUnknown`)):alert(n(`dash.codexRestartPartial`,{count:String(r.surviving.length)})),a.current&&uc(r.code)&&o.current?.(r.code),r.code},[e,n])}}var fc={"gpt-5.6-sol":be,"gpt-5.6-terra":Ce,"gpt-5.6-luna":xe},pc={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function mc(e){return e.slice(e.lastIndexOf(`/`)+1)}function hc(e){return fc[e]??fc[mc(e)]??null}function gc(e){let t=hc(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:pc,"aria-hidden":!0}),e):e}function _c(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 vc(e,t,n,r){let{isEmpty:i,...a}=r,o=I(e,t,n,a);return{...o,state:_c(o,i,r.enabled!==!1)}}function yc({className:e,style:t}){return(0,z.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function bc({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,z.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,z.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,z.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,z.jsx)(yc,{})},t))]})}function xc({children:e,busy:t=!0,live:n=!0,className:r}){return(0,z.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,z.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{children:e})]})}var Sc=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,z.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,z.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,z.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,z.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,z.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},Cc=Object.freeze({"gpt-daybreak-blue-latest":`gpt-5.6-sol`});Object.freeze(Object.keys(Cc));var wc=new Set([`gpt-5.5`,`gpt-5.4`,`gpt-5.4-mini`,`gpt-5.3-codex-spark`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`]),Tc=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function Ec(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...Tc];let r=new Set(Tc),i=null;for(let e of n){let n=`${e.provider.trim()}/${e.model.trim()}`,a=t.get(n);if(a===void 0)continue;let o=a.filter(e=>r.has(e));if(i===null)i=o;else{let e=new Set(o);i=i.filter(t=>e.has(t))}}if(i===null)return[...Tc];let a=new Set(i);return Tc.filter(e=>a.has(e))}var Dc=0;function Oc(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++Dc}`}}function kc(e){return e===`disabled`?`disabled`:`auto`}var Ac=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,jc=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,Mc=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Nc(e){return Ac.test(e.trim())}function Pc(e){return`combo/${e.trim()}`}function Fc(e,t){return(typeof t==`string`?t.trim():``)||Pc(e)}function Ic(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!Mc.test(n));return{...e,alias:n?t:null,model:Fc(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function Lc(e){return typeof e==`string`&&e.trim()?e.trim():null}function Rc(e){return e===`round-robin`?`round-robin`:`failover`}function zc(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Bc(e){return typeof e==`string`&&Tc.includes(e)?e:null}function Vc(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Hc(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=Vc(t.weight);a.push(Oc(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():Fc(r,Lc(t.alias)),alias:Lc(t.alias),nativeAlias:t.nativeAlias===!0,displayName:Lc(t.displayName),strategy:Rc(t.strategy),stickyLimit:zc(t.stickyLimit),defaultEffort:Bc(t.defaultEffort),imageInput:kc(t.imageInput),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Uc(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 Wc(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 Gc(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 Kc(e,t){return e.id!==t.id||e.alias!==t.alias||e.nativeAlias!==t.nativeAlias||e.displayName!==t.displayName||e.strategy!==t.strategy||e.stickyLimit!==t.stickyLimit||e.defaultEffort!==t.defaultEffort||(e.imageInput??`auto`)!==(t.imageInput??`auto`)||e.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 qc(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.imageInput===`disabled`?{imageInput:`disabled`}:{},...e.strategy===`round-robin`?{stickyLimit:e.stickyLimit}:{},...e.alias&&e.alias.trim()?{alias:e.alias.trim()}:{},...e.nativeAlias?{nativeAlias:!0}:{},...e.displayName&&e.displayName.trim()?{displayName:e.displayName.trim()}:{}}}}function Jc(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Nc(n))return`invalidId`;if(t.existingIds.includes(n))return`duplicateId`;if(Object.hasOwn(t.providers,`combo`))return`reservedNamespace`;if(Object.hasOwn(t.providers,n))return`providerCollision`;let r=e.alias?.trim()??``,i=e.displayName?.trim()??``;if(r){if(!jc.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&Mc.test(r)&&!e.nativeAlias)return`aliasNativeFamily`;if((t.existingAliases??[]).includes(r))return`duplicateAlias`}let a=[...e.displayName??``].some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127});if(e.displayName!==null&&(i.length>128||a))return`invalidDisplayName`;if(e.nativeAlias&&!wc.has(r))return`unsupportedNativeAlias`;if(e.nativeAlias&&!i)return`missingNativeAliasDisplayName`;if(e.targets.length<1)return`noTargets`;for(let n of e.targets){if(!n.provider.trim()||!n.model.trim())return`incompleteTarget`;if(!Object.hasOwn(t.providers,n.provider.trim()))return`unknownProvider`}let o=new Set;for(let t of e.targets){let e=`${t.provider.trim()}/${t.model.trim()}`;if(o.has(e))return`duplicateTarget`;o.add(e)}if(e.strategy===`round-robin`){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 Yc(e=``){return{id:e,model:e?Pc(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,targets:[Oc()]}}function Xc(e,t){return e.length!==0&&e.every(e=>{let n=e.provider.trim(),r=e.model.trim();return!n||!r?!1:!!t.find(e=>e.provider===n&&e.id===r)?.inputModalities?.includes(`image`)})}function Zc(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function Qc(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function $c(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 el(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||$c(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 tl({value:e,onChange:t,disabled:n}){let r=Z();return(0,z.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,z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(a)},i))})}function nl({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Z(),o=i??Tc,s=t!==null&&!o.includes(t);return(0,z.jsxs)(z.Fragment,{children:[(0,z.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,z.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,z.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]}),s?(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function rl({targets:e,models:t,imageInput:n,disabled:r,onChange:i}){let a=Z(),o=Xc(e,t),s=o&&n!==`disabled`;return(0,z.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":a(`cws.capabilities`),children:[(0,z.jsx)(`span`,{className:`field-label`,children:a(`cws.capabilities`)}),(0,z.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`cwi-capability-label`,children:a(`cws.capability.imageInput`)}),(0,z.jsx)(`p`,{className:`muted cwi-capability-hint`,children:a(o?`cws.capability.imageInputHint`:`cws.capability.imageInputUnavailable`)})]}),(0,z.jsx)(pt,{on:s,onClick:()=>{o&&i({imageInput:n===`auto`?`disabled`:`auto`})},disabled:r||!o,label:a(`cws.capability.imageInput`)})]})]})}function il({targets:e,strategy:t,providers:n,models:r,onChange:i}){let a=Z(),o=Zc(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,z.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,_=el(r,p.provider,n),v=p.model&&!_.includes(p.model)?[p.model,..._]:_,y=!p.provider;return(0,z.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,z.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,z.jsx)(Te,{width:14,height:14,"aria-hidden":`true`})}),(0,z.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:m===0,"aria-label":a(`cws.target.moveUp`),onClick:()=>f(m,m-1),children:(0,z.jsx)(ue,{width:14,height:14,"aria-hidden":`true`})}),(0,z.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,z.jsx)(X,{width:14,height:14,"aria-hidden":`true`})})]}),(0,z.jsxs)(`select`,{className:`input`,value:p.provider,"aria-label":a(`cws.target.provider`),onChange:e=>{let t=e.target.value,i=el(r,t,n)[0]??``;d(m,{provider:t,model:i})},children:[(0,z.jsx)(`option`,{value:``,children:a(`cws.target.pickProvider`)}),g.map(e=>(0,z.jsx)(`option`,{value:e.name,children:e.disabled?a(`cws.target.disabled`,{name:pn(e.name,a)}):pn(e.name,a)},e.name))]}),(0,z.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,z.jsx)(`option`,{value:``,children:y?a(`cws.target.pickProviderFirst`):v.length===0?a(`cws.target.noModels`):a(`cws.target.pickModel`)}),v.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]}),t===`round-robin`&&(0,z.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=Qc(e.target.value,1,1e4);t!==void 0&&d(m,{weight:t})}}),(0,z.jsx)(`div`,{className:`cwi-target-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>i(e.filter((e,t)=>t!==m)),"aria-label":a(`common.remove`),children:(0,z.jsx)(oe,{width:14,height:14})})})]},p.clientKey??`${p.provider}:${p.model}`)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>i([...e,Oc()]),children:[(0,z.jsx)(ne,{width:14,height:14}),` `,a(`cws.target.add`)]})]})}function al({existingIds:e,existingAliases:t,providerMap:n,providers:r,models:i,onClose:a,onSubmit:o}){let s=Z(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(()=>Yc()),[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)(()=>Ec(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=Jc(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:Fc(i,a)});if(!e.ok){m(e.error||s(`cws.saveFailed`));return}}finally{f(!1)}};return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:y,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:v}),(0,z.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,z.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:s(`cws.addTitle`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:d,"aria-label":s(`common.close`),children:(0,z.jsx)(Y,{width:16,height:16})})]}),(0,z.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:s(`cws.addSubtitle`)}),p&&(0,z.jsx)($,{tone:`err`,children:p}),(0,z.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-id`,children:s(`cws.field.id`)}),(0,z.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:l.id,disabled:d,onChange:e=>u(t=>({...t,id:e.target.value,model:Fc(e.target.value,t.alias)}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.idInternalHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:s(`cws.field.alias`)}),(0,z.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:Fc(t.id,e.target.value)}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.aliasHint`)}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.idHint`,{model:l.id.trim()?Fc(l.id,l.alias):`…`})})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:s(`cws.strategy`)}),(0,z.jsx)(tl,{value:l.strategy,disabled:d,onChange:e=>u(t=>({...t,strategy:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:l.strategy===`failover`?s(`cws.strategy.failoverHint`):s(`cws.strategy.roundRobinHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:s(`cws.field.defaultEffort`)}),(0,z.jsx)(nl,{id:`cwi-new-effort`,value:l.defaultEffort,disabled:d,allowedEfforts:g,onChange:e=>u(t=>({...t,defaultEffort:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.defaultEffortHint`)})]}),l.strategy===`round-robin`&&(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:s(`cws.field.stickyLimit`)}),(0,z.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:l.stickyLimit,disabled:d,onChange:e=>{let t=Qc(e.target.value,1,100);t!==void 0&&u(e=>({...e,stickyLimit:t}))}}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:s(`cws.field.stickyLimitHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:s(`cws.targets`)}),(0,z.jsx)(il,{targets:l.targets,strategy:l.strategy,providers:r,models:i,onChange:e=>u(t=>({...t,targets:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:l.strategy===`failover`?s(`cws.targets.failoverHint`):s(`cws.targets.roundRobinHint`)})]}),(0,z.jsx)(rl,{targets:l.targets,models:i,imageInput:l.imageInput??`auto`,disabled:d,onChange:e=>u(t=>({...t,...e}))})]}),(0,z.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:v,disabled:d,children:s(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{b()},disabled:d,children:s(d?`common.saving`:`cws.create`)})]})]})]})}var ol=[`config`,`about`],sl=e=>`cws-detail-tab-${e}`,cl=e=>`cws-detail-panel-${e}`;function ll({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providers:a,models:o,onBack:s,onSaved:c,onRequestRemove:l,onSave:u,onDirtyChange:d}){let f=Z(),[p,m]=(0,_.useState)(`config`),h=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%ol.length;else if(e.key===`ArrowLeft`)n=(t-1+ol.length)%ol.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=ol.length-1;else return;e.preventDefault(),m(ol[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[]),[g,v]=(0,_.useState)(e),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(!1),T=!Kc(g,e),E=`${e.id}:${e.alias??``}:${e.nativeAlias}:${e.displayName??``}:${e.strategy}:${e.stickyLimit}:${e.defaultEffort}:${e.imageInput??`auto`}:${e.targets.map(e=>`${e.provider}/${e.model}:${e.weight??1}`).join(`,`)}`,D=(0,_.useMemo)(()=>{let e=new Map;for(let t of o)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[o]),O=(0,_.useMemo)(()=>Ec(g.targets,D),[g.targets,D]),k=(0,_.useCallback)(t=>{let n=t(g);v(n),d(!Kc(n,e))},[g,e,d]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{v(e),S(null),m(`config`),d(!1)},0);return()=>window.clearTimeout(t)},[E]);let A=async()=>{try{await navigator.clipboard.writeText(e.model),w(!0),window.setTimeout(()=>w(!1),1200)}catch{}},j=async()=>{let a=Jc(g,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){S({ok:!1,text:f(`cws.err.${a}`)});return}b(!0);let o=g.id.trim(),s=g.alias?.trim()||null,l=g.displayName?.trim()||null,d={...g,id:o,alias:s,displayName:l,model:Fc(o,s)},p=!t&&o!==e.id?e.id:void 0;try{let e=await u(d,t,p);if(!e.ok){S({ok:!1,text:e.error||f(`cws.saveFailed`)});return}S({ok:!0,text:t?f(`cws.created`,{model:d.model}):f(`cws.saved`)}),c(d)}finally{b(!1)}},M=t?g.id.trim()?Fc(g.id,g.alias):f(`cws.addTitle`):e.model;return(0,z.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,z.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[s&&(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:s,"aria-label":f(`cws.backToAll`),children:[(0,z.jsx)(fe,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),f(`cws.allCombos`)]}),(0,z.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:M}),!t&&(0,z.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{A()},title:f(`cws.copyModel`),children:f(C?`cws.copied`:`cws.copyModel`)}),(0,z.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&l&&(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,z.jsx)(oe,{width:14,height:14}),` `,f(`common.remove`)]}),(0,z.jsx)(`button`,{id:t?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!T||y,onClick:()=>{j()},children:f(y?`common.saving`:t?`cws.create`:`common.save`)})]})]}),x&&(0,z.jsx)($,{tone:x.ok?`ok`:`err`,children:x.text}),(0,z.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":f(`cws.tabsLabel`),children:ol.map((e,t)=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:sl(e),"aria-selected":p===e,"aria-controls":cl(e),tabIndex:p===e?0:-1,className:`btn btn-sm ${p===e?`btn-primary`:`btn-ghost`}`,onClick:()=>m(e),onKeyDown:e=>h(e,t),children:f(e===`config`?`cws.tab.config`:`cws.tab.about`)},e))}),(0,z.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:cl(`config`),"aria-labelledby":sl(`config`),hidden:p!==`config`,children:(0,z.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:f(`cws.field.id`)}),(0,z.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:g.id,disabled:y,onChange:e=>k(t=>({...t,id:e.target.value,model:Fc(e.target.value,t.alias)}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:t?f(`cws.field.idInternalHint`):f(`cws.field.idHintEdit`,{model:Fc(g.id,g.alias)})})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:f(`cws.field.alias`)}),(0,z.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:g.alias??``,placeholder:Pc(g.id.trim()||`…`),disabled:y,onChange:e=>k(t=>Ic(t,e.target.value))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.aliasHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,z.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:g.nativeAlias,disabled:y,onChange:e=>k(t=>({...t,nativeAlias:e.target.checked}))}),` `,f(`cws.field.nativeAlias`)]}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.nativeAliasHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:f(`cws.field.displayName`)}),(0,z.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:g.displayName??``,maxLength:128,disabled:y,onChange:e=>k(t=>({...t,displayName:e.target.value||null}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.displayNameHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:f(`cws.strategy`)}),(0,z.jsx)(tl,{value:g.strategy,disabled:y,onChange:e=>k(t=>({...t,strategy:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g.strategy===`failover`?f(`cws.strategy.failoverHint`):f(`cws.strategy.roundRobinHint`)})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-effort`,children:f(`cws.field.defaultEffort`)}),(0,z.jsx)(nl,{id:`cwi-effort`,value:g.defaultEffort,disabled:y,allowedEfforts:O,onChange:e=>k(t=>({...t,defaultEffort:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:f(`cws.field.defaultEffortHint`)})]}),g.strategy===`round-robin`&&(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`label`,{htmlFor:`cwi-sticky`,children:f(`cws.field.stickyLimit`)}),(0,z.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:g.stickyLimit,disabled:y,onChange:e=>{let t=Qc(e.target.value,1,100);t!==void 0&&k(e=>({...e,stickyLimit:t}))}})]}),(0,z.jsxs)(`div`,{className:`cwi-field`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:f(`cws.targets`)}),(0,z.jsx)(il,{targets:g.targets,strategy:g.strategy,providers:a,models:o,onChange:e=>k(t=>({...t,targets:e}))}),(0,z.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:g.strategy===`failover`?f(`cws.targets.failoverHint`):f(`cws.targets.roundRobinHint`)})]}),(0,z.jsx)(rl,{targets:g.targets,models:o,imageInput:g.imageInput??`auto`,disabled:y,onChange:e=>k(t=>({...t,...e}))})]})}),(0,z.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:cl(`about`),"aria-labelledby":sl(`about`),hidden:p!==`about`,tabIndex:0,children:(0,z.jsxs)(`section`,{className:`pwi-section`,children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:f(`cws.aboutTitle`)}),(0,z.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:f(`cws.aboutBody`)})]})})]})}function ul({model:e,onCancel:t,onConfirm:n}){let r=Z(),i=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,z.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,z.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,z.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,z.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function dl({onKeep:e,onDiscard:t}){let n=Z(),r=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]);let i=(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,z.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,z.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,z.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,z.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function fl(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:`cws.attention.few`)}function pl({combos:e,cataloguedComboIds:t,onSelect:n,onAdd:r}){let i=Z(),a=Uc(e),o=Gc(e,{cataloguedComboIds:t});return(0,z.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,z.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,z.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:i(`cws.overviewTitle`)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,children:[(0,z.jsx)(ne,{width:14,height:14}),` `,i(`cws.add`)]})]}),(0,z.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:i(`cws.overviewBlurb`)}),(0,z.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,z.jsx)(`strong`,{children:e.length}),(0,z.jsx)(`span`,{children:i(`cws.count.total`)})]}),(0,z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,z.jsx)(`strong`,{children:a.failover.length}),(0,z.jsx)(`span`,{children:i(`cws.count.failover`)})]}),(0,z.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,z.jsx)(`strong`,{children:a.roundRobin.length}),(0,z.jsx)(`span`,{children:i(`cws.count.roundRobin`)})]})]}),(0,z.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.howTitle`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.howTitle`)}),(0,z.jsx)(`p`,{className:`muted`,style:{margin:0},children:i(`cws.howBody`)})]}),o.length>0&&(0,z.jsxs)(`section`,{className:`pwi-section`,"aria-label":i(`cws.attentionTitle`),children:[(0,z.jsx)(`h3`,{className:`pwi-section-title`,children:i(`cws.attentionTitle`)}),(0,z.jsx)(`div`,{className:`cwi-attention-list`,children:o.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>n(e.id),children:[(0,z.jsx)(se,{width:14,height:14,"aria-hidden":`true`}),(0,z.jsx)(`code`,{className:`chip`,children:e.model}),(0,z.jsx)(`span`,{className:`muted`,children:fl(e.reason,i)}),(0,z.jsx)(fe,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function ml({combos:e,providers:t,models:n,cataloguedComboIds:r,loading:i,onRefresh:a,onSave:o,onRemove:s,onAdd:c,adding:l,onCloseAdd:u,onCreated:d}){let f=Z(),p=(0,_.useMemo)(()=>Object.fromEntries(t.map(e=>[e.name,{disabled:e.disabled}])),[t]),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(void 0),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),T=(0,_.useMemo)(()=>Yc(),[]),E=(0,_.useMemo)(()=>Wc(e,m),[e,m]),D=(0,_.useMemo)(()=>Uc(E),[E]),O=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),k=g&&e.some(e=>e.id===g)?g:null,A=e.find(e=>e.id===k)??null,j=A&&C?.id===A.id?C:A,[M,N]=(0,_.useState)(!1),P=[],F=[];if(j)for(let t of e)t.id!==j.id&&(P.push(t.id),t.alias&&F.push(t.alias));let I=(0,_.useCallback)(e=>{if(e!==k){if(!M){v(e),w(null);return}b(e)}},[k,M]),L=()=>{y!==void 0&&(v(y),w(null),N(!1),b(void 0))},R=()=>b(void 0),B=y!==void 0&&M,V=!i&&e.length===0;return(0,z.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,z.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":f(`cws.railAria`),children:[(0,z.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`div`,{className:`combos-workspace-rail-title`,children:f(`nav.combos`)}),(0,z.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,z.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,z.jsx)(ne,{width:14,height:14}),` `,f(`cws.add`)]})]}),(0,z.jsx)(`div`,{className:`cwi-search-row`,children:(0,z.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,z.jsx)(le,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,z.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,z.jsx)(`div`,{className:`combos-workspace-rail-list`,children:E.length===0&&e.length>0?(0,z.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:f(`cws.noSearchResults`)}):(0,z.jsx)(z.Fragment,{children:[[`failover`,D.failover,`cws.group.failover`],[`round-robin`,D.roundRobin,`cws.group.roundRobin`]].map(([e,t,n])=>t.length>0?(0,z.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,z.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,z.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),f(n),(0,z.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,z.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${k===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>I(e.id),"aria-current":k===e.id?`true`:void 0,children:[(0,z.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,z.jsx)(we,{width:16,height:16})}),(0,z.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,z.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?f(`cws.targetCountOne`):f(`cws.targetCount`,{count:e.targets.length})}),(0,z.jsx)(fe,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,z.jsx)(`div`,{className:`combos-workspace-main`,children:j?(0,z.jsx)(ll,{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,z.jsx)(ll,{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,z.jsx)(pl,{combos:e,cataloguedComboIds:r,onSelect:e=>I(e),onAdd:c})}),l&&!V&&(0,z.jsx)(al,{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,z.jsx)(ul,{model:e.find(e=>e.id===x)?.model??Pc(x),onCancel:()=>S(null),onConfirm:()=>{(async()=>{let e=await s(x);S(null),e.ok&&(k===x&&(v(null),w(null)),a())})()}}),B&&(0,z.jsx)(dl,{onKeep:R,onDiscard:L})]})}function hl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function gl(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function _l(e){return qn(e)}function vl({apiBase:e,active:t=!0,onCountChange:n}){let r=Z(),i=`ocx.combos.workspace.v1:${e}`,a=(0,_.useMemo)(()=>_l(i),[i]),[o,s]=(0,_.useState)(a??null),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),m=(e,t)=>{l(e),d(t)};(0,_.useEffect)(()=>{if(!c||!u)return;let e=window.setTimeout(()=>{l(``),d(!1)},5e3);return()=>window.clearTimeout(e)},[c,u]);let h=(0,_.useCallback)(async t=>{let[n,r,a]=await Promise.all([fetch(`${e}/api/combos`,{signal:t}),fetch(`${e}/api/config`,{signal:t}),fetch(`${e}/api/models`,{signal:t})]);if(!n.ok||!r.ok||!a.ok)throw Error(`combo workspace load failed`);let o=await n.json(),c=await r.json(),l=await a.json(),u=Array.isArray(l)?l:Array.isArray(l?.models)?l.models:[],d=Hc(o),f=c.providers??{},p=Hr(f),m=Object.entries(f).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:!Object.hasOwn(p,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl})),h=[],g=new Set;for(let e of u){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.provider!=`string`||typeof t.id!=`string`)continue;let n=t.provider.trim(),r=t.id.trim();if(!n||!r)continue;if(n===`combo`){g.add(r);continue}if(t.disabled===!0)continue;let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0,a=Array.isArray(t.inputModalities)?t.inputModalities.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):void 0;h.push({provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{},...a&&a.length>0?{inputModalities:a}:{}})}for(let[e,t]of Object.entries(f)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;!n||t.disabled||h.some(t=>t.provider===e&&t.id===n)||h.push({provider:e,id:n,namespaced:`${e}/${n}`})}let _={combos:d,providers:m,models:h,cataloguedComboIds:[...g]};return Jn(i,_),s(_),_},[e,i]),g=vc(i,[e],h,{isEmpty:()=>!1,initialData:a??void 0,enabled:t}),{state:v}=g,y=v.data??o??void 0,b=y?.combos??[];(0,_.useEffect)(()=>{y&&n?.(b.length)},[b.length,y,n]);let x=y?.providers??[],S=y?.models??[],C=new Set(y?.cataloguedComboIds??[]),w=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(qc(t,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=hl(o);if(!a.ok||s||!gl(o)){let e=s||r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(i?r(`cws.renamed`,{from:Pc(i),to:t.model}):n?r(`cws.created`,{model:t.model}):r(`cws.saved`),!0),{ok:!0}}catch{let e=r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}},T=async t=>{try{let n=await fetch(`${e}/api/combos?id=${encodeURIComponent(t)}`,{method:`DELETE`}),i=n.ok?await n.json():await n.json().catch(()=>null),a=hl(i);if(!n.ok||a||!gl(i)){let e=a||r(`cws.removeFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(r(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=r(`cws.removeFailed`);return m(e,!1),{ok:!1,error:e}}};if(v.showSkeleton&&!y)return(0,z.jsx)(bc,{label:r(`cws.loading`),rows:5});if(v.kind===`failed-cold`&&!y){let e=v.error instanceof Error?v.error.message:r(`cws.loadFailed`);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g.refresh(),children:r(`common.retry`)})]})}return(0,z.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,z.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,z.jsx)($,{tone:u?`ok`:`err`,children:c})}),v.showError&&(0,z.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,z.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,z.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":v.refreshing,children:[(0,z.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:v.refreshing?r(`common.loading`):``}),(0,z.jsx)(ml,{combos:b,providers:x,models:S,cataloguedComboIds:C,loading:!1,onRefresh:()=>g.refresh(),onSave:w,onRemove:T,onAdd:()=>p(!0),adding:f,onCloseAdd:()=>p(!1),onCreated:()=>g.refresh()})]})]})}var yl=0;function bl(){return yl+=1,`candidate-${yl}`}function xl(e,t){return{provider:e,model:t,key:bl()}}function Sl(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))continue;let e=typeof n.suiteId==`string`?n.suiteId.trim():``,r=n.evidenceLayer;!e||r!==`protocol_conformance`&&r!==`live_route_compatibility`||t.push({suiteId:e,evidenceLayer:r})}return t}function Cl(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:Sl(t.requiredSuites)};return(t.minStatus===`PROBED`||t.minStatus===`VERIFIED`)&&(n.minStatus=t.minStatus),typeof t.maxEvidenceAgeMs==`number`&&Number.isFinite(t.maxEvidenceAgeMs)&&t.maxEvidenceAgeMs>=0&&(n.maxEvidenceAgeMs=t.maxEvidenceAgeMs),(t.unknownEvidence===`allow`||t.unknownEvidence===`penalize`||t.unknownEvidence===`exclude`)&&(n.unknownEvidence=t.unknownEvidence),(t.degradedEvidence===`allow`||t.degradedEvidence===`penalize`||t.degradedEvidence===`exclude`)&&(n.degradedEvidence=t.degradedEvidence),n}var wl={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},Tl={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function El(e){return e===!0?`true`:e===!1?`false`:``}function Dl(e){return e===void 0?``:String(e)}function Ol(e=``,t=``){return{id:``,alias:``,candidates:[xl(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...wl},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...Tl},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function kl(e){let t=Cl(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:bl()})),require:{minContextWindow:Dl(e.require.minContextWindow),minQuotaHeadroom:Dl(e.require.minQuotaHeadroom),tools:El(e.require.tools),imageInput:El(e.require.imageInput),structuredOutput:El(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:El(e.require.localOnly),remoteAllowed:El(e.require.remoteAllowed),encryptedCodexTasks:El(e.require.encryptedCodexTasks)},optimize:{latency:String(e.optimize.latency),health:String(e.optimize.health),cost:String(e.optimize.cost),quota:String(e.optimize.quota)},limits:{maxEstimatedCostUsd:Dl(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:Dl(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function Al(e){let t=e.trim();return t?Number(t):void 0}function jl(e){if(e===`true`)return!0;if(e===`false`)return!1}function Ml(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Nl(e,t,n){let r=Ml({minContextWindow:Al(e.require.minContextWindow),minQuotaHeadroom:Al(e.require.minQuotaHeadroom),tools:jl(e.require.tools),imageInput:jl(e.require.imageInput),structuredOutput:jl(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:jl(e.require.localOnly),remoteAllowed:jl(e.require.remoteAllowed),encryptedCodexTasks:jl(e.require.encryptedCodexTasks)}),i=Al(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?Ml({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:Al(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=Ml({maxEstimatedCostUsd:i,onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:void 0});return{mode:t,id:e.id.trim(),...t===`update`&&n?{expectedRevision:n}:{},profile:{...e.alias.trim()?{alias:e.alias.trim()}:{},candidates:e.candidates.map(e=>({provider:e.provider.trim(),model:e.model.trim()})),...Object.keys(r).length>0?{require:r}:{},optimize:{latency:Number(e.optimize.latency),health:Number(e.optimize.health),cost:Number(e.optimize.cost),quota:Number(e.optimize.quota)},...Object.keys(o).length>0?{limits:o}:{},unknownEvidence:{...e.unknownEvidence},...a&&Object.keys(a).length>0?{compatibility:a}:{}}}}function Pl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;if(typeof t==`string`&&t.trim())return t;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.message;if(typeof e==`string`&&e.trim())return e}}function Fl(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Il(e,t){return e.filter(e=>e.provider===t)}var Ll={en:{maxEvidenceAgeMs:`Maximum evidence age (ms)`,unknownEvidence:`Unknown evidence`,degradedEvidence:`Degraded evidence`},de:{maxEvidenceAgeMs:`Maximales Evidenzalter (ms)`,unknownEvidence:`Unbekannte Evidenz`,degradedEvidence:`Eingeschränkte Evidenz`},ko:{maxEvidenceAgeMs:`최대 증거 유효 기간 (ms)`,unknownEvidence:`알 수 없는 증거`,degradedEvidence:`저하된 증거`},zh:{maxEvidenceAgeMs:`证据最大有效期(毫秒)`,unknownEvidence:`未知证据`,degradedEvidence:`降级证据`},"zh-TW":{maxEvidenceAgeMs:`證據最大有效期限(毫秒)`,unknownEvidence:`未知證據`,degradedEvidence:`降級證據`},ru:{maxEvidenceAgeMs:`Максимальный возраст доказательств (мс)`,unknownEvidence:`Неизвестные доказательства`,degradedEvidence:`Ухудшенные доказательства`},ja:{maxEvidenceAgeMs:`エビデンスの最大有効期間 (ms)`,unknownEvidence:`不明なエビデンス`,degradedEvidence:`低下したエビデンス`},tr:{maxEvidenceAgeMs:`Maksimum kanıt yaşı (ms)`,unknownEvidence:`Bilinmeyen kanıt`,degradedEvidence:`Bozulmuş kanıt`}},Rl=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],zl=[`reasoningEffort`,`serviceTier`],Bl={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},Vl=Object.keys(Bl),Hl=[`latency`,`health`,`cost`,`quota`],Ul=[`capability`,`health`,`quota`,`cost`],Wl=[`allow`,`penalize`,`exclude`],Gl=[`allow`,`exclude`];function Kl(e){return`${e.evidenceLayer}:${e.suiteId}`}function ql(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Jl(e){let t=new Set,n=[];for(let r of e){if(!ql(r))continue;let e=typeof r.suiteId==`string`?r.suiteId.trim():``,i=r.evidenceLayer;if(!e||i!==`protocol_conformance`&&i!==`live_route_compatibility`)continue;let a={suiteId:e,evidenceLayer:i},o=Kl(a);t.has(o)||(t.add(o),n.push({...a,key:o}))}return n.sort((e,t)=>{let n=e.evidenceLayer.localeCompare(t.evidenceLayer);return n===0?e.suiteId.localeCompare(t.suiteId):n})}function Yl(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function Xl(e,t){return e===void 0?t:`${Math.round(e)}ms`}function Zl(e,t){return e==null?t:`${Math.round(e*100)}%`}function Ql(e,t,n){switch(e){case`satisfied`:return t(`routing.capOutcome.satisfied`);case`exceeded`:return t(`routing.capOutcome.exceeded`);case`unknown-allowed`:return t(`routing.capOutcome.unknown-allowed`);case`unknown-excluded`:return t(`routing.capOutcome.unknown-excluded`);default:return n}}function $l(e,t){switch(e){case`capability-unsatisfied`:return t(`routing.exclusion.capability-unsatisfied`);case`unknown-capability`:return t(`routing.exclusion.unknown-capability`);case`cost-limit`:return t(`routing.exclusion.cost-limit`);case`cost-limit-unknown`:return t(`routing.exclusion.cost-limit-unknown`);case`cooldown`:return t(`routing.exclusion.cooldown`);case`unknown-health`:return t(`routing.exclusion.unknown-health`);case`unknown-quota`:return t(`routing.exclusion.unknown-quota`);case`unknown-price`:return t(`routing.exclusion.unknown-price`);default:return t(`routing.exclusion.other`,{code:e})}}function eu(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>ql(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&ql(e.require)&&ql(e.optimize)&&ql(e.limits)&&ql(e.unknownEvidence):!1).map(e=>{let t=Cl(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function tu(e){let t=Array.isArray(e)?e:e&&typeof e==`object`&&Array.isArray(e.models)?e.models:[],n=new Set,r=[];for(let e of t){if(!e||typeof e!=`object`||Array.isArray(e))continue;let t=typeof e.provider==`string`?e.provider.trim():``,i=typeof e.id==`string`?e.id.trim():``;if(!t||!i||t===`combo`||t===`policy`||e.disabled===!0)continue;let a=JSON.stringify([t,i]);n.has(a)||(n.add(a),r.push({provider:t,id:i}))}return r}function nu(e,t,n){let r=n??t;if(r){let t=e.find(e=>e.id===r);if(t)return t}return e[0]??null}function ru({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=Ze(),a=Ll[r],o=i(`routing.unavailable`),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)({}),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(``),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,B]=(0,_.useState)(``),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)([]),[G,ee]=(0,_.useState)(!1),te=(0,_.useRef)(null),K=(0,_.useRef)(0),q=(0,_.useRef)(null),J=(0,_.useRef)(!0),Y=(0,_.useCallback)(()=>{J.current=!1,q.current?.abort(),K.current++},[]),ne=(0,_.useRef)(0),re=(0,_.useCallback)((e,t)=>{T({message:e,ok:t})},[]);(0,_.useEffect)(()=>{if(!w?.ok)return;let e=window.setTimeout(()=>T(null),5e3);return()=>window.clearTimeout(e)},[w]);let ie=(0,_.useCallback)(()=>{ne.current+=1,L(null),B(``),H(!1)},[]),ae=(0,_.useCallback)(e=>{te.current=e,x(e),C(e?kl(e):null),T(null),ie()},[ie]),oe=(0,_.useCallback)(async t=>{if(!J.current)return;q.current?.abort();let n=new AbortController;q.current=n;let{signal:r}=n,i=++K.current;y(``);try{let[n,a,o,s,l]=await Promise.all([fetch(`${e}/api/routing-profiles`,{signal:r}),fetch(`${e}/api/routing-analytics`,{signal:r}),fetch(`${e}/api/config`,{signal:r}),fetch(`${e}/api/models`,{signal:r}),fetch(`${e}/api/lab/catalog`,{signal:r})]);if(!n.ok)throw Error(`load-${n.status}`);let[d,p,h,_,v]=await Promise.all([n.json(),a.ok?a.json():Promise.resolve(null),o.ok?o.json():Promise.resolve({}),s.ok?s.json():Promise.resolve([]),l.ok?l.json().catch(()=>null):Promise.resolve(null)]);if(i!==K.current)return;let y=eu(d),b=te.current,S=nu(y,b?.id??null,t),w=h.providers??{},T=Object.entries(w).filter(([,e])=>e.disabled!==!0).map(([e])=>e).sort((e,t)=>e<t?-1:+(e>t)),E=Object.fromEntries(Object.entries(w).filter(([,e])=>e.disabled!==!0&&typeof e.defaultModel==`string`).map(([e,t])=>[e,t.defaultModel.trim()]));te.current=S,c(y),x(S),C(S?kl(S):null),u(p),f(T),m(E),g(tu(_)),v&&Array.isArray(v.scenarios)?(W(Jl(v.scenarios)),ee(!1)):(W([]),ee(!0)),(!b||!S||b.id!==S.id||b.revision!==S.revision)&&ie()}catch(e){if(i!==K.current||r.aborted)return;y(e instanceof Error?e.message:String(e))}finally{q.current===n&&(q.current=null)}},[e,ie]);(0,_.useEffect)(()=>{if(!t){Y();return}J.current=!0;let e=window.setTimeout(()=>void oe(),0);return()=>{window.clearTimeout(e),Y()}},[t,Y,oe]),(0,_.useEffect)(()=>{n?.(s.length)},[n,s.length]);let se=d[0]??``,ce=p[se]??Il(h,se)[0]?.id??``,le=()=>{te.current=null,x(null),C(Ol(se,ce)),T(null),ie()},ue=()=>{if(b){C(kl(b)),T(null);return}ae(s[0]??null)},X=async()=>{if(!(!S||E)){D(!0),T(null);try{let t=Nl(S,b?`update`:`create`,b?.revision),n=await fetch(`${e}/api/routing-profiles`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await Ct(n);if(!n.ok){let e=await n.json().catch(()=>null);re(Pl(e)??i(`routing.loadFailed`),!1);return}if(!Fl(r)){re(Pl(r)??i(`routing.loadFailed`),!1);return}await oe(t.id),re(i(`common.ok`),!0)}catch(e){re(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},de=async()=>{if(!(!b||E)&&window.confirm(i(`routing.removeConfirm`,{id:b.id}))){D(!0),T(null);try{let t=await fetch(`${e}/api/routing-profiles?id=${encodeURIComponent(b.id)}`,{method:`DELETE`}),n=await Ct(t);if(!t.ok){let e=await t.json().catch(()=>null);re(Pl(e)??i(`routing.loadFailed`),!1);return}if(!Fl(n)){re(Pl(n)??i(`routing.loadFailed`),!1);return}te.current=null,await oe(),re(i(`common.ok`),!0)}catch(e){re(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},fe=(e,t,n)=>{C(r=>{if(!r)return r;let i=r.candidates.map((r,i)=>i===e?t===`provider`?{...r,provider:n,model:p[n]??Il(h,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},pe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,xl(se,ce)]})},me=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},he=async()=>{if(!b)return;let t=++ne.current;H(!0),L(null),B(``);try{let n={},r=O.trim()?Number(O.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),A&&(n.toolsRequired=!0),M&&(n.imageInputRequired=!0),P&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:b.id,evidence:n})});if(t!==ne.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==ne.current)return;B(Pl(e)??i(`routing.dryRunError`,{status:a.status}));return}let o=await a.json();if(t!==ne.current)return;L(o)}catch(e){if(t!==ne.current)return;B(e instanceof Error?e.message:String(e))}finally{t===ne.current&&H(!1)}},ge=S?.candidates.map(e=>Il(h,e.provider))??[];return(0,z.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,z.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:le,children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void oe(),children:i(`common.retry`)})]}),v?(0,z.jsxs)($,{tone:`err`,children:[i(`routing.loadFailed`),`: `,v]}):null,w?(0,z.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,s.length>0?(0,z.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:s.map(e=>(0,z.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>ae(e),"aria-pressed":b?.id===e.id,children:(0,z.jsxs)(`div`,{className:`card-badges`,children:[(0,z.jsx)(`strong`,{children:e.id}),(0,z.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,z.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),X()},children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,b?.model??(0,z.jsx)(`code`,{children:`policy/…`})]}),b?(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,b.revision]}):null]}),(0,z.jsxs)(`div`,{className:`model-grid`,children:[(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`id`}),(0,z.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`alias`}),(0,z.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,z.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[S.candidates.map((e,t)=>{let n=[...new Set([e.provider,...d])].filter(Boolean),r=`routing-model-options-${t}`;return(0,z.jsxs)(`div`,{className:`model-card`,children:[(0,z.jsxs)(`div`,{className:`model-grid`,children:[(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`provider`}),(0,z.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>fe(t,`provider`,e.target.value),children:[(0,z.jsx)(`option`,{value:``,disabled:!0,children:i(`routing.none`)}),n.map(e=>(0,z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`model`}),(0,z.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>fe(t,`model`,e.target.value)}),(0,z.jsx)(`datalist`,{id:r,children:ge[t]?.map(e=>(0,z.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S.candidates.length===1,onClick:()=>me(t),"aria-label":i(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:i(`common.remove`)})]},e.key)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:pe,children:[(0,z.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,z.jsxs)(`div`,{className:`model-grid`,children:[Vl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:Bl[e].min,max:Bl[e].max,step:Bl[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),zl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Rl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,z.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,z.jsx)(`option`,{value:`true`,children:i(`routing.yes`)}),(0,z.jsx)(`option`,{value:`false`,children:i(`routing.no`)})]})]},e))]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,z.jsx)(`div`,{className:`model-grid`,children:Hl.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,required:!0,value:S.optimize[e],onChange:t=>C(n=>n&&{...n,optimize:{...n.optimize,[e]:t.target.value}})})]},e))})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,z.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,value:S.limits.maxEstimatedCostUsd,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,maxEstimatedCostUsd:e.target.value}})})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:`onUnknownCost`}),(0,z.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Gl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,z.jsx)(`div`,{className:`model-grid`,children:Ul.map(e=>(0,z.jsxs)(`label`,{className:`field-label`,children:[(0,z.jsx)(`code`,{children:e}),(0,z.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Wl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,z.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,z.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:S.compatibility.enabled,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),i(`routing.compatibility.enabled`)]}),S.compatibility.enabled?(0,z.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,z.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),G?(0,z.jsx)(`div`,{style:{marginTop:6},children:(0,z.jsx)($,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,U.length>0?(0,z.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:U.map(e=>(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:Yl(S.compatibility.requiredSuites,e),onChange:t=>C(n=>{if(!n)return n;let r=t.target.checked?[...n.compatibility.requiredSuites,{suiteId:e.suiteId,evidenceLayer:e.evidenceLayer}]:n.compatibility.requiredSuites.filter(t=>t.suiteId!==e.suiteId||t.evidenceLayer!==e.evidenceLayer);return{...n,compatibility:{...n.compatibility,requiredSuites:r}}})}),(0,z.jsxs)(`span`,{children:[e.suiteId,` `,(0,z.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,z.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,z.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,z.jsx)(`option`,{value:`PROBED`,children:i(`lab.verdict.PROBED`)}),(0,z.jsx)(`option`,{value:`VERIFIED`,children:i(`lab.verdict.VERIFIED`)})]})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[a.maxEvidenceAgeMs,(0,z.jsx)(`input`,{className:`input`,type:`number`,min:0,value:S.compatibility.maxEvidenceAgeMs,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,maxEvidenceAgeMs:e.target.value}})})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[a.unknownEvidence,(0,z.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Wl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]}),(0,z.jsxs)(`label`,{className:`field-label`,children:[a.degradedEvidence,(0,z.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Wl.map(e=>(0,z.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,z.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,z.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:i(E?`common.saving`:`common.save`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:ue,children:i(`common.cancel`)}),b?(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void de(),children:i(`common.remove`)}):null]})]}):null,(0,z.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,z.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,z.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,z.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),ie()}})]}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),ie()}}),i(`routing.dryRunTools`)]}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),ie()}}),i(`routing.dryRunImage`)]}),(0,z.jsxs)(`label`,{className:`checkbox`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),ie()}}),i(`routing.dryRunStructured`)]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||V,onClick:()=>void he(),children:i(`routing.dryRunRun`)}),R?(0,z.jsx)($,{tone:`err`,children:R}):null,I?(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`routing.candidate`)}),(0,z.jsx)(`th`,{children:i(`routing.eligible`)}),(0,z.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,z.jsx)(`th`,{children:i(`routing.costCap`)}),(0,z.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,z.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,z.jsxs)(`tr`,{children:[(0,z.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,z.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,z.jsx)(`td`,{children:e.exclusions.map(e=>$l(e.code,i)).join(`, `)||i(`routing.none`)}),(0,z.jsx)(`td`,{children:Ql(e.cost?.capOutcome,i,o)}),(0,z.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):o})]},`${e.provider}/${e.model}`))})]}):null]}),(0,z.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,z.jsx)(`h3`,{children:i(`routing.analytics`)}),l?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`card-badges`,children:[(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,l.totalRequests]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,Zl(l.successRate,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,Zl(l.fallbackRate,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,Xl(l.durationMs.p50,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,Xl(l.durationMs.p95,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,Xl(l.durationMs.p99,o)]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,l.cooldownTriggeringFailures]}),(0,z.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,l.confidence??o]}),l.historyTruncated?(0,z.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`routing.candidate`)}),(0,z.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,z.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,z.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,z.jsx)(`tbody`,{children:l.breakdown.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,z.jsx)(`td`,{children:e.requests}),(0,z.jsx)(`td`,{children:Zl(e.successRate,o)}),(0,z.jsx)(`td`,{children:Xl(e.p50DurationMs,o)})]},`${e.provider}/${e.model}`))})]})]}):(0,z.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var iu=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],au=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],ou=[`present`,`corrupt`,`purged_unavailable`];function su(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function cu(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function lu(e){return e===null||typeof e==`string`}function uu(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function du(e){if(!su(e)||typeof e.projectionAvailable!=`boolean`||e.projectionIncompatible!==void 0&&typeof e.projectionIncompatible!=`boolean`)return null;for(let t of[`sqliteSchemaVersion`,`builtAtMs`,`eventCount`,`subjectCount`,`observationCount`,`claimCount`,`verdictCount`,`artifactCount`,`corruptionCount`])if(!uu(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function fu(e){return!su(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!iu.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||e.suiteId.length===0||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.projectionSpecVersion!=`string`||typeof e.verdict!=`string`||!au.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!cu(e.scenarioManifestDigests)||!lu(e.claimSourceDigest)||!cu(e.contributingEventIds)||!cu(e.contradictingEventIds)||!cu(e.notes)?null:e}function pu(e){return!su(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(fu).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function mu(e){return!su(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>su(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function hu(e){return!su(e)||!su(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function gu(e){return!su(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!iu.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.scenarioId!=`string`||typeof e.scenarioVersion!=`string`||typeof e.scenarioManifestDigest!=`string`||typeof e.outcome!=`string`||typeof e.completedAt!=`number`||!Number.isFinite(e.completedAt)||typeof e.executionMode!=`string`||typeof e.excluded!=`boolean`||!lu(e.exclusionReason)?null:e}function _u(e){return!su(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(gu).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function vu(e){if(!su(e)||!su(e.event))return null;let t={...e.event};return delete t.payload_json,typeof t.eventKind!=`string`||typeof t.eventId!=`string`||typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt)||typeof t.producer!=`string`||typeof t.producerVersion!=`string`||typeof t.excluded!=`boolean`||!lu(t.exclusionReason)?null:t}function yu(e){if(!su(e)||!su(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!ou.includes(t.status)||!lu(t.artifactClass)||!lu(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!lu(t.lastError)?null:t}function bu(e){let t={},n=e.subjectQuery.trim();return e.layer&&(t.layer=e.layer),e.verdict&&(t.verdict=e.verdict),n&&(t.subjectId=n),e.suiteId.trim()&&(t.suiteId=e.suiteId.trim()),t}function xu(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function Su(e,t){let n=new Map(t.map(e=>[e.subjectId,e.subjectKind])),r=new Map;for(let t of e){let e=r.get(t.subjectId);e||(e={subjectId:t.subjectId,subjectKind:n.get(t.subjectId)??``,byLayer:xu()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function Cu(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function wu(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function Tu(e){let t=new Set;e.suiteManifestDigest&&t.add(e.suiteManifestDigest);for(let n of e.scenarioManifestDigests)n&&t.add(n);return e.claimSourceDigest&&t.add(e.claimSourceDigest),[...t]}var Eu=50,Du=200,Ou=6,ku=200;async function Au(e,t,n){return St(await fetch(`${e}${t}`,{signal:n}))}function ju(e,t){let n=new URLSearchParams({limit:String(Eu)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Mu=class extends Error{};function Nu(){return new Mu}function Pu(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw Nu()}function Fu(e){if(!su(e)||!Array.isArray(e.verdicts))throw Nu();let t=pu(e);if(t.verdicts.length!==e.verdicts.length)throw Nu();return Pu(e,t.hasMore,t.nextCursor),t}function Iu(e){if(!su(e)||!Array.isArray(e.subjects))throw Nu();let t=mu(e);if(t.subjects.length!==e.subjects.length)throw Nu();return Pu(e,t.hasMore,t.nextCursor),t}function Lu(e){if(!su(e)||!Array.isArray(e.observations))throw Nu();let t=_u(e);if(t.observations.length!==e.observations.length)throw Nu();return Pu(e,t.hasMore,t.nextCursor),t}async function Ru(e,t){let n=du(await Au(e,`/api/lab/status`,t));if(!n)throw Nu();return n}async function zu(e,t,n,r){return Fu(await Au(e,`/api/lab/verdicts?${ju({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Bu(e,t,n){return Iu(await Au(e,`/api/lab/subjects?${ju({},t)}`,n))}async function Vu(e){let t=[],n=new Set,r;for(let i=0;i<Du;i++){let i=await e(r);if(t.push(...i.rows),!i.hasMore)return{rows:t,truncated:!1};let a=i.nextCursor;if(!a||n.has(a)||a===r)throw new Mu;n.add(a),r=a}return{rows:t,truncated:!0}}async function Hu(e,t){return Vu(async n=>{let r=await Bu(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function Uu(e,t,n){let r=hu(await Au(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw Nu();return r}async function Wu(e,t,n,r){return Lu(await Au(e,`/api/lab/observations?${ju({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Gu(e,t,n){return Vu(async r=>{let i=await Wu(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Ku(e,t,n){let r=vu(await Au(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw Nu();return r}async function qu(e,t,n){let r=yu(await Au(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw Nu();return r}function Ju(e){if(!su(e)||e.verificationStatus!==`not_verification`||!su(e.summary))throw Nu();let t=e.summary;if(t.verificationStatus!==`not_verification`||typeof t.subjectId!=`string`||typeof t.recentProductionAttempts!=`number`||typeof t.recentSuccessfulAttempts!=`number`||typeof t.recentRouteErrorSignals!=`number`||t.lastObservedProductionAttempt!==void 0&&typeof t.lastObservedProductionAttempt!=`number`)throw Nu();return{verificationStatus:`not_verification`,summary:t}}async function Yu(e,t,n){return Ju(await Au(e,`/api/lab/production-signals?${ju({subjectId:t})}`,n))}function Xu(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function Zu(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function Qu(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function $u(e){if(!su(e)||!Xu(e,[`evidence`,`trustClass`,`locallyVerified`])||e.trustClass!==`community_untrusted_v1`||e.locallyVerified!==!1||!Array.isArray(e.evidence)||e.evidence.length>4096)return null;let t=[];for(let n of e.evidence){if(!su(n)||!Xu(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!Zu(n.bundleId)||!Zu(n.publisherKeyId)||!Qu(n.activeRecordCount)||!Qu(n.revokedRecordCount))return null;t.push({trustClass:`community_untrusted_v1`,status:`cryptographically_valid`,bundleId:n.bundleId,publisherKeyId:n.publisherKeyId,activeRecordCount:n.activeRecordCount,revokedRecordCount:n.revokedRecordCount})}return{evidence:t,trustClass:`community_untrusted_v1`,locallyVerified:!1}}async function ed(e,t){let n=$u(await Au(e,`/api/lab/public/community`,t));if(!n)throw Nu();return n}async function td(e,t,n){let[r,i]=await Promise.all([Ru(e,n),ed(e,n).catch(e=>{if(n.aborted)throw e;return null})]);if(!r.projectionAvailable)return{status:r,verdicts:[],subjects:[],subjectsTruncated:!1,hasMore:!1,community:i};let[a,o]=await Promise.all([zu(e,t,void 0,n),Hu(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function nd(e,t,n,r){return zu(e,t,n,r)}async function rd(e,t,n,r){let i=e.slice(0,ku),a=[],o=0,s=async()=>{for(;;){if(n.aborted)throw new DOMException(`Aborted`,`AbortError`);let e=o++;if(e>=i.length)return;try{a.push(await r(i[e]))}catch(e){if(n.aborted)throw e}}},c=Math.min(t,i.length);return await Promise.all(Array.from({length:c},()=>s())),a}async function id(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=Tu(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([Uu(e,t.subjectId,n),Gu(e,a,n),rd(r,Ou,n,t=>Ku(e,t,n)),rd(i,Ou,n,t=>qu(e,t,n)),Yu(e,t.subjectId,n).catch(e=>{if(n.aborted)throw e;return null})]);return{subject:o,observations:s.rows,observationsTruncated:s.truncated,events:c,artifacts:l,production:u}}var ad={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},od={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},sd={UNKNOWN:`lab.verdict.UNKNOWN`,CLAIMED:`lab.verdict.CLAIMED`,PROBED:`lab.verdict.PROBED`,VERIFIED:`lab.verdict.VERIFIED`,DEGRADED:`lab.verdict.DEGRADED`,BLOCKED:`lab.verdict.BLOCKED`,UNSUPPORTED:`lab.verdict.UNSUPPORTED`},cd={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function ld(e,t){if(!(e instanceof Error))return t;let n=e.message;return n===`Failed to fetch`||n.includes(`NetworkError`)||n.includes(`network error`)?t:n||t}function ud({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,z.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,z.jsx)(`span`,{children:n}),(0,z.jsx)(`span`,{className:`suite`,children:t})]}):(0,z.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,z.jsx)(`span`,{children:n}),(0,z.jsx)(`span`,{className:`suite`,children:t})]})}function dd({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,z.jsx)(`span`,{className:`muted`,children:`-`}):(0,z.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,z.jsx)(ud,{verdict:e.verdict,caption:e.suiteId,label:t(sd[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function fd({data:e,t,locale:n}){let{status:r}=e,i=[{label:t(`lab.subjectCount`),value:String(r.subjectCount??0)},{label:t(`lab.verdictCount`),value:String(r.verdictCount??0)},{label:t(`lab.observationCount`),value:String(r.observationCount??0)},{label:t(`lab.eventCount`),value:String(r.eventCount??0)}];return r.builtAtMs&&i.push({label:t(`lab.builtAt`),value:wu(r.builtAtMs,n)}),(0,z.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,z.jsxs)(`div`,{className:`lab-status-card`,children:[(0,z.jsx)(`span`,{className:`label`,children:e.label}),(0,z.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function pd({community:e,locale:t}){if(!e||e.evidence.length===0)return null;let n=e.evidence.reduce((e,t)=>e+t.activeRecordCount,0),r=e.evidence.reduce((e,t)=>e+t.revokedRecordCount,0);return(0,z.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,z.jsx)(`h3`,{className:`lab-matrix-title`,children:Re(t,`community.title`)}),(0,z.jsx)(`p`,{className:`muted`,children:Re(t,`community.notLocalVerdict`)}),(0,z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:Re(t,`community.bundles`)}),(0,z.jsx)(`dd`,{children:e.evidence.length})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:Re(t,`community.activeRecords`)}),(0,z.jsx)(`dd`,{children:n})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:Re(t,`community.revokedRecords`)}),(0,z.jsx)(`dd`,{children:r})]})]})]})}function md({verdict:e,detail:t,loading:n,error:r,t:i,locale:a,onClose:o}){let s=new Set([...e.contributingEventIds,...e.contradictingEventIds]).size;return(0,z.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,z.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,z.jsx)(`h3`,{children:Cu(e.subjectId)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,z.jsx)(`dd`,{children:i(ad[e.evidenceLayer])})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,z.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,z.jsx)(`dd`,{children:i(sd[e.verdict])})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,z.jsx)(`dd`,{children:wu(e.asOf,a)})]})]}),n&&(0,z.jsx)(xc,{busy:!0,children:i(`common.loading`)}),r&&(0,z.jsx)($,{tone:`err`,children:r}),t&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,z.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,z.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,z.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,z.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,z.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,z.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,z.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,z.jsx)(`dd`,{children:wu(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,z.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,z.jsx)(`span`,{children:e.outcome}),(0,z.jsx)(`span`,{className:`muted`,children:wu(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,z.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,z.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,z.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,z.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,z.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`mono`,title:e.digest,children:Cu(e.digest)}),(0,z.jsx)(`span`,{children:e.artifactClass??`-`}),(0,z.jsx)(`span`,{children:Re(a,cd[e.status])})]},e.digest))})]})]})]})}function hd({apiBase:e,active:t=!0,onCountChange:n}){let{t:r,locale:i}=Ze(),[a,o]=(0,_.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),T=(0,_.useMemo)(()=>bu(a),[a]),E=JSON.stringify(T),D=(0,_.useCallback)(t=>td(e,T,t),[e,T]),O=vc(`lab-matrix:${e}:${E}`,[e,E],D,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:t,pauseWhenHidden:!0}),k=(0,_.useCallback)(()=>{S.current?.abort(),S.current=null,c(null),u(null),f(!1)},[]),A=(0,_.useCallback)(()=>{w.current=null,C.current?.abort(),C.current=null,m(null),g(null),x(null),y(!1)},[]);(0,_.useEffect)(()=>{S.current?.abort()},[O.data]),(0,_.useEffect)(()=>()=>{S.current?.abort(),C.current?.abort()},[]);let j=(0,_.useCallback)(e=>{A(),k(),o(e)},[A,k]),M=s!==null&&s.baseData===O.data&&s.queryKey===E?s:null,N=l!==null&&l.baseData===O.data&&l.queryKey===E?l.message:null,P=(0,_.useMemo)(()=>{if(!t||!O.data?.status.projectionAvailable)return null;let e=O.data.status.verdictCount;return typeof e==`number`?e:O.data.verdicts.length+(M?.verdicts.length??0)},[t,O.data,M]);(0,_.useEffect)(()=>{n?.(P)},[n,P]);let F=(0,_.useMemo)(()=>O.data?[...O.data.verdicts,...M?.verdicts??[]]:[],[O.data,M]),I=(0,_.useMemo)(()=>O.data?Su(F,O.data.subjects):[],[F,O.data]),L=(0,_.useCallback)(async()=>{let t=M?.nextCursor??O.data?.nextCursor,n=O.data;if(!t||!n||d)return;S.current?.abort();let i=new AbortController;S.current=i;let a=E;u(null),f(!0);try{let r=await nd(e,T,t,i.signal);if(i.signal.aborted)return;c(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...r.verdicts],nextCursor:r.nextCursor,hasMore:r.hasMore}})}catch(e){i.signal.aborted||u({baseData:n,queryKey:a,message:ld(e,r(`lab.loadFailed`))})}finally{S.current===i&&(S.current=null,f(!1))}},[e,d,T,E,O.data,r,M]),R=(0,_.useCallback)(async n=>{if(!t)return;C.current?.abort();let i=new AbortController;C.current=i,w.current=n.projectionKey,m(n),g(null),x(null),y(!0);try{let t=await id(e,n,i.signal);!i.signal.aborted&&w.current===n.projectionKey&&g(t)}catch(e){!i.signal.aborted&&w.current===n.projectionKey&&x(ld(e,r(`lab.detailLoadFailed`)))}finally{C.current===i&&(C.current=null,!i.signal.aborted&&w.current===n.projectionKey&&y(!1))}},[t,e,r]),B=O.refresh,V=(0,_.useCallback)(()=>{A(),k(),B({forceLoading:!0})},[A,B,k]),H=t?p:null,U=M?M.hasMore:O.data?.hasMore??!1,W=[{value:``,label:r(`lab.filter.all`)},...iu.map(e=>({value:e,label:r(ad[e])}))],G=[{value:``,label:r(`lab.filter.all`)},...au.map(e=>({value:e,label:r(sd[e])}))],ee=[{value:``,label:r(`lab.filter.all`)},...(O.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${Cu(e.subjectId)} · ${e.subjectKind}`}))];if(O.state.showSkeleton)return(0,z.jsx)(bc,{label:r(`lab.loading`),rows:5});let te=O.state.showError?ld(O.error,r(`lab.loadFailed`)):null,K=O.data?.status,q=K&&!K.projectionAvailable,J=K?.projectionIncompatible===!0;return(0,z.jsxs)(`div`,{className:`lab-page`,children:[(0,z.jsx)(`div`,{className:`lab-toolbar`,children:(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:V,disabled:O.refreshing,children:[(0,z.jsx)(re,{}),r(`lab.refresh`)]})}),O.refreshing&&!O.state.showSkeleton&&(0,z.jsx)(xc,{busy:!0,live:!te,children:r(`common.loading`)}),te&&(0,z.jsx)($,{tone:`err`,children:te}),J&&(0,z.jsx)($,{tone:`err`,children:r(`lab.projectionIncompatible`)}),q&&!J&&(0,z.jsx)(gt,{title:r(`lab.projectionUnavailable`)}),O.data&&(0,z.jsx)(pd,{community:O.data.community,locale:i}),O.data&&K?.projectionAvailable&&!J&&(0,z.jsxs)(`div`,{className:`lab-layout`,children:[(0,z.jsxs)(`div`,{className:`lab-main`,children:[(0,z.jsx)(fd,{data:O.data,t:r,locale:i}),(0,z.jsxs)(`div`,{className:`lab-filters`,children:[(0,z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,z.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:r(`lab.filter.layer`)}),(0,z.jsx)(ht,{id:`lab-filter-layer`,value:a.layer,options:W,onChange:e=>j(t=>({...t,layer:e})),label:r(`lab.filter.layer`),portal:!1})]}),(0,z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,z.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:r(`lab.filter.verdict`)}),(0,z.jsx)(ht,{id:`lab-filter-verdict`,value:a.verdict,options:G,onChange:e=>j(t=>({...t,verdict:e})),label:r(`lab.filter.verdict`),portal:!1})]}),(0,z.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,z.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:r(`lab.filter.subject`)}),(0,z.jsx)(ht,{id:`lab-filter-subject`,value:a.subjectQuery,options:ee,onChange:e=>j(t=>({...t,subjectQuery:e})),label:r(`lab.filter.subject`),portal:!1})]})]}),I.length===0?(0,z.jsx)(gt,{title:r(`lab.empty`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,z.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.matrixTitle`)}),(0,z.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,z.jsxs)(`table`,{className:`lab-matrix`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,z.jsx)(`th`,{children:r(`lab.subjectKind`)}),iu.map(e=>(0,z.jsx)(`th`,{children:r(od[e])},e))]})}),(0,z.jsx)(`tbody`,{children:I.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`subject`,title:e.subjectId,children:Cu(e.subjectId)}),(0,z.jsx)(`td`,{className:`kind`,children:e.subjectKind||Re(i,`subjectKindUnknown`)}),iu.map(t=>(0,z.jsx)(`td`,{children:(0,z.jsx)(dd,{rows:e.byLayer[t],t:r,selectedKey:H?.projectionKey??null,onSelect:e=>{R(e)}})},t))]},e.subjectId))})]})})]}),(0,z.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,z.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.verdictsTitle`)}),(0,z.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,z.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,z.jsx)(`th`,{children:r(`lab.col.layer`)}),(0,z.jsx)(`th`,{children:r(`lab.col.suite`)}),(0,z.jsx)(`th`,{children:r(`lab.col.verdict`)}),(0,z.jsx)(`th`,{children:r(`lab.col.asOf`)})]})}),(0,z.jsx)(`tbody`,{children:F.map(e=>{let t=H?.projectionKey===e.projectionKey;return(0,z.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,z.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":Re(i,`selectVerdict`,{subject:Cu(e.subjectId)}),onClick:()=>{R(e)},children:Cu(e.subjectId)})}),(0,z.jsx)(`td`,{children:r(ad[e.evidenceLayer])}),(0,z.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,z.jsx)(`td`,{children:(0,z.jsx)(ud,{verdict:e.verdict,caption:e.suiteId,label:r(sd[e.verdict])})}),(0,z.jsx)(`td`,{children:wu(e.asOf,i)})]},e.projectionKey)})})]})})]}),N&&(0,z.jsx)($,{tone:`err`,children:N}),U&&(0,z.jsx)(`div`,{className:`lab-load-more`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{L()},children:r(d?`common.loading`:`lab.loadMore`)})})]})]}),H&&(0,z.jsx)(md,{verdict:H,detail:h,loading:v,error:b,t:r,locale:i,onClose:A})]})]})}var gd=[`catalog`,`combos`,`routing`,`compatibility`];function _d(e){return e===`catalog`?`models`:`models/${e}`}function vd(e=window.location.hash){let t=et(e);return t===`models/combos`||t===`combos`||t.startsWith(`combos/`)?`combos`:t===`models/routing`||t===`routing`||t.startsWith(`routing/`)?`routing`:t===`models/compatibility`||t===`lab`||t.startsWith(`lab/`)?`compatibility`:`catalog`}function yd(e){nt(_d(e))}function bd(e){return`models-tab-${e}`}function xd(e){return`models-panel-${e}`}var Sd={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function Cd({tab:e,onSelect:t,meta:n}){let r=Z(),i=(0,_.useRef)(null);i.current===null&&(i.current=new Map);let a=e=>{t(e),window.requestAnimationFrame(()=>{i.current.get(e)?.focus({preventScroll:!0})})},o=t=>{let n=gd.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+gd.length)%gd.length:t.key===`ArrowRight`?r=(n+1)%gd.length:t.key===`Home`?r=0:t.key===`End`&&(r=gd.length-1),r!==null&&(t.preventDefault(),a(gd[r]))};return(0,z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:gd.map(t=>{let s=t===e,c=n?.[t];return(0,z.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:bd(t),"aria-selected":s,"aria-controls":xd(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(Sd[t]),c?(0,z.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function wd(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??[],contextWindow:n?.contextWindow,modelContextWindows:n?.modelContextWindows,discovery:n?.discovery}}).sort((e,t)=>e.native===t.native?e.provider.localeCompare(t.provider):e.native?-1:1)}function Td(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ed(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Dd(e){if(!Td(e))throw Error(`invalid selected models response`);let t=e.selected;if(!Td(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ed(t)]))}async function Od(e,t=fetch,n){let r=await t(`${e}/api/selected-models`,n?{signal:n}:void 0);if(!r.ok)throw Error(`selected models HTTP ${r.status}`);return Dd(await r.json())}function kd(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Ad(e,t,n,r,i){return kd(e,t,n,r)&&!i}async function jd(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 Md(e,t){return e===t}function Nd(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 Pd=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Fd=Array.from({length:18},(e,t)=>1e5+t*5e4),Id=new Set(Fd),Ld=`custom`,Rd=[4,8,16,32,64,128,256,500,1e3],zd=new Set(Rd),Bd=`ocx-models-collapsed:v2`;function Vd(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?`${e/1e3}k`:e.toLocaleString()}function Hd(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Ud(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);Ad(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?gn(a.namespaced,r):a.namespaced})}return i}function Wd(e=localStorage){try{let t=e.getItem(Bd);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 Gd(e,t=localStorage){try{t.setItem(Bd,JSON.stringify([...e]))}catch{}}function Kd({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Z(),i=e&&t?.status===`failed`?t:void 0;return(0,z.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,z.jsx)(ce,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,z.jsxs)(`span`,{children:[i&&n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${Nd(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>nt(`providers`),children:r(`models.openProviderSettings`)})]})]})}var qd={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function Jd(e){let t=e.replace(/[_,\s]/g,``);if(!t)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}function Yd({apiBase:e,restartEpoch:t=0}){let[n,r]=(0,_.useState)(null),i=(0,_.useRef)(!0);(0,_.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,_.useCallback)(t=>{oc(e,{signal:t}).then(e=>{t?.aborted||!i.current||r(e.state)})},[e]),{restarting:o,restart:s}=dc(e,{onSettled:()=>a()});(0,_.useEffect)(()=>{let e=new AbortController;return a(e.signal),()=>e.abort()},[a,t]);let[c,l]=(0,_.useState)(vd),[u,d]=(0,_.useState)(()=>new Set([vd()])),f=(0,_.useCallback)(e=>{l(e),d(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,_.useEffect)(()=>{let e=()=>f(vd());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[f]);let p=(0,_.useCallback)(e=>{yd(e),f(e)},[f]),m=c===`catalog`,[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),S=Z(),C=`ocx.models.catalog.v1:${e}`,w=(0,_.useMemo)(()=>qn(C),[C]),[T,E]=(0,_.useState)(()=>w?.models??[]),[D,O]=(0,_.useState)(()=>w?.providers??[]),[k,A]=(0,_.useState)(()=>new Set(w?.disabled??[])),[j,M]=(0,_.useState)(()=>w?.selectedModels??null),[N,P]=(0,_.useState)({}),[F,I]=(0,_.useState)({}),[R,B]=(0,_.useState)(()=>w?.contextCaps??{}),[V,H]=(0,_.useState)(()=>w?.contextCapValue??35e4),[W,G]=(0,_.useState)(``),[ee,te]=(0,_.useState)(!1),[K,q]=(0,_.useState)({}),[Y,ne]=(0,_.useState)({}),ie=Wd(),[ae,oe]=(0,_.useState)(()=>ie??new Set),le=(0,_.useRef)(ie===null),[ue,X]=(0,_.useState)(``),[de,pe]=(0,_.useState)(!1),[me,he]=(0,_.useState)(0),ge=(e,t)=>{pe(e),X(t),he(e=>e+1)};(0,_.useEffect)(()=>{if(!ue)return;let e=setTimeout(()=>X(``),de?6e3:8e3);return()=>clearTimeout(e)},[ue,de,me]);let[_e,ve]=(0,_.useState)(!1),ye=(0,_.useRef)(!1),be=(0,_.useRef)(0),xe=(0,_.useRef)(!1),[Se,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)(!0),[Ee,De]=(0,_.useState)(!1),[Oe,ke]=(0,_.useState)(``),Ae=(0,_.useRef)(!1),[je,Me]=(0,_.useState)(``),[Ne,Pe]=(0,_.useState)(!1),[Fe,Ie]=(0,_.useState)(!1),[Le,Re]=(0,_.useState)(!1),[ze,Be]=(0,_.useState)(`add`),[Ve,He]=(0,_.useState)(``),[Ue,We]=(0,_.useState)(``),[Ge,Ke]=(0,_.useState)(``),[qe,Je]=(0,_.useState)(``),[Ye,Xe]=(0,_.useState)(``),[Ze,Qe]=(0,_.useState)(!1),[$e,et]=(0,_.useState)([`text`]),[tt,nt]=(0,_.useState)(!1),[rt,it]=(0,_.useState)([]),at=(0,_.useRef)(!1),[Q,ot]=(0,_.useState)(!1),[st,ct]=(0,_.useState)(``),[lt,ut]=(0,_.useState)(null),[dt,ft]=(0,_.useState)([]),[mt,vt]=(0,_.useState)(``),[yt,bt]=(0,_.useState)(``),[xt,wt]=(0,_.useState)({}),[Tt,Et]=(0,_.useState)({contextWindow:null,modelContextWindows:{}}),[Dt,Ot]=(0,_.useState)(new Set),[kt,At]=(0,_.useState)(!1),[jt,Mt]=(0,_.useState)(!1),[Nt,Pt]=(0,_.useState)(``),[Ft,It]=(0,_.useState)(null),Lt=(0,_.useRef)(null),[Rt,zt]=(0,_.useState)(null),[Bt,Vt]=(0,_.useState)(!1),[Ht,Ut]=(0,_.useState)(null);(0,_.useEffect)(()=>()=>{Lt.current&&clearTimeout(Lt.current)},[]);let Wt=(0,_.useMemo)(()=>Ud(T,k,j??{},S),[T,k,j,S]),Gt=(0,_.useMemo)(()=>{let e=new Set(Wt.map(e=>e.value));return Yt(T.filter(t=>e.has(t.namespaced)),Rt?.model)},[T,Rt?.model,Wt]),Kt=(0,_.useCallback)(async()=>{try{let t=await Ct(await fetch(`${e}/api/shadow-call-settings`));t&&zt(t)}catch{}},[e]),qt=(0,_.useCallback)(async()=>{if(!Ae.current)try{let t=await fetch(`${e}/api/v2`);if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){Ce(null);return}let n=await Ct(t);if(!n||typeof n.enabled!=`boolean`){Ce(null);return}Ce({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{Ce(null)}finally{Te(!1)}},[e]),Jt=(0,_.useCallback)(async t=>{let[n,r,i,a]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),Od(e,fetch,t)]),[o,s,c]=await Promise.all([St(n),St(r),St(i)]);if(o===void 0||s===void 0||c===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let l=Hd(o),u=typeof s.value==`number`&&Number.isFinite(s.value)&&s.value>0?s.value:typeof s.cap==`number`&&Number.isFinite(s.cap)&&s.cap>0?s.cap:void 0,d=u===void 0?35e4:u,f={models:o,providers:c,selectedModels:a,disabled:[...l],contextCaps:s.caps??{},contextCapValue:d};return Jn(C,f),f},[e,C]),Xt=(0,_.useCallback)(e=>{let t=wd(e.models,e.providers);Ut(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),E(e.models),O(e.providers),A(new Set(e.disabled)),M(e.selectedModels),H(e.contextCapValue),B(e.contextCaps)},[]),Zt=vc(C,[e],async e=>{let t=await Jt(e);if(e.aborted)throw Error(`models request aborted`);return Xt(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:w??void 0,enabled:m}),Qt=Zt.state,$t=(0,_.useCallback)(async(e=!1)=>{if(xe.current&&!e)return!1;xe.current=!0;let t=++be.current;try{let e=await Jt(new AbortController().signal);return Md(t,be.current)?(Xt(e),L(C,e),!0):!1}catch{return!1}finally{Md(t,be.current)&&(xe.current=!1)}},[Xt,C,Jt]);(0,_.useEffect)(()=>{if(!m)return;let e=window.setTimeout(()=>{Kt(),qt()},0),t=window.setInterval(()=>{Ae.current||qt()},1e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[m,Kt,qt]);let en=(0,_.useMemo)(()=>wd(T,D),[T,D]),tn=T.length>0||Qt.data!==void 0,nn=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;ut(e.provider),ft(t),vt(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));bt(r),wt(i),Et({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Ot(new Set),At(!1),Pt(``)},on=e=>{vt(e)},sn=async()=>{if(!lt)return;let t=Jd(yt);if(!en.find(e=>e.provider===lt)){Pt(S(`models.contextSaveFailed`));return}if(kt&&t===void 0){Pt(S(`models.contextInvalid`));return}let n={};for(let e of Dt){let t=Jd(xt[e]??``);if(t===void 0){Pt(S(`models.contextInvalid`));return}t!==(Tt.modelContextWindows[e]??null)&&(n[e]=t)}let r=kt&&t!==Tt.contextWindow;if(!r&&Object.keys(n).length===0){ut(null),ge(!0,S(`models.contextUnchanged`));return}Mt(!0),Pt(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await St(await fetch(`${e}/api/providers?name=${encodeURIComponent(lt)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),S(`models.contextSaveFailed`))}catch(e){Pt(e instanceof Error?e.message:S(`models.contextSaveFailed`));return}finally{Mt(!1)}ut(null),ge(!0,S(`models.contextSaved`)),await $t(!0)};(0,_.useEffect)(()=>{if(!le.current||en.length===0)return;le.current=!1;let e=new Set(en.map(e=>e.provider));oe(e),Gd(e)},[en]);let cn=(0,_.useMemo)(()=>j?T.filter(e=>Ad(j,e.provider,e.id,e.native===!0,k.has(e.namespaced))).length:0,[k,T,j]),ln=(0,_.useMemo)(()=>({catalog:tn?S(`models.active`,{active:cn,total:T.length}):void 0,combos:h===null?void 0:String(h),routing:v===null?void 0:String(v),compatibility:b===null?void 0:String(b)}),[tn,h,b,cn,T.length,v,S]),un=async(t,n,r,i)=>{++be.current,ve(!0),ye.current=!0,X(``);let a=null;try{(await jd(e,t,n,r,i)).ok||(a=`models.saveFailed`)}catch{a=`models.networkError`}finally{let e=await $t(!0);a?(pe(!1),X(S(a))):e&&(pe(!0),X(S(`models.applied`))),ve(!1),ye.current=!1}},dn=async t=>{ve(!0),ye.current=!0,X(``);let n=R[t]===void 0;try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,enabled:n})});try{let e=await St(r,S(`models.capSaveFailed`));B(e?.caps??{}),pe(!0),X(S(`models.capApplied`)),await $t(!0)}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{ve(!1),ye.current=!1}},fn=e=>{oe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Gd(n),n})},mn=e=>{oe(()=>{let t=e?new Set(en.map(e=>e.provider)):new Set;return Gd(t),t})},_n=async t=>{ve(!0),ye.current=!0,X(``);try{let n=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await St(n,S(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&H(e.value),B(e?.caps??{}),pe(!0),X(S(`models.capApplied`)),await $t(!0)}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{ve(!1),ye.current=!1}},vn=(0,_.useMemo)(()=>{let e=en.filter(e=>!e.native);return e.length>0&&e.every(e=>R[e.provider]===V)&&Object.keys(R).every(e=>R[e]===V)},[en,R,V]),yn=e=>{!Number.isSafeInteger(e)||e<=0||_n(vn?{value:e,setAll:!0}:{value:e})},bn=(e,t)=>{if(t===`custom`){q(t=>({...t,[e]:!0})),ne(t=>({...t,[e]:String(R[e]??V)}));return}q(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==R[e]&&_n({provider:e,enabled:!0,value:n})},xn=e=>{let t=Number((Y[e]??``).replace(/[_,\s]/g,``));if(!Number.isSafeInteger(t)||t<=0){ge(!1,S(`models.capSaveFailed`));return}q(t=>({...t,[e]:!1})),_n({provider:e,enabled:!0,value:t})},Sn=e=>{if(e===`custom`){te(!0),G(String(V));return}te(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==V&&yn(t)},Cn=()=>{let e=Number(W.replace(/[_,\s]/g,``));if(!Number.isSafeInteger(e)||e<=0){ge(!1,S(`models.capSaveFailed`));return}te(!1),yn(e)},wn=()=>{_n({setAll:!vn})},Tn=async t=>{if(!(!Rt||Bt)){Vt(!0),zt({...Rt,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Vt(!1)}}},En=async t=>{if(!(!Se||Ae.current)&&Se.multiAgentMode!==t){De(!0),Ae.current=!0,ke(``),X(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})});try{let e=await St(n,S(`models.saveFailed`));qt(),pe(!0),X(S(`models.v2Applied`)),ke((e?.warnings??[]).join(` `))}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{De(!1),Ae.current=!1}}},Dn=async t=>{if(!(!Se||Ae.current)){if(!Number.isInteger(t)||t<1){ge(!1,S(`models.v2ThreadsInvalid`));return}if(Se.maxConcurrentThreadsPerSession!==t){De(!0),Ae.current=!0,ke(``),X(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:t})});try{let e=await St(n,S(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){pe(!1),X(S(`models.saveFailed`));return}Ce({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`}),pe(!0),X(S(`models.v2ThreadsApplied`)),Pe(!1)}catch(e){pe(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{pe(!1),X(S(`models.networkError`))}finally{De(!1),Ae.current=!1}}}},On=e=>{if(e===`custom`){Pe(!0),Me(String(Se?.maxConcurrentThreadsPerSession??``));return}Pe(!1),Dn(Number(e))},kn=(e,t)=>{Lt.current&&clearTimeout(Lt.current),Lt.current=setTimeout(()=>{It({namespaced:e,rect:t.getBoundingClientRect()})},300)},An=(e,t)=>{Lt.current&&clearTimeout(Lt.current),It({namespaced:e,rect:t.getBoundingClientRect()})},jn=()=>{Lt.current&&clearTimeout(Lt.current),Lt.current=setTimeout(()=>It(null),120)},Mn=()=>{Lt.current&&clearTimeout(Lt.current)},Nn=async(t,n,r,i,a,o)=>{ot(!0),ct(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,modelId:n,displayName:r,contextWindow:i,inputModalities:a,reasoningEfforts:o})});try{await St(s,S(`models.customSaveFailed`)),Re(!1),ge(!0,S(`models.customAdded`)),await $t(!0)}catch(e){ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{ct(S(`models.networkError`))}finally{ot(!1)}},Pn=async(t,n)=>{ot(!0),ct(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await St(r,S(`models.customSaveFailed`)),Re(!1),ge(!0,S(`models.customUpdated`)),await $t(!0)}catch(e){ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{ct(S(`models.networkError`))}finally{ot(!1)}},Fn=async t=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(ge(!0,S(`models.customDeleted`)),await $t(!0)):ge(!1,S(`models.customSaveFailed`))}catch{ge(!1,S(`models.networkError`))}},In=Qt.data??w,Ln=Qt.kind===`failed-cold`?Qt.error instanceof Error?Qt.error.message:S(`models.loadFail`):null,Rn=Qt.showSkeleton&&!In,zn=j??{},Bn=e=>{let{provider:t,rows:n,native:r,liveModels:i,discovery:a}=e,o=ae.has(t),s=e=>Ad(zn,t,e.id,e.native===!0,k.has(e.namespaced)),c=n.filter(s).length,l=R[t]!==void 0,u=R[t]??V,d=r,f=i&&a?.status===`failed`?a:void 0,p=(N[t]??``).trim().toLowerCase(),m=p?n.filter(e=>e.id.toLowerCase().includes(p)):n,h=m.toSorted((e,t)=>Number(!s(e))-Number(!s(t))),g=F[t]??60,_=h.slice(0,g),v=m.length-_.length,y=n.length>0,b=!y||n.every(s),x=!y||n.every(e=>!s(e)),C=e=>{y&&un(`provider`,t,n.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,z.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,z.jsxs)(`div`,{className:`row group-head models-provider-head${o?``:` open`}`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>fn(t),"aria-expanded":!o,style:{flex:1,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,z.jsx)(fe,{style:{width:14,height:14,color:`var(--muted)`,transform:o?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,z.jsx)(`span`,{className:`text-body font-semibold`,children:hn(t)}),d&&(0,z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.nativeGroupLabel`)}),f&&(0,z.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:Nd(S,f),children:S(`models.discoveryFailedBadge`)}),(0,z.jsx)(`span`,{className:`muted mono text-label`,children:S(`models.active`,{active:c,total:n.length})})]}),(0,z.jsxs)(`div`,{className:`row models-provider-actions`,children:[!d&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>nn(e),"aria-haspopup":`dialog`,children:S(`models.contextSettings`)}),!d&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),Be(`add`),He(t),We(``),Ke(``),Je(``),Xe(``),Qe(!1),et([`text`]),nt(!1),it([]),at.current=!1,ct(``),Re(!0)},"aria-label":S(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:_e||b,onClick:()=>C(!0),children:S(`models.allOn`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:_e||x,onClick:()=>C(!1),children:S(`models.allOff`)}),!d&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(pt,{on:l,onClick:()=>dn(t),disabled:_e,label:S(`models.capValue`,{value:Vd(u)})}),l&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(ht,{value:K[t]?`custom`:String(u),options:[...!Id.has(u)&&!K[t]?[{value:String(u),label:Vd(u)}]:[],...Fd.map(e=>({value:String(e),label:Vd(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>bn(t,e),disabled:_e,label:S(`models.capValue`,{value:Vd(u)})}),K[t]&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:Y[t]??``,onChange:e=>ne(n=>({...n,[t]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&xn(t)},disabled:_e,"aria-label":S(`models.customPlaceholder`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>xn(t),disabled:_e,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]})]})]})]})]}),!o&&(0,z.jsxs)(`div`,{className:`models-provider-body`,children:[d&&(0,z.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:S(`models.nativeHint`)}),n.length===0&&(0,z.jsx)(Kd,{liveModels:i,discovery:a,showFailureBadge:!1}),n.length>30&&(0,z.jsx)(`input`,{className:`input`,placeholder:S(`models.search`),value:N[t]??``,onChange:e=>P(n=>({...n,[t]:e.target.value})),"aria-label":S(`models.search`)}),_.map(e=>{let n=!s(e);return(0,z.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>kn(e.namespaced,t.currentTarget),onMouseLeave:jn,onFocus:t=>An(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||It(null)},children:[(0,z.jsxs)(`div`,{className:`row models-model-row`,children:[(0,z.jsx)(pt,{on:!n,onClick:()=>void un(`models`,t,[{id:e.id,native:e.native===!0}],n),disabled:_e,label:e.native?e.id:e.namespaced}),(0,z.jsx)(`code`,{className:`mono text-control`,style:{color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:e.native?gc(e.id):gn(e.namespaced,S)}),e.custom&&(0,z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.customBadge`)}),e.contextCapped&&(0,z.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.contextCappedValue`,{value:Vd(e.contextCap??V)})})]}),Ft?.namespaced===e.namespaced&&(()=>{let t=Ft.rect,r=t.bottom+4,i=r+360>window.innerHeight;return(0,z.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:t.left+24,...i?{bottom:window.innerHeight-t.top+4}:{top:r}},onMouseEnter:Mn,onMouseLeave:jn,children:[(0,z.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,z.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,z.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:S(`models.customBadge`)}),(0,z.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipProvider`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:pn(e.provider,S)}),(e.contextWindow||e.contextCap)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipContext`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:Vd(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipModalities`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,z.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipStatus`)}),(0,z.jsx)(`span`,{className:`model-tip-val`,children:S(n?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,z.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{Be(`edit`),He(e.provider),We(e.customId),Ke(e.id),Je(e.displayName??``),Xe(e.contextWindow?String(e.contextWindow):``),Qe(!1),et(e.inputModalities??[`text`]),nt(Array.isArray(e.reasoningEfforts)),it(e.reasoningEfforts??[]),at.current=Array.isArray(e.reasoningEfforts),ct(``),Re(!0),It(null)},children:S(`models.customEdit`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{window.confirm(S(`models.customDeleteConfirm`,{name:e.displayName??e.id}))&&Fn(e.customId),It(null)},children:S(`models.customDelete`)})]})]})})()]},e.namespaced)}),v>0&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>I(e=>({...e,[t]:g+60})),className:`btn btn-ghost btn-sm models-show-more`,children:S(`models.showMore`,{n:v})})]})]},t)},Vn=Ht?en.filter(e=>e.provider===Ht):en,Hn=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`models-control-top-row`,children:[(0,z.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!Rt||void 0,children:[(0,z.jsxs)(`span`,{className:`models-shadow-label`,children:[S(`models.shadowCallIntercept`),` `,(0,z.jsx)(_t,{content:S(`models.shadowCallInterceptHint`,{models:rn(Rt?.sourceModels)}),side:`top`,maxWidth:320,children:(0,z.jsx)(`span`,{style:{cursor:`help`},"aria-label":S(`models.shadowCallInterceptHint`,{models:rn(Rt?.sourceModels)}),children:`ⓘ`})})]}),(0,z.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:S(`models.shadowCallOriginal`,{models:an(Rt?.sourceModels)})}),(0,z.jsx)(pt,{on:Rt?.enabled??!1,onClick:()=>void Tn({enabled:!Rt?.enabled}),disabled:!Rt||Bt,label:S(`models.shadowCallIntercept`)}),(0,z.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,z.jsx)(ht,{value:Rt?.model??``,options:Gt,onChange:e=>{zt(t=>t&&{...t,model:e}),Tn({model:e})},disabled:!Rt||Bt||!Rt.enabled,label:S(`models.shadowCallIntercept`)})})]}),(we||Se)&&(0,z.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2Label`)}),(0,z.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Se?.multiAgentMode??`default`)===e,className:`btn btn-sm${(Se?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(Se?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(Se?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!Se||Ee,onClick:()=>void En(e),children:S(`models.v2Mode_${e}`)},e))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!Se,onClick:()=>Ie(!0),"aria-label":S(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,z.jsx)(ce,{width:14,height:14,"aria-hidden":`true`})})]})]}),Se&&(Se.enabled||Se.agentsMaxThreadsConflict||Oe)&&(0,z.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[Se.enabled&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2ThreadsLabel`)}),(0,z.jsx)(ht,{value:Ne?`custom`:Se.maxConcurrentThreadsPerSession!==null&&Se.maxConcurrentThreadsPerSession!==void 0?zd.has(Se.maxConcurrentThreadsPerSession)?String(Se.maxConcurrentThreadsPerSession):`custom`:``,options:[...Se.maxConcurrentThreadsPerSession===null||Se.maxConcurrentThreadsPerSession===void 0?[{value:``,label:S(`models.v2ThreadsDefault`)}]:[],...Se.maxConcurrentThreadsPerSession!==null&&Se.maxConcurrentThreadsPerSession!==void 0&&!zd.has(Se.maxConcurrentThreadsPerSession)&&!Ne?[{value:`custom`,label:String(Se.maxConcurrentThreadsPerSession)}]:[],...Rd.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>On(e),disabled:Ee,label:S(`models.v2ThreadsLabel`)}),Ne&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:je,onChange:e=>Me(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Dn(Number(je.replace(/[_,\s]/g,``)))},disabled:Ee,"aria-label":S(`models.v2ThreadsLabel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:Ee,onClick:()=>{Dn(Number(je.replace(/[_,\s]/g,``)))},children:S(`models.v2ThreadsApply`)})]})]}),Se.enabled&&Se.agentsMaxThreadsConflict&&(0,z.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:S(`models.v2Conflict`)}),Oe&&(0,z.jsx)(`span`,{className:`muted text-label`,children:Oe})]}),(0,z.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:S(`models.contextCapLabel`)}),(0,z.jsx)(ht,{value:ee?Ld:String(V),options:[...!Id.has(V)&&!ee?[{value:String(V),label:Vd(V)}]:[],...Fd.map(e=>({value:String(e),label:Vd(e)})),{value:Ld,label:S(`models.custom`)}],onChange:e=>Sn(e),disabled:_e,label:S(`models.contextCapLabel`)}),ee&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:W,onChange:e=>G(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Cn()},disabled:_e,"aria-label":S(`models.customPlaceholder`)}),(0,z.jsx)(`button`,{type:`button`,onClick:Cn,disabled:_e,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]}),(0,z.jsx)(pt,{on:vn,onClick:wn,disabled:_e,label:S(`models.setAll`)}),(0,z.jsx)(`span`,{className:`muted text-label leading-body`,children:S(`models.setAllHint`,{value:Vd(V)})})]}),(()=>{let e=T.filter(e=>e.custom).length;return e===0?null:(0,z.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,z.jsx)(`span`,{className:`models-chip mono text-caption`,children:S(`models.customSummary`,{count:e})})})})(),(0,z.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,z.jsx)(ce,{width:15,height:15,"aria-hidden":`true`}),(0,z.jsx)(`span`,{children:S(`models.orderHint`)})]})]}),Un=(0,z.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>mn(!0),disabled:_e,children:[(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`}),` `,S(`models.collapseAll`)]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>mn(!1),disabled:_e,children:[(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,S(`models.expandAll`)]})]}),Wn=(0,z.jsx)(z.Fragment,{children:en.length===0&&(0,z.jsx)(gt,{icon:(0,z.jsx)(U,{}),title:S(`models.noRouted`),children:S(`models.noRoutedHint`)})}),Gn=(0,z.jsxs)(z.Fragment,{children:[Fe&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.v2Label`),onClick:()=>Ie(!1),onKeyDown:e=>{e.key===`Escape`&&Ie(!1)},children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:S(`models.v2Label`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ie(!1),"aria-label":S(`common.close`),children:`×`})]}),(0,z.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:S(`models.v2Help`)}),(0,z.jsx)(`div`,{className:`models-help-link`,children:(0,z.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:S(`models.v2DocsLink`)})}),(0,z.jsx)(`div`,{className:`modal-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Ie(!1),children:S(`common.ok`)})})]})}),lt&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.contextSettings`),onClick:()=>{jt||ut(null)},onKeyDown:e=>{e.key===`Escape`&&!jt&&ut(null)},children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:S(`models.contextSettingsTitle`,{provider:pn(lt,S)})}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ut(null),disabled:jt,"aria-label":S(`common.close`),children:`×`})]}),Nt&&(0,z.jsx)($,{tone:`err`,children:Nt}),(0,z.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:S(`models.contextHint`)}),(0,z.jsxs)(`div`,{className:`models-context-fields`,children:[(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextDefault`),(0,z.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:yt,onChange:e=>{bt(e.target.value),At(!0)},disabled:jt,placeholder:S(`models.contextAutomatic`),autoFocus:!0})]}),dt.length>0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.contextModel`),(0,z.jsx)(ht,{value:mt,options:dt.map(e=>({value:e,label:e})),onChange:on,disabled:jt,label:S(`models.contextModel`)})]}),(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextModelOverride`),(0,z.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:xt[mt]??``,onChange:e=>{wt(t=>({...t,[mt]:e.target.value})),Ot(e=>new Set(e).add(mt))},disabled:jt,placeholder:S(`models.contextAutomatic`)})]})]})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ut(null),disabled:jt,children:S(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void sn(),disabled:jt,children:S(jt?`models.customSaving`:`models.customApply`)})]})]})}),Le&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.customAdd`),onClick:()=>{Q||Re(!1)},onKeyDown:e=>{e.key===`Escape`&&!Q&&Re(!1)},children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{children:S(ze===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:pn(Ve,S)})}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Re(!1),disabled:Q,"aria-label":S(`common.close`),children:`×`})]}),st&&(0,z.jsx)($,{tone:`err`,children:st}),(0,z.jsxs)(`div`,{className:`models-field-stack`,children:[(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldModelId`),(0,z.jsx)(`input`,{className:`input`,value:Ge,onChange:e=>Ke(e.target.value),disabled:Q,placeholder:S(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldDisplayName`),(0,z.jsx)(`input`,{className:`input`,value:qe,onChange:e=>Je(e.target.value),disabled:Q,placeholder:S(`models.customFieldDisplayNamePlaceholder`)})]}),(0,z.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldContext`),(0,z.jsxs)(`div`,{className:`row models-field-row`,children:[(0,z.jsx)(ht,{value:Ze?`custom`:Ye,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:S(`models.custom`)}],onChange:e=>{if(e===`custom`){Qe(!0);return}Qe(!1),Xe(e)},disabled:Q,label:S(`models.customFieldContext`)}),Ze&&(0,z.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:Ye,onChange:e=>Xe(e.target.value),disabled:Q,placeholder:S(`models.customPlaceholder`),"aria-label":S(`models.customFieldContext`)})]})]}),(0,z.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldModalities`),(0,z.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:$e.includes(e),onChange:t=>{et(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Q}),(0,z.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,z.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldReasoning`),(0,z.jsx)(`div`,{className:`row models-field-row`,children:(0,z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:tt,onChange:e=>{if(nt(e.target.checked),e.target.checked&&!at.current){at.current=!0;let e=T.find(e=>e.provider===Ve&&e.id===Ge),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;it(t??[...Pd])}},disabled:Q}),(0,z.jsx)(`span`,{className:`text-control`,children:S(`models.customFieldReasoningOverride`)})]})}),tt&&(0,z.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:Pd.map(e=>(0,z.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:rt.includes(e),onChange:t=>{it(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:Q}),(0,z.jsx)(`span`,{className:`text-control`,children:S(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Re(!1),disabled:Q,children:S(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Q||!Ge.trim(),onClick:()=>{let e=Ge.trim(),t=qe.trim(),n=Ye?Number(Ye.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;if(ze===`add`){let n=tt?rt:void 0;Nn(Ve,e,t||void 0,r,$e.length>0?$e:void 0,n)}else Pn(Ue,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:$e,reasoningEfforts:tt?rt:null})},children:S(Q?`models.customSaving`:ze===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),Kn=(0,z.jsxs)(`div`,{className:`models-workspace-shell`,children:[ue&&(0,z.jsxs)(`div`,{className:`action-toast notice ${de?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[de?(0,z.jsx)(J,{}):(0,z.jsx)(se,{}),(0,z.jsx)(`span`,{children:ue})]}),Qt.showError&&(0,z.jsx)($,{tone:`err`,children:S(`models.loadFail`)}),(0,z.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":Qt.refreshing||void 0,children:[(0,z.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":S(`nav.models`),children:[(0,z.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,z.jsx)(`span`,{className:`models-workspace-rail-title`,children:S(`models.workspace.providers`)}),(0,z.jsx)(`span`,{className:`models-workspace-rail-count`,children:en.length})]}),(0,z.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,z.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ht===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ut(null),"aria-current":Ht===null?`true`:void 0,children:[(0,z.jsx)(`span`,{className:`models-workspace-rail-name`,children:S(`models.workspace.allProviders`)}),(0,z.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:cn,total:T.length})})]}),en.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>Ad(zn,t,e.id,e.native===!0,k.has(e.namespaced))).length;return(0,z.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Ht===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>Ut(t),"aria-current":Ht===t?`true`:void 0,children:[(0,z.jsx)(`span`,{className:`models-workspace-rail-name`,children:pn(t,S)}),(0,z.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,z.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":S(`models.workspace.mainAria`),children:[Hn,Un,(0,z.jsx)(`div`,{className:`models-provider-list`,children:Vn.map(e=>Bn(e))}),en.length===0&&Wn]})]}),Gn]});return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{children:S(`nav.models`)}),(0,z.jsx)(`div`,{className:`page-head-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{s()},disabled:o,"aria-label":S(o?`dash.codexRestarting`:`dash.codexRestart`),title:S(o?`dash.codexRestarting`:`dash.codexRestart`),children:(0,z.jsx)(re,{})})})]}),(0,z.jsx)($s,{state:n,controller:{restarting:o,restart:s}}),(0,z.jsx)(Cd,{tab:c,onSelect:p,meta:ln}),(0,z.jsx)(`p`,{className:`page-sub`,children:S(qd[c])}),(0,z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:xd(`catalog`),"aria-labelledby":bd(`catalog`),hidden:c!==`catalog`,children:(0,z.jsx)(Sc,{pageName:S(`models.tab.catalog`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:Rn?(0,z.jsx)(bc,{label:S(`models.loading`),rows:5}):Ln===null?Kn:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:Ln}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Zt.refresh(),children:S(`common.retry`)})]})})}),(0,z.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:xd(`combos`),"aria-labelledby":bd(`combos`),hidden:c!==`combos`,children:u.has(`combos`)&&(0,z.jsx)(Sc,{pageName:S(`models.tab.combos`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,z.jsx)(vl,{apiBase:e,active:c===`combos`,onCountChange:g})})}),(0,z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:xd(`routing`),"aria-labelledby":bd(`routing`),hidden:c!==`routing`,children:u.has(`routing`)&&(0,z.jsx)(Sc,{pageName:S(`models.tab.routing`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,z.jsx)(ru,{apiBase:e,active:c===`routing`,onCountChange:y})})}),(0,z.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:xd(`compatibility`),"aria-labelledby":bd(`compatibility`),hidden:c!==`compatibility`,children:u.has(`compatibility`)&&(0,z.jsx)(Sc,{pageName:S(`models.tab.compatibility`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,z.jsx)(hd,{apiBase:e,active:c===`compatibility`,onCountChange:x})})})]})}var Xd=`section`;function Zd(e,t){return[e,Xd,t].join(`-`)}function Qd(e){return[e,Xd,``].join(`-`)}var $d=1200;function ef({scope:e,items:t,ariaLabel:n}){let[r,i]=(0,_.useState)(t[0]?.id??``),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useCallback)(()=>{a.current=null,o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),c=(0,_.useCallback)(()=>{s();let n=null,r=1/0;for(let i of t){let t=document.getElementById(Zd(e,i.id));if(!t)continue;let a=Math.abs(t.getBoundingClientRect().top-72);a<r&&(r=a,n=i.id)}n&&i(n)},[s,t,e]);(0,_.useEffect)(()=>()=>s(),[s]),(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(Zd(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=a.current;if(n){let r=document.getElementById(Zd(e,n));t.some(e=>e.isIntersecting&&e.target===r)&&(s(),i(n));return}let r=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!r)return;let o=r.target.id.slice(Qd(e).length);i(e=>e===o?e:o)},{rootMargin:`-72px 0px -60% 0px`,threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[s,t,e]);let l=t=>{let n=document.getElementById(Zd(e,t));n&&(a.current=t,o.current!==null&&clearTimeout(o.current),o.current=setTimeout(c,$d),i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,z.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,z.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":Zd(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>l(t.id),children:[t.label,t.meta?(0,z.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function tf({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s,ultraMode:c,ultraSaving:l,onUltraModeSave:u,ultraLoadFailed:d,onUltraModeRetry:f}){let p=Z(),m=(c.hintText??``).trim().length>0;return(0,z.jsxs)(`div`,{className:`swi-delegation`,children:[d&&(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeLoadFail`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`common.retry`)})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`sub.delegation.model`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.delegation.modelHint`)})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,z.jsx)(ht,{value:e,options:[{value:``,label:p(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:gn(`${e.provider}/${e.model}`,p)}))],onChange:e=>s({model:e||null,effort:t||null}),disabled:o,label:p(`dash.injectionLabel`),align:`right`}),e&&n.length>0&&(0,z.jsx)(ht,{value:t,options:[{value:``,label:p(`dash.injectionEffortNone`)},...n.map(e=>({value:e,label:e}))],onChange:t=>s({model:e||null,effort:t||null}),disabled:o,label:p(`dash.injectionEffortLabel`),align:`right`})]})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`dash.syncCodexSubagentDefaults`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>s({syncCodexSubagentDefaults:!a}),disabled:o||!e,"aria-label":p(`dash.syncCodexSubagentDefaults`),"aria-pressed":a,children:(0,z.jsx)(`span`,{className:`knob`})})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`dash.multiAgentGuidance`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.multiAgentGuidanceHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":p(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,z.jsx)(`span`,{className:`knob`})})]}),(0,z.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,z.jsxs)(`div`,{className:`setting-copy`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeHint`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`switch ${m?`on`:``}`,onClick:()=>u({multiAgentModeHintText:m?null:rf}),disabled:o||l||!m&&!c.multiAgentV2Enabled,"aria-label":p(`sub.ultraMode`),"aria-pressed":m,children:(0,z.jsx)(`span`,{className:`knob`})}),!c.multiAgentV2Enabled&&(0,z.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeV2Required`)})]}),m&&(0,z.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,z.jsx)(nf,{initialHint:c.hintText??``,disabled:o||l,onSave:u,preset:`Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning sub-agents no longer applies. Delegate independent sub-tasks to sub-agents whenever parallel work would materially improve speed or quality — do not serialize work that can run concurrently. Each sub-agent runs in its own context and can use all available tools; prefer spawning specialists over doing everything yourself. This mode remains active until a later multi-agent mode developer message changes it.`,labels:{text:p(`sub.ultraModeText`),preset:p(`sub.ultraModePreset`),save:p(`common.save`)}},c.hintText)})]})}function nf({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,_.useState)(e);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`textarea`,{className:`input swi-ultra-mode-textarea`,value:a,onChange:e=>o(e.target.value),disabled:t,rows:4,"aria-label":i.text}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>o(r),disabled:t,children:i.preset}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{a.trim().length!==0&&n({multiAgentModeHintText:a})},disabled:t||a.trim().length===0,children:i.save})]})}var rf=`Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning sub-agents no longer applies. Delegate independent sub-tasks to sub-agents whenever parallel work would materially improve speed or quality — do not serialize work that can run concurrently. Each sub-agent runs in its own context and can use all available tools; prefer spawning specialists over doing everything yourself. This mode remains active until a later multi-agent mode developer message changes it.`;function af({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=Z(),[c,l]=(0,_.useState)(``),u=(0,_.useMemo)(()=>new Set(t),[t]),d=t.length>=5,f=(0,_.useMemo)(()=>{let t=c.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,c]),p=(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]);return(0,z.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,z.jsx)(ef,{scope:`subagents`,items:p,ariaLabel:s(`sub.sections`)}),(0,z.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,z.jsxs)(`section`,{id:Zd(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,z.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,z.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,z.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,z.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,z.jsx)(ce,{width:15,height:15,"aria-hidden":`true`}),(0,z.jsx)(`span`,{children:(0,z.jsx)($e,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,z.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,z.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,z.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,z.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,z.jsx)(`span`,{className:`swi-featured-name`,children:gc(e)}),(0,z.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,z.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,z.jsx)(ue,{})}),(0,z.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,z.jsx)(X,{})}),(0,z.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,z.jsx)(Y,{})})]})]},e))}),(0,z.jsx)(`div`,{className:`swi-save-row`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,z.jsxs)(`section`,{id:Zd(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,z.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,z.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,z.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,z.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,z.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,z.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,z.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,z.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,z.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,z.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,z.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,z.jsx)(W,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:gc(e)})]}),(0,z.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,z.jsx)(J,{style:{width:14,height:14}}):(0,z.jsx)(ne,{style:{width:14,height:14}})})]},e)})})]})]}),(0,z.jsxs)(`section`,{id:Zd(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,z.jsx)(`div`,{className:`swi-featured-head`,children:(0,z.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,z.jsx)(tf,{model:o.model,effort:o.effort,efforts:o.efforts,available:o.available,guidanceEnabled:o.guidanceEnabled,syncCodexDefaults:o.syncCodexDefaults,saving:o.saving,onSave:o.onSave,ultraMode:o.ultraMode,ultraSaving:o.ultraSaving,onUltraModeSave:o.onUltraModeSave,ultraLoadFailed:o.ultraLoadFailed,onUltraModeRetry:o.onUltraModeRetry})]})]})]})}function of(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=rr(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 Ot(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`);let n=await fetch(`${e}/api/injection-model`);v(await Ot(n))}catch{}finally{i(!1)}}},[e,v,r])}}function sf(e){return qn(e)}function cf({apiBase:e}){let t=Z(),n=`ocx.subagents.v1:${e}`,r=sf(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=of(e),[m,h]=(0,_.useState)({enabled:!1,hintText:null,multiAgentV2Enabled:!1}),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),x=(0,_.useRef)(0),S=(0,_.useRef)(e);(0,_.useEffect)(()=>{S.current=e,x.current++},[e]);let C=(0,_.useCallback)(async n=>{if(S.current!==e)return!1;let r=++x.current,i=await St(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));return!i||n?.aborted||r!==x.current||S.current!==e?!1:(b(!1),h({enabled:i.enabled??!1,hintText:i.multiAgentModeHintText??null,multiAgentV2Enabled:i.enabled===!0&&i.multiAgentMode===`v2`}),!0)},[e,t]);(0,_.useEffect)(()=>{let e=new AbortController;return(async()=>{await C(e.signal)})().catch(()=>{e.signal.aborted||(l(!1),b(!0),s(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[C,t]);let w=async n=>{if(g)return;let r=e;v(!0),s(``);try{if(await St(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),S.current!==r||!await C())return;l(!0),s(t(`sub.ultraModeSaved`))}catch(e){if(S.current!==r)return;l(!1),s(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{v(!1)}},T=(0,_.useCallback)(async()=>{try{if(!await C())return;l(!1),s(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{l(!1),b(!0),s(t(`sub.ultraModeLoadFail`))}},[C,t]),E=(0,_.useCallback)(async()=>{let r=await St(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),Jn(n,s),s},[e,n,t]),D=vc(n,[e],E,{isEmpty:()=>!1,initialData:r??void 0}),{state:O}=D,k=D.refresh,A=O.data??r,j=A?.available??[],M=e=>{u||(s(``),a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e]))},N=(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)})},P=async()=>{if(!(u||f.current)){f.current=!0,d(!0),s(``);try{let r=await St(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),Jn(n,{available:j,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)}}};if(O.showSkeleton&&!A)return(0,z.jsx)(bc,{label:t(`sub.loading`),rows:4});if(O.kind===`failed-cold`){let e=O.error instanceof Error?O.error.message:t(`sub.loadFail`);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:t(`common.retry`)})]})}return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,z.jsx)($,{tone:c?`ok`:`err`,children:o}),O.showError&&(0,z.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),(0,z.jsx)(af,{available:j,chosen:i,busy:u,onToggle:M,onMove:N,onSave:()=>{P()},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)},ultraMode:m,ultraSaving:g,onUltraModeSave:e=>{w(e)},ultraLoadFailed:y,onUltraModeRetry:()=>{T()}}})]})}function lf(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 uf(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 df(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var ff=(e,t)=>Math.abs(e-t)<1.01,pf=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},mf,hf=()=>{if(mf!==void 0)return mf;if(typeof navigator>`u`)return mf=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return mf=!0;let e=navigator.maxTouchPoints;return mf=navigator.platform===`MacIntel`&&e!==void 0&&e>0},gf=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},_f=e=>e,vf=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},yf=(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(gf(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(gf(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},bf={passive:!0},xf=typeof window>`u`||`onscrollend`in window,Sf=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&xf,o=0,s=a?null:pf(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,bf),a&&r.addEventListener(`scrollend`,u,bf),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Cf=(e,t)=>Sf(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),wf=(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`]},Tf=(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})},Ef=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:_f,rangeExtractor:vf,onChange:()=>{},measureElement:wf,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=e>0?s[0]?.key??n.getItemKey(0):null,l=e>0?s[e-1]?.key??n.getItemKey(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==c||t.getItemKey(o-1)!==l)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>e&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==l)&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=!1,s=0;if(r&&this.scrollOffset!==null){let[e,t]=r,n=this.getMeasurements(),{count:i,getItemKey:a}=this.options,c=0;for(;c<i&&a(c)!==e;)c++;if(c<i){let e=n[c];if(e){let n=Math.max(0,e.start+t);n!==this.scrollOffset&&(s=n-this.scrollOffset,this.scrollOffset=n,o=!0)}}}(o||i)&&(this.pendingScrollAnchor=[o?r[0]:null,o?r[1]:0,i,s])},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=uf(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.targetWindow=this.scrollElement&&`ownerDocument`in this.scrollElement?this.scrollElement.ownerDocument.defaultView:this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{if(t&&this._intendedScrollOffset===null&&e===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;let n=this.getScrollOffset();this.scrollDirection=t?n===e?this.scrollDirection:n<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!hf()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,bf),e.addEventListener(`touchend`,n,bf),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&&(hf()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?i!==0&&(this._iosDeferredAdjustment+=i):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),r&&this.scrollToEnd({behavior:r})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;if(this._iosDeferredAdjustment<0&&e>=t-1){this._iosDeferredAdjustment=0;return}let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=uf(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(e,t,n,r,i,a,o,s)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s}),{key:!1}),this.getMeasurements=uf(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s},c)=>{let l=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let u=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=e*2,a=this._flatMeasurements;if(!a||a.length<i){let e=new Float64Array(i);a&&u>0&&e.set(a.subarray(0,u*2)),a=e,this._flatMeasurements=a}let o;if(u===0)o=t+n;else{let e=u-1;o=a[e*2]+a[e*2+1]+s}for(let t=u;t<e;t++){let e=r(t),n=l.get(e),i=typeof n==`number`?n:this.options.estimateSize(t);a[t*2]=o,a[t*2+1]=i,o+=i+s}let c=lf(e,a,r);return this.measurementsCache=c,c}let d=this.measurementsCache.slice(0,u),f=Array(a).fill(void 0),p=new Float64Array(a),m=0;for(let e=0;e<u;e++){let t=d[e];t&&(f[t.lane]===void 0&&m++,f[t.lane]=e,p[t.lane]=t.end)}for(let i=u;i<e;i++){let e=r(i),c=this.laneAssignments.get(i),u,h,g=o===`estimate`||l.has(e);if(c!==void 0&&this.options.lanes>1){u=c;let e=f[u],r=e===void 0?void 0:d[e];h=r?r.end+s:t+n}else if(m===a){let e=0,t=p[0],n=f[0];for(let r=1;r<a;r++){let i=p[r];(i<t||i===t&&f[r]<n)&&(e=r,t=i,n=f[r])}u=e,h=t+s,g&&this.laneAssignments.set(i,u)}else u=i%this.options.lanes,h=t+n,g&&this.laneAssignments.set(i,u);let _=l.get(e),v=typeof _==`number`?_:this.options.estimateSize(i),y=h+v;d[i]={index:i,start:h,size:v,end:y,key:e,lane:u},f[u]===void 0&&m++,f[u]=i,p[u]=y}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=uf(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=kf(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=uf(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=this.itemSizeCache.get(i)??n,s=t-o;if(s!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,c=a?this.getTotalSize():0,l=this.getScrollOffset()+this.scrollAdjustments,u=this.itemSizeCache.has(i)?r+o<=l&&this.scrollDirection!==`backward`:r<l,d=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?u:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},s,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++;let f=!1;a?f=this.applyScrollAdjustment(this.getTotalSize()-c):d&&(f=this.applyScrollAdjustment(s)),this.notify(f)}},this.getVirtualItems=uf(()=>[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 df(t[Df(0,t.length-1,r?e=>n[e*2]:e=>df(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`){if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t]}if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0;let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0,e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:e=`auto`}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}applyScrollAdjustment(e,t){return e===0?!1:hf()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=e,!1):(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&ff(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()}},Df=(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 Of(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 kf(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=Of(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=Df(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 Af=typeof document<`u`?_.useLayoutEffect:_.useEffect;function jf({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`}},s=e=>{let t=a.current;if(!t.enabled||!t.container)return;o(e);let n=!!e.options.horizontal,r=t.mode===`transform`,i=n?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let a of c){let o=a.start-s,c=e.elementsCache.get(a.key);c&&t.lastPositions.get(c)!==o&&(t.lastPositions.set(c,o),r?c.style.transform=n?`translate3d(${o}px, 0, 0)`:`translate3d(0, ${o}px, 0)`:c.style[i]=`${o}px`)}},c={...r,onChange:(t,n)=>{var o;let c=a.current,l=!0;if(c.enabled){s(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,rt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=_.useState(()=>{let e=new Ef(c);return Object.assign(e,{containerRef:t=>{let n=a.current;if(n.container=t,n.lastSize=null,t&&n.enabled){let r=e.getTotalSize();n.lastSize=r;let i=e.options.horizontal?`width`:`height`;t.style[i]=`${r}px`}}})});return l.setOptions(c),Af(()=>l._didMount(),[]),Af(()=>(o(l),l._willUpdate())),Af(()=>{s(l)}),l}function Mf(e){return jf({observeElementRect:yf,observeElementOffset:Cf,scrollToFn:Tf,...e})}var Nf=32;function Pf(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Ff(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 If(e){let t=e.trim();if(t&&!Ff(t)&&!(t.length>4096))return Pf(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,Nf)}function Lf(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r||n!==void 0&&e===n:!1}var Rf={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 正文。`},"zh-TW":{label:`錯誤請求`,description:`代理無法理解該請求。重試前請檢查模型、訊息結構、標頭和 JSON 本文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`},ru:{label:`Некорректный запрос`,description:`Прокси не смог интерпретировать запрос. Перед повторной попыткой проверьте модель, формат сообщений, заголовки и тело JSON.`},ja:{label:`不正なリクエスト`,description:`プロキシがリクエストを解釈できませんでした。再試行前にモデル、メッセージ形式、ヘッダー、JSON 本文を確認してください。`},tr:{label:`Hatalı istek`,description:`Proxy isteği anlayamadı. Yeniden denemeden önce modeli, mesaj yapısını, başlıkları ve JSON gövdesini kontrol edin.`}},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 使用的账号/提供商凭据。`},"zh-TW":{label:`未授權`,description:`憑證缺失、已過期或無效。請重新登入,或重新整理 opencodex 使用的帳號/供應商憑證。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`},ru:{label:`Не авторизован`,description:`Учётные данные отсутствуют, истекли или недействительны. Войдите заново или обновите учётные данные аккаунта или провайдера, которые использует opencodex.`},ja:{label:`認証が必要`,description:`認証情報が不在・期限切れ・無効です。opencodex が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`},tr:{label:`Yetkisiz erişim`,description:`Kimlik bilgileri eksik, süresi dolmuş veya geçersiz. opencodex tarafından kullanılan hesap veya sağlayıcı kimlik bilgilerini yeniden doğrulayın.`}},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:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},"zh-TW":{label:`需要付款`,description:`上游供應商因帳單、額度或方案許可權不可用而拒絕了請求。請儲值、更新帳單資訊或切換供應商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`},ru:{label:`Требуется оплата`,description:`Вышестоящий провайдер отклонил запрос из-за проблем с оплатой, кредитами или доступом по тарифному плану. Пополните баланс, обновите платёжные данные или переключитесь на другого провайдера.`},ja:{label:`支払いが必要`,description:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`},tr:{label:`Ödeme gerekli`,description:`Yukarı akış sağlayıcısı faturalandırma, kredi veya plan erişimi bulunmadığından isteği reddetti. Kredi ekleyin, ödeme bilgilerini güncelleyin veya sağlayıcı değiştirin.`}},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 密钥无效。`},"zh-TW":{label:`禁止存取`,description:`帳號已認證,但無權使用此模型或操作。常見原因是方案/訂閱限制(例如 Ollama Cloud Pro)、組織策略或模型許可權——不一定是 API 金鑰無效。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key.`},ru:{label:`Доступ запрещён`,description:`Аккаунт аутентифицирован, но не имеет права использовать эту модель или операцию. Часто причина — ограничение тарифа или подписки (например, Ollama Cloud Pro), политика организации или права доступа к модели, а не обязательно неверный API-ключ.`},ja:{label:`アクセス禁止`,description:`アカウントは認証済みですがこのモデルや操作の使用が許可されていません。多くはプラン/サブスクリプション制限(例: Ollama Cloud Pro)、組織ポリシー、モデル権限であり、API キーが不正とは限りません。`},tr:{label:`Erişim yasaklandı`,description:`Hesabın kimliği doğrulandı ancak bu modeli veya işlemi kullanma izni yok. Genellikle plan/abonelik sınırı (örn. Ollama Cloud Pro), organizasyon politikası veya model izni kaynaklıdır.`}},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 提供商配置。`},"zh-TW":{label:`未找到`,description:`找不到請求的路由、模型、帳號或上游資源。請確認模型名稱和 opencodex 供應商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`},ru:{label:`Не найдено`,description:`Запрошенный маршрут, модель, аккаунт или вышестоящий ресурс не найден. Проверьте имя модели и конфигурацию провайдера в opencodex.`},ja:{label:`見つかりません`,description:`要求されたルート、モデル、アカウント、上流リソースが見つかりませんでした。モデル名と opencodex プロバイダー設定を確認してください。`},tr:{label:`Bulunamadı`,description:`İstenen rota, model, hesap veya yukarı akış kaynağı bulunamadı. Model adını ve opencodex sağlayıcı yapılandırmasını doğrulayın.`}},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:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},"zh-TW":{label:`請求逾時`,description:`代理或上游供應商未能在限定時間內完成請求。請縮小請求後重試,或切換供應商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`},ru:{label:`Тайм-аут запроса`,description:`Обработка запроса заняла слишком много времени, и прокси или вышестоящий провайдер не успел её завершить. Повторите попытку с меньшим запросом или через другого провайдера.`},ja:{label:`リクエストタイムアウト`,description:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`},tr:{label:`İstek zaman aşımı`,description:`Proxy veya yukarı akış sağlayıcısı isteği tamamlayamadan zaman aşımına uğradı. Daha küçük bir istek veya farklı bir sağlayıcı ile tekrar deneyin.`}},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:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},"zh-TW":{label:`狀態衝突`,description:`請求與當前帳號、會話或供應商狀態衝突。請重新整理會話,或等待當前操作完成後重試。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`},ru:{label:`Конфликт`,description:`Запрос конфликтует с текущим состоянием аккаунта, сессии или провайдера. Обновите сессию или повторите попытку после завершения текущей операции.`},ja:{label:`状態の衝突`,description:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`},tr:{label:`Durum çakışması`,description:`İstek mevcut hesap, oturum veya sağlayıcı durumuyla çakışıyor. Oturumu yenileyin veya aktif işlem bittikten sonra tekrar deneyin.`}},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、文件大小或对话历史。`},"zh-TW":{label:`請求過大`,description:`提示、附件或生成的負載超過了代理或上游限制。請減少 token、檔案大小或對話歷史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`},ru:{label:`Слишком большой запрос`,description:`Промпт, вложения или сформированная полезная нагрузка превышают лимит прокси или вышестоящего провайдера. Сократите количество токенов, размер файлов или историю диалога.`},ja:{label:`リクエストが大きすぎます`,description:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`},tr:{label:`İstek çok büyük`,description:`İstemi, ekler veya oluşturulan veri proxy ya da yukarı akış sınırını aşıyor. Jeton sayısını, dosya boyutunu veya sohbet geçmişini azaltın.`}},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:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},"zh-TW":{label:`內容無效`,description:`供應商接受了請求格式,但拒絕了其中的內容。請檢查模型選項、工具定義、訊息角色和不支援的欄位。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`},ru:{label:`Недопустимое содержимое`,description:`Провайдер принял формат запроса, но отклонил его содержимое. Проверьте параметры модели, определения инструментов, роли сообщений и неподдерживаемые поля.`},ja:{label:`内容の検証失敗`,description:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`},tr:{label:`Geçersiz içerik`,description:`Sağlayıcı istek formatını kabul etti ancak içeriğini reddetti. Model seçeneklerini, araç tanımlarını, mesaj rollerini ve desteklenmeyen alanları kontrol edin.`}},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 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},"zh-TW":{label:`供應商依賴失敗`,description:`opencodex 路由請求時,必需的上游依賴失敗。請稍後重試,或切換到另一個已配置的供應商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`},ru:{label:`Сбой зависимости провайдера`,description:`Необходимая вышестоящая зависимость дала сбой, пока opencodex маршрутизировал запрос. Повторите попытку позже или переключитесь на другого настроенного провайдера.`},ja:{label:`プロバイダー依存の失敗`,description:`opencodex がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı bağımlılığı başarısız`,description:`opencodex isteği yönlendirirken gerekli bir yukarı akış bağımlılığı başarısız oldu. Daha sonra tekrar deneyin veya başka bir sağlayıcıya geçin.`}},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:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},"zh-TW":{label:`限流`,description:`已達到上游供應商的速率或額度限制。請等待額度視窗重設,或切換帳號/供應商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`},ru:{label:`Превышен лимит запросов`,description:`Достигнут лимит скорости или квота вышестоящего провайдера. Дождитесь сброса окна квоты или переключитесь на другой аккаунт или провайдера.`},ja:{label:`レート制限`,description:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`},tr:{label:`Oran sınırı aşıldı`,description:`Yukarı akış sağlayıcısının hız veya kota sınırına ulaşıldı. Kota penceresinin sıfırlanmasını bekleyin ya da hesap/sağlayıcı değiştirin.`}},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 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},"zh-TW":{label:`客戶端已取消`,description:`opencodex 完成路由前,客戶端已斷開連線或取消請求。如果不是有意取消,請重試。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`},ru:{label:`Запрос закрыт клиентом`,description:`Клиент отключился или отменил запрос до того, как opencodex завершил его маршрутизацию. Если отмена была случайной, повторите попытку.`},ja:{label:`クライアントがリクエストをクローズ`,description:`opencodex がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`},tr:{label:`İstemci isteği kapattı`,description:`opencodex yönlendirmeyi bitirmeden önce istemci bağlantıyı kesti veya isteği iptal etti. İptal kazara yapıldıysa tekrar deneyin.`}},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 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},"zh-TW":{label:`代理錯誤`,description:`opencodex 處理請求時發生內部錯誤。請先重試一次;如果重複出現,請檢查代理日誌。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`},ru:{label:`Ошибка прокси`,description:`В opencodex произошла внутренняя ошибка при обработке запроса. Повторите попытку один раз; если ошибка повторяется, проверьте логи прокси.`},ja:{label:`プロキシエラー`,description:`opencodex がリクエスト処理中に内部エラーに遭遇しました。1 回再試行し、繰り返す場合はプロキシログを確認してください。`},tr:{label:`Proxy hatası`,description:`opencodex isteği işlerken dahili bir hatayla karşılaştı. Bir kez tekrar deneyin, tekrarlarsa proxy günlüklerini kontrol edin.`}},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:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},"zh-TW":{label:`上游回應錯誤`,description:`上游供應商透過代理返回了無效或失敗的回應。請重試,或將請求路由到其他供應商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Некорректный ответ провайдера`,description:`Вышестоящий провайдер вернул через прокси недействительный или ошибочный ответ. Повторите попытку или направьте запрос другому провайдеру.`},ja:{label:`上流レスポンス不良`,description:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Kötü yukarı akış yanıtı`,description:`Yukarı akış sağlayıcısı proxy üzerinden geçersiz veya başarısız bir yanıt döndürdü. Tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}},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:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},"zh-TW":{label:`供應商不可用`,description:`代理或上游供應商暫時不可用或過載。請稍後重試,或切換供應商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`},ru:{label:`Провайдер недоступен`,description:`Прокси или вышестоящий провайдер временно недоступен или перегружен. Немного подождите, затем повторите попытку или смените провайдера.`},ja:{label:`プロバイダー利用不可`,description:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`},tr:{label:`Sağlayıcı kullanılamıyor`,description:`Proxy veya yukarı akış sağlayıcısı geçici olarak kullanılamıyor veya aşırı yüklü. Kısa bir süre bekleyip tekrar deneyin ya da sağlayıcı değiştirin.`}},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:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},"zh-TW":{label:`上游逾時`,description:`上游供應商未在代理逾時前回應。請縮小請求後重試,或選擇回應更快的供應商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`},ru:{label:`Тайм-аут вышестоящего провайдера`,description:`Вышестоящий провайдер не ответил до истечения тайм-аута прокси. Повторите попытку с меньшим запросом или выберите более быстрого провайдера.`},ja:{label:`上流タイムアウト`,description:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`},tr:{label:`Yukarı akış zaman aşımı`,description:`Yukarı akış sağlayıcısı proxy zaman aşımı süresinden önce yanıt vermedi. Daha küçük bir istekle tekrar deneyin veya daha hızlı bir sağlayıcı seçin.`}},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:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},"zh-TW":{label:`供應商過載`,description:`上游供應商過載或容量受限。請等待後重試,或切換到其他帳號/供應商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`},ru:{label:`Провайдер перегружен`,description:`Вышестоящий провайдер перегружен или ограничен по мощности. Подождите и повторите попытку либо переключитесь на другой аккаунт или провайдера.`},ja:{label:`プロバイダー過負荷`,description:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı aşırı yüklü`,description:`Yukarı akış sağlayıcısı aşırı yüklü veya kapasitesi sınırlı. Bekleyip tekrar deneyin veya başka bir hesap/sağlayıcıya geçin.`}}},zf={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:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},"zh-TW":{label:`請求錯誤`,description:`代理或上游供應商拒絕了該請求。請檢查請求結構、憑證、模型名稱和供應商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`},ru:{label:`Ошибка запроса`,description:`Прокси или вышестоящий провайдер отклонил запрос. Проверьте структуру запроса, учётные данные, имя модели и конфигурацию провайдера.`},ja:{label:`リクエストエラー`,description:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`},tr:{label:`İstek hatası`,description:`Proxy veya yukarı akış sağlayıcısı isteği reddetti. İstek yapısını, kimlik bilgilerini, model adını ve sağlayıcı yapılandırmasını kontrol edin.`}},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 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},"zh-TW":{label:`伺服器或上游錯誤`,description:`opencodex 或上游供應商處理請求時失敗。請稍後重試,或將請求路由到其他供應商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Ошибка сервера или провайдера`,description:`opencodex или вышестоящий провайдер завершил обработку запроса с ошибкой. Повторите попытку позже или направьте запрос другому провайдеру.`},ja:{label:`サーバーまたは上流エラー`,description:`opencodex または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Sunucu veya yukarı akış hatası`,description:`opencodex veya bir yukarı akış sağlayıcısı isteği işlerken başarısız oldu. Daha sonra tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}}};function Bf(e){return e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function Vf(e,t){if(e<400)return null;let n=Bf(t);return(Rf[Math.trunc(e)]??(e<500?zf.client:zf.server))[n]}var Hf=[`provider`,`usage`,`injection`];function Uf(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function Wf(e){return new Date(e).toLocaleTimeString()}function Gf(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function Kf(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function qf({entries:e}){let{t}=Ze();return(0,z.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,z.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,z.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,z.jsx)(`div`,{style:{overflowX:`auto`},children:(0,z.jsxs)(`table`,{className:`table text-label`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,z.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,z.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,z.jsx)(`th`,{children:`thinking`}),(0,z.jsx)(`th`,{children:`effort`}),(0,z.jsx)(`th`,{children:`beta`}),(0,z.jsx)(`th`,{children:`metadata`}),(0,z.jsx)(`th`,{children:`system`})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`muted mono`,children:Wf(e.at)}),(0,z.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,z.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,z.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,z.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,z.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,z.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,z.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,z.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,z.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function Jf({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=Ze();return e?n?r.length===0?(0,z.jsxs)(`div`,{className:`empty`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,z.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,z.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,z.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Uf(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,z.jsxs)(`div`,{className:`empty`,children:[(0,z.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,z.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function Yf({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=Ze();return(0,z.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,z.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,z.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=Kf(e,n);return(0,z.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,z.jsx)(pt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,z.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,z.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,z.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function Xf({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=Ze();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,z.jsx)(`h2`,{children:o(`debug.title`)}),(0,z.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,z.jsx)(re,{}),` `,o(`debug.refresh`)]}),(0,z.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function Zf(e){return`debug-settings:${e}`}function Qf({apiBase:e,embedded:t,active:n=!0}){let{t:r}=Ze(),i=`ocx.debug.settings.v1:${e}`,a=qn(i),o=Zf(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(`provider`),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useRef)(0),y=(0,_.useRef)(0),b=(0,_.useRef)(0),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=vc(o,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Jn(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),T=w.state,E=w.data??a??null,D=I(`debug-claude-inbound:${e}`,[e,E?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:n&&!!E?.claude}).data??[],O=Mf({count:d.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),k=(0,_.useCallback)(e=>Gf(E,e),[E]);(0,_.useEffect)(()=>{if(!E||k(l))return;let e=Hf.find(k);if(!e)return;let t=window.setTimeout(()=>u(e),0);return()=>window.clearTimeout(t)},[E,l,k]);let A=k(l),j=l===`provider`?`${e}/api/debug/logs`:l===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,M=(0,_.useCallback)(async(e,t)=>{let n=++b.current;if(!A){n===b.current&&(f([]),v.current=0);return}g(!0);try{let r=new URLSearchParams({limit:`500`});!e&&v.current>0&&r.set(`after`,String(v.current));let i=await fetch(`${j}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==b.current)return;let a=await i.json();if(t?.aborted||n!==b.current||a.length===0)return;f(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===b.current&&g(!1)}},[j,A]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${l}:${A}`,r=C.current!==t;if(C.current=t,!r&&d.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&f([]),M(!0,i.signal)},0);return()=>{window.clearTimeout(a),b.current+=1,i.abort()}},[n,e,l,A]);let N=(0,_.useEffectEvent)(e=>{M(e)});(0,_.useEffect)(()=>{if(!n||!p||!A)return;let e=setInterval(()=>N(!1),1e3);return()=>clearInterval(e)},[n,p,A]),(0,_.useEffect)(()=>{p&&d.length>0&&O.scrollToIndex(d.length-1,{align:`end`})},[d,p,O]);let P=async t=>{let n=++y.current;c(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let a=await r.json();if(n!==y.current)return;Jn(i,a),L(o,a)}catch{}},a=(x.current??Promise.resolve()).then(r,r);x.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===y.current&&c(!1)}},F=async(e,t)=>{await P({[e]:t})},R=async()=>{await P({reset:!0})};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Xf,{embedded:t,refreshing:h,streamEnabled:A,follow:p,onRefresh:()=>void M(!0),onFollowChange:m}),!E&&T.showError?(0,z.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,z.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:r(`common.retry`)})]}):T.showSkeleton&&!E?(0,z.jsx)(bc,{label:r(`debug.loading`),rows:3}):E?(0,z.jsx)(Yf,{debug:E,debugBusy:s,stream:l,onSetFlag:(e,t)=>{F(e,t)},onReset:()=>{R()},onStreamChange:u}):null,E&&T.showError&&(0,z.jsx)($,{tone:`err`,children:r(`debug.loadFailed`)}),E?.claude&&(0,z.jsx)(qf,{entries:D}),(0,z.jsx)(Jf,{debug:!!E,stream:l,streamEnabled:A,entries:d,scrollContainerRef:S,lineVirtualizer:O})]})}function $f(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function ep(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function tp(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),ep(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),ep(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function np(e){return e.requestedSpeedLabel||void 0}function rp(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 ip(e){return e===void 0||typeof e==`string`}function ap(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!ip(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!ip(e.profile.id)||!ip(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!ip(e.selected.provider)||!ip(e.selected.model)||!ip(e.selected.reason)))return!1;if(e.candidates===void 0)return!0;if(!Array.isArray(e.candidates))return!1;for(let t of e.candidates){if(!t||typeof t!=`object`||!ip(t.provider)||!ip(t.model)||t.eligible!==void 0&&typeof t.eligible!=`boolean`)return!1;if(t.exclusions!==void 0){if(!Array.isArray(t.exclusions))return!1;for(let e of t.exclusions)if(!e||typeof e!=`object`||!ip(e.code))return!1}}return!0}function op(e){if(e.routeDecision===void 0||ap(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function sp(e){return`ocx.logs.list.v1:${e}`}function cp(e){if(!Array.isArray(e))return null;for(let t of e)if(!t||typeof t!=`object`||typeof t.timestamp!=`number`||typeof t.model!=`string`||typeof t.provider!=`string`||typeof t.status!=`number`||typeof t.durationMs!=`number`||!ap(t.routeDecision))return null;return e}function lp(e){return e===`cursor`||e.startsWith(`cursor-`)}function up(e,t){if(!e.usage)return;let n=pp(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(lp(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function dp(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 fp(e){let t=dp(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function pp(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 mp(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 hp(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function gp(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 _p(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 vp(e,t){return!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}var yp=3,bp={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`},xp={usage_estimated:`logs.detail.estimate.usage_estimated`,cache_detail_missing:`logs.detail.estimate.cache_detail_missing`,expected_price_overlay:`logs.detail.estimate.expected_price_overlay`,provider_cost_overlay:`logs.detail.estimate.provider_cost_overlay`},Sp={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"oauth-401":`logs.detail.attempt.recovery.oauth401`,"key-429":`logs.detail.attempt.recovery.key429`,"rate-limit-429":`logs.detail.attempt.recovery.rateLimit429`,"anthropic-oauth-429":`logs.detail.attempt.recovery.anthropicOauth429`,"image-413":`logs.detail.attempt.recovery.image413`,"empty-completion":`logs.detail.attempt.recovery.emptyCompletion`};function Cp(e){return bp[e]}function wp(e){return xp[e]}function Tp(e){return Sp[e]??`logs.detail.attempt.recovery.unknown`}function Ep(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function Dp(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Op(e,t,n){let r=n?{timeZone:n}:void 0;try{return{date:new Date(e).toLocaleDateString(t,r),time:new Date(e).toLocaleTimeString(t,r)}}catch{return{date:new Date(e).toLocaleDateString(t),time:new Date(e).toLocaleTimeString(t)}}}function kp(e,t,n){let{date:r,time:i}=Op(e,t,n);return`${r} ${i}`}function Ap(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 jp(e){let t=0,n=0,r=0,i=0;for(let a of e){let e=dp(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 Mp({apiBase:e}){let{t,locale:n}=Ze(),r=sp(e),i=cp(qn(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(`all`),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(),h=(0,_.useRef)(null),g=Ue.find(e=>e.code===n)?.htmlLang,[v,y]=(0,_.useState)();(0,_.useEffect)(()=>{let t=new AbortController,n=!1;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{n||!e||typeof e.timeZone==`string`&&e.timeZone.trim()&&y(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[b,x]=(0,_.useState)($f),[S,C]=(0,_.useState)(()=>$f()===`debug`);(0,_.useEffect)(()=>{let e=()=>x($f());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{b===`debug`&&C(!0)},[b]);let w=ep,T=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/logs?limit=2000`,{signal:t});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let i=await n.json(),a=(Array.isArray(i)?i:i.logs??[]).map(op);return Jn(r,a),a},[e,r]),E=vc(r,[e],T,{isEmpty:e=>e.length===0,enabled:b===`logs`,pollMs:a?2e3:void 0,initialData:i??void 0}),D=E.state,O=D.data??i??[],k=E.refresh,A=!E.refreshing&&D.showError,j=!E.refreshing&&!D.showError&&D.data!==void 0,[M,N]=(0,_.useState)({error:null,count:0});j&&M.count!==0?N({error:null,count:0}):A&&M.error!==D.error&&N(e=>({error:D.error,count:e.count+1}));let P=M.count>=yp||!a&&A,F=s?Vf(s.status,n):null,I=d.trim();(0,_.useEffect)(()=>{let e=!1;if(!I){m(void 0);return}return If(I).then(t=>{e||m(t)}),()=>{e=!0}},[I]);let L=O.filter(e=>rp(e,l)&&(!I||Lf(e.conversationId,I,p))),R=I?jp(L):null,B=Mf({count:L.length,getScrollElement:()=>h.current,estimateSize:()=>44,overscan:15}),V=B.getVirtualItems(),H=V.length>0?V[0].start:0,U=V.length>0?B.getTotalSize()-V[V.length-1].end:0;return(0,z.jsxs)(`div`,{className:`logs-page`,children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{children:t(`nav.logs`)}),b===`logs`&&(0,z.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,z.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":b===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:b===`logs`?0:-1,className:`page-tab${b===`logs`?` page-tab--active`:``}`,onClick:()=>w(`logs`),onKeyDown:tp,children:t(`logs.tabLogs`)}),(0,z.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":b===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:b===`debug`?0:-1,className:`page-tab${b===`debug`?` page-tab--active`:``}`,onClick:()=>w(`debug`),onKeyDown:tp,children:t(`logs.tabDebug`)})]}),S&&(0,z.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:b!==`debug`,children:(0,z.jsx)(Qf,{apiBase:e,embedded:!0,active:b===`debug`})}),(0,z.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:b!==`logs`,children:[(0,z.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,z.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,z.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,z.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm${l===e?` btn-primary`:` btn-ghost`}`,style:{background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},onClick:()=>u(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,z.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,z.jsx)(`input`,{type:`search`,className:`input mono`,value:d,onChange:e=>f(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),I&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f(``),children:t(`logs.filter.conversation.clear`)})]}),R&&(0,z.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,z.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:R.requests,tokens:bn(R.totalTokens,g??n),cost:vp(R.estimatedCostUsd,g)}),` `,(0,z.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),R.unpricedRequests+R.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:R.unpricedRequests,unmetered:R.unmeteredRequests})}`:``]})]})}),D.kind===`failed-cold`&&(0,z.jsxs)($,{tone:`err`,children:[D.error instanceof Error?`${t(`logs.loadError`)} ${D.error.message}`:t(`logs.loadError`),` `,(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k({forceLoading:!0}),disabled:D.refreshing,children:t(`common.retry`)})]}),P&&O.length>0&&(0,z.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k({forceLoading:!0}),disabled:E.refreshing,children:t(`common.retry`)})]}),D.kind===`failed-cold`?null:D.showSkeleton&&O.length===0?(0,z.jsx)(bc,{label:t(`common.loading`),rows:6}):L.length===0?(0,z.jsx)(gt,{title:t(`logs.noRequests`)}):(0,z.jsx)(z.Fragment,{children:(0,z.jsx)(`div`,{ref:h,className:`tbl-wrap logs-table-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:t(`logs.col.time`)}),(0,z.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,z.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,z.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,z.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,z.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,z.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,z.jsx)(`th`,{children:t(`logs.col.status`)}),(0,z.jsx)(`th`,{children:t(`logs.col.request`)}),(0,z.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,z.jsxs)(`tbody`,{children:[H>0&&(0,z.jsx)(`tr`,{children:(0,z.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:H}})}),V.map(e=>{let r=L[L.length-1-e.index],i=hp(r),a=Op(r.timestamp,g,v);return(0,z.jsxs)(`tr`,{"data-index":e.index,ref:B.measureElement,children:[(0,z.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,z.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,z.jsx)(`span`,{children:a.date}),(0,z.jsx)(`span`,{children:a.time})]})}),(0,z.jsx)(`td`,{className:`num mono log-col-tokens`,title:up(r,t),children:(()=>{let e=fp(r),{read:i,write:a}=pp(r);return e===void 0?(0,z.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,z.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,z.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,bn(e,n)]}),i!==void 0&&i>0&&(0,z.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,bn(i,n)]}),a!==void 0&&a>0&&(0,z.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,bn(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,z.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(lp(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,z.jsx)(`td`,{className:`num mono log-col-rate`,children:gp(r.displayMetrics?.tokPerSecond,g)}),(0,z.jsx)(`td`,{className:`num mono log-col-cost`,children:_p(r.displayMetrics?.cost,g)}),(0,z.jsx)(`td`,{className:`mono log-col-model`,title:Ap(r),children:(0,z.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,z.jsx)(`span`,{children:gc(r.resolvedModel??r.model)}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,z.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,z.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),np(r)&&(0,z.jsx)(`span`,{className:`badge badge-amber`,children:np(r)})]})}),(0,z.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,z.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,z.jsx)(`span`,{children:mp(r)}),i&&(0,z.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,z.jsx)(`td`,{className:`muted`,children:pn(r.provider,t)}),(0,z.jsx)(`td`,{children:(0,z.jsxs)(`span`,{className:`log-status-cell`,children:[(0,z.jsx)(`span`,{className:`mono font-semibold`,style:{color:Dp(r.status)},children:r.status}),(0,z.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>c(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,z.jsx)(`td`,{className:`muted mono`,children:(0,z.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,z.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),U>0&&(0,z.jsx)(`tr`,{children:(0,z.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:U}})})]})]})})}),s&&(0,z.jsx)(Pp,{detail:s,detailInfo:F,localeCode:n,localeTag:g,serverTimeZone:v,t,onClose:()=>c(null),onFilterConversation:e=>{f(e),c(null)}})]})]})}function Np(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 Pp({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Np(!0),[l,u]=(0,_.useState)(!1),d=pp(e),f=e.displayMetrics?.cost,p=hp(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,z.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,z.jsx)(`span`,{className:`mono`,style:{color:Dp(e.status)},children:e.status}),t&&(0,z.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,z.jsx)(Y,{})})]}),t&&(0,z.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,z.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,z.jsx)(`span`,{className:`mono`,children:kp(e.timestamp,r,i)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,z.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,z.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,z.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,z.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,z.jsx)(`span`,{className:`mono`,children:gc(e.resolvedModel??e.model)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,z.jsx)(`span`,{children:pn(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[mp(e),p?` (${p})`:``]})]}),e.errorCode&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,z.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,z.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,z.jsx)(`span`,{className:`mono`,children:(e.routeDecision.candidates??[]).map(e=>`${typeof e.provider==`string`&&e.provider.length>0?e.provider:`–`}/${typeof e.model==`string`&&e.model.length>0?e.model:`–`}${e.eligible===!0?` ✓`:e.eligible===!1?` ✗`:` ?`}`).join(` `)||`–`})]}):(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,z.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,z.jsx)(`span`,{className:`mono`,children:gp(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,z.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Cp(e.displayMetrics.tokPerSecond.reason))})]}),(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,z.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.total,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.input,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.cacheRead,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.cacheWrite,r)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,z.jsx)(`span`,{className:`mono`,children:vp(f.estimate.cost.output,r)}),f.estimate.price&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,z.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,z.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Ep(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,z.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,z.jsx)(`li`,{children:a(wp(e))},e))})]}):(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,z.jsx)(`span`,{className:`mono`,children:`—`}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,z.jsx)(`span`,{children:f?.kind===`unavailable`?a(Cp(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,z.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,z.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{className:`num`,children:`#`}),(0,z.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,z.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,z.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,z.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,z.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,z.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=hp(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(Tp(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(Cp(t.reason)):a(`logs.detail.attempt.completed`));return(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,z.jsxs)(`td`,{children:[(0,z.jsx)(`span`,{children:pn(e.provider,a)}),(0,z.jsx)(`br`,{}),(0,z.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`br`,{}),(0,z.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[mp(e),n?` (${n})`:``]})]}),i&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`br`,{}),(0,z.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Ep(i.status))]})]})]}),(0,z.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,z.jsx)(`td`,{className:`num mono`,children:gp(e.displayMetrics?.tokPerSecond,r)}),(0,z.jsx)(`td`,{className:`num mono`,children:_p(t,r)}),(0,z.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,z.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,z.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,z.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.usage?bn(e.usage.inputTokens,n):`—`}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.usage?bn(e.usage.outputTokens,n):`—`}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,z.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:bn(d.read,n)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,z.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:bn(d.write,n)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,z.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:bn(e.usage.reasoningOutputTokens,n)}),(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,z.jsx)(`span`,{className:`mono`,children:fp(e)===void 0?`—`:bn(fp(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,z.jsx)(`span`,{className:`mono`,children:bn(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,z.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,z.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,z.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,z.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function Fp(e){return`${Math.round(e*100)}%`}function Ip(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 Lp(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 Rp(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 zp(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Bp(e){let t=Rp(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?zp(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 Vp({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,z.jsxs)(`div`,{className:`usage-filters`,children:[(0,z.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,z.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,z.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,z.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,z.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,z.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,z.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(e===`all`?`usage.range.available`:`usage.range.${e}`);return(0,z.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 Hp({summary:e,activeDays:t,locale:n,t:r}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:bn(e.totalTokens,n)})]}),(0,z.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:bn(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,z.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,bn(e.cacheCreationInputTokens??0,n)]})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:Fp(e.coverageRatio)})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,z.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,z.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,z.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:_o(e.estimatedCostUsd,n)}),(0,z.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,z.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function Up({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,z.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,z.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,z.jsx)(`div`,{className:`daybar-track`,children:(0,z.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,z.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Ip(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,z.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,z.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,z.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,z.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,z.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Ip(e.model,e.provider)}}),(0,z.jsx)(`span`,{className:`daybar-tip-name`,children:gc(e.model)}),(0,z.jsx)(`span`,{className:`daybar-tip-val`,children:bn(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,z.jsx)(`span`,{className:`daybar-count`,children:bn(e.totalTokens,t)}),(0,z.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function Wp({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,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,z.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,z.jsx)(Up,{weekBars:n,locale:r,t:i}):(0,z.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,z.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,z.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,z.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,z.jsxs)(`div`,{className:`heatmap-body`,children:[(0,z.jsxs)(`div`,{className:`heatmap-days`,children:[(0,z.jsx)(`span`,{}),(0,z.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,z.jsx)(`span`,{}),(0,z.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,z.jsx)(`span`,{}),(0,z.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,z.jsx)(`span`,{})]}),(0,z.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,z.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,z.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,z.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,z.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,z.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:bn(e.totalTokens,r)})}),(0,z.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,z.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,z.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,z.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,z.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function Gp({title:e,titleId:t,children:n}){return(0,z.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,z.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function Kp({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,z.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:i(`logs.col.model`)}),(0,z.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,z.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,z.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`mono`,children:gc(e.model)}),(0,z.jsx)(`td`,{className:`muted`,children:pn(e.provider,i)}),(0,z.jsx)(`td`,{className:`num`,children:e.requests}),(0,z.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,z.jsx)(`td`,{className:`num mono`,children:bn(e.totalTokens,r)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`div`,{className:`usage-bar`,children:(0,z.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,z.jsxs)(Gp,{title:s,titleId:c,children:[(0,z.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function qp({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,z.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`mono`,children:pn(e.provider,n)}),(0,z.jsx)(`td`,{className:`num`,children:e.requests}),(0,z.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,z.jsx)(`td`,{className:`num mono`,children:bn(e.totalTokens,t)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`div`,{className:`usage-bar`,children:(0,z.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,z.jsx)(Gp,{title:i,titleId:a,children:o}):(0,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,z.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function Jp({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,z.jsxs)(`div`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,z.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,z.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,z.jsx)(Gp,{title:r,titleId:i,children:a}):(0,z.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,z.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function Yp({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,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Hp,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,z.jsx)(Wp,{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,z.jsx)(Kp,{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,z.jsx)(qp,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Fp(e.summary.coverageRatio):`—`,body:e?(0,z.jsx)(Jp,{summary:e.summary,t:u,workspace:!0}):null}];return(0,z.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,z.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,z.jsx)(ef,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,z.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,z.jsx)(gt,{title:u(`usage.empty`)}):f.map(e=>(0,z.jsx)(`div`,{id:Zd(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var Xp=new Map;function Zp(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function Qp(e,t,n){let r=Zp(e,t,n);return Xp.get(r)??qn(r)}function $p(e,t,n,r){let i=Zp(e,t,n);Xp.set(i,r),Jn(i,r)}function em({apiBase:e}){let{t,locale:n}=Ze(),[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 $p(e,r,a,i),i},[e,r,a]),u=Zp(e,r,a),d=Qp(e,r,a),f=vc(u,[e,r,a],l,{isEmpty:()=>!1,initialData:d??void 0}),{state:p}=f,m=p.data??d??null,h=(0,_.useMemo)(()=>Bp(m?.days??[]),[m?.days]),g=(0,_.useMemo)(()=>Lp(m?.days??[]),[m?.days]),v=(0,_.useMemo)(()=>(m?.days??[]).filter(e=>e.requests>0).length,[m?.days]),y=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(m?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[m?.models,s]),b=(0,_.useMemo)(()=>(m?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[m?.providers]);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,z.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,z.jsx)(Vp,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),p.showSkeleton&&!m?(0,z.jsx)(bc,{label:t(`usage.loading`),rows:5}):p.kind===`failed-cold`?(0,z.jsxs)($,{tone:`err`,children:[p.error instanceof Error?`${t(`usage.loadError`)} ${p.error.message}`:t(`usage.loadError`),` `,(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,z.jsxs)(z.Fragment,{children:[p.showError&&(0,z.jsx)($,{tone:`err`,children:t(`usage.loadError`)}),m?.historyTruncated&&(0,z.jsx)($,{tone:`warn`,children:(()=>{let e=tm(m.snapshotWindowStart),n=tm(m.snapshotWindowEnd);return e!==null&&n!==null?t(`usage.historyTruncatedWindow`,{start:e,end:n}):t(`usage.historyTruncated`)})()}),(0,z.jsx)(Yp,{data:m,heatmap:h,weekBars:g,activeDays:v,filteredModels:y,modelQuery:s,onModelQuery:c,sortedProviders:b,range:r,locale:n,t})]})]})}function tm(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function nm(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 rm={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 im(e,t){let n=rm[e.key];return n?t(n):e.label}function am(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function om(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function sm({report:e,locale:t}){let n=Z(),[r,i]=(0,_.useState)(null),a=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),o=a.find(e=>e.key===r)??null,s=(0,_.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),c=(0,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,z.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,z.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":n(`storage.section.buckets`),children:[(0,z.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,z.jsx)(`span`,{className:`storage-workspace-rail-title`,children:n(`storage.section.buckets`)}),(0,z.jsx)(`span`,{className:`storage-workspace-rail-count`,children:a.length})]}),(0,z.jsx)(`div`,{className:`storage-workspace-rail-list`,children:a.length===0?(0,z.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:n(`storage.empty`)}):a.map(e=>(0,z.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,z.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,z.jsx)(`span`,{className:`storage-workspace-rail-name`,children:im(e,n)}),(0,z.jsx)(`span`,{className:`storage-workspace-rail-size`,children:nm(e.bytes,t)})]}),(0,z.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,n(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,z.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":o?im(o,n):n(`storage.section.largest`),children:o?(0,z.jsxs)(`div`,{className:`stw-detail`,children:[(0,z.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,z.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>i(null),children:[(0,z.jsx)(fe,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),n(`modal.back`)]})}),(0,z.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,z.jsx)(`h2`,{className:`stw-detail-title`,children:im(o,n)}),(0,z.jsxs)(`dl`,{className:`stw-kv`,children:[(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.size`)}),(0,z.jsx)(`dd`,{className:`stw-kv-mono`,children:nm(o.bytes,t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.files`)}),(0,z.jsx)(`dd`,{className:`stw-kv-mono`,children:o.fileCount.toLocaleString(t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.oldest`)}),(0,z.jsx)(`dd`,{children:am(o.oldest,t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.newest`)}),(0,z.jsx)(`dd`,{children:am(o.newest,t)})]}),(0,z.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,z.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,z.jsx)(`dd`,{className:`stw-kv-mono`,children:om(o,t,n)})]})]}),(o.largest?.length??0)>0&&(0,z.jsxs)(`div`,{className:`stw-section`,children:[(0,z.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),o.largest.map(e=>(0,z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,z.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,z.jsx)(`span`,{className:`stw-file-size`,children:nm(e.bytes,t)})]},e.path))]})]})]}):(0,z.jsxs)(`div`,{className:`stw-overview`,children:[(0,z.jsxs)(`div`,{className:`stw-summary`,children:[(0,z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,z.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.total`)}),(0,z.jsx)(`div`,{className:`stw-summary-value`,children:nm(e.total.bytes,t)})]}),(0,z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,z.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.files`)}),(0,z.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,z.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,z.jsx)(`div`,{className:`stw-summary-label`,children:n(`storage.card.home`)}),(0,z.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),s.length>0?(0,z.jsxs)(`div`,{className:`stw-section`,children:[(0,z.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.section.largest`)}),s.map(e=>{let r=c.get(e.bucketKey);return(0,z.jsxs)(`div`,{className:`stw-file-row`,children:[(0,z.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),r&&(0,z.jsx)(`span`,{className:`stw-file-bucket`,children:im(r,n)}),(0,z.jsx)(`span`,{className:`stw-file-size`,children:nm(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,z.jsxs)(`p`,{className:`stw-hint`,children:[(0,z.jsx)(q,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),n(`storage.workspace.selectBucket`)]})]})})]})}var cm=1024**3,lm=[10,25,50],um=(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 dm({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`)))}let r=await t.json();s(r),l(!0)}catch(e){v(um(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:nm(a.bytes,t)})),r()}catch(e){v(um(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,z.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,z.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,z.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,z.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,z.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,z.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,z.jsx)(`div`,{className:`storage-manual-panel__presets`,children:lm.map(e=>(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,z.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,z.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:nm(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,z.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,z.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,z.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,z.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,z.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,z.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,z.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,z.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,z.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,z.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 fm({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=vc(`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:nm(a.bytes,t)})),r()}catch(e){p(um(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,z.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,z.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,z.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,z.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,z.jsx)(xc,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,z.jsx)(bc,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,z.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,z.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,z.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,z.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,z.jsx)(`th`,{})]})}),(0,z.jsx)(`tbody`,{children:x.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{className:`muted`,children:w(e)}),(0,z.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,z.jsx)(`td`,{className:`num mono`,children:nm(e.bytes,t)}),(0,z.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,z.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,z.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,z.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,z.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,z.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:nm(c.bytes,t),id:c.id})}),f&&(0,z.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,z.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,z.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function pm(e){let{job:t,...n}=e;return n}function mm(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/cm*100)/100));return e.target.reduceToBytes===void 0?{policy:pm(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:pm(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/cm*100)/100))}}async function hm(e){await new Promise(t=>window.setTimeout(t,e))}function gm({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=qn(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=mm(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,Jn(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*cm)}}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*cm)},target:n,schedule:s.schedule,mode:s.mode}},L=async t=>{let r=I();if(!r){y(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),y(null),g(null);try{let t=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i)});if(!t.ok){y(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){y(n(`storage.policy.saveFailed`));return}M(r.policy),g(n(`storage.policy.saved`))}catch{y(n(`storage.policy.saveFailed`))}finally{f(!1)}},R=async()=>{O.current?.abort();let i=new AbortController;O.current=i;let{signal:a}=i;m(!0),y(null),g(null);try{let i=I();if(!i){y(n(`storage.policy.invalid`));return}let o=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i),signal:a});if(a.aborted)return;if(!o.ok){y(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){y(n(`storage.policy.saveFailed`));return}M(s.policy);let c=await fetch(`${e}/api/storage/cleanup-policy/run`,{method:`POST`,signal:a});if(a.aborted)return;if(c.status===409){let e=await c.json().catch(()=>({}));if(a.aborted)return;e.policy&&M(e.policy),y(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&M(e.policy),e.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}y(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&M(l.policy),l.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){y(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await hm(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=pm(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:nm(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:nm(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,z.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,z.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,z.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,z.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,z.jsx)(`div`,{className:`storage-policy-enable`,children:(0,z.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,z.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void L({enabled:!s.enabled}),children:(0,z.jsx)(`span`,{className:`toggle-knob`})}),(0,z.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,z.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,z.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,z.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,z.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,z.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,z.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value: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,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,z.jsx)(Ha,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(Va(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(Va(E,-.1,0,1e4,.1))}})]})]})]}),(0,z.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,z.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,z.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,z.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,z.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,z.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value: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,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,z.jsx)(Ha,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(Va(S,1,1,100))},onDecrement:()=>{N(),C(Va(S,-1,1,100))}})]})]}),(0,z.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,z.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,z.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,z.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,z.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value: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,z.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,z.jsx)(Ha,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(Va(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(Va(w,-.1,0,1e4,.1))}})]})]})]}),(0,z.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,z.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,z.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,z.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,z.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,z.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,z.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,z.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,z.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,z.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,z.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,z.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,z.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,z.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,z.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,z.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,z.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[B(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:nm(s.lastRun.freedBytes,t)})}`:``]})]}),(0,z.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,z.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,z.jsx)(`span`,{className:`storage-policy-meta-value`,children:B(s.nextRun)})]})]}),(0,z.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,z.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,z.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,z.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function _m({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,z.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,z.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,z.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,z.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,z.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,z.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,z.jsx)(gm,{apiBase:e,locale:t,t:n,onDone:o}),(0,z.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,z.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,z.jsx)(dm,{apiBase:e,locale:t,t:n,onDone:o}):(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,z.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,z.jsx)(fm,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,z.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function vm({apiBase:e}){let{t,locale:n}=Ze(),r=`ocx.storage.report.v1:${e}`,i=qn(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 Jn(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=vc(`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,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,z.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,z.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,z.jsx)(re,{}),` `,t(`storage.refresh`)]})]})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,z.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,z.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,z.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,z.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,z.jsx)(bc,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,z.jsx)(z.Fragment,{children:(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,z.jsxs)(z.Fragment,{children:[m.showError&&(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,z.jsx)(gt,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,z.jsx)(sm,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,z.jsx)(xc,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,z.jsx)(_m,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}var ym=`/api/codex-auth/features/default-mode-request-user-input`;function bm({apiBase:e}){let t=Z(),[n,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(0),h=(0,_.useCallback)(async()=>{if(f.current)return;let t=++m.current;try{let n=await fetch(`${e}${ym}`);if(!n.ok)throw Error(`load`);let i=await n.json();if(f.current||t!==m.current)return;p.current=i.enabled===!0,r(p.current),a(!0),l(!1)}catch{!f.current&&t===m.current&&l(!0)}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=window.setInterval(()=>{h()},3e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[h]);let g=(0,_.useCallback)(async()=>{if(f.current||!i||c)return;let n=!p.current,o=p.current;p.current=n,r(n),f.current=!0,s(!0),d(null),m.current++;try{let i=await fetch(`${e}${ym}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await St(i)??{};if(o.ok!==!0)throw Error(String(i.status));p.current=o.enabled===!0,r(p.current),a(!0),d({tone:`ok`,message:t(o.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){p.current=o,r(o);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);d({tone:`err`,message:n})}finally{f.current=!1,s(!1)}},[e,i,c,t]),v=o||!i||c;return(0,z.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,z.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,z.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,z.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,z.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
|
|
54
54
|
default_mode_request_user_input = true`})]}),(0,z.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[c&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:t(`common.retry`)}),(0,z.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:v,"aria-pressed":n,"aria-label":t(`codexAuth.requestUserInput`),title:t(`codexAuth.requestUserInput`),children:(0,z.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,z.jsx)(`div`,{className:`codex-request-user-input-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function xm({apiBase:e}){let t=Z(),[n,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(0),h=(0,_.useCallback)(async()=>{if(p.current)return;let t=++m.current;try{let n=await fetch(`${e}/api/settings`);if(!n.ok)throw Error(`load`);let i=await n.json();if(p.current||t!==m.current)return;if(typeof i.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);f.current=i.codexAccountPickerEnabled,r(i.codexAccountPickerEnabled),a(!0),l(!1)}catch{!p.current&&t===m.current&&l(!0)}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=window.setInterval(()=>{h()},3e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[h]);let g=(0,_.useCallback)(async()=>{if(p.current||!i)return;let n=f.current,o=!n;f.current=o,r(o),p.current=!0,s(!0),d(null),m.current+=1;try{let n=await St(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexAccountPickerEnabled:o})}))??{};if(n.ok!==!0||typeof n.codexAccountPickerEnabled!=`boolean`)throw Error(`unconfirmed`);f.current=n.codexAccountPickerEnabled,r(n.codexAccountPickerEnabled),a(!0),l(!1),d(n.catalogRefreshPending===!0?{tone:`warn`,message:t(`codexAuth.catalogRefreshPending`)}:{tone:`ok`,message:t(`codexAuth.accountPickerUpdated`)})}catch{f.current=n,r(n),d({tone:`err`,message:t(`codexAuth.accountPickerUpdateFailed`)})}finally{p.current=!1,s(!1)}},[e,i,t]),v=c&&!i;return(0,z.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":o||!i&&!v||void 0,children:[(0,z.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,z.jsx)(`strong`,{children:t(`codexAuth.accountPickerTitle`)}),(0,z.jsx)(`div`,{className:`card-sub`,role:v?`status`:void 0,children:t(v?`codexAuth.accountPickerLoadFailed`:i?n?`codexAuth.accountPickerOnDesc`:`codexAuth.accountPickerOffDesc`:`common.loading`)}),i&&n&&(0,z.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.accountPickerCompatibility`)}),i&&c&&(0,z.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:t(`codexAuth.accountPickerRefreshFailed`)})]}),(0,z.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[c&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},disabled:o,children:t(`common.retry`)}),i&&(0,z.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:o,"aria-pressed":n,"aria-label":t(`codexAuth.accountPickerTitle`),title:t(`codexAuth.accountPickerTitle`),children:(0,z.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,z.jsx)(`div`,{className:`codex-account-picker-feedback is-${u.tone}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function Sm(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 Cm({state:e,busy:t,onEnable:n}){let r=Z();return(0,z.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,z.jsxs)(`div`,{className:`row`,children:[(0,z.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===null?(0,z.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,z.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,z.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===null&&(0,z.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc openai-account-mode-banner__desc--pending`,"aria-hidden":`true`,children:`\xA0`}),e===`pool`&&(0,z.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,z.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>nt(`providers`),children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,z.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,z.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,z.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,z.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>nt(`providers`),children:r(`codexAuth.openProviders`)})]})]})}function wm(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 Tm({apiBase:e}){let t=Z(),n=`ocx.codex-auth.config.v1:${e}`,r=qn(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=$o(wm(r));if(i===`absent`||i===`disabled`||i===`invalid`){a(i);let e=i===`disabled`?`disabled`:`absent`;s(e),Jn(n,{bannerState:i,accountModeState:e});return}let o=Sm(r);a(o),s(o),Jn(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 os(e,i),await p()}catch(e){e instanceof as?f(t(e.i18nKey)):f(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{u(!1)}};return(0,z.jsx)(z.Fragment,{children:(0,z.jsx)(Po,{apiBase:e,accountModeState:o,banner:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Cm,{state:i,busy:l,onEnable:()=>{m()}}),d&&(0,z.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:d})]}),advancedExtras:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(xm,{apiBase:e}),(0,z.jsx)(bm,{apiBase:e})]})})})}function Em(e){return e?[`responses`,`chat`,`messages`]:[`responses`,`chat`]}function Dm(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 Om(e){return e.id}function km(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.ambiguous===!0||!(typeof t.requests7d!=`number`||!Number.isFinite(t.requests7d)||typeof t.totalRequests!=`number`||!Number.isFinite(t.totalRequests)||t.lastUsedAt!==void 0&&(typeof t.lastUsedAt!=`string`||Number.isNaN(new Date(t.lastUsedAt).getTime())))}var Am=new Set([`required`,`accepted`,`rejected`]);function jm(e){return Array.isArray(e)&&e.length>0&&e.every(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.endpoint==`string`&&Am.has(t.bearer)&&Am.has(t.dedicated)&&Am.has(t.xApiKey)})}var Mm={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 Nm(e){let t=e||Mm.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 Pm(e,t){let n=new Date(e);return!e||Number.isNaN(n.getTime())?`—`:n.toLocaleDateString(t)}function Fm({url:e}){return(0,z.jsx)(Im,{text:e,hintKey:`api.copyUrlHint`,copiedKey:`api.urlCopied`,className:`api-endpoint-url-btn`,children:(0,z.jsx)(`code`,{className:`api-code api-code-inline api-endpoint-url`,children:e})})}function Im({text:e,hintKey:t,copiedKey:n,className:r,children:i}){let{t:a}=Ze(),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,rt.createPortal)((0,z.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,x={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};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`button`,{type:`button`,...x,children:i}),b]})}function Lm({text:e}){return(0,z.jsx)(Im,{text:e,hintKey:`api.copyExampleHint`,copiedKey:`api.exampleCopied`,className:`api-example-copy-btn`,children:(0,z.jsx)(`code`,{className:`api-code api-example-pre`,children:e})})}function Rm(e,t){return t(e===`required`?`api.auth.required`:e===`accepted`?`api.auth.accepted`:`api.auth.rejected`)}function zm({endpoints:e,claudeCodeEnabled:t,authMatrix:n}){let{t:r}=Ze();return(0,z.jsxs)(`div`,{className:`panel api-panel`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:r(`api.endpointsTitle`)}),(0,z.jsxs)(`div`,{className:`api-endpoints`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted small`,children:r(`api.baseUrl`)}),(0,z.jsx)(Fm,{url:e.baseUrl})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted small`,children:r(`api.responsesEndpoint`)}),(0,z.jsx)(Fm,{url:e.responses})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted small`,children:r(`api.chatCompletionsEndpoint`)}),(0,z.jsx)(Fm,{url:e.chatCompletions})]}),t&&(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted small`,children:r(`api.messagesEndpoint`)}),(0,z.jsx)(Fm,{url:e.messages})]}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`muted small`,children:r(`api.modelsEndpoint`)}),(0,z.jsx)(Fm,{url:e.models})]})]}),(0,z.jsx)(`p`,{className:`muted small`,children:r(`api.endpointNote`)}),(0,z.jsxs)(`div`,{className:`api-auth-matrix-block`,children:[(0,z.jsx)(`h4`,{className:`api-auth-matrix-title`,children:r(`api.authTitle`)}),(0,z.jsx)(`div`,{className:`api-auth-matrix-scroll`,children:(0,z.jsxs)(`table`,{className:`api-auth-matrix`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:r(`api.auth.endpoint`)}),(0,z.jsx)(`th`,{children:(0,z.jsx)(`code`,{children:`Authorization: Bearer`})}),(0,z.jsx)(`th`,{children:(0,z.jsx)(`code`,{children:`x-opencodex-api-key`})}),(0,z.jsx)(`th`,{children:(0,z.jsx)(`code`,{children:`x-api-key`})})]})}),(0,z.jsx)(`tbody`,{children:n.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.endpoint})}),(0,z.jsx)(`td`,{children:Rm(e.bearer,r)}),(0,z.jsx)(`td`,{children:Rm(e.dedicated,r)}),(0,z.jsx)(`td`,{children:Rm(e.xApiKey,r)})]},e.endpoint))})]})}),(0,z.jsx)(`p`,{className:`muted small`,children:r(`api.authLoopback`)}),(0,z.jsx)(`p`,{className:`muted small`,children:r(`api.authBaseUrlNote`)})]})]})}function Bm({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:_}=Ze();return(0,z.jsxs)(z.Fragment,{children:[a&&(0,z.jsxs)(`div`,{className:`panel api-panel panel-accent api-newkey-panel`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:_(`api.newKeyTitle`)}),(0,z.jsx)(`p`,{className:`muted small`,children:_(`api.newKeyNote`)}),(0,z.jsxs)(`div`,{className:`api-form-row`,children:[(0,z.jsx)(`code`,{className:`api-code`,style:{flex:1,wordBreak:`break-all`},children:a}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:p,children:o?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(J,{}),` `,_(`api.copied`)]}):_(`api.copy`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,style:{alignSelf:`flex-start`},onClick:f,children:_(`api.dismiss`)})]}),(0,z.jsxs)(`div`,{className:`panel api-panel api-generate-panel`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:_(`api.generateTitle`)}),(0,z.jsxs)(`div`,{className:`api-form-row`,children:[(0,z.jsx)(`input`,{id:`api-key-name`,type:`text`,placeholder:_(`api.keyNamePlaceholder`),"aria-label":_(`api.keyNamePlaceholder`),value:r,maxLength:64,onChange:e=>u(e.target.value),className:`input`}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:d,disabled:i,children:[(0,z.jsx)(ne,{}),` `,_(i?`api.generating`:`api.generate`)]})]})]}),l&&(0,z.jsxs)(`div`,{className:`panel api-panel`,style:{marginTop:`1rem`},"aria-busy":t,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:t?_(`api.activeKeysLoading`):_(`api.activeKeys`,{count:e.length})}),t?(0,z.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":_(`common.loading`)}):e.length>0?(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:_(`api.colName`)}),(0,z.jsx)(`th`,{children:_(`api.colKey`)}),(0,z.jsx)(`th`,{children:_(`api.colCreated`)}),(0,z.jsx)(`th`,{})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:e.name}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.prefix})}),(0,z.jsx)(`td`,{children:Pm(e.createdAt,c)}),(0,z.jsx)(`td`,{children:s===e.id?(0,z.jsxs)(`span`,{className:`api-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-danger`,onClick:()=>g(e.id),children:_(`api.confirm`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:h,children:_(`common.cancel`)})]}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,"aria-label":_(`api.deleteAria`),onClick:()=>m(e.id),children:(0,z.jsx)(Y,{})})})]},e.id))})]})}):n?(0,z.jsx)(`p`,{className:`muted`,children:_(`api.keysLoadFailed`)}):(0,z.jsx)(`p`,{className:`muted`,children:_(`api.noKeys`)})]})]})}function Vm({filteredModels:e,modelsLoading:t,modelsRefreshing:n=!1,modelsLoadFailed:r,modelCount:i,hasModelData:a,modelQuery:o,copiedModelId:s,modelTests:c,claudeCodeEnabled:l,onModelQueryChange:u,onCopyModelId:d,onTestModel:f,onRetryModels:p,canTestModels:m,sourceLabel:h,protocolLabel:g}){let{t:_}=Ze();return(0,z.jsxs)(`div`,{className:`panel api-panel api-models-panel`,children:[(0,z.jsxs)(`div`,{className:`api-panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:_(`api.modelsTitle`)}),(0,z.jsx)(`span`,{className:`muted mono text-label`,children:_(`api.modelsCount`,{count:e.length})})]}),(0,z.jsx)(`p`,{className:`muted small`,children:_(`api.modelsSubtitle`)}),(0,z.jsx)(`input`,{type:`search`,className:`input`,value:o,onChange:e=>u(e.target.value),placeholder:_(`api.modelsSearch`),"aria-label":_(`api.modelsSearch`)}),r&&(0,z.jsxs)(`div`,{className:`api-models-error`,children:[(0,z.jsx)(`p`,{className:`muted small`,role:`alert`,children:_(`api.modelsLoadFailed`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:_(`common.retry`)})]}),n&&!t&&(0,z.jsx)(`p`,{className:`muted small`,"aria-live":`polite`,children:_(`api.modelsLoading`)}),t?(0,z.jsx)(bc,{label:_(`api.modelsLoading`),rows:3}):a?e.length===0?(0,z.jsx)(`p`,{className:`muted small api-models-empty`,children:i===0?_(`api.modelsEmpty`):_(`api.modelsNoMatch`,{query:o.trim()})}):(0,z.jsx)(`div`,{className:`api-models-scroll`,children:(0,z.jsxs)(`table`,{className:`tbl`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:_(`api.colModel`)}),(0,z.jsx)(`th`,{children:_(`api.colSource`)}),(0,z.jsx)(`th`,{children:_(`api.colProtocols`)})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>{let t=Om(e),n=Em(l);return(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsxs)(`div`,{className:`api-model-cell`,children:[(0,z.jsx)(`code`,{children:t}),e.displayName!==e.id&&(0,z.jsx)(`span`,{className:`muted small`,children:e.displayName})]})}),(0,z.jsx)(`td`,{children:h(e)}),(0,z.jsx)(`td`,{children:(0,z.jsxs)(`div`,{className:`api-model-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>{d(t)},children:_(s===t?`api.modelCopied`:`api.copyModelId`)}),n.map(n=>{let r=c[t]?.[n],i=r?.state??`idle`;return(0,z.jsxs)(`span`,{className:`api-model-test-chip`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,disabled:i===`testing`||!m,title:m?void 0:_(`api.auth.testNeedsFreshKey`),onClick:()=>{f(e,n)},children:_(`api.auth.testProtocol`,{protocol:g(n)})}),i!==`idle`&&(0,z.jsx)(`span`,{className:`api-test-note api-test-note--${i}`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:i===`testing`?_(`api.testingModel`):i===`ok`?_(`api.testSucceeded`):r?.detail??_(`api.testFailed`)})]},n)})]})})]},t)})})]})}):null]})}function Hm({endpoints:e,claudeCodeEnabled:t}){let{t:n}=Ze(),r=JSON.stringify(n(`api.usageSampleInput`)),i=`curl ${e.chatCompletions} \\
|
|
55
55
|
-H "x-opencodex-api-key: ocx_YOUR_KEY_HERE" \\
|
|
56
56
|
-H "Content-Type: application/json" \\
|
|
@@ -73,4 +73,4 @@ default_mode_request_user_input = true`})]}),(0,z.jsxs)(`div`,{className:`codex-
|
|
|
73
73
|
}'`;return(0,z.jsxs)(`section`,{className:`panel api-panel awi-usage-panel`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:n(`api.workspace.usageExamples`)}),(0,z.jsxs)(`div`,{className:`awi-usage-panel-body`,children:[(0,z.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,z.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageChatTitle`)}),(0,z.jsx)(Lm,{text:i})]}),(0,z.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,z.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageResponsesTitle`)}),(0,z.jsx)(Lm,{text:a})]}),t&&(0,z.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,z.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageMessagesTitle`)}),(0,z.jsx)(Lm,{text:o})]})]})]})}var Um=[`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`],Wm={opencode:`api.clientConfig.clientOpencode`,pi:`api.clientConfig.clientPi`,omp:`api.clientConfig.clientOmp`,hermes:`api.clientConfig.clientHermes`,openclaw:`api.clientConfig.clientOpenclaw`,kimi:`api.clientConfig.clientKimi`,gajae:`api.clientConfig.clientGajae`,dsh:`api.clientConfig.clientDsh`,mcode:`api.clientConfig.clientMcode`},Gm={opencode:`/provider-icons/opencode.svg`,pi:`/provider-icons/pi.svg`};function Km({client:e,apiBase:t,onOpenDetails:n,onCopy:r,onDownload:i}){let a=Z(),[o,s]=(0,_.useState)(0),c=[t,e,String(o)].join(`|`),[l,u]=(0,_.useState)(null);(0,_.useEffect)(()=>{let n=new AbortController,r=!1;return(async()=>{try{let i=await fetch(`${t}/api/client-config?client=${encodeURIComponent(e)}`,{signal:n.signal});if(!i.ok)throw Error(String(i.status));let a=await i.json();if(r)return;u({key:c,data:a,failed:!1})}catch{if(r)return;u({key:c,data:null,failed:!0})}})(),()=>{r=!0,n.abort()}},[t,e,c]);let d=l!==null&&l.key===c?l:null,f=d?.data??null,p=d?.failed??!1,m=d===null,h=a(Wm[e]),g=Gm[e],v=f?.text??``,y=(0,_.useCallback)(t=>{f&&n(e,f,v,t.currentTarget)},[e,f,v,n]);return(0,z.jsxs)(`li`,{className:`awi-clientconfig-row`,children:[(0,z.jsx)(`span`,{className:`awi-clientconfig-mark`,"aria-hidden":`true`,children:g?(0,z.jsx)(`img`,{src:g,alt:``,width:20,height:20}):(0,z.jsx)(`span`,{className:`awi-clientconfig-monogram`,children:h.slice(0,1)})}),(0,z.jsxs)(`span`,{className:`awi-clientconfig-identity`,children:[(0,z.jsx)(`span`,{className:`awi-clientconfig-name`,children:h}),(0,z.jsx)(`span`,{className:`muted text-label awi-clientconfig-meta`,children:m?a(`api.clientConfig.loading`):p||!f?(0,z.jsx)(`span`,{role:`alert`,children:a(`api.clientConfig.rowError`,{client:h})}):a(`api.clientConfig.rowMeta`,{destination:f.destination,count:f.modelCount})})]}),(0,z.jsx)(`span`,{className:`awi-clientconfig-row-actions`,children:p&&!m?(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e=>e+1),children:a(`common.retry`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":a(`api.clientConfig.copyAria`,{client:h}),disabled:!f,onClick:()=>{f&&r(e,v)},children:a(`api.clientConfig.copy`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"aria-label":a(`api.clientConfig.downloadAria`,{client:h}),disabled:!f,onClick:()=>{f&&i(e,f,v)},children:a(`api.clientConfig.download`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":a(`api.clientConfig.detailsAria`,{client:h}),disabled:!f,onClick:y,children:a(`api.clientConfig.details`)})]})})]})}function qm({client:e,envelope:t,json:n,hasKeys:r,onClose:i,onCopy:a,onDownload:o}){let s=Z(),c=(0,_.useRef)(null),l=`awi-clientconfig-dialog-${e}`;(0,_.useEffect)(()=>{let e=c.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]);let u=(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,z.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,z.jsxs)(`div`,{className:`modal-card awi-clientconfig-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{id:l,children:s(Wm[e])}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:s(`common.close`)})]}),(0,z.jsx)(`pre`,{className:`api-code api-example-pre awi-clientconfig-json`,tabIndex:0,role:`group`,"aria-label":s(`api.clientConfig.jsonLabel`,{client:s(Wm[e])}),children:n}),(0,z.jsx)(`p`,{className:`muted small awi-clientconfig-count`,children:s(`api.clientConfig.modelCount`,{count:t.modelCount})}),t.modelsWithoutLimits>0&&(0,z.jsx)(`p`,{className:`muted small awi-clientconfig-degraded`,children:s(`api.clientConfig.missingLimits`,{count:t.modelsWithoutLimits,total:t.modelCount})}),!r&&(0,z.jsx)(`p`,{className:`muted small awi-clientconfig-nokey`,children:s(`api.clientConfig.noKeyYet`,{env:t.apiKeyEnv})}),(0,z.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,z.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.destination`)}),(0,z.jsx)(Lm,{text:t.destination})]}),(0,z.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,z.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.envHint`)}),(0,z.jsx)(Lm,{text:t.exportHint})]}),(0,z.jsx)(`p`,{className:`muted small awi-clientconfig-merge`,children:s(`api.clientConfig.mergeWarning`)}),(0,z.jsx)(`p`,{className:`muted text-label awi-clientconfig-where-title`,children:s(`api.clientConfig.whereDisclosure`)}),(0,z.jsx)(`p`,{className:`muted small`,children:s(`api.clientConfig.whereBody`)}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:s(`api.clientConfig.copy`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:o,children:s(`api.clientConfig.download`)})]})]})]})}function Jm({apiBase:e,baseUrl:t,hasKeys:n}){let r=Z(),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(``),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(i!==null)return;let e=c.current;e&&(c.current=null,e.isConnected&&e.focus())},[i]);let l=(0,_.useCallback)(async(e,t,n)=>{try{await navigator.clipboard.writeText(t),s(n?r(`api.clientConfig.copiedAnnounceClient`,{client:r(Wm[e])}):r(`api.clientConfig.copiedAnnounce`))}catch{s(r(`api.clientConfig.copyFailed`))}},[r]),u=(0,_.useCallback)((e,t,n)=>{let i=URL.createObjectURL(new Blob([n],{type:t.mediaType})),a=document.createElement(`a`);a.href=i,a.download=t.filename,a.click(),URL.revokeObjectURL(i),s(r(`api.clientConfig.downloadedAnnounce`,{filename:t.filename,destination:t.destination}))},[r]),d=(0,_.useCallback)(()=>a(null),[]),f=(0,_.useCallback)((e,t,n,r)=>{c.current=r,a({client:e,envelope:t,json:n})},[]);return(0,z.jsxs)(`section`,{className:`panel api-panel awi-clientconfig-panel`,children:[(0,z.jsx)(`div`,{className:`api-panel-head awi-clientconfig-head`,children:(0,z.jsx)(`h3`,{className:`panel-title`,children:r(`api.clientConfig.title`)})}),(0,z.jsx)(`ul`,{className:`awi-clientconfig-rows`,"aria-label":r(`api.clientConfig.rowsLabel`),children:Um.map(t=>(0,z.jsx)(Km,{client:t,apiBase:e,onOpenDetails:f,onCopy:(e,t)=>{l(e,t,!0)},onDownload:u},t))}),(0,z.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,z.jsx)(`span`,{className:`muted text-label`,children:r(`api.baseUrl`)}),(0,z.jsx)(Lm,{text:t})]}),(0,z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:o}),i&&(0,z.jsx)(qm,{client:i.client,envelope:i.envelope,json:i.json,hasKeys:n,onClose:d,onCopy:()=>{l(i.client,i.json,!1)},onDownload:()=>u(i.client,i.envelope,i.json)})]})}function Ym({keys:e,keysLoading:t,keysLoadFailed:n,attributionSince:r,localeTag:i,busy:a,onSelect:o}){let s=Z();return(0,z.jsxs)(`div`,{className:`panel api-panel awi-keylist-panel`,"aria-busy":t,children:[(0,z.jsx)(`div`,{className:`api-panel-head`,children:(0,z.jsx)(`h3`,{className:`panel-title`,children:t?s(`api.activeKeysLoading`):s(`api.activeKeys`,{count:e.length})})}),t?(0,z.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":s(`common.loading`)}):e.length===0?(0,z.jsx)(`p`,{className:`muted small`,children:s(n?`api.keysLoadFailed`:`api.noKeys`)}):(0,z.jsx)(`div`,{className:`tbl-wrap`,children:(0,z.jsxs)(`table`,{className:`tbl awi-keylist-table`,children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:s(`api.colName`)}),(0,z.jsx)(`th`,{children:s(`api.colKey`)}),(0,z.jsx)(`th`,{children:s(`api.attribution.requests7d`)}),(0,z.jsx)(`th`,{children:s(`api.attribution.lastUsed`)})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`button`,{type:`button`,className:`awi-keylist-name`,disabled:a,onClick:()=>o(e.id),children:e.name})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.prefix})}),(0,z.jsx)(`td`,{children:r?e.usage.ambiguous?s(`api.attribution.railAmbiguous`):e.usage.requests7d.toLocaleString(i):s(`api.attribution.unavailable`)}),(0,z.jsx)(`td`,{children:!r||e.usage.ambiguous?`—`:e.usage.lastUsedAt?Pm(e.usage.lastUsedAt,i):s(`api.attribution.neverUsed`)})]},e.id))})]})})]})}function Xm({keys:e,apiBase:t,attributionSince:n,historyTruncated:r,authMatrix:i,keysLoading:a,keysLoadFailed:o,endpoints:s,claudeCodeEnabled:c,localeTag:l,newName:u,creating:d,newKey:f,copied:p,filteredModels:m,modelsLoading:h,modelsRefreshing:g=!1,modelsLoadFailed:v,modelCount:y,hasModelData:b,modelQuery:x,copiedModelId:S,modelTests:C,canTestModels:w,onNewNameChange:T,onCreate:E,onDismissNewKey:D,onCopyKey:O,onDelete:k,onRename:A,onModelQueryChange:j,onCopyModelId:M,onTestModel:N,onRetryModels:P,sourceLabel:F,protocolLabel:I}){let L=Z(),[R,B]=(0,_.useState)(null),[V,H]=(0,_.useState)(!1),[U,W]=(0,_.useState)(!1),[G,ee]=(0,_.useState)(!1),[te,K]=(0,_.useState)(!1),[q,J]=(0,_.useState)(``),[Y,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(!1),[ae,se]=(0,_.useState)(!1),ce=R?e.find(e=>e.id===R)??null:null,le=G||Y,ue=(0,_.useMemo)(()=>[{id:`keys`,label:L(`api.section.keys`),meta:a?void 0:String(e.length)},{id:`connect`,label:L(`api.section.connect`)},{id:`endpoints`,label:L(`api.section.endpoints`)},{id:`models`,label:L(`api.section.models`),meta:String(y)},{id:`examples`,label:L(`api.section.examples`)}],[L,e.length,a,y]),X=()=>{H(!1),W(!1)},de=()=>{B(null),X(),K(!1),ie(!1),se(!1)};(0,_.useEffect)(()=>{if(!V)return;let e=window.setTimeout(()=>W(!0),300);return()=>window.clearTimeout(e)},[V]);let pe=()=>{ce&&H(!0)},me=async()=>{if(!(!ce||!U||G)){ee(!0),se(!1);try{await k(ce.id)?(X(),B(null)):se(!0)}finally{ee(!1)}}},he=()=>{ce&&(J(ce.name),ie(!1),K(!0))},ge=async()=>{if(!ce||Y)return;let e=q.trim();if(!e||e===ce.name){K(!1);return}ne(!0),ie(!1);try{await A(ce.id,e)?K(!1):ie(!0)}finally{ne(!1)}};return(0,z.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!ce&&(0,z.jsx)(ef,{scope:`api`,items:ue,ariaLabel:L(`api.workspace.sections`)}),(0,z.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,z.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":L(`api.workspace.details`),children:ce?(0,z.jsxs)(`div`,{className:`awi-detail`,children:[(0,z.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,z.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:de,disabled:le,children:[(0,z.jsx)(fe,{className:`awi-back-chevron`,"aria-hidden":`true`}),L(`modal.back`)]})}),(0,z.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,z.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,z.jsx)(`h2`,{className:`awi-detail-title`,children:ce.name}),(0,z.jsx)(`span`,{className:`awi-detail-actions`,children:V?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{me()},disabled:!U||G,children:[(0,z.jsx)(oe,{}),` `,L(G?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:X,disabled:G,children:L(`common.cancel`)})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:he,disabled:te,children:L(`api.key.rename`)},`rename`),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:pe,"aria-label":L(`api.deleteAria`),children:[(0,z.jsx)(oe,{}),` `,L(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),V&&(0,z.jsx)(`p`,{className:`muted awi-delete-hint`,children:L(`api.workspace.deleteConfirm`)}),ae&&(0,z.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:L(`api.deleteFailed`)}),te&&(0,z.jsxs)(`div`,{className:`awi-rename`,children:[(0,z.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:L(`api.key.name`)}),(0,z.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:q,maxLength:64,disabled:Y,onChange:e=>J(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),ge())}}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{ge()},disabled:Y,children:L(Y?`api.key.renaming`:`api.key.saveName`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>K(!1),disabled:Y,children:L(`common.cancel`)}),re&&(0,z.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:L(`api.key.renameFailed`)})]}),(0,z.jsxs)(`div`,{className:`awi-section`,children:[(0,z.jsx)(`h3`,{className:`awi-section-title`,children:L(`api.workspace.keyDetails`)}),(0,z.jsxs)(`dl`,{className:`awi-kv`,children:[(0,z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,z.jsx)(`dt`,{children:L(`api.workspace.keyPrefix`)}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:ce.prefix})})]}),(0,z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,z.jsx)(`dt`,{children:L(`api.colCreated`)}),(0,z.jsx)(`dd`,{children:Pm(ce.createdAt,l)})]})]})]}),(0,z.jsxs)(`div`,{className:`awi-section`,children:[(0,z.jsx)(`h3`,{className:`awi-section-title`,children:L(`api.attribution.title`)}),n?ce.usage.ambiguous?(0,z.jsx)(`p`,{className:`muted`,children:L(`api.attribution.ambiguous`)}):(0,z.jsxs)(`dl`,{className:`awi-kv`,children:[(0,z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,z.jsx)(`dt`,{children:L(`api.attribution.requests7d`)}),(0,z.jsx)(`dd`,{children:ce.usage.requests7d.toLocaleString(l)})]}),(0,z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,z.jsx)(`dt`,{children:L(r?`api.attribution.totalRequestsAvailable`:`api.attribution.totalRequests`)}),(0,z.jsx)(`dd`,{children:ce.usage.totalRequests.toLocaleString(l)})]}),(0,z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,z.jsx)(`dt`,{children:L(`api.attribution.lastUsed`)}),(0,z.jsx)(`dd`,{children:ce.usage.lastUsedAt?Pm(ce.usage.lastUsedAt,l):L(`api.attribution.neverUsed`)})]}),(0,z.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,z.jsx)(`dt`,{children:L(r?`api.attribution.sinceAvailable`:`api.attribution.since`)}),(0,z.jsx)(`dd`,{children:Pm(n,l)})]})]}):(0,z.jsx)(`p`,{className:`muted`,children:L(`api.attribution.unavailableDetail`)})]})]})]}):(0,z.jsx)(`div`,{className:`awi-overview`,children:(0,z.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,z.jsxs)(`div`,{id:Zd(`api`,`keys`),className:`awi-section-anchor`,children:[(0,z.jsx)(Bm,{keys:e,keysLoading:a,keysLoadFailed:o,newName:u,creating:d,newKey:f,copied:p,confirmDelete:null,localeTag:l,showKeyList:!1,onNewNameChange:T,onCreate:E,onDismissNewKey:D,onCopyKey:O,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,z.jsx)(Ym,{keys:e,keysLoading:a,keysLoadFailed:o,attributionSince:n,localeTag:l,busy:le,onSelect:e=>{B(e),X(),K(!1),ie(!1),se(!1)}})]}),(0,z.jsx)(`div`,{id:Zd(`api`,`connect`),className:`awi-section-anchor`,children:(0,z.jsx)(Jm,{apiBase:t,baseUrl:s.baseUrl,hasKeys:e.length>0})}),(0,z.jsx)(`div`,{id:Zd(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,z.jsx)(zm,{endpoints:s,claudeCodeEnabled:c,authMatrix:i})}),(0,z.jsx)(`div`,{id:Zd(`api`,`models`),className:`awi-section-anchor`,children:(0,z.jsx)(Vm,{filteredModels:m,modelsLoading:h,modelsRefreshing:g,modelsLoadFailed:v,modelCount:y,hasModelData:b,modelQuery:x,copiedModelId:S,modelTests:C,claudeCodeEnabled:c,onModelQueryChange:j,onCopyModelId:M,onTestModel:N,onRetryModels:P,canTestModels:w,sourceLabel:F,protocolLabel:I})}),(0,z.jsx)(`div`,{id:Zd(`api`,`examples`),className:`awi-section-anchor`,children:(0,z.jsx)(Hm,{endpoints:s,claudeCodeEnabled:c})})]})})})})]})}var Zm=[],Qm=15e3;function $m(e){let t=e.replace(/\/$/,``);if(!t)return Mm;try{return new URL(t).host?Nm(`${t}/v1/responses`):Mm}catch{return Mm}}function eh(e){return!e||!jm(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!km(e.usage))?null:e}function th({apiBase:e,active:t=!0}){let{t:n,locale:r}=Ze(),i=Ue.find(e=>e.code===r)?.htmlLang,a=`ocx.apikeys.list.v2:${e}`,o=`ocx.apikeys.models.v1:${e}`,s=`api-keys:${e}`,c=`api-models:${e}`,l=eh(qn(a)),u=qn(o),[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)(!1),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),O=(0,_.useRef)(!1),k=(0,_.useCallback)(async t=>{let r=await Ct(await fetch(`${e}/api/keys`,{signal:t}));if(!r||!jm(r.authMatrix))throw Error(n(`api.keysLoadFailed`));let i=r.keys??[];if(i.some(e=>!km(e.usage)))throw Error(n(`api.keysLoadFailed`));let o=i,s=Nm(r.endpoint??``),c={keys:o,endpoints:{baseUrl:r.baseUrl??s.baseUrl,responses:r.responsesEndpoint??r.endpoint??Mm.responses,chatCompletions:r.chatCompletionsEndpoint??s.chatCompletions,messages:r.messagesEndpoint??s.messages,models:r.modelsEndpoint??s.models},claudeCodeEnabled:r.claudeCodeEnabled!==!1,...r.attributionSince?{attributionSince:r.attributionSince}:{},...r.historyTruncated===!0?{historyTruncated:!0}:{},authMatrix:r.authMatrix};return Jn(a,c),c},[e,a,n]),A=(0,_.useCallback)(async t=>{let r=await fetch(`${e}/v1/models`,{signal:t});if(!r.ok)throw Error(n(`api.modelsLoadFailed`));let i=await r.json(),a=Array.isArray(i)?i:typeof i==`object`&&i&&Array.isArray(i.data)?i.data:null;if(!a)throw Error(n(`api.modelsLoadFailed`));let s=a.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`).map(e=>Dm(e)).sort((e,t)=>Om(e).localeCompare(Om(t)));return Jn(o,s),s},[e,o,n]),j=vc(s,[e],k,{isEmpty:e=>e.keys.length===0,initialData:l??void 0,enabled:t}),M=vc(c,[e],A,{isEmpty:e=>e.length===0,initialData:u??void 0,enabled:t}),N=j.state,P=M.state,F=N.data??l,I=P.data??u??Zm,L=F?.keys??[],R=F?.endpoints??$m(e),B=F?.claudeCodeEnabled??!0,V=F?.attributionSince,H=F?.historyTruncated===!0,U=F?.authMatrix??[],W=j.refresh,G=M.refresh,ee=(0,_.useMemo)(()=>{let e=p.trim().toLowerCase();return e?I.filter(t=>Om(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):I},[p,I]),te=async t=>{if(O.current)return!1;O.current=!0,C(!0),f(null);try{let r=t??b,i=await St(await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:r||`default`})}),n(`api.createFailed`));return typeof i?.key!=`string`||i.key.length===0?(f(n(`api.createFailed`)),!1):(T(i.key),x(``),W(),!0)}catch{return f(n(`api.createFailed`)),!1}finally{O.current=!1,C(!1)}},K=async t=>{f(null);let n=Cn(Qm);try{return(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal})).ok?(W(),!0):!1}catch{return!1}finally{n.clear()}},q=async(t,n)=>{f(null);let r=Cn(Qm);try{return(await fetch(`${e}/api/keys`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,name:n}),signal:r.signal})).ok?(W(),!0):!1}catch{return!1}finally{r.clear()}},J=async()=>{if(w){f(null);try{await navigator.clipboard.writeText(w),D(!0),window.setTimeout(()=>D(!1),2e3)}catch{D(!1),f(n(`api.key.copyFailed`))}}},Y=async e=>{try{await navigator.clipboard.writeText(e),g(e),window.setTimeout(()=>g(t=>t===e?null:t),2e3)}catch{}},ne=e=>e.native?n(`api.sourceNative`):e.provider===`combo`?n(`api.sourceCombo`):e.custom?n(`api.sourceCustom`):pn(e.provider,n),re=e=>n(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),ie=(e,t)=>e===`responses`?{url:R.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:R.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:R.chatCompletions,body:{model:t,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1}},ae=(e,t,n)=>y(r=>({...r,[e]:{...r[e],[t]:n}})),oe=async(e,t)=>{if(!w)return;let r=Om(e),i=ie(t,r);ae(r,t,{state:`testing`});try{let e=await fetch(i.url,{method:`POST`,headers:{"Content-Type":`application/json`,"x-opencodex-api-key":w},body:JSON.stringify(i.body)});if(!e.ok){let n=await e.text();ae(r,t,{state:`error`,detail:n.slice(0,160)||String(e.status)});return}ae(r,t,{state:`ok`})}catch(e){ae(r,t,{state:`error`,detail:e instanceof Error?e.message:n(`api.testFailed`)})}},se=n(`api.subtitle`).split(`{authHeader}`);return(0,z.jsxs)(`section`,{className:`api-page`,"aria-busy":N.refreshing||P.refreshing||void 0,children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:n(`api.title`)})}),(0,z.jsxs)(`p`,{className:`page-sub`,children:[se[0],(0,z.jsx)(`code`,{children:`x-opencodex-api-key`}),se[1]]}),d&&(0,z.jsx)($,{tone:`err`,children:d}),N.showError&&F&&(0,z.jsx)($,{tone:`err`,children:n(`api.keysLoadFailed`)}),N.showSkeleton&&!F?(0,z.jsx)(bc,{label:n(`api.activeKeysLoading`),rows:4}):N.kind===`failed-cold`&&!F?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($,{tone:`err`,children:N.error instanceof Error?N.error.message:n(`api.keysLoadFailed`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>W(),children:n(`common.retry`)})]}):(0,z.jsx)(z.Fragment,{children:(0,z.jsx)(Xm,{keys:L,apiBase:e,attributionSince:V,historyTruncated:H,authMatrix:U,keysLoading:!1,keysLoadFailed:N.showError,endpoints:R,claudeCodeEnabled:B,localeTag:i,newName:b,creating:S,newKey:w,copied:E,filteredModels:ee,modelsLoading:P.showSkeleton&&!P.data&&!u,modelsRefreshing:P.refreshing&&P.showError&&(P.data!==void 0||u!==null),modelsLoadFailed:P.showError,modelCount:I.length,hasModelData:P.data!==void 0||u!==null,modelQuery:p,copiedModelId:h,modelTests:v,onNewNameChange:x,onCreate:()=>{te()},onDismissNewKey:()=>T(null),onCopyKey:()=>{J()},onDelete:K,onRename:q,onModelQueryChange:m,onCopyModelId:e=>{Y(e)},onTestModel:(e,t)=>{oe(e,t)},onRetryModels:()=>{G({forceLoading:!0})},canTestModels:w!==null,sourceLabel:ne,protocolLabel:re})})]})}function nh(e,t){let n=(e??[]).map(e=>({value:e,label:gc(e)}));return[{value:``,label:t},...n]}function rh(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}var ih=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`];function ah(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=ih.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(`
|
|
74
74
|
`)}function oh(e){return e?e.backend??`auto`:`inherit`}function sh(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function ch(e,t){return{...e,model:t}}function lh(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 uh({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,z.jsxs)(`label`,{className:`toggle`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,z.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function dh({supported:e,checked:t,onChange:n}){let r=Z(),i=e?void 0:`claude-system-env-unsupported`;return(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,z.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,z.jsx)(`span`,{className:`desc`,id:i,children:(0,z.jsx)($e,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,z.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,z.jsx)(uh,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function fh({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=Z(),a=t??e;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,z.jsx)(ht,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,z.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function ph(){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 mh(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 hh(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 gh({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=Z();return(0,z.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,z.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsx)(ht,{value:e.authMode,options:[{value:`auto`,label:i(`claude.authModeAuto`)},{value:`subscription`,label:i(`claude.authModeSubscription`)},{value:`proxy`,label:i(`claude.authModeProxy`)}],onChange:t=>r({...e,authMode:t}),label:i(`claude.authMode`),style:{minWidth:220},align:`right`,portal:!0})})]}),e.authModeOrigin&&(0,z.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,z.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,z.jsxs)(`span`,{children:[e.authModeOrigin===`manual`?i(`claude.effectiveMode.manual`,{mode:e.markerMode===`proxy`?i(`claude.authModeProxy`):i(`claude.authModeSubscription`)}):e.authModeOrigin===`auto-present`?i(`claude.effectiveMode.autoPresent`,{source:hh(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,z.jsx)(dh,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,z.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsx)(ht,{value:e.fastMode===null?`auto`:e.fastMode?`on`:`off`,options:[{value:`auto`,label:i(`claude.fastAuto`)},{value:`on`,label:i(`claude.fastOn`)},{value:`off`,label:i(`claude.fastOff`)}],onChange:t=>r({...e,fastMode:t===`auto`?null:t===`on`}),label:i(`claude.fastMode`),style:{minWidth:140},align:`right`,portal:!0})})]}),(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,z.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,z.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,z.jsx)(uh,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,z.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,z.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,z.jsx)(`div`,{className:`setting-controls`,children:(0,z.jsx)(ht,{value:e.autoCompactWindow===null?``:String(e.autoCompactWindow),options:t,onChange:t=>r({...e,autoCompactWindow:t===``?null:Number(t)}),label:i(`claude.autoCompactWindow`),style:{minWidth:130},align:`right`,portal:!0})})]}),(0,z.jsxs)(`div`,{className:`setting-row`,children:[(0,z.jsxs)(`div`,{className:`setting-label`,children:[(0,z.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,z.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,z.jsx)(uh,{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,z.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,z.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,z.jsx)(`span`,{className:`title`,children:i(o)}),(0,z.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,z.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,z.jsx)(ht,{value:oh(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]:sh(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,z.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:ch(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,z.jsx)(`datalist`,{id:c,children:n.map(e=>(0,z.jsx)(`option`,{value:e},e))})]})]},t)})]})}function _h({manualEnv:e}){let t=Z();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,z.jsx)($e,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,z.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,z.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,z.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,z.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function vh({rows:e,onRowsChange:t}){let n=Z();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,z.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,z.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,z.jsx)(`input`,{className:`input mono`,value:r.from,placeholder:n(`claude.mapFrom`),"aria-label":n(`claude.mapFrom`),onChange:n=>t(e.map((e,t)=>t===i?{...e,from:n.target.value}:e)),style:{flex:1}}),(0,z.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,z.jsx)(`input`,{className:`input mono`,value:r.to,placeholder:n(`claude.mapTo`),"aria-label":n(`claude.mapTo`),onChange:n=>t(e.map((e,t)=>t===i?{...e,to:n.target.value}:e)),style:{flex:1}}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>t(e.filter((e,t)=>t!==i)),"aria-label":n(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,z.jsx)(Y,{})})]},r.id))}),(0,z.jsx)(`div`,{style:{marginTop:8},children:(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:ph(),from:``,to:``}]),children:[(0,z.jsx)(ne,{}),` `,n(`claude.addMapping`)]})})]})}var yh=`etc`;function bh(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:yh,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function xh({aliases:e}){let t=Z();return(0,z.jsxs)(`div`,{className:`claude-aliases`,children:[(0,z.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,z.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,z.jsx)(`div`,{className:`claude-aliases-scroll`,children:bh(e).map(([e,n])=>(0,z.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,z.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===yh?t(`claude.aliasProviderOther`):e,(0,z.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,z.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,z.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,z.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,z.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function Sh({apiBase:e,active:t=!0}){let n=Z(),{locale:r}=Ze(),i=Ue.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=`claude-code:${e}`,s=(0,_.useMemo)(()=>qn(a),[a]),[c,l]=(0,_.useState)(()=>s?.state??null),[u,d]=(0,_.useState)(()=>s?.rows??[]),[f,p]=(0,_.useState)(!!s),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(`settings`),[x,S]=(0,_.useState)(!1),C=(0,_.useRef)(!1),w=(0,_.useCallback)(async t=>{let r=await St(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`,...rh(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:ph(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return l(i),d(o),p(!0),Jn(a,s),s},[e,a,n]),T=vc(o,[e],w,{isEmpty:()=>!1,enabled:t,initialData:s??void 0}),E=T.state,D=E.data??s,O=c??D?.state??null,k=f?u:D?.rows??u,A=(0,_.useMemo)(()=>nh(O?.available,n(`claude.smallFastModelUnsetOption`)),[O?.available,n]),j=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,9e5,1e6],t=O?.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:mh(e,i)}))]},[O?.autoCompactWindow,n,i]),M=async()=>{if(!O||C.current)return;C.current=!0,S(!0),h(``);let t=!O.enabled;try{await St(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t})}),n(`claude.saveFailed`)),l({...O,enabled:t}),T.refresh()}catch(e){v(!1),h(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}finally{C.current=!1,S(!1)}},N=async()=>{if(!O)return;h(``);let t={};for(let e of k)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await St(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:O.enabled,authMode:O.authMode,systemEnv:O.systemEnv,fastMode:O.fastMode,autoContext:O.autoContext,autoCompactWindow:O.autoCompactWindow,injectAgents:O.injectAgents,smallFastModel:O.smallFastModel,modelMap:t,webSearchSidecar:lh(O.webSearchSidecar),visionSidecar:lh(O.visionSidecar)})}),n(`claude.saveFailed`)),v(!0),h(n(`claude.saved`)),T.refresh()}catch(e){v(!1),h(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(E.kind===`disabled`&&!D)return null;if(E.showSkeleton&&!D)return(0,z.jsx)(bc,{label:n(`claude.loading`),rows:3});if(E.kind===`failed-cold`){let e=E.error instanceof Error?E.error.message:n(`claude.loadFail`);return(0,z.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,z.jsx)($,{tone:`err`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>T.refresh(),children:n(`common.retry`)})]})}if(!O)return null;let P=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,z.jsx)(gh,{state:O,autoCompactOptions:j,availableModels:O.available??[],onStateChange:l})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,z.jsx)(_h,{manualEnv:ah(O)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,z.jsx)(fh,{value:O.smallFastModel,tierHaikuModel:O.tierModels?.haiku,options:A,onChange:e=>l({...O,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),meta:String(k.length),body:(0,z.jsx)(vh,{rows:k,onRowsChange:e=>{p(!0),d(e)}})},{id:`aliases`,label:n(`claude.aliases`),meta:String(O.aliases.length),body:(0,z.jsx)(xh,{aliases:O.aliases})}],F=P.find(e=>e.id===y)??P[0],I=y===`settings`||y===`smallFast`||y===`modelMap`;return(0,z.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[m&&(0,z.jsx)($,{tone:g?`ok`:`err`,children:m}),E.showError&&(0,z.jsx)($,{tone:`err`,children:n(`claude.loadFail`)}),O&&(0,z.jsxs)(`div`,{className:`claudecode-connection-head`,children:[(0,z.jsx)(`span`,{id:`claudecode-connection-label`,children:n(`claude.enabledLabel`)}),(0,z.jsx)(pt,{on:O.enabled,onClick:()=>void M(),disabled:x,label:n(`claude.toggleAria`)})]}),(0,z.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,z.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,z.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:P.map(e=>(0,z.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${y===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>b(e.id),"aria-current":y===e.id?`true`:void 0,children:(0,z.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,z.jsxs)(`section`,{className:`claudecode-workspace-main`,"aria-label":F.label,children:[(0,z.jsxs)(`div`,{className:`ccw-main-head`,children:[(0,z.jsxs)(`h3`,{className:`ccw-main-title`,children:[F.label,F.meta==null?null:(0,z.jsx)(`span`,{className:`count`,children:F.meta})]}),(0,z.jsx)(`div`,{className:`claudecode-workspace-save`,"data-visible":I?`true`:`false`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!I,tabIndex:I?0:-1,"aria-hidden":!I,onClick:()=>{N()},children:n(`common.save`)})})]}),(0,z.jsx)(`div`,{className:`ccw-body`,children:F.body})]})]})]})}function Ch(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 wh(e){return new Set(Object.keys(e))}function Th(e,t){return t!==null&&e===t}function Eh(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function Dh(e){return{read(t){let n=Eh(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=Eh(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function Oh(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var kh=[`opus`,`fable`,`sonnet`,`haiku`],Ah=Dh(`ocx.claudeDesktop.collapsedFamilies.v2`),jh={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function Mh(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 Nh(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:kh.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 Ph(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function Fh(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 Ih(e){return qn(e)}function Lh(e){let t=Ih(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?Mh(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function Rh({apiBase:e,active:t=!0,onPortChange:n}){let{t:r,locale:i}=Ze(),a=Ue.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,_.useMemo)(()=>Lh(o),[o]),[l,u]=(0,_.useState)(()=>c.profile),[d,f]=(0,_.useState)(()=>c.savedProfile),[p,m]=(0,_.useState)(()=>c.destinations),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)({}),[w,T]=(0,_.useState)({}),[E,D]=(0,_.useState)(()=>Ah.read()??new Set(kh)),[O,k]=(0,_.useState)({}),A=(0,_.useRef)(null),j=(0,_.useCallback)(async t=>{let n=await St(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(Ph(n,r(`claudeDesktop.loadFail`)));let i=Nh(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f(Mh(i)),m(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),Ah.read()===null){let e=Object.fromEntries(kh.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;D(wh(e))}return Jn(o,a),a},[e,o,r,m,u,f]),M=vc(s,[e],j,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0}),N=M.state,P=N.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),F=P?.data??null,I=l??P?.profile??null,L=d??P?.profile??null,R=P?Object.fromEntries(P.data.models.map(e=>[e.route,P.profile.assignments[e.route]?.family??`opus`])):{},B=Object.keys(p).length>0?p:R;(0,_.useEffect)(()=>{if(n){if(typeof F?.port==`number`){n(F.port);return}N.kind===`failed-cold`&&n(null)}},[F?.port,N.kind,n]);let V=(0,_.useMemo)(()=>I!==null&&L!==null&&JSON.stringify(I)!==JSON.stringify(L),[I,L]),H=(0,_.useMemo)(()=>{let e=Object.fromEntries(kh.map(e=>[e,[]]));if(!F||!I)return e;for(let t of F.models)e[I.assignments[t.route]?.family??`opus`].push(t);return e},[F,I]),U=(0,_.useMemo)(()=>{let e={};for(let t of kh){let n=H[t].filter(e=>e.available).map(e=>e.route).sort(),r=I?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[H,I]),W=`ocx.claude-desktop.status.v1:${e}`,G=`claude-desktop-status:${e}`,ee=qn(W),te=vc(G,[e],async t=>{let n=await Ct(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return Jn(W,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:ee??void 0}),K=te.state,q=K.data??ee??null,J=K.showError,Y=(e,t)=>{!I||I.assignments[e]?.family===t||(u(n=>{if(!n)return n;let r=n.assignments[e];if(!r||r.family===t)return n;let i={...n.assignments,[e]:{...r,family:t}},a={...n.defaults};return a[r.family]===e&&(a[r.family]=Object.keys(i).filter(t=>t!==e&&i[t].family===r.family).sort()[0]??null),a[t]===null&&(a[t]=e),{...n,assignments:i,defaults:a}}),m(n=>({...n,[e]:t})),y(r(`claudeDesktop.moved`,{route:e,family:r(jh[t])})))},ne=e=>{let t=Oh(E,e);Ah.write(t),D(t)},re=async t=>{if(!(!I||b)){x(`save`),g(null);try{await St(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:I})}),r(`claudeDesktop.saveFailed`)),f(Mh(I)),t?(x(`apply`),(await St(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`}),r(`claudeDesktop.applyFailed`)))?.saved===!1?(g({tone:`warn`,text:r(`claudeDesktop.appliedMarkerUnsaved`)}),y(r(`claudeDesktop.appliedMarkerUnsaved`))):(g({tone:`ok`,text:r(`claudeDesktop.savedApplied`)}),y(r(`claudeDesktop.savedAppliedAnnounce`)))):(g({tone:`ok`,text:r(`claudeDesktop.saved`)}),y(r(`claudeDesktop.savedAnnounce`))),te.refresh()}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.updateFailed`);g({tone:`err`,text:t}),y(t)}finally{x(null)}}},ie=()=>{if(!I)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(I,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),y(r(`claudeDesktop.exported`))},ae=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(r(`claudeDesktop.importExpected`));let n=Nh({...F,profile:e});u(n),g({tone:`ok`,text:r(`claudeDesktop.importReady`)}),y(r(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.importInvalid`);g({tone:`err`,text:t}),y(r(`claudeDesktop.importFailed`,{error:t}))}},oe=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&Y(n,t)};if(N.kind===`disabled`&&!P)return null;if(N.showSkeleton&&!P)return(0,z.jsx)(bc,{label:r(`claudeDesktop.loading`),rows:4});if(N.kind===`failed-cold`){let e=N.error instanceof Error?N.error.message:r(`claudeDesktop.loadFail`);return(0,z.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,z.jsx)($,{tone:`err`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>M.refresh(),children:r(`claudeDesktop.retry`)})]})}return!F||!I?null:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,z.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,z.jsx)(`input`,{ref:A,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ae(e)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ie,children:r(`claudeDesktop.exportJson`)})]})}),(0,z.jsxs)(`div`,{className:`claude-status-bar ${J&&!q?`not-applied`:q?q.desiredEnabled?q.activeProfile===!1?`not-applied`:q.stale?`stale`:q.applied?`applied`:`not-applied`:`not-applied`:`pending`}`,"aria-busy":!q&&!J||void 0,children:[(0,z.jsx)(`span`,{className:`claude-status-dot`}),(0,z.jsx)(`span`,{children:J&&!q?r(`claudeDesktop.loadFail`):q?q.desiredEnabled?q.activeProfile===!1?r(`claudeDesktop.status.notActiveProfile`):q.stale?r(`claudeDesktop.status.stale`):q.applied?r(`claudeDesktop.status.applied`):r(`claudeDesktop.status.notApplied`):r(`claudeDesktop.status.disabled`):r(`claudeDesktop.loading`)}),q?.health.lastRequestAt&&(0,z.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(q.health.lastRequestAt).toLocaleTimeString(a)]}),q&&q.health.requestCount>0&&(0,z.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:q.health.requestCount,errors:q.health.errorCount})})]}),(0,z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:v}),h&&(0,z.jsx)($,{tone:h.tone,children:h.text}),N.showError&&(0,z.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),J&&q&&(0,z.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),(0,z.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,z.jsx)(`span`,{className:`claude-dirty${V?` active`:``}`,children:r(V?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,z.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!V||b!==null,onClick:()=>void re(!1),children:r(b===`save`?`claudeDesktop.saving`:`common.save`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:b!==null,onClick:()=>void re(!0),children:b===`apply`?r(`claudeDesktop.applying`):b===`save`?r(`claudeDesktop.saving`):q?.desiredEnabled===!1?r(`claudeDesktop.enableApply`):r(`claudeDesktop.saveApply`)})]})]}),F.models.length===0&&(0,z.jsx)(gt,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),(0,z.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:kh.map(e=>{let t=H[e],n=Ch(t,S[e]??``,w[e]??6),i=E.has(e),a=U[e];return(0,z.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>oe(t,e),children:[(0,z.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,z.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,z.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>ne(e),children:[(0,z.jsx)(fe,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,z.jsx)(`span`,{className:`ocx-group-name`,children:r(jh[e])}),(0,z.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,z.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&I.defaults[e]===null&&(0,z.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==I.defaults[e]&&(0,z.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,z.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,z.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:S[e]??``,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),T(t=>({...t,[e]:6}))}}),(0,z.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,z.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,z.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=I.assignments[t.route],i=Fh(t.contextWindow,r),a=B[t.route]??`opus`,o=O[t.route]??Th(t.route,U[e]);return(0,z.jsxs)(`article`,{className:`claude-model-card${o?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,z.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>k(e=>({...e,[t.route]:!o})),children:[(0,z.jsx)(fe,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,z.jsxs)(`span`,{className:`claude-model-names`,children:[(0,z.jsx)(`strong`,{title:t.label,children:t.label}),(0,z.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,z.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,z.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,z.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,z.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,z.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),I.defaults[e]===t.route&&(0,z.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,z.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,z.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[U[e]===t.route&&I.defaults[e]!==t.route&&(0,z.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,z.jsxs)(`div`,{className:`claude-field`,children:[(0,z.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,z.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,z.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,z.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:I.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(jh[e])})]}),(0,z.jsxs)(`div`,{className:`claude-move-row`,children:[(0,z.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,z.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:kh.map(e=>(0,z.jsx)(`option`,{value:e,children:r(jh[e])},e))}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>Y(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>T(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})}var zh=`integrations/claude`,Bh=`integrations/claude/desktop`;function Vh(e=typeof window<`u`?window.location.hash:``){return et(e)===Bh?`desktop`:`code`}function Hh(e){let t=qn(`ocx.claude-desktop.v1:${e}`);return typeof t?.data?.port==`number`?t.data.port:null}function Uh({apiBase:e,active:t=!0}){let[n,r]=(0,_.useState)(Vh),i=Z(),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=Hh(e),[c,l]=(0,_.useState)(null),u=c?.base===e?c.port:s,d=c?.base===e,f=(0,_.useCallback)(t=>{l(n=>n?.base===e&&n.port===t?n:{base:e,port:t})},[e]);(0,_.useEffect)(()=>{let e=()=>r(Vh());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let p=e=>{nt(e===`desktop`?Bh:zh),r(e),window.requestAnimationFrame(()=>{(e===`code`?a:o).current?.focus({preventScroll:!0})})},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(n===`code`?`desktop`:`code`)):e.key===`Home`?(e.preventDefault(),p(`code`)):e.key===`End`&&(e.preventDefault(),p(`desktop`))};return(0,z.jsxs)(`section`,{className:`claude-page`,children:[(0,z.jsxs)(`div`,{className:`claude-page-intro`,children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:i(n===`code`?`claude.pageTitle`:`claudeDesktop.title`)})}),n===`code`?(0,z.jsx)(`p`,{className:`page-sub`,children:i(`claude.subtitle`)}):(0,z.jsx)(`p`,{className:`page-sub`,children:u==null?i(d?`claudeDesktop.loadFail`:`claudeDesktop.loading`):i(`claudeDesktop.subtitle`,{port:u})})]}),(0,z.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":i(`claude.tabsLabel`),children:[(0,z.jsx)(`button`,{type:`button`,role:`tab`,ref:a,"aria-selected":n===`code`,"aria-controls":`claude-code-panel`,id:`claude-code-tab`,className:n===`code`?`active`:``,tabIndex:n===`code`?0:-1,onKeyDown:m,onClick:()=>p(`code`),children:i(`claude.tabCode`)}),(0,z.jsx)(`button`,{type:`button`,role:`tab`,ref:o,"aria-selected":n===`desktop`,"aria-controls":`claude-desktop-panel`,id:`claude-desktop-tab`,className:n===`desktop`?`active`:``,tabIndex:n===`desktop`?0:-1,onKeyDown:m,onClick:()=>p(`desktop`),children:i(`claude.tabDesktop`)})]}),(0,z.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:n!==`code`,children:(0,z.jsx)(Sh,{apiBase:e,active:t&&n===`code`},e)}),(0,z.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:n!==`desktop`,children:(0,z.jsx)(Rh,{apiBase:e,active:t&&n===`desktop`,onPortChange:f},e)})]})}function Wh(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 Gh=Dh(`ocx.grok.collapsedGroups.v2`),Kh=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],qh=new Set(Kh.map(e=>e.id));function Jh(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 Yh({apiBase:e,active:t=!0}){let n=Z(),r=`ocx.grok.status.v1:${e}`,i=qn(r),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(()=>Gh.read()??new Set(qh)),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(``),h=(0,_.useCallback)(async t=>{let i=await St(await fetch(`${e}/api/grok`,{signal:t}),n(`grok.loadFail`));if(!i)throw Error(n(`grok.loadFail`));let a={...i,candidates:i.candidates??[],excluded:i.excluded??[]};return Jn(r,a),a},[e,r,n]),g=`grok-status:${e}`,v=vc(g,[e],h,{isEmpty:()=>!1,initialData:i??void 0,enabled:t}),{state:y}=v,b=v.refresh,x=y.data??i,S=(0,_.useMemo)(()=>new Set(x?.excluded??[]),[x]),C=a??S,w=(0,_.useMemo)(()=>a!==null&&(a.size!==S.size||[...a].some(e=>!S.has(e))),[a,S]),T=(0,_.useMemo)(()=>new Map((x?.models??[]).map(e=>[e.id,e.alias])),[x]),E=e=>{let t=Oh(s,e);Gh.write(t),c(t)},D=e=>{let t=e?new Set(Kh.map(e=>e.id)):new Set;Gh.write(t),c(t)},O=(e,t)=>{o(n=>{let r=new Set(n??S);return t?r.delete(e):r.add(e),r})},k=async t=>{if(!l){u(`save`),f(null);try{await St(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...C]})}),n(`grok.saveFailed`));let i=[...C];if(x&&L(g,{...x,excluded:i}),o(null),t){u(`apply`);let t=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.message??e.error??n(`grok.applyFailed`))}let r=await t.json().catch(()=>({}));r.skippedReason?(f({tone:`err`,text:r.message??n(`grok.applySkipped`)}),m(r.message??n(`grok.applySkipped`))):(f({tone:`ok`,text:n(`grok.savedApplied`)}),m(n(`grok.savedApplied`))),await b()}else f({tone:`ok`,text:n(`grok.saved`)}),m(n(`grok.saved`)),x&&Jn(r,{...x,excluded:i})}catch(e){let t=e instanceof Error?e.message:n(`grok.saveFailed`);f({tone:`err`,text:t}),m(t)}finally{u(null)}}};if(y.showSkeleton&&!x)return(0,z.jsx)(`section`,{className:`grok-page`,children:(0,z.jsx)(bc,{label:n(`grok.loading`),rows:4})});if(y.kind===`failed-cold`){let e=y.error instanceof Error?y.error.message:n(`grok.loadFail`);return(0,z.jsxs)(`section`,{className:`grok-page`,children:[(0,z.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>b(),children:n(`common.retry`)})]})}return(0,z.jsxs)(`section`,{className:`grok-page`,"aria-busy":y.refreshing||void 0,children:[(0,z.jsx)(`h2`,{className:`page-title`,children:n(`grok.title`)}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`grok.subtitle`)}),(0,z.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:p}),d&&(0,z.jsx)($,{tone:d.tone,children:d.text}),y.showError&&(0,z.jsx)($,{tone:`err`,children:n(`grok.loadFail`)}),x&&x.candidates.length>0&&(0,z.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,z.jsx)(`span`,{className:`claude-dirty${w?` active`:``}`,children:n(w?`grok.unsaved`:`grok.upToDate`)}),(0,z.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!w||l!==null,onClick:()=>void k(!1),children:n(l===`save`?`grok.saving`:`common.save`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!w||l!==null,onClick:()=>void k(!0),children:n(l===`apply`?`grok.applying`:l===`save`?`grok.saving`:`grok.saveApply`)})]})]}),x?.present?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,z.jsx)(`span`,{children:n(`grok.endpoint`)}),(0,z.jsx)(`code`,{children:x.baseUrl??`—`})]}),(0,z.jsx)(`p`,{className:`page-sub`,children:(0,z.jsx)(`code`,{children:x.configPath})})]}):(0,z.jsxs)(gt,{title:n(`grok.notConfiguredTitle`),children:[n(`grok.notConfiguredHint`),(0,z.jsx)(`br`,{}),(0,z.jsx)(`code`,{children:x?.configPath})]}),x&&x.candidates.length>0&&(0,z.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,z.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>D(!0),disabled:l!==null,children:[(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`}),` `,n(`models.collapseAll`)]}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>D(!1),disabled:l!==null,children:[(0,z.jsx)(fe,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,n(`models.expandAll`)]})]}),Kh.map(e=>{let t=Wh(x.candidates,T,C,e.id);if(t.total===0)return null;let r=s.has(e.id);return(0,z.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,z.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,z.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,z.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>E(e.id),children:[(0,z.jsx)(fe,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,z.jsx)(`span`,{className:`ocx-group-name`,children:n(e.tkey)}),(0,z.jsx)(`span`,{className:`ocx-group-count`,children:n(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!r&&(0,z.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,z.jsxs)(`div`,{className:`grok-model-row`,children:[(0,z.jsx)(pt,{on:e.enabled,onClick:()=>O(e.id,!e.enabled),disabled:l!==null,label:n(`grok.toggleModel`,{id:e.id})}),(0,z.jsxs)(`span`,{className:`grok-model-names`,children:[(0,z.jsx)(`strong`,{title:e.id,children:e.id}),(0,z.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,z.jsx)(`span`,{className:`claude-model-context`,children:Jh(e.contextWindow,n)})]},e.id))})]},e.id)})]})]})}var Xh={"not-installed":`integrations.state.notInstalled`,unknown:`integrations.state.unknown`,absent:`integrations.state.absent`,current:`integrations.state.current`,stale:`integrations.state.stale`,conflict:`integrations.state.conflict`,unsafe:`integrations.state.unsafe`},Zh={"not-installed":`badge badge-muted`,unknown:`badge badge-muted`,absent:`badge badge-muted`,current:`badge badge-green`,stale:`badge badge-amber`,conflict:`badge integration-badge--danger`,unsafe:`badge integration-badge--danger-outline`};function Qh({state:e,installed:t,id:n}){let r=Z(),i=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,z.jsx)(`span`,{id:n,className:Zh[i],"data-integration-state":i,children:r(Xh[i])})}function $h({copyKey:e,vars:t}){let n=Z()(e,t),r=t?.path;if(!r||!n.includes(r))return(0,z.jsx)(`p`,{children:n});let[i,...a]=n.split(r);return(0,z.jsxs)(`p`,{children:[i,(0,z.jsx)(`code`,{children:r}),a.join(r)]})}function eg({copy:e,onConfirm:t,onClose:n}){let r=Z(),i=(0,_.useRef)(null),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(null),l=`integration-consequence-dialog-title`;(0,_.useEffect)(()=>{let e=i.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]);let u=(0,_.useCallback)(e=>{e.preventDefault(),a||n()},[n,a]),d=(0,_.useCallback)(async()=>{if(!a){o(!0),c(null);try{await t()}catch(e){c(e instanceof Error?e.message:r(`integrations.error.generic`)),o(!1)}}},[t,a,r]),f=[(0,z.jsx)($h,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,z.jsx)($h,{copyKey:e.breakageKey,vars:e.vars},`breakage`),(0,z.jsx)($h,{copyKey:e.undoKey,vars:e.vars},`undo`)];return e.sideEffectKey&&f.push((0,z.jsx)($h,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,z.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,z.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>{a||n()}}),(0,z.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,z.jsxs)(`div`,{className:`modal-head`,children:[(0,z.jsx)(`h3`,{id:l,children:r(e.titleKey,e.vars)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:n,disabled:a,children:r(`common.close`)})]}),(0,z.jsx)(`div`,{className:`integration-consequence-body`,children:f}),s&&(0,z.jsx)($,{tone:`err`,children:s}),(0,z.jsx)(`div`,{className:`modal-actions`,children:(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void d(),disabled:a,children:r(e.confirmKey)})})]})]})}var tg=[`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`],ng=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),rg=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),ig=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]);function ag(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function og(e){return!ag(e)||!ng.has(String(e.reason))?!1:typeof e.error==`string`&&rg.has(String(e.code))&&tg.includes(e.clientId)&&ig.has(String(e.state))&&typeof e.message==`string`}var sg=class extends Error{refusal;status;body;constructor(e,t){let n=og(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`IntegrationApiError`,this.status=e,this.body=t,this.refusal=n}};async function cg(e){try{let t=await e.json();return ag(t)?t:{}}catch{return{}}}async function lg(e){if(!e.ok)throw new sg(e.status,await cg(e));let t=await Ct(e);if(t==null)throw new sg(e.status,{});return t}async function ug(e,t){return lg(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function dg(e,t,n){return lg(await fetch(`${e}/api/client-integrations/${encodeURIComponent(t)}`,{signal:n}))}async function fg(e,t,n){let r=t?`?client=${encodeURIComponent(t)}`:``;return lg(await fetch(`${e}/api/client-integrations/journal${r}`,{signal:n}))}async function pg(e,t,n,r){return lg(await fetch(`${e}/api/client-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}async function mg(e,t,n=!1,r){return lg(await fetch(`${e}/api/client-integrations/restore`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:t,confirmDrift:n}),signal:r}))}async function hg(e){try{let t=await e;return t.ok?await Ct(t)??null:null}catch{return null}}async function gg(e,t){let n=await hg(fetch(`${e}/api/startup-health`,{signal:t}));return n?{routingInjected:n.routingInjected===!0,status:typeof n.status==`string`?n.status:void 0,recommendedCommand:typeof n.recommendedCommand==`string`?n.recommendedCommand:null}:null}async function _g(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await Ct(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function vg(e,t){let n=await hg(fetch(`${e}/api/claude-code`,{signal:t}));return n?{enabled:n.enabled===!0,authMode:typeof n.authMode==`string`?n.authMode:void 0}:null}async function yg(e,t){let n=await hg(fetch(`${e}/api/claude-desktop/status`,{signal:t}));return!n||typeof n.desiredEnabled!=`boolean`||typeof n.installed!=`boolean`||typeof n.observedKind!=`string`?null:{desiredEnabled:n.desiredEnabled,installed:n.installed,observedKind:n.observedKind,applied:n.applied===!0,stale:n.stale===!0,activeProfile:typeof n.activeProfile==`boolean`?n.activeProfile:null,appliedAt:typeof n.appliedAt==`string`?n.appliedAt:null}}async function bg(e,t){let n=await hg(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var xg=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),Sg=new Set([`native_integration_refused`,`native_integration_failed`]),Cg=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function wg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Tg(e){return wg(e)?typeof e.error==`string`&&Sg.has(String(e.code))&&xg.has(String(e.clientId))&&Cg.has(String(e.reason))&&typeof e.message==`string`:!1}var Eg=class extends Error{refusal;status;body;constructor(e,t){let n=Tg(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`NativeApiError`,this.status=e,this.body=t,this.refusal=n}};async function Dg(e){try{let t=await e;return t.ok?await Ct(t)??null:null}catch{return null}}async function Og(e){try{let t=await e.json();return wg(t)?t:{}}catch{return{}}}async function kg(e){if(!e.ok)throw new Eg(e.status,await Og(e));let t=await Ct(e);if(t==null)throw new Eg(e.status,{});return t}function Ag(e,t){return Dg(fetch(`${e}/api/native-integrations`,{signal:t}))}async function jg(e,t,n,r){return kg(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var Mg={integration_mutation_busy:`integrations.error.busy`};function Ng(e){return e instanceof sg?e.refusal:null}function Pg(e){return e instanceof Eg?e.refusal:null}function Fg(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var Ig=new Set([`non_loopback`]);function Lg(e,t,n){return t.reason===`orphaned_marker`?e(`integrations.native.error.orphanedMarker`,{path:n??``}):t.reason===`home_mismatch`?`${e(`integrations.native.error.homeMismatch`)} ${t.message}`:t.reason===`not_installed`?e(`integrations.native.error.notInstalled`):t.reason===`config_busy`?e(`integrations.native.error.configBusy`):t.reason===`metadata_unreadable`?e(`integrations.native.error.desktopUnsafeMetadata`,{path:n??``}):t.reason===`cleanup_incomplete`?e(`integrations.native.error.desktopCleanupIncomplete`,{paths:(t.residualPaths??[]).join(`, `)}):t.message||e(`integrations.error.generic`)}function Rg(e,t,n,r){let i=Pg(t);if(i)return Lg(e,i,r);let a=Ng(t);if(!a){let r=Mg[t instanceof sg?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}let o=Ig.has(a.reason)?e(Fg(a.reason),{client:a.clientId}):a.message||e(Fg(a.reason));return a.snapshotPath?e(a.residual?`integrations.error.residual`:`integrations.error.recover`,{message:o,path:a.snapshotPath}):a.reason===`conflict`||a.reason===`unsafe`?`${e(Fg(a.reason))} ${o}`:o}function zg({apiBase:e,row:t,onClose:n,onRestored:r}){let i=Z(),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(null),d=async()=>{if(!s){c(!0),u(null);try{await mg(e,t.opId,a),r(),n()}catch(e){if(Ng(e)?.reason===`drift_requires_confirm`){o(!0),c(!1);return}u(Rg(i,e)),c(!1)}}};return(0,z.jsx)(`dialog`,{className:`modal-overlay`,open:!0,style:{display:`flex`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`integration-restore-title`,onCancel:e=>{e.preventDefault(),n()},children:(0,z.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,children:[(0,z.jsx)(`div`,{className:`modal-head`,children:(0,z.jsx)(`h3`,{id:`integration-restore-title`,children:i(a?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,z.jsx)(`div`,{className:`modal-desc`,children:i(a?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,z.jsx)(`p`,{className:`integration-path`,children:t.configPath}),l&&(0,z.jsx)($,{tone:`err`,children:l}),(0,z.jsxs)(`div`,{className:`modal-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,disabled:s,children:i(`common.cancel`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void d(),disabled:s,children:i(s?`integrations.restore.pending`:a?`integrations.restore.confirmDrift`:`integrations.restore.confirm`)})]})]})})}var Bg={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`};function Vg(e){return e===`current`||e===`stale`}function Hg(e){let t={id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`,toggle:`codex`,toggleBlocked:null,togglePath:null,status:null,detail:null,detailVars:null};return e?e.routingInjected===!0?{...t,state:e.status===`error`?`stale`:`current`,installed:!0,applied:!0,detailKey:`integrations.detail.codexRouted`}:{...t,state:`absent`,installed:!0,applied:!1,detail:e.recommendedCommand??null,detailKey:e.recommendedCommand?null:`integrations.detail.codexAbsent`}:{...t,state:`unknown`,installed:!1,applied:!1,detailKey:null}}function Ug(e,t){let n={hash:`integrations/keys`,labelKey:`integrations.tab.keys`};return e===`checking`?{...n,state:`checking`,detailKey:`integrations.detail.keyChecking`,detailVars:null}:e===`unavailable`||t===null?{...n,state:`unavailable`,detailKey:`integrations.detail.keyUnavailable`,detailVars:null}:{...n,state:t>0?`issued`:`none-issued`,detailKey:t>0?`integrations.detail.keyCount`:`integrations.detail.keyNone`,detailVars:t>0?{count:String(t)}:null}}function Wg(e){return e?e.enabled===!0?e.authMode===`subscription`?`claude.authModeSubscription`:e.authMode===`proxy`?`claude.authModeProxy`:e.authMode===`auto`?`claude.authModeAuto`:null:`integrations.detail.claudeOff`:null}function Gg(e,t,n){let r={id:`claude`,hash:`integrations/claude`,labelKey:`integrations.tab.claude`,toggle:`claude`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null},i=Wg(e);if(n===void 0){if(!e)return{...r,state:`unknown`,installed:!1,applied:!1,detailKey:i};let t=e.enabled===!0;return{...r,state:t?`current`:`absent`,installed:!0,applied:t,detailKey:i}}return n?t?{...r,state:t.state,installed:t.installed,applied:t.state===`current`,detailKey:i}:{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:i}:{...r,state:`unknown`,installed:!1,applied:!1,detailKey:i}}function Kg(e,t,n){let r={id:`claudeDesktop`,hash:`integrations/claude/desktop`,labelKey:`claudeDesktop.title`,toggle:`claude-desktop`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null};if(!e||!n||!t||typeof e.desiredEnabled!=`boolean`)return{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:null};let i=e.desiredEnabled;if(e.applied!==!0)return{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:i,detailKey:i?`integrations.detail.desktopDesiredOnNotApplied`:`integrations.detail.desktopDesiredOff`};let a=e.stale===!0||e.activeProfile===!1;return{...r,state:a?`stale`:`current`,installed:!0,applied:!0,toggleOn:i,detailKey:e.activeProfile===!1?`integrations.detail.desktopNotServed`:a?`integrations.detail.desktopStale`:`integrations.detail.desktopCurrent`}}function qg(e){if(!e)return{detailKey:null,detailVars:null};let t=e.present===!0;return{detailKey:t?`integrations.detail.grokModels`:`integrations.detail.grokAbsent`,detailVars:t?{count:String(e.models?.length??0)}:null}}function Jg(e,t,n){let r={id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`,toggle:`grok`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null},i=qg(e);if(n===void 0){if(!e)return{...r,state:`unknown`,installed:!1,applied:!1,...i};let t=e.present===!0;return{...r,state:t?`current`:`absent`,installed:t,applied:t,...i}}return n?t?{...r,state:t.state,installed:t.installed,applied:t.state===`current`,...i}:{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,...i}:{...r,state:`unknown`,installed:!1,applied:!1,...i}}function Yg(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:Bg[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&Vg(e.state),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function Xg(e){let t=e.native?.find(e=>e.clientId===`claude`),n=e.native?.find(e=>e.clientId===`grok`),r=new Map(e.clients.map(e=>[e.clientId,e])),i=[Hg(e.codex),Gg(e.claude,t,e.nativeSettled),Kg(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),Jg(e.grok,n,e.nativeSettled)];for(let t of tg){let n=r.get(t);if(n){i.push(Yg(n));continue}e.clientsSettled||i.push({id:t,hash:`integrations/${t}`,labelKey:Bg[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:Ug(e.keyPhase,e.keyCount),rows:i}}function Zg(e){return{detected:e.filter(e=>e.installed).length,applied:e.filter(e=>e.applied).length,stale:e.filter(e=>e.state===`stale`).length,unknown:e.filter(e=>e.state===`unknown`).length}}var Qg={titleKey:`integrations.dialog.grok.title`,changesKey:`integrations.dialog.grok.changes`,breakageKey:`integrations.dialog.grok.breakage`,undoKey:`integrations.dialog.grok.undo`,confirmKey:`integrations.dialog.grok.confirm`},$g={titleKey:`integrations.dialog.desktop.title`,changesKey:`integrations.dialog.desktop.changes`,breakageKey:`integrations.dialog.desktop.breakage`,undoKey:`integrations.dialog.desktop.undo`,sideEffectKey:`integrations.dialog.desktop.restart`,confirmKey:`integrations.dialog.desktop.confirm`},e_={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`};function t_(e){return e.state===`current`||e.state===`stale`}function n_({row:e,pending:t,result:n,onOpen:r,onToggle:i}){let a=Z(),o=e.detail??(e.detailKey?a(e.detailKey,e.detailVars??void 0):null),s=e.toggleBlocked!==null&&(e.applied||e.toggleBlocked.reason===`orphaned_marker`),c=s&&e.toggleBlocked&&(e.toggle===`claude`||e.toggle===`grok`)?Rg(a,new Eg(409,{error:`native integration change refused`,code:`native_integration_refused`,clientId:e.toggle,reason:e.toggleBlocked.reason,message:e.toggleBlocked.message}),void 0,e.togglePath??void 0):null;return(0,z.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,children:[(0,z.jsxs)(`div`,{className:`integration-card-head`,children:[(0,z.jsx)(`h4`,{children:(0,z.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:r,children:a(e.labelKey)})}),(0,z.jsx)(Qh,{state:e.state,installed:e.installed})]}),o&&(0,z.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:o}),n?.tone===`err`&&(0,z.jsx)($,{tone:`err`,children:n.text}),n?.tone===`ok`&&(0,z.jsx)($,{tone:`ok`,children:n.text}),(0,z.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&i&&(0,z.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,z.jsx)(pt,{on:e.toggleOn??e.applied,onClick:i,disabled:e.state===`unknown`||!e.installed||e.state===`conflict`||e.state===`unsafe`||s||t,label:e.applied?a(`integrations.action.disable`):a(`integrations.action.apply`)}),c&&(0,z.jsx)(`p`,{className:`integration-toggle-blocked`,children:c})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,tabIndex:-1,children:a(`integrations.action.settings`)})]})]})}function r_({apiBase:e,active:t=!0}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)({}),[d,f]=(0,_.useState)(null),p=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(d!==null)return;let e=p.current;e&&(p.current=null,e.isConnected&&e.focus())},[d]);let m=(0,_.useCallback)(async t=>(await ug(e,t)).clients,[e]),h=(0,_.useCallback)(async t=>(await fg(e,void 0,t)).operations,[e]),g=(0,_.useCallback)(t=>gg(e,t),[e]),v=(0,_.useCallback)(t=>_g(e,t),[e]),y=(0,_.useCallback)(t=>vg(e,t),[e]),b=(0,_.useCallback)(t=>yg(e,t),[e]),x=(0,_.useCallback)(t=>bg(e,t),[e]),S=(0,_.useCallback)(async t=>(await Ag(e,t))?.clients??null,[e]),C=vc(`integration-states:${e}`,[e],m,{isEmpty:e=>e.length===0,enabled:t}),w=vc(`integration-journal-all:${e}`,[e],h,{isEmpty:e=>e.length===0,enabled:t}),T=vc(`integration-codex:${e}`,[e],g,{isEmpty:e=>e===null,enabled:t}),E=vc(`integration-keys:${e}`,[e],v,{isEmpty:()=>!1,enabled:t}),D=vc(`integration-claude:${e}`,[e],y,{isEmpty:e=>e===null,enabled:t}),O=vc(`integration-claude-desktop:${e}`,[e],b,{isEmpty:e=>e===null,enabled:t}),k=vc(`integration-grok:${e}`,[e],x,{isEmpty:e=>e===null,enabled:t}),A=vc(`integration-native:${e}`,[e],S,{isEmpty:e=>e===null,enabled:t}),j=C.state.data??[],M=w.state.data??[],N=j.filter(t_),P=j.filter(e=>e.installed),F=C.state.kind!==`cold`&&C.state.kind!==`retrying-cold`,I=A.state.data??null,L=I!==null,R=E.state.kind===`cold`||E.state.kind===`retrying-cold`?`checking`:E.state.kind===`failed-cold`||E.state.kind===`failed-with-stale`?`unavailable`:`settled`,{keysRow:B,rows:V}=Xg({clients:j,clientsSettled:F,codex:T.state.data??null,keyCount:E.state.data??null,keyPhase:R,claude:D.state.data??null,claudeDesktop:O.state.data??null,grok:k.state.data??null,native:I,nativeSettled:L}),H=Zg(V),U=()=>{C.refresh(),w.refresh(),T.refresh(),E.refresh(),D.refresh(),O.refresh(),k.refresh(),A.refresh()},W=async()=>{if(r||N.length===0)return;let t=[n(`integrations.bulk.title`),n(`integrations.bulk.body`)].join(`
|
|
75
75
|
|
|
76
|
-
`);if(!confirm(t))return;i(!0),o(null);let a=[];for(let t of N)try{await pg(e,t.clientId,!1)}catch(e){a.push(`${t.clientId}: ${Rg(n,e)}`)}let s=!1;try{s=(await ug(e)).clients.some(t_)}catch{a.push(n(`integrations.error.stale`))}s&&a.length===0&&a.push(n(`integrations.error.stale`)),U(),i(!1),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},G=M[0]?.at,[ee,te]=(0,_.useState)(null),K=()=>{A.refresh(),D.refresh(),k.refresh()},q=(e,t)=>{u(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},J=async(t,r)=>{if(!ee&&t.toggle){te(t.id),q(t.id,null);try{if(t.status)await pg(e,t.status.clientId,r),U();else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await jg(e,t.toggle,r);i.reason===`non_loopback_removed`?q(t.id,{tone:`ok`,text:n(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&q(t.id,{tone:`ok`,text:n(`integrations.native.msg.nonLoopbackSuperseded`)}),K()}}catch(e){q(t.id,{tone:`err`,text:Rg(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&K()}finally{te(null)}}},Y=(e,t)=>{if(e.status||t||e.id===`claude`||e.toggle===null){J(e,t);return}let n=document.activeElement;p.current=n?.tagName===`BUTTON`?n:null,f(e)};return(0,z.jsxs)(`section`,{className:`integrations-overview`,children:[(0,z.jsxs)(`div`,{className:`integration-summary`,children:[(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,z.jsx)(`strong`,{children:H.detected})]}),(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,z.jsx)(`strong`,{children:H.applied})]}),(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,z.jsx)(`strong`,{children:H.stale})]}),H.unknown>0&&(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,z.jsx)(`strong`,{children:H.unknown})]}),(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,z.jsx)(`strong`,{children:G?new Date(G).toLocaleString():n(`integrations.status.unknown`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void W(),disabled:r||N.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,z.jsx)(i_,{row:B}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),C.state.kind===`failed-cold`&&(0,z.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),C.state.kind===`failed-with-stale`&&(0,z.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,z.jsx)($,{tone:a.tone,children:a.text}),V.length===0?C.state.kind===`failed-cold`?null:(0,z.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,z.jsx)(`ul`,{className:`integration-cards`,children:V.map(e=>(0,z.jsx)(n_,{row:e,pending:ee!==null,result:l[e.id]??null,onOpen:()=>nt(e.hash),onToggle:e.toggle?()=>Y(e,!(e.toggleOn??e.applied)):null},e.id))}),F&&P.length===0&&(0,z.jsxs)(`div`,{className:`integration-empty`,children:[(0,z.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,z.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,z.jsx)(`h4`,{children:n(`integrations.rollback.title`)}),M.length===0?(0,z.jsxs)(`div`,{className:`integration-empty`,children:[(0,z.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,z.jsx)(`ul`,{className:`integration-history`,children:M.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`integration-history-kind`,children:n(e_[e.kind])}),(0,z.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,z.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,z.jsx)(`span`,{className:`badge badge-muted`,children:n(`integrations.action.snapshotExpired`)}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>c(e),children:e.undoable?n(`integrations.action.undo`):n(`integrations.action.restorePoint`)})]},e.opId))}),s&&(0,z.jsx)(zg,{apiBase:e,row:s,onClose:()=>c(null),onRestored:U}),d&&(0,z.jsx)(eg,{copy:{...d.toggle===`claude-desktop`?$g:Qg,vars:{path:d.togglePath??``}},onClose:()=>f(null),onConfirm:async()=>{await J(d,!1),f(null)}})]})}function i_({row:e}){let t=Z(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,z.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,z.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,z.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,z.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>nt(e.hash),children:t(`integrations.action.manageKeys`)})]})}var a_={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`},o_={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`},s_={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`};function c_({apiBase:e,client:t,active:n=!0}){let r=Z(),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),u=(0,_.useCallback)(n=>dg(e,t,n),[e,t]),d=(0,_.useCallback)(async n=>(await fg(e,t,n)).operations,[e,t]),f=vc(`integration-state:${e}:${t}`,[e,t],u,{isEmpty:()=>!1,enabled:n}),p=vc(`integration-journal:${e}:${t}`,[e,t],d,{isEmpty:e=>e.length===0,enabled:n}),m=f.state.data??null,h=p.state.data??[],g=()=>{f.refresh(),p.refresh()},v=async n=>{if(!(!m||i)){a(!0),s(null);try{await pg(e,t,n),g()}catch(e){s(Rg(r,e))}finally{a(!1)}}},y=()=>void v(!(m&&(m.state===`current`||m.state===`stale`)));if(!m)return(0,z.jsx)(`section`,{className:`integration-client-page`,children:f.state.kind===`failed-cold`?(0,z.jsx)($,{tone:`err`,children:r(`integrations.error.load`)}):(0,z.jsx)(`p`,{className:`page-sub`,children:r(`common.loading`)})});let b=m.state===`current`||m.state===`stale`,x=!m.installed||m.state===`conflict`||m.state===`unsafe`;return(0,z.jsxs)(`section`,{className:`integration-client-page`,children:[(0,z.jsxs)(`div`,{className:`integration-client-head`,children:[(0,z.jsx)(`h3`,{children:r(o_[t])}),(0,z.jsx)(Qh,{state:m.state,installed:m.installed,id:`integration-state-${t}`}),(0,z.jsx)(pt,{on:b,onClick:y,disabled:x||i,label:r(b?`integrations.action.disable`:`integrations.action.apply`)})]}),m.state===`stale`&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void v(!0),disabled:i,children:r(`integrations.action.refresh`)}),(0,z.jsx)(`p`,{className:`page-sub`,children:r(a_[t])}),(0,z.jsx)(`p`,{className:`integration-path`,children:m.configPath}),m.appliedAt&&(0,z.jsxs)(`p`,{className:`integration-meta`,children:[r(`integrations.status.appliedAt`),`: `,new Date(m.appliedAt).toLocaleString()]}),m.retentionDegraded&&(0,z.jsx)($,{tone:`err`,children:r(`integrations.retention.degraded`)}),o&&(0,z.jsx)($,{tone:`err`,children:o}),(0,z.jsx)(`h4`,{children:r(`integrations.rollback.title`)}),h.length===0?(0,z.jsx)(`p`,{className:`page-sub`,children:r(`integrations.rollback.empty`)}):(0,z.jsx)(`ul`,{className:`integration-history`,children:h.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`integration-history-kind`,children:r(s_[e.kind])}),(0,z.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,z.jsx)(`span`,{className:`badge badge-muted`,children:r(`integrations.action.snapshotExpired`)}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>l(e),children:e.undoable?r(`integrations.action.undo`):r(`integrations.action.restorePoint`)})]},e.opId))}),c&&(0,z.jsx)(zg,{apiBase:e,row:c,onClose:()=>l(null),onRestored:g})]})}var l_=[{id:`overview`,hash:`integrations`,labelKey:`integrations.tab.overview`},{id:`keys`,hash:`integrations/keys`,labelKey:`integrations.tab.keys`},{id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`},{id:`claude`,hash:`integrations/claude`,labelKey:`integrations.tab.claude`},{id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`},{id:`opencode`,hash:`integrations/opencode`,labelKey:`integrations.tab.opencode`},{id:`pi`,hash:`integrations/pi`,labelKey:`integrations.tab.pi`},{id:`omp`,hash:`integrations/omp`,labelKey:`integrations.tab.omp`},{id:`hermes`,hash:`integrations/hermes`,labelKey:`integrations.tab.hermes`},{id:`openclaw`,hash:`integrations/openclaw`,labelKey:`integrations.tab.openclaw`},{id:`kimi`,hash:`integrations/kimi`,labelKey:`integrations.tab.kimi`},{id:`gajae`,hash:`integrations/gajae`,labelKey:`integrations.tab.gajae`},{id:`dsh`,hash:`integrations/dsh`,labelKey:`integrations.tab.dsh`},{id:`mcode`,hash:`integrations/mcode`,labelKey:`integrations.tab.mcode`}],u_=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`]);function d_(e=window.location.hash){let t=et(e);return t===`integrations/claude/desktop`?`claude`:l_.find(e=>e.hash===t)?.id??`overview`}function f_(e){return`integrations-tab-${e}`}function p_(e){return`integrations-panel-${e}`}function m_({apiBase:e}){let t=Z(),[n,r]=(0,_.useState)(d_),[i,a]=(0,_.useState)(()=>new Set([d_()])),o=(0,_.useRef)(null);o.current===null&&(o.current=new Map);let s=e=>{r(e),a(t=>t.has(e)?t:new Set([...t,e]))};(0,_.useEffect)(()=>{let e=()=>s(d_());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let c=(e,t)=>{let n=l_.find(t=>t.id===e);n&&(nt(n.hash),s(e),t&&window.requestAnimationFrame(()=>{o.current.get(e)?.focus({preventScroll:!0})}))},l=e=>{let t=l_.findIndex(e=>e.id===n),r=null;e.key===`ArrowLeft`?r=(t-1+l_.length)%l_.length:e.key===`ArrowRight`?r=(t+1)%l_.length:e.key===`Home`?r=0:e.key===`End`&&(r=l_.length-1),r!==null&&(e.preventDefault(),c(l_[r].id,!0))};return(0,z.jsxs)(`section`,{className:`integrations-page`,children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:t(`nav.integrations`)})}),(0,z.jsx)(`p`,{className:`page-sub`,children:t(`integrations.subtitle`)}),(0,z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`integrations.tabsLabel`),children:l_.map(e=>(0,z.jsx)(`button`,{ref:t=>{t?o.current.set(e.id,t):o.current.delete(e.id)},type:`button`,role:`tab`,id:f_(e.id),"aria-selected":n===e.id,"aria-controls":p_(e.id),tabIndex:n===e.id?0:-1,className:`page-tab${n===e.id?` page-tab--active`:``}`,onClick:()=>c(e.id,!0),onKeyDown:l,children:t(e.labelKey)},e.id))}),l_.map(r=>{if(!i.has(r.id))return null;let a=n===r.id;return(0,z.jsxs)(`div`,{role:`tabpanel`,id:p_(r.id),"aria-labelledby":f_(r.id),hidden:!a,children:[r.id===`overview`&&(0,z.jsx)(r_,{apiBase:e,active:a}),r.id===`keys`&&(0,z.jsx)(th,{apiBase:e,active:a}),r.id===`codex`&&(0,z.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,z.jsx)(`h3`,{id:`codex-integration-title`,children:t(`integrations.codex.title`)}),(0,z.jsx)(`p`,{children:t(`integrations.codex.body`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>nt(`startup`),children:t(`integrations.codex.openService`)})]}),r.id===`claude`&&(0,z.jsx)(Uh,{apiBase:e,active:a}),r.id===`grok`&&(0,z.jsx)(Yh,{apiBase:e,active:a}),u_.has(r.id)&&(0,z.jsx)(c_,{apiBase:e,client:r.id,active:a})]},r.id)})]})}function h_(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 g_={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},__={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},v_={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function y_({ok:e,yes:t,no:n}){return(0,z.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function b_({failed:e,data:t}){let{t:n}=Ze(),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`?se:J,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,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,z.jsx)(`div`,{className:`startup-hero-icon`,children:(0,z.jsx)(i,{})}),(0,z.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,z.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:g_[t.status])}),(0,z.jsx)(`h3`,{children:n(e?`startup.error`:__[t.status])}),(0,z.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(Yn(t)):n(`startup.safeDetail`)})]})]}),(0,z.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,z.jsxs)(`section`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,z.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,z.jsxs)(`section`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,z.jsx)(`div`,{className:`value`,children:n(v_[t.protection])})]}),(0,z.jsxs)(`section`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,z.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function x_({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=Ze(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,z.jsxs)(`section`,{className:`panel startup-details`,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,z.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,z.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:o(`startup.service`)}),(0,z.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,z.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,z.jsx)(y_,{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,z.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,z.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,z.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:o(`startup.shim`)}),(0,z.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,z.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,z.jsx)(y_,{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,z.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,z.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,z.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 S_({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=Ze();return(0,z.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,z.jsx)(me,{})]}),(0,z.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,z.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,z.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,z.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,z.jsx)(y_,{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,z.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,z.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,z.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,z.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,z.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,z.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function C_({data:e,copied:t,onCopy:n}){let{t:r}=Ze(),i=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,z.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,z.jsx)(te,{})]}),(0,z.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,z.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,z.jsxs)(`div`,{className:`startup-command-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,z.jsx)(`code`,{children:i})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(i),children:r(t===i?`startup.copied`:`startup.copy`)})]}),(0,z.jsxs)(`div`,{className:`startup-command-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,z.jsx)(`code`,{children:e.commands.installShim})]}),(0,z.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,z.jsxs)(`div`,{className:`startup-command-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,z.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,z.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,z.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,z.jsx)(me,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var w_=`ocx.startup.page.v1:`;function T_(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function E_(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=T_([`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 D_({apiBase:e}){let{t}=Ze(),n=`${w_}${e}`,r=(0,_.useMemo)(()=>qn(n),[n]),i=`startup-page:${e}`,[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(()=>r?.tray??null),[l,u]=(0,_.useState)(()=>!r?.data),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>r?.warning??null),[S,C]=(0,_.useState)(()=>r?.fix??null),[w,T]=(0,_.useState)(()=>!r?.data),E=(0,_.useRef)(!!r?.data),D=(0,_.useCallback)(async r=>{let i=E.current;i||(u(!0),T(!0));try{let i=fetch(`${e}/api/settings`,{signal:r}).then(async e=>e.ok?await e.json():null).catch(()=>null),a=await fetch(`${e}/api/startup-health`,{signal:r});if(!a.ok)throw Error(`fetch failed`);let o=await a.json();y(e=>e?.kind===`error`&&(o.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?o.serviceViable:o.shimInstalled&&o.shimHealthy))?null:e),E.current=!0;let s=qn(n);Jn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:s?.tray??null});let l=o.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:r}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!h_(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([i,l]).then(([e,i])=>{if(r.aborted)return;let a=o.platform===`win32`?i.tray:null;if(o.platform===`win32`?(c(a),m(i.error)):(c(null),m(!1)),u(!1),T(!1),e){let r=E_(e.codexRuntime,t,o.platform);x(r.warning),C(r.fix),Jn(n,{data:o,warning:r.warning,fix:r.fix,tray:a});return}let s=qn(n);Jn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:a})}),o}catch(e){throw r.aborted?e:(i||(c(null),m(!0),x(null),C(null)),T(!1),u(!1),e)}},[e,n,t]),O=vc(i,[e],D,{isEmpty:()=>!1,initialData:r?.data??void 0}),k=O.state,A=O.refresh,j=k.data??r?.data??null,M=k.refreshing,N=!!j?.diagnosticStale||k.showError;(0,_.useEffect)(()=>{if(!j?.diagnosticStale)return;let e=window.setTimeout(A,2e3);return()=>window.clearTimeout(e)},[j,A]);let P=async e=>{try{await navigator.clipboard.writeText(e),o(e),window.setTimeout(()=>o(t=>t===e?null:t),1600)}catch{o(null)}},F=async t=>{f(!0),m(!1);try{let n=await fetch(`${e}/api/windows-tray`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t})});if(!n.ok)throw Error(`tray action failed`);let r=await n.json();if(!h_(r.status))throw Error(`invalid tray action status`);c(r.status),m(!1)}catch{c(null),m(!0)}finally{f(!1)}},I=async(t,n)=>{g(t),y(null);try{let r=await fetch(`${e}/api/startup-action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t,repair:n?.repair===!0})});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(typeof e?.error==`string`?e.error:`installation failed`)}y({kind:`success`,action:t,repair:n?.repair===!0}),A()}catch(e){y({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:j?.localRoutingDependency===!0})}finally{g(null)}};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h2`,{children:t(`startup.title`)}),(0,z.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,z.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>nt(`dashboard`),children:t(`startup.backToDashboard`)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),disabled:M,children:[(0,z.jsx)(re,{}),` `,t(`startup.refresh`)]})]})]}),k.showSkeleton&&!j?(0,z.jsx)(bc,{label:t(`startup.loading`),rows:5}):k.kind===`failed-cold`?(0,z.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,z.jsx)($,{tone:`err`,children:k.error instanceof Error?k.error.message:t(`startup.error`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),children:t(`common.retry`)})]}):j?(0,z.jsxs)(z.Fragment,{children:[k.showError&&(0,z.jsx)($,{tone:`err`,children:t(`startup.error`)}),N&&(0,z.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(w||b)&&(0,z.jsx)(`div`,{className:`startup-runtime-notice-slot${w&&!b?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":w&&!b?!0:void 0,children:b&&(0,z.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,z.jsx)(`p`,{className:`startup-runtime-notice__text`,children:b}),S&&(0,z.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,z.jsx)(`code`,{children:S}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void P(S),children:t(a===S?`startup.copied`:`startup.copy`)})]})]})}),(0,z.jsx)(b_,{failed:N,data:j}),(0,z.jsx)(x_,{data:j,failed:N,loading:M,installBusy:h,installResult:v,onInstall:(e,t)=>{I(e,t)}}),j.platform===`win32`&&(0,z.jsx)(S_,{tray:s,trayLoading:l,trayError:p,trayBusy:d,onTrayAction:e=>{F(e)}}),(0,z.jsx)(C_,{data:j,copied:a,onCopy:e=>{P(e)}})]}):null]})}var O_=3e5,k_=6e5,A_=`https://github.com/lidge-jun/opencodex`;async function j_(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function M_({apiBase:e,onOpenUpdate:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=I(`sidebar-star:${e}`,[e],t=>j_(`${e}/api/github/star`,t),{pollMs:O_}),c=I(`sidebar-update-badge:${e}`,[e],t=>j_(`${e}/api/update/badge`,t),{pollMs:k_}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??A_,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,z.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,z.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,z.jsx)(pe,{}),` `,n(`common.github`)]}),(0,z.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,z.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,z.jsx)(Ee,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,z.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,z.jsx)(de,{"aria-hidden":`true`}),m&&(0,z.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var N_=`opencodex-admin-token-dialog`,P_=`OpenCodex`;function F_(e,t=qe()){let n=Be[t],r=n[`auth.adminTokenTitle`];return new Promise(t=>{let i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=!1,o=document.createElement(`dialog`);o.id=N_,o.className=`modal-overlay`,o.setAttribute(`aria-labelledby`,`${N_}-title`);let s=document.createElement(`form`);s.className=`modal-card`,s.method=`post`,s.action=window.location.href,s.autocomplete=`on`;let c=document.createElement(`div`);c.className=`modal-head`;let l=document.createElement(`h3`);l.id=`${N_}-title`,l.textContent=r,c.append(l);let u=document.createElement(`div`),d=document.createElement(`label`);d.className=`field-label`,d.htmlFor=`${N_}-username`,d.textContent=n[`auth.adminAccountLabel`];let f=document.createElement(`input`);f.id=d.htmlFor,f.className=`input`,f.type=`text`,f.name=`username`,f.autocomplete=`username`,f.value=P_,f.readOnly=!0,u.append(d,f);let p=document.createElement(`div`);p.style.marginTop=`var(--space-4)`;let m=document.createElement(`label`);m.className=`field-label`,m.htmlFor=`${N_}-password`,m.textContent=n[`auth.adminTokenFieldLabel`];let h=document.createElement(`input`);h.id=m.htmlFor,h.className=`input`,h.type=`password`,h.name=`password`,h.autocomplete=`current-password`,h.required=!0,h.spellcheck=!1,h.autocapitalize=`none`,p.append(m,h);let g=document.createElement(`div`);g.className=`notice notice-err`,g.setAttribute(`role`,`alert`),g.hidden=!0;let _=document.createElement(`div`);_.className=`modal-actions`;let v=document.createElement(`button`);v.type=`button`,v.className=`btn btn-ghost`,v.textContent=n[`common.cancel`];let y=document.createElement(`button`);y.type=`submit`,y.className=`btn btn-primary`,y.textContent=n[`common.ok`],_.append(v,y),s.append(c,u,p,g,_),o.append(s);let b=e=>{a||(a=!0,o.open&&o.close(),o.remove(),i?.focus(),t(e))};s.addEventListener(`submit`,t=>{t.preventDefault();let r=h.value.trim();if(!r){h.value=``,h.reportValidity();return}h.disabled=!0,y.disabled=!0,g.hidden=!0,e(r).then(e=>{if(!a){if(e===`accepted`){b(r);return}h.value=``,h.disabled=!1,y.disabled=!1,g.textContent=e===`rejected`?n[`auth.adminTokenRejected`]:n[`auth.adminTokenUnavailable`],g.hidden=!1,h.focus()}}).catch(()=>{a||(h.value=``,h.disabled=!1,y.disabled=!1,g.textContent=n[`auth.adminTokenUnavailable`],g.hidden=!1,h.focus())})}),v.addEventListener(`click`,()=>b(null)),o.addEventListener(`cancel`,e=>{e.preventDefault(),b(null)}),document.body.append(o),typeof o.showModal==`function`?o.showModal():o.setAttribute(`open`,``),queueMicrotask(()=>h.focus())})}var I_=!1,L_=null,R_=null,z_=!1,B_=F_,V_=`/opencodex-session`,H_=`/api/settings`;function U_(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/`)}catch{return!1}}var W_=`opencodex-api-token`,G_=null,K_=null,q_=null;function J_(){return G_}function Y_(e){G_=e}function X_(){G_=null,K_=null,q_=null}function Z_(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function Q_(){ev(Z_(`opencodex-session-token`),Z_(`opencodex-session-csrf`),Z_(`opencodex-session-origin`))}function $_(e){e!=null&&J_()===e&&X_()}function ev(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(G_=e,K_=t,q_=n,!0)}function tv(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 nv(){if(!R_)return null;try{let e=await R_(V_,{cache:`no-store`});if(!e.ok)return null;let t=await e.text();return ev(tv(t,`opencodex-session-token`),tv(t,`opencodex-session-csrf`),tv(t,`opencodex-session-origin`))?J_():null}catch{return null}}async function rv(e){if(!R_)return`unavailable`;try{let[t,n]=av(H_,{cache:`no-store`},e),r=await R_(t,n);return r.status===401?`rejected`:r.ok?`accepted`:`unavailable`}catch{return`unavailable`}}function iv(){try{sessionStorage.removeItem(W_)}catch{}}function av(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),q_&&K_&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,q_);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,K_)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function ov(e){return z_?null:L_||(L_=(async()=>{if(z_)return null;let t=J_();if(t&&t!==e)return t;let n=await nv();if(n)return n;let r=await B_(rv);return r?(Y_(r),r):(z_=!0,null)})().finally(()=>{L_=null}),L_)}function sv(){if(I_)return;I_=!0,iv(),Q_();let e=window.fetch.bind(window);R_=e,window.fetch=async(t,n)=>{if(!U_(t))return e(t,n);let r=J_(),[i,a]=r?av(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;let s=J_();if(s&&s!==r){let[r,i]=av(t,n,s),a=await e(r,i);if(a.status!==401)return a;$_(s)}else $_(r);let c=await ov(r);if(!c)return o;let[l,u]=av(t,n,c),d=await e(l,u);return d.status===401&&$_(c),d}}var cv=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`logs`,`usage`,`storage`,`codex-auth`,`integrations`]);function lv(e){let t=et(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:t===`combos`||t===`routing`||t===`lab`?`models`:t===`api`||t===`claude`||t===`grok`?`integrations`:cv.has(t)?t:`dashboard`}var uv=[`dashboard/providers`,`dashboard/models`],dv=[`models/combos`,`models/routing`,`models/compatibility`],fv=[`integrations/keys`,`integrations/codex`,`integrations/claude`,`integrations/claude/desktop`,`integrations/grok`,`integrations/opencode`,`integrations/pi`,`integrations/omp`,`integrations/hermes`,`integrations/openclaw`,`integrations/kimi`,`integrations/gajae`,`integrations/dsh`];function pv(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`models`&&dv.includes(e)||t===`dashboard`&&(e===`dashboard/update`||uv.includes(e))||t===`integrations`&&fv.includes(e)}function mv(e){let t=lv(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`claude`?{page:`integrations`,replaceTo:`integrations/claude`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:pv(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var hv=[`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 gv(){try{for(let e of hv)localStorage.removeItem(e)}catch{}}function _v(){let[e,t]=(0,_.useState)(lv);(0,_.useEffect)(()=>{gv()},[]);let n=(0,_.useCallback)(e=>{let n=mv(e);n.replaceTo&&tt(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(et(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,_.useEffect)(()=>{let n=mv(et(window.location.hash));n.replaceTo&&tt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{nt(n?`${e}/${n}`:e),t(e)}}}var vv=15e3;function yv(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 bv(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function xv(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=vv,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 bv(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:yv(o,a.status,i)}:{accepted:!0}}sv();var Sv={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,"codex-auth":`nav.codexAuth`,integrations:`nav.integrations`},Cv=``,wv=`ocx-theme`,Tv=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:V},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:ge},{id:`providers`,tkey:`nav.providers`,Icon:H},{id:`models`,tkey:`nav.models`,Icon:U},{id:`subagents`,tkey:`nav.subagents`,Icon:W},{id:`logs`,tkey:`nav.logs`,Icon:G},{id:`usage`,tkey:`nav.usage`,Icon:K},{id:`storage`,tkey:`nav.storage`,Icon:q},{id:`integrations`,tkey:`nav.integrations`,Icon:Ce}],Ev={light:be,dark:xe,system:Se},Dv={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function Ov(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 kv(){let e=localStorage.getItem(wv);return e===`light`||e===`dark`?e:`system`}function Av(){let{page:e,navigateToPage:t}=_v(),[n,r]=(0,_.useState)(vd);(0,_.useEffect)(()=>{let e=()=>r(vd());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[i,a]=(0,_.useState)(kv),{locale:o,setLocale:s}=Ze(),c=Z(),[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>u(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,_.useEffect)(()=>{let e=document.documentElement;i===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(wv)):(e.setAttribute(`data-theme`,i),localStorage.setItem(wv,i))},[i]);let m=I(`app-healthz:${Cv}`,[],async e=>{let t=await fetch(`${Cv}/healthz`,{signal:e});return t.ok?Ov(await t.json()):null},{pollMs:3e4}),h=()=>a(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),g=Ev[i],v=m.data??`2.20.0`,[y,b]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!l)return;let e=e=>{e.key===`Escape`&&u(!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}},[l]),(0,_.useEffect)(()=>{if(l){p.current=!0;let e=setTimeout(()=>f.current?.focus(),200);return()=>clearTimeout(e)}p.current&&(p.current=!1,d.current?.focus())},[l]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&u(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[x,S]=(0,_.useState)(0),{restarting:C,restart:w}=dc(Cv,{onSettled:()=>S(e=>e+1)}),T=async()=>{if(!confirm(c(`dash.stopConfirm`)))return;b(!0);let e=await xv(Cv,{formatFailure:e=>c(`dash.stopFailed`,{status:String(e)})});e.accepted||(b(!1),alert(e.message))},E=(0,z.jsxs)(`div`,{className:`brand`,children:[(0,z.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":c(`app.logoAria`)}),(0,z.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,z.jsxs)(`span`,{className:`ver`,children:[`v`,v]})]});return(0,z.jsxs)(`div`,{className:`app`,children:[(0,z.jsxs)(`header`,{className:`mobile-topbar`,inert:l,children:[(0,z.jsx)(`button`,{ref:d,type:`button`,className:`menu-toggle`,onClick:()=>u(e=>!e),"aria-expanded":l,"aria-controls":`app-sidebar`,"aria-label":c(l?`nav.closeMenu`:`nav.openMenu`),title:c(l?`nav.closeMenu`:`nav.openMenu`),children:(0,z.jsx)(ee,{})}),E,(0,z.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:T,disabled:y,"aria-label":c(`dash.stop`),title:c(`dash.stop`),children:(0,z.jsx)(me,{})}),(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{w()},disabled:C,"aria-label":c(`dash.codexRestart`),title:c(`dash.codexRestart`),children:(0,z.jsx)(re,{})})]})]}),l&&(0,z.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>u(!1),"aria-hidden":`true`}),(0,z.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${l?` open`:``}`,ref:f,tabIndex:-1,children:[(0,z.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,z.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>u(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,z.jsx)(Y,{})})]}),(0,z.jsx)(`nav`,{children:Tv.map(n=>{let{id:r,tkey:i,Icon:a}=n,o=r===e;return(0,z.jsx)(`div`,{className:`nav-entry`,children:(0,z.jsxs)(`button`,{type:`button`,className:`nav-item${o?` active`:``}`,"data-page":r,onClick:()=>{t(r),u(!1)},"aria-current":o?`page`:void 0,children:[(0,z.jsx)(a,{}),` `,c(i)]})},r)})}),(0,z.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,z.jsxs)(`div`,{className:`lang-toggle`,children:[(0,z.jsx)(Ce,{"aria-hidden":!0}),(0,z.jsx)(ht,{value:o,options:Ue.map(e=>({value:e.code,label:Ve(e.code)})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,z.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:h,"aria-label":`${c(`theme.label`)}: ${c(Dv[i])}`,title:`${c(`theme.label`)}: ${c(Dv[i])}`,children:[(0,z.jsx)(g,{}),` `,(0,z.jsx)(`span`,{className:`mode`,children:c(Dv[i])})]}),(0,z.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,z.jsx)(`span`,{className:`sidebar-action-label`,children:c(`dash.actions`)}),(0,z.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:T,disabled:y,"aria-label":c(y?`dash.stopping`:`dash.stop`),title:c(y?`dash.stopping`:`dash.stop`),children:(0,z.jsx)(me,{})}),(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{w()},disabled:C,"aria-label":c(C?`dash.codexRestarting`:`dash.codexRestart`),title:c(C?`dash.codexRestarting`:`dash.codexRestart`),children:(0,z.jsx)(re,{})})]})]}),(0,z.jsx)(M_,{apiBase:Cv,onOpenUpdate:()=>{u(!1),t(`dashboard`,`update`)}})]})]}),(0,z.jsx)(`main`,{className:`main`,inert:l,children:(0,z.jsx)(`div`,{className:`main-inner${e===`models`&&n===`combos`?` main-inner--combos`:``}`,children:(0,z.jsxs)(Sc,{pageName:c(Sv[e]),title:c(`errorBoundary.title`),message:c(`errorBoundary.message`),detailsLabel:c(`errorBoundary.details`),reloadLabel:c(`errorBoundary.reload`),children:[e===`dashboard`&&(0,z.jsx)(wr,{apiBase:Cv}),e===`startup`&&(0,z.jsx)(D_,{apiBase:Cv}),e===`providers`&&(0,z.jsx)(Qs,{apiBase:Cv}),e===`models`&&(0,z.jsx)(Yd,{apiBase:Cv,restartEpoch:x},Cv),e===`subagents`&&(0,z.jsx)(cf,{apiBase:Cv},Cv),e===`logs`&&(0,z.jsx)(Mp,{apiBase:Cv}),e===`usage`&&(0,z.jsx)(em,{apiBase:Cv}),e===`storage`&&(0,z.jsx)(vm,{apiBase:Cv}),e===`codex-auth`&&(0,z.jsx)(Tm,{apiBase:Cv}),e===`integrations`&&(0,z.jsx)(m_,{apiBase:Cv})]},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,z.jsx)(_.StrictMode,{children:(0,z.jsx)(Qe,{children:(0,z.jsx)(Av,{})})}));
|
|
76
|
+
`);if(!confirm(t))return;i(!0),o(null);let a=[];for(let t of N)try{await pg(e,t.clientId,!1)}catch(e){a.push(`${t.clientId}: ${Rg(n,e)}`)}let s=!1;try{s=(await ug(e)).clients.some(t_)}catch{a.push(n(`integrations.error.stale`))}s&&a.length===0&&a.push(n(`integrations.error.stale`)),U(),i(!1),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},G=M[0]?.at,[ee,te]=(0,_.useState)(null),K=()=>{A.refresh(),D.refresh(),k.refresh()},q=(e,t)=>{u(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},J=async(t,r)=>{if(!ee&&t.toggle){te(t.id),q(t.id,null);try{if(t.status)await pg(e,t.status.clientId,r),U();else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await jg(e,t.toggle,r);i.reason===`non_loopback_removed`?q(t.id,{tone:`ok`,text:n(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&q(t.id,{tone:`ok`,text:n(`integrations.native.msg.nonLoopbackSuperseded`)}),K()}}catch(e){q(t.id,{tone:`err`,text:Rg(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&K()}finally{te(null)}}},Y=(e,t)=>{if(e.status||t||e.id===`claude`||e.toggle===null){J(e,t);return}let n=document.activeElement;p.current=n?.tagName===`BUTTON`?n:null,f(e)};return(0,z.jsxs)(`section`,{className:`integrations-overview`,children:[(0,z.jsxs)(`div`,{className:`integration-summary`,children:[(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,z.jsx)(`strong`,{children:H.detected})]}),(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,z.jsx)(`strong`,{children:H.applied})]}),(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,z.jsx)(`strong`,{children:H.stale})]}),H.unknown>0&&(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,z.jsx)(`strong`,{children:H.unknown})]}),(0,z.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,z.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,z.jsx)(`strong`,{children:G?new Date(G).toLocaleString():n(`integrations.status.unknown`)})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void W(),disabled:r||N.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,z.jsx)(i_,{row:B}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),C.state.kind===`failed-cold`&&(0,z.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),C.state.kind===`failed-with-stale`&&(0,z.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,z.jsx)($,{tone:a.tone,children:a.text}),V.length===0?C.state.kind===`failed-cold`?null:(0,z.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,z.jsx)(`ul`,{className:`integration-cards`,children:V.map(e=>(0,z.jsx)(n_,{row:e,pending:ee!==null,result:l[e.id]??null,onOpen:()=>nt(e.hash),onToggle:e.toggle?()=>Y(e,!(e.toggleOn??e.applied)):null},e.id))}),F&&P.length===0&&(0,z.jsxs)(`div`,{className:`integration-empty`,children:[(0,z.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,z.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,z.jsx)(`h4`,{children:n(`integrations.rollback.title`)}),M.length===0?(0,z.jsxs)(`div`,{className:`integration-empty`,children:[(0,z.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,z.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,z.jsx)(`ul`,{className:`integration-history`,children:M.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`integration-history-kind`,children:n(e_[e.kind])}),(0,z.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,z.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,z.jsx)(`span`,{className:`badge badge-muted`,children:n(`integrations.action.snapshotExpired`)}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>c(e),children:e.undoable?n(`integrations.action.undo`):n(`integrations.action.restorePoint`)})]},e.opId))}),s&&(0,z.jsx)(zg,{apiBase:e,row:s,onClose:()=>c(null),onRestored:U}),d&&(0,z.jsx)(eg,{copy:{...d.toggle===`claude-desktop`?$g:Qg,vars:{path:d.togglePath??``}},onClose:()=>f(null),onConfirm:async()=>{await J(d,!1),f(null)}})]})}function i_({row:e}){let t=Z(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,z.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,z.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,z.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,z.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>nt(e.hash),children:t(`integrations.action.manageKeys`)})]})}var a_={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`},o_={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`},s_={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`};function c_({apiBase:e,client:t,active:n=!0}){let r=Z(),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),u=(0,_.useCallback)(n=>dg(e,t,n),[e,t]),d=(0,_.useCallback)(async n=>(await fg(e,t,n)).operations,[e,t]),f=vc(`integration-state:${e}:${t}`,[e,t],u,{isEmpty:()=>!1,enabled:n}),p=vc(`integration-journal:${e}:${t}`,[e,t],d,{isEmpty:e=>e.length===0,enabled:n}),m=f.state.data??null,h=p.state.data??[],g=()=>{f.refresh(),p.refresh()},v=async n=>{if(!(!m||i)){a(!0),s(null);try{await pg(e,t,n),g()}catch(e){s(Rg(r,e))}finally{a(!1)}}},y=()=>void v(!(m&&(m.state===`current`||m.state===`stale`)));if(!m)return(0,z.jsx)(`section`,{className:`integration-client-page`,children:f.state.kind===`failed-cold`?(0,z.jsx)($,{tone:`err`,children:r(`integrations.error.load`)}):(0,z.jsx)(`p`,{className:`page-sub`,children:r(`common.loading`)})});let b=m.state===`current`||m.state===`stale`,x=!m.installed||m.state===`conflict`||m.state===`unsafe`;return(0,z.jsxs)(`section`,{className:`integration-client-page`,children:[(0,z.jsxs)(`div`,{className:`integration-client-head`,children:[(0,z.jsx)(`h3`,{children:r(o_[t])}),(0,z.jsx)(Qh,{state:m.state,installed:m.installed,id:`integration-state-${t}`}),(0,z.jsx)(pt,{on:b,onClick:y,disabled:x||i,label:r(b?`integrations.action.disable`:`integrations.action.apply`)})]}),m.state===`stale`&&(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void v(!0),disabled:i,children:r(`integrations.action.refresh`)}),(0,z.jsx)(`p`,{className:`page-sub`,children:r(a_[t])}),(0,z.jsx)(`p`,{className:`integration-path`,children:m.configPath}),m.appliedAt&&(0,z.jsxs)(`p`,{className:`integration-meta`,children:[r(`integrations.status.appliedAt`),`: `,new Date(m.appliedAt).toLocaleString()]}),m.retentionDegraded&&(0,z.jsx)($,{tone:`err`,children:r(`integrations.retention.degraded`)}),o&&(0,z.jsx)($,{tone:`err`,children:o}),(0,z.jsx)(`h4`,{children:r(`integrations.rollback.title`)}),h.length===0?(0,z.jsx)(`p`,{className:`page-sub`,children:r(`integrations.rollback.empty`)}):(0,z.jsx)(`ul`,{className:`integration-history`,children:h.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`span`,{className:`integration-history-kind`,children:r(s_[e.kind])}),(0,z.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,z.jsx)(`span`,{className:`badge badge-muted`,children:r(`integrations.action.snapshotExpired`)}):(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>l(e),children:e.undoable?r(`integrations.action.undo`):r(`integrations.action.restorePoint`)})]},e.opId))}),c&&(0,z.jsx)(zg,{apiBase:e,row:c,onClose:()=>l(null),onRestored:g})]})}var l_=[{id:`overview`,hash:`integrations`,labelKey:`integrations.tab.overview`},{id:`keys`,hash:`integrations/keys`,labelKey:`integrations.tab.keys`},{id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`},{id:`claude`,hash:`integrations/claude`,labelKey:`integrations.tab.claude`},{id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`},{id:`opencode`,hash:`integrations/opencode`,labelKey:`integrations.tab.opencode`},{id:`pi`,hash:`integrations/pi`,labelKey:`integrations.tab.pi`},{id:`omp`,hash:`integrations/omp`,labelKey:`integrations.tab.omp`},{id:`hermes`,hash:`integrations/hermes`,labelKey:`integrations.tab.hermes`},{id:`openclaw`,hash:`integrations/openclaw`,labelKey:`integrations.tab.openclaw`},{id:`kimi`,hash:`integrations/kimi`,labelKey:`integrations.tab.kimi`},{id:`gajae`,hash:`integrations/gajae`,labelKey:`integrations.tab.gajae`},{id:`dsh`,hash:`integrations/dsh`,labelKey:`integrations.tab.dsh`},{id:`mcode`,hash:`integrations/mcode`,labelKey:`integrations.tab.mcode`}],u_=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`]);function d_(e=window.location.hash){let t=et(e);return t===`integrations/claude/desktop`?`claude`:l_.find(e=>e.hash===t)?.id??`overview`}function f_(e){return`integrations-tab-${e}`}function p_(e){return`integrations-panel-${e}`}function m_({apiBase:e}){let t=Z(),[n,r]=(0,_.useState)(d_),[i,a]=(0,_.useState)(()=>new Set([d_()])),o=(0,_.useRef)(null);o.current===null&&(o.current=new Map);let s=e=>{r(e),a(t=>t.has(e)?t:new Set([...t,e]))};(0,_.useEffect)(()=>{let e=()=>s(d_());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let c=(e,t)=>{let n=l_.find(t=>t.id===e);n&&(nt(n.hash),s(e),t&&window.requestAnimationFrame(()=>{o.current.get(e)?.focus({preventScroll:!0})}))},l=e=>{let t=l_.findIndex(e=>e.id===n),r=null;e.key===`ArrowLeft`?r=(t-1+l_.length)%l_.length:e.key===`ArrowRight`?r=(t+1)%l_.length:e.key===`Home`?r=0:e.key===`End`&&(r=l_.length-1),r!==null&&(e.preventDefault(),c(l_[r].id,!0))};return(0,z.jsxs)(`section`,{className:`integrations-page`,children:[(0,z.jsx)(`div`,{className:`page-head`,children:(0,z.jsx)(`h2`,{children:t(`nav.integrations`)})}),(0,z.jsx)(`p`,{className:`page-sub`,children:t(`integrations.subtitle`)}),(0,z.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`integrations.tabsLabel`),children:l_.map(e=>(0,z.jsx)(`button`,{ref:t=>{t?o.current.set(e.id,t):o.current.delete(e.id)},type:`button`,role:`tab`,id:f_(e.id),"aria-selected":n===e.id,"aria-controls":p_(e.id),tabIndex:n===e.id?0:-1,className:`page-tab${n===e.id?` page-tab--active`:``}`,onClick:()=>c(e.id,!0),onKeyDown:l,children:t(e.labelKey)},e.id))}),l_.map(r=>{if(!i.has(r.id))return null;let a=n===r.id;return(0,z.jsxs)(`div`,{role:`tabpanel`,id:p_(r.id),"aria-labelledby":f_(r.id),hidden:!a,children:[r.id===`overview`&&(0,z.jsx)(r_,{apiBase:e,active:a}),r.id===`keys`&&(0,z.jsx)(th,{apiBase:e,active:a}),r.id===`codex`&&(0,z.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,z.jsx)(`h3`,{id:`codex-integration-title`,children:t(`integrations.codex.title`)}),(0,z.jsx)(`p`,{children:t(`integrations.codex.body`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>nt(`startup`),children:t(`integrations.codex.openService`)})]}),r.id===`claude`&&(0,z.jsx)(Uh,{apiBase:e,active:a}),r.id===`grok`&&(0,z.jsx)(Yh,{apiBase:e,active:a}),u_.has(r.id)&&(0,z.jsx)(c_,{apiBase:e,client:r.id,active:a})]},r.id)})]})}function h_(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 g_={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},__={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},v_={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function y_({ok:e,yes:t,no:n}){return(0,z.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function b_({failed:e,data:t}){let{t:n}=Ze(),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`?se:J,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,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,z.jsx)(`div`,{className:`startup-hero-icon`,children:(0,z.jsx)(i,{})}),(0,z.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,z.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:g_[t.status])}),(0,z.jsx)(`h3`,{children:n(e?`startup.error`:__[t.status])}),(0,z.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(Yn(t)):n(`startup.safeDetail`)})]})]}),(0,z.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,z.jsxs)(`section`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,z.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,z.jsxs)(`section`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,z.jsx)(`div`,{className:`value`,children:n(v_[t.protection])})]}),(0,z.jsxs)(`section`,{className:`stat`,children:[(0,z.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,z.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function x_({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=Ze(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,z.jsxs)(`section`,{className:`panel startup-details`,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,z.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,z.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:o(`startup.service`)}),(0,z.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,z.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,z.jsx)(y_,{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,z.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,z.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,z.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:o(`startup.shim`)}),(0,z.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,z.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,z.jsx)(y_,{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,z.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,z.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,z.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 S_({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=Ze();return(0,z.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,z.jsx)(me,{})]}),(0,z.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,z.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,z.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,z.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,z.jsx)(y_,{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,z.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,z.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,z.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,z.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,z.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,z.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function C_({data:e,copied:t,onCopy:n}){let{t:r}=Ze(),i=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,z.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,z.jsxs)(`div`,{className:`panel-head`,children:[(0,z.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,z.jsx)(te,{})]}),(0,z.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,z.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,z.jsxs)(`div`,{className:`startup-command-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,z.jsx)(`code`,{children:i})]}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(i),children:r(t===i?`startup.copied`:`startup.copy`)})]}),(0,z.jsxs)(`div`,{className:`startup-command-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,z.jsx)(`code`,{children:e.commands.installShim})]}),(0,z.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,z.jsxs)(`div`,{className:`startup-command-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,z.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,z.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,z.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,z.jsx)(me,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var w_=`ocx.startup.page.v1:`;function T_(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function E_(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=T_([`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 D_({apiBase:e}){let{t}=Ze(),n=`${w_}${e}`,r=(0,_.useMemo)(()=>qn(n),[n]),i=`startup-page:${e}`,[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(()=>r?.tray??null),[l,u]=(0,_.useState)(()=>!r?.data),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>r?.warning??null),[S,C]=(0,_.useState)(()=>r?.fix??null),[w,T]=(0,_.useState)(()=>!r?.data),E=(0,_.useRef)(!!r?.data),D=(0,_.useCallback)(async r=>{let i=E.current;i||(u(!0),T(!0));try{let i=fetch(`${e}/api/settings`,{signal:r}).then(async e=>e.ok?await e.json():null).catch(()=>null),a=await fetch(`${e}/api/startup-health`,{signal:r});if(!a.ok)throw Error(`fetch failed`);let o=await a.json();y(e=>e?.kind===`error`&&(o.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?o.serviceViable:o.shimInstalled&&o.shimHealthy))?null:e),E.current=!0;let s=qn(n);Jn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:s?.tray??null});let l=o.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:r}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!h_(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([i,l]).then(([e,i])=>{if(r.aborted)return;let a=o.platform===`win32`?i.tray:null;if(o.platform===`win32`?(c(a),m(i.error)):(c(null),m(!1)),u(!1),T(!1),e){let r=E_(e.codexRuntime,t,o.platform);x(r.warning),C(r.fix),Jn(n,{data:o,warning:r.warning,fix:r.fix,tray:a});return}let s=qn(n);Jn(n,{data:o,warning:s?.warning??null,fix:s?.fix??null,tray:a})}),o}catch(e){throw r.aborted?e:(i||(c(null),m(!0),x(null),C(null)),T(!1),u(!1),e)}},[e,n,t]),O=vc(i,[e],D,{isEmpty:()=>!1,initialData:r?.data??void 0}),k=O.state,A=O.refresh,j=k.data??r?.data??null,M=k.refreshing,N=!!j?.diagnosticStale||k.showError;(0,_.useEffect)(()=>{if(!j?.diagnosticStale)return;let e=window.setTimeout(A,2e3);return()=>window.clearTimeout(e)},[j,A]);let P=async e=>{try{await navigator.clipboard.writeText(e),o(e),window.setTimeout(()=>o(t=>t===e?null:t),1600)}catch{o(null)}},F=async t=>{f(!0),m(!1);try{let n=await fetch(`${e}/api/windows-tray`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t})});if(!n.ok)throw Error(`tray action failed`);let r=await n.json();if(!h_(r.status))throw Error(`invalid tray action status`);c(r.status),m(!1)}catch{c(null),m(!0)}finally{f(!1)}},I=async(t,n)=>{g(t),y(null);try{let r=await fetch(`${e}/api/startup-action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t,repair:n?.repair===!0})});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(typeof e?.error==`string`?e.error:`installation failed`)}y({kind:`success`,action:t,repair:n?.repair===!0}),A()}catch(e){y({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:j?.localRoutingDependency===!0})}finally{g(null)}};return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`page-head`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h2`,{children:t(`startup.title`)}),(0,z.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,z.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>nt(`dashboard`),children:t(`startup.backToDashboard`)}),(0,z.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),disabled:M,children:[(0,z.jsx)(re,{}),` `,t(`startup.refresh`)]})]})]}),k.showSkeleton&&!j?(0,z.jsx)(bc,{label:t(`startup.loading`),rows:5}):k.kind===`failed-cold`?(0,z.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,z.jsx)($,{tone:`err`,children:k.error instanceof Error?k.error.message:t(`startup.error`)}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(),children:t(`common.retry`)})]}):j?(0,z.jsxs)(z.Fragment,{children:[k.showError&&(0,z.jsx)($,{tone:`err`,children:t(`startup.error`)}),N&&(0,z.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(w||b)&&(0,z.jsx)(`div`,{className:`startup-runtime-notice-slot${w&&!b?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":w&&!b?!0:void 0,children:b&&(0,z.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,z.jsx)(`p`,{className:`startup-runtime-notice__text`,children:b}),S&&(0,z.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,z.jsx)(`code`,{children:S}),(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void P(S),children:t(a===S?`startup.copied`:`startup.copy`)})]})]})}),(0,z.jsx)(b_,{failed:N,data:j}),(0,z.jsx)(x_,{data:j,failed:N,loading:M,installBusy:h,installResult:v,onInstall:(e,t)=>{I(e,t)}}),j.platform===`win32`&&(0,z.jsx)(S_,{tray:s,trayLoading:l,trayError:p,trayBusy:d,onTrayAction:e=>{F(e)}}),(0,z.jsx)(C_,{data:j,copied:a,onCopy:e=>{P(e)}})]}):null]})}var O_=3e5,k_=6e5,A_=`https://github.com/lidge-jun/opencodex`;async function j_(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function M_({apiBase:e,onOpenUpdate:t}){let n=Z(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=I(`sidebar-star:${e}`,[e],t=>j_(`${e}/api/github/star`,t),{pollMs:O_}),c=I(`sidebar-update-badge:${e}`,[e],t=>j_(`${e}/api/update/badge`,t),{pollMs:k_}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??A_,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,z.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,z.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,z.jsx)(pe,{}),` `,n(`common.github`)]}),(0,z.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,z.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,z.jsx)(Ee,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,z.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,z.jsx)(de,{"aria-hidden":`true`}),m&&(0,z.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var N_=`opencodex-admin-token-dialog`,P_=`OpenCodex`;function F_(e,t=qe()){let n=Be[t],r=n[`auth.adminTokenTitle`];return new Promise(t=>{let i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=!1,o=document.createElement(`dialog`);o.id=N_,o.className=`modal-overlay`,o.setAttribute(`aria-labelledby`,`${N_}-title`);let s=document.createElement(`form`);s.className=`modal-card`,s.method=`post`,s.action=window.location.href,s.autocomplete=`on`;let c=document.createElement(`div`);c.className=`modal-head`;let l=document.createElement(`h3`);l.id=`${N_}-title`,l.textContent=r,c.append(l);let u=document.createElement(`div`),d=document.createElement(`label`);d.className=`field-label`,d.htmlFor=`${N_}-username`,d.textContent=n[`auth.adminAccountLabel`];let f=document.createElement(`input`);f.id=d.htmlFor,f.className=`input`,f.type=`text`,f.name=`username`,f.autocomplete=`username`,f.value=P_,f.readOnly=!0,u.append(d,f);let p=document.createElement(`div`);p.style.marginTop=`var(--space-4)`;let m=document.createElement(`label`);m.className=`field-label`,m.htmlFor=`${N_}-password`,m.textContent=n[`auth.adminTokenFieldLabel`];let h=document.createElement(`input`);h.id=m.htmlFor,h.className=`input`,h.type=`password`,h.name=`password`,h.autocomplete=`current-password`,h.required=!0,h.spellcheck=!1,h.autocapitalize=`none`,p.append(m,h);let g=document.createElement(`div`);g.className=`notice notice-err`,g.setAttribute(`role`,`alert`),g.hidden=!0;let _=document.createElement(`div`);_.className=`modal-actions`;let v=document.createElement(`button`);v.type=`button`,v.className=`btn btn-ghost`,v.textContent=n[`common.cancel`];let y=document.createElement(`button`);y.type=`submit`,y.className=`btn btn-primary`,y.textContent=n[`common.ok`],_.append(v,y),s.append(c,u,p,g,_),o.append(s);let b=e=>{a||(a=!0,o.open&&o.close(),o.remove(),i?.focus(),t(e))};s.addEventListener(`submit`,t=>{t.preventDefault();let r=h.value.trim();if(!r){h.value=``,h.reportValidity();return}h.disabled=!0,y.disabled=!0,g.hidden=!0,e(r).then(e=>{if(!a){if(e===`accepted`){b(r);return}h.value=``,h.disabled=!1,y.disabled=!1,g.textContent=e===`rejected`?n[`auth.adminTokenRejected`]:n[`auth.adminTokenUnavailable`],g.hidden=!1,h.focus()}}).catch(()=>{a||(h.value=``,h.disabled=!1,y.disabled=!1,g.textContent=n[`auth.adminTokenUnavailable`],g.hidden=!1,h.focus())})}),v.addEventListener(`click`,()=>b(null)),o.addEventListener(`cancel`,e=>{e.preventDefault(),b(null)}),document.body.append(o),typeof o.showModal==`function`?o.showModal():o.setAttribute(`open`,``),queueMicrotask(()=>h.focus())})}var I_=!1,L_=null,R_=null,z_=!1,B_=F_,V_=`/opencodex-session`,H_=`/api/settings`;function U_(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/`)}catch{return!1}}var W_=`opencodex-api-token`,G_=null,K_=null,q_=null;function J_(){return G_}function Y_(e){G_=e}function X_(){G_=null,K_=null,q_=null}function Z_(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function Q_(){ev(Z_(`opencodex-session-token`),Z_(`opencodex-session-csrf`),Z_(`opencodex-session-origin`))}function $_(e){e!=null&&J_()===e&&X_()}function ev(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(G_=e,K_=t,q_=n,!0)}function tv(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 nv(){if(!R_)return null;try{let e=await R_(V_,{cache:`no-store`});if(!e.ok)return null;let t=await e.text();return ev(tv(t,`opencodex-session-token`),tv(t,`opencodex-session-csrf`),tv(t,`opencodex-session-origin`))?J_():null}catch{return null}}async function rv(e){if(!R_)return`unavailable`;try{let[t,n]=av(H_,{cache:`no-store`},e),r=await R_(t,n);return r.status===401?`rejected`:r.ok?`accepted`:`unavailable`}catch{return`unavailable`}}function iv(){try{sessionStorage.removeItem(W_)}catch{}}function av(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),q_&&K_&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,q_);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,K_)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function ov(e){return z_?null:L_||(L_=(async()=>{if(z_)return null;let t=J_();if(t&&t!==e)return t;let n=await nv();if(n)return n;let r=await B_(rv);return r?(Y_(r),r):(z_=!0,null)})().finally(()=>{L_=null}),L_)}function sv(){if(I_)return;I_=!0,iv(),Q_();let e=window.fetch.bind(window);R_=e,window.fetch=async(t,n)=>{if(!U_(t))return e(t,n);let r=J_(),[i,a]=r?av(t,n,r):[t,n],o=await e(i,a);if(o.status!==401)return o;let s=J_();if(s&&s!==r){let[r,i]=av(t,n,s),a=await e(r,i);if(a.status!==401)return a;$_(s)}else $_(r);let c=await ov(r);if(!c)return o;let[l,u]=av(t,n,c),d=await e(l,u);return d.status===401&&$_(c),d}}var cv=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`logs`,`usage`,`storage`,`codex-auth`,`integrations`]);function lv(e){let t=et(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:t===`combos`||t===`routing`||t===`lab`?`models`:t===`api`||t===`claude`||t===`grok`?`integrations`:cv.has(t)?t:`dashboard`}var uv=[`dashboard/providers`,`dashboard/models`],dv=[`models/combos`,`models/routing`,`models/compatibility`],fv=[`integrations/keys`,`integrations/codex`,`integrations/claude`,`integrations/claude/desktop`,`integrations/grok`,`integrations/opencode`,`integrations/pi`,`integrations/omp`,`integrations/hermes`,`integrations/openclaw`,`integrations/kimi`,`integrations/gajae`,`integrations/dsh`];function pv(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`models`&&dv.includes(e)||t===`dashboard`&&(e===`dashboard/update`||uv.includes(e))||t===`integrations`&&fv.includes(e)}function mv(e){let t=lv(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`claude`?{page:`integrations`,replaceTo:`integrations/claude`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:pv(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var hv=[`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 gv(){try{for(let e of hv)localStorage.removeItem(e)}catch{}}function _v(){let[e,t]=(0,_.useState)(lv);(0,_.useEffect)(()=>{gv()},[]);let n=(0,_.useCallback)(e=>{let n=mv(e);n.replaceTo&&tt(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(et(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,_.useEffect)(()=>{let n=mv(et(window.location.hash));n.replaceTo&&tt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{nt(n?`${e}/${n}`:e),t(e)}}}var vv=15e3;function yv(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 bv(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function xv(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=vv,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 bv(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:yv(o,a.status,i)}:{accepted:!0}}sv();var Sv={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,"codex-auth":`nav.codexAuth`,integrations:`nav.integrations`},Cv=``,wv=`ocx-theme`,Tv=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:V},{id:`codex-auth`,tkey:`nav.codexAuth`,Icon:ge},{id:`providers`,tkey:`nav.providers`,Icon:H},{id:`models`,tkey:`nav.models`,Icon:U},{id:`subagents`,tkey:`nav.subagents`,Icon:W},{id:`logs`,tkey:`nav.logs`,Icon:G},{id:`usage`,tkey:`nav.usage`,Icon:K},{id:`storage`,tkey:`nav.storage`,Icon:q},{id:`integrations`,tkey:`nav.integrations`,Icon:Ce}],Ev={light:be,dark:xe,system:Se},Dv={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function Ov(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 kv(){let e=localStorage.getItem(wv);return e===`light`||e===`dark`?e:`system`}function Av(){let{page:e,navigateToPage:t}=_v(),[n,r]=(0,_.useState)(vd);(0,_.useEffect)(()=>{let e=()=>r(vd());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[i,a]=(0,_.useState)(kv),{locale:o,setLocale:s}=Ze(),c=Z(),[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>u(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,_.useEffect)(()=>{let e=document.documentElement;i===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(wv)):(e.setAttribute(`data-theme`,i),localStorage.setItem(wv,i))},[i]);let m=I(`app-healthz:${Cv}`,[],async e=>{let t=await fetch(`${Cv}/healthz`,{signal:e});return t.ok?Ov(await t.json()):null},{pollMs:3e4}),h=()=>a(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),g=Ev[i],v=m.data??`2.21.0`,[y,b]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!l)return;let e=e=>{e.key===`Escape`&&u(!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}},[l]),(0,_.useEffect)(()=>{if(l){p.current=!0;let e=setTimeout(()=>f.current?.focus(),200);return()=>clearTimeout(e)}p.current&&(p.current=!1,d.current?.focus())},[l]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&u(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[x,S]=(0,_.useState)(0),{restarting:C,restart:w}=dc(Cv,{onSettled:()=>S(e=>e+1)}),T=async()=>{if(!confirm(c(`dash.stopConfirm`)))return;b(!0);let e=await xv(Cv,{formatFailure:e=>c(`dash.stopFailed`,{status:String(e)})});e.accepted||(b(!1),alert(e.message))},E=(0,z.jsxs)(`div`,{className:`brand`,children:[(0,z.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":c(`app.logoAria`)}),(0,z.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,z.jsxs)(`span`,{className:`ver`,children:[`v`,v]})]});return(0,z.jsxs)(`div`,{className:`app`,children:[(0,z.jsxs)(`header`,{className:`mobile-topbar`,inert:l,children:[(0,z.jsx)(`button`,{ref:d,type:`button`,className:`menu-toggle`,onClick:()=>u(e=>!e),"aria-expanded":l,"aria-controls":`app-sidebar`,"aria-label":c(l?`nav.closeMenu`:`nav.openMenu`),title:c(l?`nav.closeMenu`:`nav.openMenu`),children:(0,z.jsx)(ee,{})}),E,(0,z.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:T,disabled:y,"aria-label":c(`dash.stop`),title:c(`dash.stop`),children:(0,z.jsx)(me,{})}),(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{w()},disabled:C,"aria-label":c(`dash.codexRestart`),title:c(`dash.codexRestart`),children:(0,z.jsx)(re,{})})]})]}),l&&(0,z.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>u(!1),"aria-hidden":`true`}),(0,z.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${l?` open`:``}`,ref:f,tabIndex:-1,children:[(0,z.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,z.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>u(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,z.jsx)(Y,{})})]}),(0,z.jsx)(`nav`,{children:Tv.map(n=>{let{id:r,tkey:i,Icon:a}=n,o=r===e;return(0,z.jsx)(`div`,{className:`nav-entry`,children:(0,z.jsxs)(`button`,{type:`button`,className:`nav-item${o?` active`:``}`,"data-page":r,onClick:()=>{t(r),u(!1)},"aria-current":o?`page`:void 0,children:[(0,z.jsx)(a,{}),` `,c(i)]})},r)})}),(0,z.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,z.jsxs)(`div`,{className:`lang-toggle`,children:[(0,z.jsx)(Ce,{"aria-hidden":!0}),(0,z.jsx)(ht,{value:o,options:Ue.map(e=>({value:e.code,label:Ve(e.code)})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,z.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:h,"aria-label":`${c(`theme.label`)}: ${c(Dv[i])}`,title:`${c(`theme.label`)}: ${c(Dv[i])}`,children:[(0,z.jsx)(g,{}),` `,(0,z.jsx)(`span`,{className:`mode`,children:c(Dv[i])})]}),(0,z.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,z.jsx)(`span`,{className:`sidebar-action-label`,children:c(`dash.actions`)}),(0,z.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:T,disabled:y,"aria-label":c(y?`dash.stopping`:`dash.stop`),title:c(y?`dash.stopping`:`dash.stop`),children:(0,z.jsx)(me,{})}),(0,z.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{w()},disabled:C,"aria-label":c(C?`dash.codexRestarting`:`dash.codexRestart`),title:c(C?`dash.codexRestarting`:`dash.codexRestart`),children:(0,z.jsx)(re,{})})]})]}),(0,z.jsx)(M_,{apiBase:Cv,onOpenUpdate:()=>{u(!1),t(`dashboard`,`update`)}})]})]}),(0,z.jsx)(`main`,{className:`main`,inert:l,children:(0,z.jsx)(`div`,{className:`main-inner${e===`models`&&n===`combos`?` main-inner--combos`:``}`,children:(0,z.jsxs)(Sc,{pageName:c(Sv[e]),title:c(`errorBoundary.title`),message:c(`errorBoundary.message`),detailsLabel:c(`errorBoundary.details`),reloadLabel:c(`errorBoundary.reload`),children:[e===`dashboard`&&(0,z.jsx)(wr,{apiBase:Cv}),e===`startup`&&(0,z.jsx)(D_,{apiBase:Cv}),e===`providers`&&(0,z.jsx)(Qs,{apiBase:Cv}),e===`models`&&(0,z.jsx)(Yd,{apiBase:Cv,restartEpoch:x},Cv),e===`subagents`&&(0,z.jsx)(cf,{apiBase:Cv},Cv),e===`logs`&&(0,z.jsx)(Mp,{apiBase:Cv}),e===`usage`&&(0,z.jsx)(em,{apiBase:Cv}),e===`storage`&&(0,z.jsx)(vm,{apiBase:Cv}),e===`codex-auth`&&(0,z.jsx)(Tm,{apiBase:Cv}),e===`integrations`&&(0,z.jsx)(m_,{apiBase:Cv})]},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,z.jsx)(_.StrictMode,{children:(0,z.jsx)(Qe,{children:(0,z.jsx)(Av,{})})}));
|